stringforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
stringforge/cy_io.py ADDED
@@ -0,0 +1,1787 @@
1
+ # ==============================================================================
2
+ # stringforge / cy_io
3
+ #
4
+ # Pure-I/O layer for the HuggingFace-hosted cy-database. Contains the core
5
+ # CYDatabase class and the two sub-dataset convenience subclasses (TDFDatabase,
6
+ # CICYDatabase) along with parquet / HF download plumbing, caching, catalog
7
+ # queries, and schema versioning.
8
+ #
9
+ # Sits at the dependency root of the stringforge package — vacua_writer and
10
+ # lcs_database import from this module, not the other way round. Also free of
11
+ # jaxvacua imports, so the sibling package can read/write the cache without
12
+ # circular dependencies.
13
+ # ==============================================================================
14
+
15
+ import datetime
16
+ import hashlib
17
+ import os
18
+ import json
19
+ import threading
20
+ import uuid
21
+ import warnings
22
+ from collections import OrderedDict, deque
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from pathlib import Path
25
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
26
+ import numpy as np
27
+ HF_REPO_ID: str = os.environ.get("STRINGFORGE_HF_REPO", "aschachner/cy-database")
28
+
29
+ _CACHE_SIZE_WARNING_MB: int = 500
30
+
31
+ def _get_default_data_dir() -> str:
32
+ r"""
33
+ **Description:**
34
+ Return the current global data directory from ``stringforge.data_dir``.
35
+
36
+ Falls back to ``~/.stringforge_cache`` if the package-level global
37
+ isn't set yet (i.e. when ``cy_io`` is imported before
38
+ ``stringforge/__init__.py`` finishes executing, or when the module
39
+ is used standalone for some reason).
40
+
41
+ Returns:
42
+ str: Path to the data directory.
43
+ """
44
+ try:
45
+ from . import data_dir
46
+ return data_dir
47
+ except ImportError:
48
+ return os.path.join(Path.home(), ".stringforge_cache")
49
+
50
+
51
+ DEFAULT_CACHE_DIR: str = _get_default_data_dir()
52
+
53
+ VAULT_DIRNAME: str = "vacua_vault"
54
+
55
+ DEFAULT_VAULT_REPO: str = "aschachner/vacua_vault"
56
+
57
+ def _resolve_vault_repo() -> str:
58
+ r"""
59
+ **Description:**
60
+ Return the HuggingFace dataset repo ID for vacua uploads. Honours
61
+ ``STRINGFORGE_VAULT_REPO`` env var, falling back to
62
+ :data:`DEFAULT_VAULT_REPO`.
63
+ """
64
+ return os.environ.get("STRINGFORGE_VAULT_REPO", DEFAULT_VAULT_REPO)
65
+
66
+
67
+ def _find_stringforge_repo_root(start: Optional[Path] = None) -> Optional[Path]:
68
+ r"""
69
+ **Description:**
70
+ Walk up from *start* (default: cwd) looking for a stringforge source
71
+ checkout. A directory counts as the repo root when it contains both
72
+ a ``setup.py`` with ``name="stringforge"`` and a ``stringforge/``
73
+ package directory.
74
+
75
+ Args:
76
+ start (Path | None): Starting directory. Defaults to cwd.
77
+
78
+ Returns:
79
+ Path | None: Absolute path to the repo root, or None if not
80
+ found.
81
+ """
82
+ current = Path(start or os.getcwd()).resolve()
83
+ for candidate in [current, *current.parents]:
84
+ setup_py = candidate / "setup.py"
85
+ pkg_dir = candidate / "stringforge"
86
+ if setup_py.is_file() and pkg_dir.is_dir():
87
+ try:
88
+ text = setup_py.read_text(encoding="utf-8", errors="replace")
89
+ except OSError:
90
+ continue
91
+ if 'name="stringforge"' in text or "name='stringforge'" in text:
92
+ return candidate
93
+ return None
94
+
95
+
96
+ def _resolve_vault_dir() -> Path:
97
+ r"""
98
+ **Description:**
99
+ Resolve the location of the permanent vacuum-solutions directory
100
+ (``vacua_vault/``).
101
+
102
+ Resolution order — uses whichever stage succeeds first:
103
+
104
+ 1. **``STRINGFORGE_VAULT`` env var** — explicit override. Recommended
105
+ for any real workflow. Set via ``export STRINGFORGE_VAULT=...``,
106
+ ``os.environ["STRINGFORGE_VAULT"] = ...``, or
107
+ :func:`stringforge.set_vault_dir`.
108
+ 2. **stringforge source checkout** — walks up from cwd looking for a
109
+ directory containing ``setup.py`` (with ``name="stringforge"``) and
110
+ a ``stringforge/`` package directory. Returns
111
+ ``<repo_root>/vacua_vault/``.
112
+ 3. **No fallback.** Raises :class:`LookupError` with explicit
113
+ instructions for how to configure the vault. This is
114
+ **deliberate**: silently creating ``vacua_vault/`` next to the
115
+ current working directory used to scatter empty vault folders
116
+ across users' filesystems. Forcing an explicit choice prevents
117
+ fragmentation.
118
+
119
+ The directory is **not** created by this function; callers create
120
+ it on demand (typically inside :class:`VacuaWriter` writer methods
121
+ via ``mkdir(parents=True, exist_ok=True)``).
122
+
123
+ Returns:
124
+ Path: Absolute path to the vault directory (may not exist yet).
125
+
126
+ Raises:
127
+ LookupError: If neither ``STRINGFORGE_VAULT`` is set nor cwd is
128
+ inside a stringforge source checkout.
129
+ """
130
+ override = os.environ.get("STRINGFORGE_VAULT")
131
+ if override:
132
+ return Path(override).expanduser().resolve()
133
+
134
+ repo_root = _find_stringforge_repo_root()
135
+ if repo_root is not None:
136
+ return repo_root / VAULT_DIRNAME
137
+
138
+ raise LookupError(
139
+ "Could not resolve a vault directory.\n\n"
140
+ " STRINGFORGE_VAULT env var: not set\n"
141
+ " stringforge repo root: not found in cwd or any parent\n\n"
142
+ "Set the vault explicitly:\n"
143
+ " - export STRINGFORGE_VAULT=/path/to/vault\n"
144
+ " - stringforge.set_vault_dir('/path/to/vault')\n"
145
+ " - os.environ['STRINGFORGE_VAULT'] = '/path/to/vault'\n\n"
146
+ "To opt into a cwd-local vault for a quick demo, set\n"
147
+ "STRINGFORGE_VAULT=. (or any explicit path)."
148
+ )
149
+
150
+
151
+ _DATASET_CONFIGS: Dict[str, str] = {
152
+ "tdf": "KS",
153
+ "cicy": "CICY",
154
+ "kklt": "KKLT",
155
+ }
156
+
157
+ SCHEMA_VERSION: int = 1
158
+
159
+ SCHEMA_CHANGELOG: Dict[int, str] = {
160
+ 1: "Initial versioned schema. Conifold basis-change matrix stored as "
161
+ "'basis_change' column; 'n_conifolds' and 'D3_tadpole' added to "
162
+ "catalog.parquet; conifold_catalog.parquet introduced. "
163
+ "The 'kklt' sub-dataset adopts v1 with an extended catalog "
164
+ "layout: polytope-grain catalog.parquet (one row per ks_id) with "
165
+ "n_rigids_dual / Q / n_coni_classes; conifold_class_catalog.parquet "
166
+ "keyed by (ks_id, coni_class_id); conifold_catalog.parquet keyed by "
167
+ "(ks_id, coni_class_id, coni_id) carrying the logical TDF link "
168
+ "(triang_id, tdf_conifold_id); optional tag columns record "
169
+ "curation and release-readiness metadata; schema.json carries a "
170
+ "TDF-compat fingerprint (tdf_schema_version, tdf_catalog_sha256).",
171
+ }
172
+
173
+ class SchemaVersionError(RuntimeError):
174
+ r"""
175
+ Raised when the schema version of the local cache does not match the
176
+ version expected by this release of the code.
177
+ """
178
+
179
+
180
+ class ValidationError(RuntimeError):
181
+ r"""
182
+ Raised when vacuum solutions fail validation checks before designation.
183
+ The ``report`` attribute contains per-solution diagnostics.
184
+ """
185
+
186
+ def __init__(self, message: str, report: Optional[List[dict]] = None):
187
+ """Initialise with message and optional per-solution diagnostic report."""
188
+ super().__init__(message)
189
+ self.report = report or []
190
+
191
+
192
+ def _require_pandas() -> Any:
193
+ r"""
194
+ **Description:**
195
+ Import and return the ``pandas`` module, raising a clear error if absent.
196
+ """
197
+ try:
198
+ import pandas as pd
199
+ return pd
200
+ except ImportError:
201
+ raise ImportError(
202
+ "The 'pandas' package is required to use CYDatabase. "
203
+ "Install it with: pip install pandas"
204
+ )
205
+
206
+
207
+ def _require_pyarrow() -> Any:
208
+ r"""
209
+ **Description:**
210
+ Import and return the ``pyarrow`` module, raising a clear error if absent.
211
+ """
212
+ try:
213
+ import pyarrow.parquet as pq
214
+ return pq
215
+ except ImportError:
216
+ raise ImportError(
217
+ "The 'pyarrow' package is required to use CYDatabase. "
218
+ "Install it with: pip install pyarrow"
219
+ )
220
+
221
+
222
+ def _require_hf_hub() -> Any:
223
+ r"""
224
+ **Description:**
225
+ Import and return the ``hf_hub_download`` function, raising a clear
226
+ error if ``huggingface_hub`` is absent.
227
+ """
228
+ try:
229
+ from huggingface_hub import hf_hub_download
230
+ return hf_hub_download
231
+ except ImportError:
232
+ raise ImportError(
233
+ "The 'huggingface_hub' package is required to use CYDatabase. "
234
+ "Install it with: pip install huggingface-hub"
235
+ )
236
+
237
+
238
+ def _require_hf_api() -> Any:
239
+ r"""
240
+ **Description:**
241
+ Import and return a fresh ``HfApi`` instance, raising a clear error
242
+ if ``huggingface_hub`` is absent. Used for write operations
243
+ (uploading files, opening pull requests, identifying the
244
+ authenticated user).
245
+ """
246
+ try:
247
+ from huggingface_hub import HfApi
248
+ return HfApi()
249
+ except ImportError:
250
+ raise ImportError(
251
+ "The 'huggingface_hub' package is required for upload "
252
+ "operations. Install it with: pip install huggingface-hub"
253
+ )
254
+
255
+
256
+ def _safe_concat(frames: List[Any], **kwargs: Any) -> Any:
257
+ r"""
258
+ Concatenate DataFrames, filtering out empty frames to avoid the pandas
259
+ ``FutureWarning`` about all-NA columns during concatenation.
260
+ """
261
+ pd = _require_pandas()
262
+ non_empty = [f for f in frames if len(f) > 0]
263
+ if not non_empty:
264
+ return pd.DataFrame()
265
+ return pd.concat(non_empty, **kwargs)
266
+
267
+
268
+ def _decode_array(value: Any) -> Optional[np.ndarray]:
269
+ r"""
270
+ **Description:**
271
+ Convert a parquet column entry to a numpy array.
272
+
273
+ Parquet stores multi-dimensional arrays either as nested lists or as
274
+ bytes-serialised numpy arrays (depending on the serialisation scheme used
275
+ when the dataset was written). This helper normalises both cases.
276
+
277
+ Args:
278
+ value: Raw column value from a parquet row.
279
+
280
+ Returns:
281
+ ``np.ndarray`` if the value is array-like, ``None`` if the value is
282
+ ``None`` or a pandas ``NA``.
283
+ """
284
+ if value is None:
285
+ return None
286
+ try:
287
+ import pandas as pd
288
+ if pd.isna(value):
289
+ return None
290
+ except (TypeError, ValueError):
291
+ pass
292
+ if isinstance(value, np.ndarray):
293
+ return value
294
+ return np.array(value)
295
+
296
+
297
+ def _decode_invariants(value: Any) -> Optional[np.ndarray]:
298
+ r"""
299
+ **Description:**
300
+ Decode a GV/GW ``invariants`` column entry. Like :func:`_decode_array`,
301
+ but additionally parses **decimal-string** encodings back to exact Python
302
+ ints: BPS invariants can exceed ``int64`` (which parquet cannot store), so
303
+ the KKLT GV split records them as strings. Numeric (``int64`` / float)
304
+ encodings -- e.g. the TDF split -- pass through unchanged.
305
+
306
+ Returns an ``object``-dtype array of Python ints for the string case (so
307
+ arbitrary-precision values survive), otherwise the plain numeric array.
308
+ """
309
+ arr = _decode_array(value)
310
+ if arr is None:
311
+ return None
312
+ if arr.dtype.kind in ("U", "S", "O"):
313
+ try:
314
+ return np.array([int(x) for x in arr.tolist()], dtype=object)
315
+ except (TypeError, ValueError):
316
+ return arr
317
+ return arr
318
+
319
+
320
+ def _parse_gv_row(row: Any) -> Dict[str, Any]:
321
+ r"""
322
+ **Description:**
323
+ Convert a single row from the ``gv`` parquet split into a dictionary of
324
+ Gopakumar-Vafa / Gromov-Witten data.
325
+
326
+ Expected columns: ``gv_charges``, ``gv_invariants``, ``gw_charges``,
327
+ ``gw_invariants``.
328
+
329
+ Args:
330
+ row: A ``pandas.Series`` from the GV parquet file.
331
+
332
+ Returns:
333
+ Dict[str, Any]: Dictionary with keys ``"GVs"`` and ``"GWs"``, each a
334
+ dict with ``"charges"`` and ``"invariants"`` arrays.
335
+ """
336
+ return {
337
+ "GVs": {
338
+ "charges": _decode_array(row.get("gv_charges")),
339
+ "invariants": _decode_invariants(row.get("gv_invariants")),
340
+ },
341
+ "GWs": {
342
+ "charges": _decode_array(row.get("gw_charges")),
343
+ "invariants": _decode_invariants(row.get("gw_invariants")),
344
+ },
345
+ "grading_vector": _decode_array(row.get("grading_vector")),
346
+ }
347
+
348
+
349
+ def _parse_conifold_rows(rows: Any) -> List[Dict[str, Any]]:
350
+ r"""
351
+ **Description:**
352
+ Convert all rows belonging to one model from the ``conifolds`` parquet
353
+ split into a list of conifold-data dictionaries.
354
+
355
+ Expected columns per row: ``conifold_id``, ``conifold_curve``, ``ncf``,
356
+ ``basis_change``, ``flop_edge``, ``one_face_divisors``.
357
+
358
+ Args:
359
+ rows: A ``pandas.DataFrame`` containing all conifold rows for one model
360
+ (i.e. all rows sharing the same ``ks_id`` and ``triang_id``).
361
+
362
+ Returns:
363
+ List[Dict[str, Any]]: One dict per conifold, sorted by ``conifold_id``.
364
+ """
365
+ result = []
366
+ for _, row in rows.sort_values("conifold_id").iterrows():
367
+ result.append({
368
+ "conifold_id": int(row["conifold_id"]),
369
+ "conifold_curve": _decode_array(row.get("conifold_curve")),
370
+ "ncf": int(row["ncf"]) if ("ncf" in row.index and row["ncf"] is not None) else 2,
371
+ "basis_change": _decode_array(row.get("basis_change")),
372
+ "flop_edge": _decode_array(row.get("flop_edge")),
373
+ "one_face_divisors": _decode_array(row.get("one_face_divisors")),
374
+ })
375
+ return result
376
+
377
+
378
+ def _parse_polytope_row(row: Any) -> Dict[str, Any]:
379
+ r"""
380
+ **Description:**
381
+ Convert a single row from the ``polytope`` parquet split into a dict.
382
+
383
+ The mandatory column is ``polytope_points``. Any additional columns
384
+ produced by ``process_polytope`` (e.g. ``is_favorable``, ``volume``,
385
+ ``glsm_charge_matrix``) are collected into a ``"polytope_data"`` sub-dict
386
+ so they do not collide with ``lcs_tree`` constructor arguments.
387
+
388
+ Args:
389
+ row: A ``pandas.Series`` from the polytope parquet file.
390
+
391
+ Returns:
392
+ Dict[str, Any]: Contains ``"polytope_points"`` and optionally
393
+ ``"polytope_data"`` with any extra fields.
394
+ """
395
+ _RESERVED = {"ks_id", "h11", "h12", "polytope_points"}
396
+ result: Dict[str, Any] = {
397
+ "polytope_points": _decode_array(row.get("polytope_points")),
398
+ }
399
+ extra = {
400
+ k: (v.tolist() if hasattr(v, "tolist") else v)
401
+ for k, v in row.items()
402
+ if k not in _RESERVED and v is not None
403
+ }
404
+ if extra:
405
+ result["polytope_data"] = extra
406
+ return result
407
+
408
+
409
+ class _LRUShardCache:
410
+ r"""
411
+ Thread-safe LRU cache for parquet shard DataFrames.
412
+
413
+ Keeps the ``maxsize`` most-recently-used ``(split, shard_id)`` shards in
414
+ memory so that repeated loads within the same h11 bucket avoid redundant
415
+ disk reads.
416
+
417
+ Args:
418
+ maxsize (int): Maximum number of shards to keep in memory.
419
+ """
420
+
421
+ def __init__(self, maxsize: int = 32) -> None:
422
+ """Initialise the LRU shard cache with a given maximum size."""
423
+ self._cache: OrderedDict = OrderedDict()
424
+ self._maxsize = maxsize
425
+ self._lock = threading.Lock()
426
+
427
+ def get(self, key: tuple) -> Any:
428
+ """Return the cached DataFrame for *key*, or ``None`` if not cached."""
429
+ with self._lock:
430
+ if key not in self._cache:
431
+ return None
432
+ self._cache.move_to_end(key)
433
+ return self._cache[key]
434
+
435
+ def put(self, key: tuple, value: Any) -> None:
436
+ """Insert *value* under *key*, evicting the LRU entry if full."""
437
+ with self._lock:
438
+ if key in self._cache:
439
+ self._cache.move_to_end(key)
440
+ else:
441
+ if len(self._cache) >= self._maxsize:
442
+ self._cache.popitem(last=False)
443
+ self._cache[key] = value
444
+
445
+ def clear(self) -> None:
446
+ """Evict all cached shards."""
447
+ with self._lock:
448
+ self._cache.clear()
449
+
450
+ def __len__(self) -> int:
451
+ return len(self._cache)
452
+
453
+
454
+ class CYDatabase:
455
+ r"""
456
+ **Description:**
457
+ Pure-I/O interface for Calabi-Yau geometry data stored in the
458
+ HuggingFace-hosted ``cy-database``.
459
+
460
+ The database is organised into sub-datasets (``dataset`` parameter):
461
+
462
+ - ``"tdf"``: toric models from the Kreuzer-Skarke list, identified by
463
+ ``(ks_id, triang_id)`` in catalogue convention.
464
+ - ``"cicy"``: Complete Intersection Calabi-Yau models, identified by
465
+ ``cicy_id``.
466
+ - ``"kklt"``: curated KKLT search index with logical links back to TDF.
467
+
468
+ ``CYDatabase`` downloads catalogues and parquet shards lazily, caches them
469
+ locally, supports offline operation, and exposes tabular query helpers. It
470
+ intentionally has no JAXVacua dependency and does not construct
471
+ ``lcs_tree`` or ``FluxVacuaFinder`` objects. Use
472
+ :class:`stringforge.lcs_database.LCSDatabase` for that model-loading bridge.
473
+
474
+ Example usage::
475
+
476
+ db = CYDatabase(dataset="tdf")
477
+ rows = db.query(h11=2, has_conifolds=True)
478
+ poly = db.get_polytope(ks_id=int(rows.iloc[0]["ks_id"]), h11=2)
479
+
480
+ offline_db = CYDatabase.from_local("./.stringforge_cache", dataset="tdf")
481
+
482
+ """
483
+
484
+
485
+ def __init__(
486
+ self,
487
+ dataset: str = "tdf",
488
+ hf_repo: str = HF_REPO_ID,
489
+ cache_dir: Optional[str] = None,
490
+ offline: bool = False,
491
+ shard_cache_size: int = 32,
492
+ cache_mode: str = "persistent",
493
+ ) -> None:
494
+ r"""
495
+ **Description:**
496
+ Initialise a :class:`CYDatabase` instance.
497
+
498
+ The catalog parquet file is downloaded on first use and cached to
499
+ ``cache_dir``. Subsequent calls are served from disk. Set
500
+ ``offline=True`` to suppress any network access.
501
+
502
+ Args:
503
+ dataset (str): Sub-dataset identifier. Must be one of
504
+ ``"tdf"`` (Kreuzer-Skarke toric models), ``"cicy"``
505
+ (Complete Intersection CY models), or ``"kklt"``
506
+ (curated KKLT index). Defaults to ``"tdf"``.
507
+ hf_repo (str): HuggingFace repository identifier of the form
508
+ ``"org/repo-name"``. Defaults to :data:`HF_REPO_ID`.
509
+ cache_dir (str | None): Local directory for cached parquet
510
+ files and vacua storage. If ``None`` (default), uses the
511
+ global ``stringforge.data_dir`` (which defaults to
512
+ ``{cwd}/.stringforge_cache`` and can be overridden via
513
+ :func:`stringforge.set_data_dir` or the
514
+ ``STRINGFORGE_DATA_DIR`` environment variable).
515
+ offline (bool): If ``True``, only serve data from the local
516
+ cache and raise an error on any cache miss. Defaults to
517
+ ``False``.
518
+ shard_cache_size (int): Number of parquet shards to keep in
519
+ memory after loading. Repeated accesses to the same shard
520
+ (common when iterating over models with the same h11) are
521
+ served from memory without a disk read. Set to ``0`` to
522
+ disable the in-memory cache. Defaults to ``32``.
523
+ cache_mode (str): Controls how downloaded shard files are
524
+ managed. ``"persistent"`` (default) keeps files on disk
525
+ and in the LRU cache for repeated use. ``"none"``
526
+ downloads each shard, reads the needed row, then deletes
527
+ the file — ideal for scanning millions of models without
528
+ accumulating disk usage.
529
+
530
+ Raises:
531
+ ValueError: If ``dataset`` is not a recognised identifier.
532
+ """
533
+ if cache_dir is None:
534
+ cache_dir = _get_default_data_dir()
535
+
536
+ if dataset not in _DATASET_CONFIGS:
537
+ raise ValueError(
538
+ f"Unknown dataset '{dataset}'. "
539
+ f"Choose one of: {list(_DATASET_CONFIGS)}"
540
+ )
541
+
542
+ self.dataset = dataset
543
+ self.hf_repo = hf_repo
544
+ self.cache_dir = Path(cache_dir) / dataset
545
+ self.offline = offline
546
+ self.cache_mode = cache_mode
547
+
548
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
549
+
550
+ # Catalog DataFrames — loaded lazily on first use.
551
+ self._catalog = None
552
+ self._conifold_catalog = None
553
+ self._vacua_catalog = None
554
+ self._designated_catalog = None
555
+
556
+ # In-memory LRU cache for recently loaded parquet shards.
557
+ self._shard_cache = _LRUShardCache(maxsize=shard_cache_size)
558
+
559
+ # One-time flag for the cache-size warning.
560
+ self._size_warned = False
561
+
562
+ # Lock that serialises file downloads so concurrent threads never
563
+ # race to download the same shard simultaneously.
564
+ self._download_lock = threading.Lock()
565
+
566
+ @classmethod
567
+ def from_local(
568
+ cls,
569
+ path: Union[str, "Path"],
570
+ dataset: Optional[str] = None,
571
+ shard_cache_size: int = 32,
572
+ ) -> "CYDatabase":
573
+ r"""
574
+ **Description:**
575
+ Create a :class:`CYDatabase` backed by a local directory, with no
576
+ network access.
577
+
578
+ This is the recommended way to work with a database that was built
579
+ locally (e.g. via ``build_tdf_database``).
580
+
581
+ The ``path`` should point to the directory that **contains** the
582
+ sub-dataset folder. For example, if the catalog lives at
583
+ ``/data/mydb/tdf/catalog.parquet``, pass ``path="/data/mydb"``.
584
+ If ``path`` itself already ends with the dataset name (e.g.
585
+ ``/data/mydb/tdf``), the parent is used automatically.
586
+
587
+ Example::
588
+
589
+ db = CYDatabase.from_local("/data/mydb")
590
+ db = CYDatabase.from_local("/data/mydb/tdf") # also works
591
+ cat = db.query(h11=3)
592
+
593
+ Args:
594
+ path (str | Path): Root directory of the local database.
595
+ dataset (str): Sub-dataset identifier (``"tdf"``, ``"cicy"``,
596
+ or ``"kklt"``).
597
+ shard_cache_size (int): In-memory shard cache size.
598
+
599
+ Returns:
600
+ CYDatabase: A fully offline database instance.
601
+ """
602
+ # Dataset resolution:
603
+ # 1. explicit `dataset=` kwarg wins
604
+ # 2. subclass default (e.g. TDFDatabase._DATASET = "tdf")
605
+ # 3. fallback to "tdf"
606
+ if dataset is None:
607
+ dataset = getattr(cls, "_DATASET", "tdf")
608
+ path = Path(path)
609
+ # If the user passed the sub-dataset directory itself, step up.
610
+ if path.name == dataset and (path / "catalog.parquet").exists():
611
+ path = path.parent
612
+ return cls(
613
+ dataset=dataset,
614
+ cache_dir=str(path),
615
+ offline=True,
616
+ shard_cache_size=shard_cache_size,
617
+ )
618
+
619
+ def __repr__(self) -> str:
620
+ r"""
621
+ **Description:**
622
+ Returns a string representation of the database object.
623
+
624
+ Returns:
625
+ str: Description of the database.
626
+ """
627
+ status = "catalog loaded" if self._catalog is not None else "catalog not yet loaded"
628
+ return (
629
+ f"CYDatabase(dataset='{self.dataset}', "
630
+ f"hf_repo='{self.hf_repo}', {status})"
631
+ )
632
+
633
+ def _check_schema(self) -> None:
634
+ r"""
635
+ **Description:**
636
+ Verify that the locally cached database was built against the same
637
+ schema version that this release of the code expects.
638
+
639
+ Downloads ``schema.json`` from the HuggingFace repository on first
640
+ call (or reads it from the local cache). Compares the stored
641
+ ``schema_version`` against :data:`SCHEMA_VERSION` and raises
642
+ :exc:`SchemaVersionError` if they differ, with a message that
643
+ explains exactly what changed and how to fix the problem.
644
+
645
+ When ``offline=True`` and no ``schema.json`` is cached, the check is
646
+ skipped with a warning rather than blocking the user.
647
+
648
+ Raises:
649
+ SchemaVersionError: If the cached schema version does not match
650
+ :data:`SCHEMA_VERSION`.
651
+ """
652
+ path = self.cache_dir / "schema.json"
653
+
654
+ if not path.exists():
655
+ if self.offline:
656
+ warnings.warn(
657
+ "schema.json not found in local cache and offline=True; "
658
+ "schema version check skipped.",
659
+ stacklevel=3,
660
+ )
661
+ return
662
+ try:
663
+ self._download_file(f"{self.dataset}/schema.json", path)
664
+ except RuntimeError:
665
+ # schema.json may not exist yet for databases built before
666
+ # versioning was introduced — skip the check gracefully.
667
+ warnings.warn(
668
+ "schema.json not found in the remote database; "
669
+ "schema version check skipped. Consider rebuilding "
670
+ "the database to enable versioning.",
671
+ stacklevel=3,
672
+ )
673
+ return
674
+
675
+ with open(path) as f:
676
+ stored = json.load(f).get("schema_version")
677
+
678
+ if stored is None or stored == SCHEMA_VERSION:
679
+ return
680
+
681
+ if stored < SCHEMA_VERSION:
682
+ changes = "\n".join(
683
+ f" v{v}: {msg}"
684
+ for v, msg in SCHEMA_CHANGELOG.items()
685
+ if v > stored
686
+ )
687
+ raise SchemaVersionError(
688
+ f"Local cache has schema v{stored}, but stringforge expects "
689
+ f"v{SCHEMA_VERSION}.\n"
690
+ f"Changes since your cached version:\n{changes}\n"
691
+ f"Run db.clear_cache() to delete the stale cache and "
692
+ f"re-download the latest database."
693
+ )
694
+
695
+ raise SchemaVersionError(
696
+ f"Local cache has schema v{stored}, but this version of stringforge "
697
+ f"only supports up to v{SCHEMA_VERSION}. "
698
+ f"Please upgrade stringforge."
699
+ )
700
+
701
+ def clear_cache(
702
+ self,
703
+ include_vacua: bool = False,
704
+ include_designated: bool = False,
705
+ keep_vault: bool = True,
706
+ remove_dir: bool = False,
707
+ ) -> None:
708
+ r"""
709
+ **Description:**
710
+ Delete all locally cached files for this dataset and reset the
711
+ in-memory catalog.
712
+
713
+ After calling this method, the next access will re-download the
714
+ catalog, schema, and any requested shards from the HuggingFace
715
+ repository. Useful after a schema version mismatch or when the
716
+ remote database has been updated.
717
+
718
+ The **permanent vacua vault** (``vacua_vault/`` — see
719
+ :func:`_resolve_vault_dir`) is **never** touched by this method:
720
+ it lives outside the cache directory and is protected by design.
721
+ The *include_designated* flag only controls the legacy
722
+ ``<cache_dir>/designated_vacua/`` location (used as a fallback
723
+ for pre-vault installations).
724
+
725
+ By default, session vacua (``<cache_dir>/vacua/``) and the
726
+ legacy designated dir are preserved. Pass
727
+ ``include_vacua=True`` / ``include_designated=True`` to delete
728
+ them as well.
729
+
730
+ By default the **directory itself is recreated empty** so the
731
+ same database instance can keep working — the next
732
+ :meth:`load` call expects the directory to exist. Pass
733
+ ``remove_dir=True`` to also remove the parent directory itself
734
+ (use this when you're done with the database for good and want
735
+ ``.stringforge_cache/`` gone from your filesystem).
736
+
737
+ Args:
738
+ include_vacua (bool): If True, also delete the
739
+ ``<cache_dir>/vacua/`` subdirectory containing session
740
+ vacuum solutions. Defaults to ``False``.
741
+ include_designated (bool): If True, also delete the legacy
742
+ ``<cache_dir>/designated_vacua/`` subdirectory. The
743
+ modern vault (``vacua_vault/``) is unaffected and must
744
+ be removed manually if desired. Defaults to ``False``.
745
+ keep_vault (bool): Reserved for symmetry; ``vacua_vault/``
746
+ is always protected and this flag has no effect in
747
+ normal use. Defaults to ``True``.
748
+ remove_dir (bool): If True, also delete ``self.cache_dir``
749
+ itself rather than recreating it empty. Implies
750
+ ``include_vacua=True`` and ``include_designated=True``
751
+ (you cannot remove the parent while keeping its
752
+ children). After this call, any further use of the
753
+ database instance will recreate the directory on first
754
+ write/download. Defaults to ``False``.
755
+
756
+ Raises:
757
+ RuntimeError: If ``offline=True``, since clearing the cache
758
+ would leave the database inaccessible.
759
+ """
760
+ if self.offline:
761
+ raise RuntimeError(
762
+ "Cannot clear cache while offline=True — doing so would "
763
+ "leave the database inaccessible. Set offline=False first."
764
+ )
765
+ # keep_vault is documented for API symmetry; the vault lives
766
+ # outside self.cache_dir so this method cannot touch it anyway.
767
+ del keep_vault
768
+ if remove_dir:
769
+ # Removing the parent implies wiping any "protected" children too.
770
+ include_vacua = True
771
+ include_designated = True
772
+ import shutil
773
+ vacua_dir = self.cache_dir / "vacua"
774
+ designated_dir = self.cache_dir / "designated_vacua"
775
+ protected: set = set()
776
+ if not include_vacua and vacua_dir.exists():
777
+ protected.add(vacua_dir)
778
+ if not include_designated and designated_dir.exists():
779
+ protected.add(designated_dir)
780
+
781
+ if protected:
782
+ for item in self.cache_dir.iterdir():
783
+ if item in protected:
784
+ continue
785
+ if item.is_dir():
786
+ shutil.rmtree(item, ignore_errors=True)
787
+ else:
788
+ item.unlink(missing_ok=True)
789
+ else:
790
+ shutil.rmtree(self.cache_dir, ignore_errors=True)
791
+ # Recreate the directory unless the caller asked to nuke it
792
+ # outright. When ``remove_dir=True``, leave it gone — the
793
+ # directory will be recreated on demand by the next write or
794
+ # download. Also prune empty parent directories *one level up*
795
+ # (e.g. when ``cache_dir`` is ``.stringforge_cache/tdf``, take
796
+ # ``.stringforge_cache`` down too if it now sits empty). Never
797
+ # cross above one level — protects against accidental cleanup
798
+ # of unrelated directories the user happened to put in the
799
+ # parent.
800
+ if not remove_dir:
801
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
802
+ else:
803
+ parent = self.cache_dir.parent
804
+ try:
805
+ parent.rmdir() # only succeeds if empty
806
+ except OSError:
807
+ pass # parent has other content; leave it
808
+ self._catalog = None
809
+ self._conifold_catalog = None
810
+ self._vacua_catalog = None
811
+ self._designated_catalog = None
812
+ self._shard_cache.clear()
813
+
814
+ def _check_cache_size(self) -> None:
815
+ r"""
816
+ **Description:**
817
+ Issue a one-time warning if the data directory exceeds
818
+ :data:`_CACHE_SIZE_WARNING_MB` (default 500 MB).
819
+
820
+ Called automatically on the first :meth:`load` or
821
+ :meth:`vacua_writer` invocation.
822
+
823
+ Returns:
824
+ None
825
+ """
826
+ if self._size_warned:
827
+ return
828
+ try:
829
+ total = sum(
830
+ f.stat().st_size
831
+ for f in self.cache_dir.rglob("*")
832
+ if f.is_file()
833
+ )
834
+ except OSError:
835
+ return
836
+ if total > _CACHE_SIZE_WARNING_MB * 1024 * 1024:
837
+ warnings.warn(
838
+ f"stringforge data directory at '{self.cache_dir}' is "
839
+ f"{total / 1024**2:.0f} MB. "
840
+ f"Use db.clear_cache() to free space.",
841
+ stacklevel=3,
842
+ )
843
+ self._size_warned = True
844
+
845
+ def _ensure_catalog(self) -> None:
846
+ r"""
847
+ **Description:**
848
+ Download the catalog parquet file if not already cached, then load it
849
+ into ``self._catalog`` as a ``pandas.DataFrame``.
850
+
851
+ The catalog is the central index: it maps every ``(ks_id, triang_id)``
852
+ (or ``cicy_id``) to shard pointers for all data splits, enabling O(1)
853
+ lookups without scanning the full dataset.
854
+
855
+ Raises:
856
+ FileNotFoundError: If ``offline=True`` and the catalog is not in
857
+ the local cache.
858
+ SchemaVersionError: If the cached database schema does not match
859
+ :data:`SCHEMA_VERSION`.
860
+ """
861
+ if self._catalog is not None:
862
+ return
863
+
864
+ self._check_schema()
865
+
866
+ pd = _require_pandas()
867
+ catalog_path = self.cache_dir / "catalog.parquet"
868
+
869
+ if not catalog_path.exists():
870
+ if self.offline:
871
+ raise FileNotFoundError(
872
+ f"Catalog not found in cache ({catalog_path}) and "
873
+ "offline=True. Run with offline=False first to "
874
+ "download it."
875
+ )
876
+ self._download_file(f"{self.dataset}/catalog.parquet", catalog_path)
877
+
878
+ self._catalog = pd.read_parquet(catalog_path)
879
+
880
+ def _ensure_conifold_catalog(self) -> None:
881
+ r"""
882
+ **Description:**
883
+ Download ``conifold_catalog.parquet`` if not already cached, then load
884
+ it into ``self._conifold_catalog``. One row per conifold limit with
885
+ columns ``ks_id``, ``triang_id``, ``conifold_id``, ``h11``, ``h12``,
886
+ ``ncf``, ``conifold_curve``, ``conifold_shard_id``,
887
+ ``conifold_row_index``.
888
+
889
+ Raises:
890
+ FileNotFoundError: If ``offline=True`` and the file is not cached,
891
+ or if the database was built without conifold data.
892
+ """
893
+ if self._conifold_catalog is not None:
894
+ return
895
+
896
+ pd = _require_pandas()
897
+ path = self.cache_dir / "conifold_catalog.parquet"
898
+
899
+ if not path.exists():
900
+ if self.offline:
901
+ raise FileNotFoundError(
902
+ f"Conifold catalog not found in cache ({path}) and "
903
+ "offline=True. Run with offline=False first to download it, "
904
+ "or rebuild the database to generate conifold_catalog.parquet."
905
+ )
906
+ self._download_file(f"{self.dataset}/conifold_catalog.parquet", path)
907
+
908
+ self._conifold_catalog = pd.read_parquet(path)
909
+
910
+ def _download_file(self, hf_path: str, local_path: Path) -> None:
911
+ r"""
912
+ **Description:**
913
+ Download a single file from the HuggingFace repository to a local path.
914
+
915
+ Args:
916
+ hf_path (str): Path within the HuggingFace repository.
917
+ local_path (Path): Destination path on the local filesystem.
918
+
919
+ Raises:
920
+ RuntimeError: If the download fails.
921
+ """
922
+ hf_hub_download = _require_hf_hub()
923
+ local_path.parent.mkdir(parents=True, exist_ok=True)
924
+ try:
925
+ # Use a no-op tqdm class to avoid ipywidgets/threading crashes
926
+ # when called from a thread pool inside Jupyter notebooks.
927
+ _quiet = type("_QuietTqdm", (), {
928
+ "__init__": lambda s, *a, **kw: None,
929
+ "__enter__": lambda s: s,
930
+ "__exit__": lambda s, *a: None,
931
+ "update": lambda s, *a, **kw: None,
932
+ "close": lambda s: None,
933
+ })
934
+ downloaded = hf_hub_download(
935
+ repo_id=self.hf_repo,
936
+ filename=hf_path,
937
+ repo_type="dataset",
938
+ local_dir=str(local_path.parent),
939
+ tqdm_class=_quiet,
940
+ )
941
+ # huggingface_hub may place the file in a subdirectory; move if needed.
942
+ if Path(downloaded) != local_path:
943
+ import shutil
944
+ shutil.move(downloaded, local_path)
945
+ except Exception as exc:
946
+ raise RuntimeError(
947
+ f"Failed to download '{hf_path}' from '{self.hf_repo}': {exc}"
948
+ ) from exc
949
+
950
+ def _fetch_shard(self, split: str, shard_id: int) -> Any:
951
+ r"""
952
+ **Description:**
953
+ Fetch a single parquet shard from the given split.
954
+
955
+ Checks the in-memory LRU shard cache first. On a cache miss the
956
+ shard is read from disk (downloading it from HuggingFace if not yet
957
+ cached locally), then stored in the LRU cache for future calls.
958
+
959
+ Args:
960
+ split (str): Name of the split directory, e.g. ``"lcs_data/h11_2"``
961
+ or ``"gv"``.
962
+ shard_id (int): Integer shard index.
963
+
964
+ Returns:
965
+ pandas.DataFrame: Contents of the shard.
966
+ """
967
+ key = (split, shard_id)
968
+
969
+ cached = self._shard_cache.get(key)
970
+ if cached is not None:
971
+ return cached
972
+
973
+ pd = _require_pandas()
974
+ shard_filename = f"data-{shard_id:05d}.parquet"
975
+ local_path = self.cache_dir / split / shard_filename
976
+
977
+ if not local_path.exists():
978
+ with self._download_lock:
979
+ # Re-check inside the lock in case another thread downloaded
980
+ # the file while this thread was waiting.
981
+ if not local_path.exists():
982
+ if self.offline:
983
+ raise FileNotFoundError(
984
+ f"Shard '{split}/{shard_filename}' not found in cache "
985
+ f"({local_path}) and offline=True."
986
+ )
987
+ hf_path = f"{self.dataset}/{split}/{shard_filename}"
988
+ self._download_file(hf_path, local_path)
989
+
990
+ df = pd.read_parquet(local_path)
991
+ self._shard_cache.put(key, df)
992
+ return df
993
+
994
+ def _cleanup_shard(self, local_path: Path) -> None:
995
+ r"""
996
+ **Description:**
997
+ Delete a shard file and remove directories left by
998
+ ``hf_hub_download``.
999
+
1000
+ ``hf_hub_download`` creates ``.cache/huggingface/`` metadata
1001
+ trees and nested ``tdf/…`` subdirectories inside each split
1002
+ folder. This helper removes the parquet file itself, any
1003
+ ``.cache`` tree in the same split directory, and prunes empty
1004
+ parent directories up to (but not including) ``self.cache_dir``.
1005
+
1006
+ Args:
1007
+ local_path (Path): Path to the parquet shard file on disk.
1008
+
1009
+ Returns:
1010
+ None
1011
+ """
1012
+ import shutil
1013
+
1014
+ # Delete the parquet file.
1015
+ local_path.unlink(missing_ok=True)
1016
+
1017
+ # Remove the .cache/huggingface tree that hf_hub_download creates
1018
+ # inside the split directory.
1019
+ split_dir = local_path.parent
1020
+ hf_cache = split_dir / ".cache"
1021
+ if hf_cache.exists():
1022
+ shutil.rmtree(hf_cache, ignore_errors=True)
1023
+
1024
+ # Remove the nested tdf/… directories that hf_hub_download creates.
1025
+ nested = split_dir / self.dataset
1026
+ if nested.exists():
1027
+ shutil.rmtree(nested, ignore_errors=True)
1028
+
1029
+ # Prune empty parent directories up to cache_dir.
1030
+ d = split_dir
1031
+ while d != self.cache_dir and d.exists():
1032
+ try:
1033
+ d.rmdir() # only succeeds if empty
1034
+ d = d.parent
1035
+ except OSError:
1036
+ break # not empty — stop climbing
1037
+
1038
+ def _fetch_row(self, split: str, shard_id: int, row_index: int) -> Any:
1039
+ r"""
1040
+ **Description:**
1041
+ Fetch a single row from a parquet shard without caching the full
1042
+ DataFrame in memory.
1043
+
1044
+ The shard file is downloaded to the local cache if not already
1045
+ present. Only the requested row is read into memory using
1046
+ PyArrow. When ``cache_mode="none"``, the shard file is deleted
1047
+ from disk after the row is extracted.
1048
+
1049
+ Args:
1050
+ split (str): Name of the split directory, e.g.
1051
+ ``"lcs_data/h11_2"`` or ``"gv"``.
1052
+ shard_id (int): Integer shard index.
1053
+ row_index (int): Row offset within the shard.
1054
+
1055
+ Returns:
1056
+ pandas.Series: The requested row.
1057
+ """
1058
+ import pyarrow.parquet as pq
1059
+
1060
+ shard_filename = f"data-{shard_id:05d}.parquet"
1061
+ local_path = self.cache_dir / split / shard_filename
1062
+
1063
+ if not local_path.exists():
1064
+ with self._download_lock:
1065
+ if not local_path.exists():
1066
+ if self.offline:
1067
+ raise FileNotFoundError(
1068
+ f"Shard '{split}/{shard_filename}' not found "
1069
+ f"in cache ({local_path}) and offline=True."
1070
+ )
1071
+ hf_path = f"{self.dataset}/{split}/{shard_filename}"
1072
+ self._download_file(hf_path, local_path)
1073
+
1074
+ table = pq.read_table(str(local_path))
1075
+ row = table.slice(row_index, 1).to_pandas().iloc[0]
1076
+
1077
+ if self.cache_mode == "none":
1078
+ self._cleanup_shard(local_path)
1079
+
1080
+ return row
1081
+
1082
+ def _fetch_rows(self, split: str, shard_id: int, mask_fn: Any) -> Any:
1083
+ r"""
1084
+ **Description:**
1085
+ Fetch rows matching a filter from a parquet shard without caching
1086
+ the full DataFrame in memory.
1087
+
1088
+ Like :meth:`_fetch_row` but applies a callable ``mask_fn`` to the
1089
+ loaded DataFrame and returns the matching subset. Used for
1090
+ conifold data where multiple rows may belong to the same model.
1091
+
1092
+ Args:
1093
+ split (str): Name of the split directory.
1094
+ shard_id (int): Integer shard index.
1095
+ mask_fn (callable): Function that takes a DataFrame and returns
1096
+ a boolean mask.
1097
+
1098
+ Returns:
1099
+ pandas.DataFrame: Matching rows.
1100
+ """
1101
+ import pyarrow.parquet as pq
1102
+
1103
+ shard_filename = f"data-{shard_id:05d}.parquet"
1104
+ local_path = self.cache_dir / split / shard_filename
1105
+
1106
+ if not local_path.exists():
1107
+ with self._download_lock:
1108
+ if not local_path.exists():
1109
+ if self.offline:
1110
+ raise FileNotFoundError(
1111
+ f"Shard '{split}/{shard_filename}' not found "
1112
+ f"in cache ({local_path}) and offline=True."
1113
+ )
1114
+ hf_path = f"{self.dataset}/{split}/{shard_filename}"
1115
+ self._download_file(hf_path, local_path)
1116
+
1117
+ df = pq.read_table(str(local_path)).to_pandas()
1118
+ result = df[mask_fn(df)]
1119
+
1120
+ if self.cache_mode == "none":
1121
+ self._cleanup_shard(local_path)
1122
+
1123
+ return result
1124
+
1125
+ def _lookup(
1126
+ self,
1127
+ ks_id: Optional[int],
1128
+ triang_id: Optional[int],
1129
+ cicy_id: Optional[int],
1130
+ h11: Optional[int] = None,
1131
+ h12: Optional[int] = None,
1132
+ ) -> Any:
1133
+ r"""
1134
+ **Description:**
1135
+ Look up the catalog row for a given model primary key.
1136
+
1137
+ For ``tdf`` models the full primary key is
1138
+ ``(h11, h12, ks_id, triang_id)``. When ``h11`` and ``h12`` are
1139
+ omitted, only ``(ks_id, triang_id)`` is used; if this yields multiple
1140
+ matches an error is raised asking the caller to disambiguate.
1141
+
1142
+ Args:
1143
+ ks_id (int | None): Kreuzer-Skarke polytope index (tdf only).
1144
+ triang_id (int | None): Triangulation index (tdf only).
1145
+ cicy_id (int | None): CICY model index (cicy only).
1146
+ h11 (int | None): Hodge number :math:`h^{1,1}` (tdf only).
1147
+ h12 (int | None): Hodge number :math:`h^{1,2}` (tdf only).
1148
+
1149
+ Returns:
1150
+ pandas.Series: The matching catalog row.
1151
+
1152
+ Raises:
1153
+ KeyError: If no matching row is found.
1154
+ ValueError: If multiple rows match — supply ``h11`` and ``h12``
1155
+ to disambiguate.
1156
+ """
1157
+ self._ensure_catalog()
1158
+ cat = self._catalog
1159
+
1160
+ if self.dataset == "tdf":
1161
+ mask = (cat["ks_id"] == ks_id) & (cat["triang_id"] == triang_id)
1162
+ if h11 is not None:
1163
+ mask = mask & (cat["h11"] == h11)
1164
+ if h12 is not None:
1165
+ mask = mask & (cat["h12"] == h12)
1166
+ else:
1167
+ mask = cat["cicy_id"] == cicy_id
1168
+
1169
+ matches = cat[mask]
1170
+ if len(matches) == 0:
1171
+ key = f"ks_id={ks_id}, triang_id={triang_id}" if self.dataset == "tdf" \
1172
+ else f"cicy_id={cicy_id}"
1173
+ if h11 is not None or h12 is not None:
1174
+ key += f", h11={h11}, h12={h12}"
1175
+ raise KeyError(
1176
+ f"No model found for {key} in the '{self.dataset}' dataset."
1177
+ )
1178
+ if len(matches) > 1:
1179
+ h_values = matches[["h11", "h12"]].drop_duplicates().values.tolist()
1180
+ raise ValueError(
1181
+ f"Multiple models match ks_id={ks_id}, triang_id={triang_id} "
1182
+ f"with (h11, h12) values {h_values}. "
1183
+ f"Please pass h11 and h12 to disambiguate."
1184
+ )
1185
+ return matches.iloc[0]
1186
+
1187
+ def info(self) -> None:
1188
+ r"""
1189
+ **Description:**
1190
+ Print a summary of the available models in this sub-dataset.
1191
+
1192
+ The summary includes total model count, Hodge-number ranges, and the
1193
+ fraction of models with GV invariants and conifold data available.
1194
+ """
1195
+ self._ensure_catalog()
1196
+ cat = self._catalog
1197
+
1198
+ n_total = len(cat)
1199
+ h11_min, h11_max = int(cat["h11"].min()), int(cat["h11"].max())
1200
+ h12_min, h12_max = int(cat["h12"].min()), int(cat["h12"].max())
1201
+ n_gv = int(cat["has_gv"].sum()) if "has_gv" in cat.columns else -1
1202
+ n_cf = int((cat["n_conifolds"] > 0).sum()) if "n_conifolds" in cat.columns else -1
1203
+
1204
+ print(f"CYDatabase — sub-dataset: '{self.dataset}'")
1205
+ print(f" Total models : {n_total:,}")
1206
+ print(f" h11 range : {h11_min} – {h11_max}")
1207
+ print(f" h12 range : {h12_min} – {h12_max}")
1208
+ if n_gv >= 0:
1209
+ print(f" With GV data : {n_gv:,} ({100*n_gv/n_total:.1f}%)")
1210
+ if n_cf >= 0:
1211
+ print(f" With conifolds: {n_cf:,} ({100*n_cf/n_total:.1f}%)")
1212
+ print(f" Cache dir : {self.cache_dir}")
1213
+
1214
+ def query_conifolds(
1215
+ self,
1216
+ h11: Optional[int] = None,
1217
+ h12: Optional[int] = None,
1218
+ ncf: Optional[int] = None,
1219
+ conifold_id: Optional[int] = None,
1220
+ **filters: Any,
1221
+ ) -> Any:
1222
+ r"""
1223
+ **Description:**
1224
+ Filter the conifold sub-catalog and return a ``pandas.DataFrame`` of
1225
+ matching conifold limits. Each row represents one conifold limit and
1226
+ carries enough information to load the corresponding model directly via
1227
+ :meth:`load_from_conifold_row`.
1228
+
1229
+ This method operates entirely on the in-memory conifold catalog and
1230
+ does not load any geometry data.
1231
+
1232
+ For filters not covered by the keyword arguments, use pandas on the
1233
+ returned DataFrame::
1234
+
1235
+ df = db.query_conifolds()
1236
+ df[df["conifold_curve"].apply(lambda c: c == [0, 1])]
1237
+
1238
+ Args:
1239
+ h11 (int | None): Filter by :math:`h^{1,1}`.
1240
+ h12 (int | None): Filter by :math:`h^{1,2}`.
1241
+ ncf (int | None): Filter by the GV invariant of the conifold node.
1242
+ conifold_id (int | None): Filter by conifold index within a model
1243
+ (0-based).
1244
+ **filters: Additional exact-match filters on any catalog column.
1245
+
1246
+ Returns:
1247
+ pandas.DataFrame: Matching rows from the conifold sub-catalog.
1248
+ """
1249
+ self._ensure_conifold_catalog()
1250
+ cat = self._conifold_catalog
1251
+ mask = np.ones(len(cat), dtype=bool)
1252
+
1253
+ if h11 is not None:
1254
+ mask &= (cat["h11"] == h11).values
1255
+ if h12 is not None:
1256
+ mask &= (cat["h12"] == h12).values
1257
+ if ncf is not None:
1258
+ mask &= (cat["ncf"] == ncf).values
1259
+ if conifold_id is not None:
1260
+ mask &= (cat["conifold_id"] == conifold_id).values
1261
+ for col, val in filters.items():
1262
+ if col in cat.columns:
1263
+ mask &= (cat[col] == val).values
1264
+ else:
1265
+ warnings.warn(f"Column '{col}' not found in conifold catalog; filter ignored.")
1266
+
1267
+ return cat[mask].reset_index(drop=True)
1268
+
1269
+ def query(
1270
+ self,
1271
+ h11: Optional[int] = None,
1272
+ h12: Optional[int] = None,
1273
+ has_conifolds: Optional[bool] = None,
1274
+ n_conifolds_min: Optional[int] = None,
1275
+ n_conifolds_max: Optional[int] = None,
1276
+ has_gv: Optional[bool] = None,
1277
+ D3_tadpole_max: Optional[int] = None,
1278
+ **filters: Any,
1279
+ ) -> Any:
1280
+ r"""
1281
+ **Description:**
1282
+ Filter the catalog and return a ``pandas.DataFrame`` of matching models.
1283
+
1284
+ This method operates entirely on the in-memory catalog and does not
1285
+ download any geometry data.
1286
+
1287
+ For filters not covered by the keyword arguments, operate on the
1288
+ returned DataFrame directly, e.g.::
1289
+
1290
+ df = db.query()
1291
+ df[df["chi"] < -200]
1292
+
1293
+ Args:
1294
+ h11 (int | None): Filter by :math:`h^{1,1}`.
1295
+ h12 (int | None): Filter by :math:`h^{1,2}`.
1296
+ has_conifolds (bool | None): If ``True``, return only models with
1297
+ at least one conifold limit available.
1298
+ n_conifolds_min (int | None): Return only models with at least this
1299
+ many conifold limits, e.g. ``n_conifolds_min=2``.
1300
+ n_conifolds_max (int | None): Return only models with at most this
1301
+ many conifold limits.
1302
+ has_gv (bool | None): If ``True``, return only models for which
1303
+ Gopakumar-Vafa invariants are stored.
1304
+ D3_tadpole_max (int | None): Return only models whose D3-tadpole
1305
+ is at most this value.
1306
+ **filters: Additional exact-match filters on catalog columns,
1307
+ e.g. ``chi=-240``.
1308
+
1309
+ Returns:
1310
+ pandas.DataFrame: Matching rows from the catalog.
1311
+ """
1312
+ self._ensure_catalog()
1313
+ mask = np.ones(len(self._catalog), dtype=bool)
1314
+
1315
+ if h11 is not None:
1316
+ mask &= (self._catalog["h11"] == h11).values
1317
+ if h12 is not None:
1318
+ mask &= (self._catalog["h12"] == h12).values
1319
+ if "n_conifolds" in self._catalog.columns:
1320
+ if has_conifolds is not None:
1321
+ if has_conifolds:
1322
+ mask &= (self._catalog["n_conifolds"] > 0).values
1323
+ else:
1324
+ mask &= (self._catalog["n_conifolds"] == 0).values
1325
+ if n_conifolds_min is not None:
1326
+ mask &= (self._catalog["n_conifolds"] >= n_conifolds_min).values
1327
+ if n_conifolds_max is not None:
1328
+ mask &= (self._catalog["n_conifolds"] <= n_conifolds_max).values
1329
+ if has_gv is not None and "has_gv" in self._catalog.columns:
1330
+ mask &= (self._catalog["has_gv"] == has_gv).values
1331
+ if D3_tadpole_max is not None and "D3_tadpole" in self._catalog.columns:
1332
+ mask &= (self._catalog["D3_tadpole"] <= D3_tadpole_max).values
1333
+ for col, val in filters.items():
1334
+ if col in self._catalog.columns:
1335
+ mask &= (self._catalog[col] == val).values
1336
+ else:
1337
+ warnings.warn(f"Column '{col}' not found in catalog; filter ignored.")
1338
+
1339
+ return self._catalog[mask].reset_index(drop=True)
1340
+
1341
+ def get_polytope(
1342
+ self,
1343
+ ks_id: int,
1344
+ h11: int,
1345
+ h12: Optional[int] = None,
1346
+ ) -> Dict[str, Any]:
1347
+ r"""
1348
+ **Description:**
1349
+ Fetch the polytope data for a model identified by ``(h11, ks_id)``,
1350
+ optionally disambiguated by ``h12``.
1351
+
1352
+ Polytope data is stored per-polytope (not per-triangulation), so
1353
+ ``triang_id`` is not required: every triangulation of the same
1354
+ polytope shares one row in the ``polytope`` parquet split. When
1355
+ multiple polytopes share the same ``(h11, ks_id)`` (which is rare),
1356
+ pass ``h12`` to disambiguate.
1357
+
1358
+ Args:
1359
+ ks_id (int): Kreuzer-Skarke polytope index.
1360
+ h11 (int): Hodge number :math:`h^{1,1}`.
1361
+ h12 (int | None): Hodge number :math:`h^{1,2}`. Optional.
1362
+
1363
+ Returns:
1364
+ Dict[str, Any]: Contains ``"polytope_points"`` (an ``np.ndarray``
1365
+ of lattice points) and optionally ``"polytope_data"`` with any
1366
+ extra polytope-level fields stored by ``process_polytope`` such
1367
+ as ``is_favorable``, ``volume``, ``glsm_charge_matrix``.
1368
+
1369
+ Raises:
1370
+ ValueError: If this database is not the ``tdf`` dataset, or the
1371
+ catalog has no ``polytope`` split, or the matching row has
1372
+ no polytope shard pointer.
1373
+ KeyError: If no row matches the supplied filters.
1374
+ """
1375
+ if self.dataset != "tdf":
1376
+ raise ValueError(
1377
+ f"get_polytope is only available for the 'tdf' dataset; "
1378
+ f"got dataset='{self.dataset}'."
1379
+ )
1380
+
1381
+ self._ensure_catalog()
1382
+ cat = self._catalog
1383
+ mask = (cat["ks_id"] == ks_id) & (cat["h11"] == h11)
1384
+ if h12 is not None:
1385
+ mask = mask & (cat["h12"] == h12)
1386
+ matches = cat[mask]
1387
+ if len(matches) == 0:
1388
+ key = f"ks_id={ks_id}, h11={h11}"
1389
+ if h12 is not None:
1390
+ key += f", h12={h12}"
1391
+ raise KeyError(
1392
+ f"No polytope found for {key} in the '{self.dataset}' dataset."
1393
+ )
1394
+
1395
+ if "polytope_shard_id" not in matches.columns:
1396
+ raise ValueError(
1397
+ "Catalog has no 'polytope_shard_id' column — this dataset does "
1398
+ "not provide a polytope split."
1399
+ )
1400
+
1401
+ row = matches.iloc[0]
1402
+ psid = row["polytope_shard_id"]
1403
+ try:
1404
+ import pandas as pd
1405
+ _has_poly = psid is not None and not pd.isna(psid)
1406
+ except (TypeError, ValueError):
1407
+ _has_poly = psid is not None
1408
+ if not _has_poly:
1409
+ key = f"ks_id={ks_id}, h11={h11}"
1410
+ if h12 is not None:
1411
+ key += f", h12={h12}"
1412
+ raise ValueError(f"No polytope data available for {key}.")
1413
+
1414
+ prid = row["polytope_row_index"]
1415
+ if self.cache_mode == "persistent":
1416
+ poly_shard = self._fetch_shard("polytope", int(psid))
1417
+ poly_row = poly_shard.iloc[int(prid)]
1418
+ else:
1419
+ poly_row = self._fetch_row("polytope", int(psid), int(prid))
1420
+
1421
+ poly_data = _parse_polytope_row(poly_row)
1422
+ points = poly_data["polytope_points"] # np.ndarray
1423
+ points = np.array([list(x) for x in points])
1424
+ poly_data["polytope_points"] = points
1425
+ return poly_data
1426
+
1427
+ def _validate_key(
1428
+ self,
1429
+ ks_id: Optional[int],
1430
+ triang_id: Optional[int],
1431
+ cicy_id: Optional[int],
1432
+ ) -> None:
1433
+ r"""
1434
+ **Description:**
1435
+ Validate that the correct primary-key arguments are supplied for the
1436
+ active sub-dataset.
1437
+
1438
+ Raises:
1439
+ ValueError: On missing or unexpected key arguments.
1440
+ """
1441
+ if self.dataset == "tdf":
1442
+ if ks_id is None or triang_id is None:
1443
+ raise ValueError(
1444
+ "Both 'ks_id' and 'triang_id' are required for dataset='tdf'."
1445
+ )
1446
+ else:
1447
+ if cicy_id is None:
1448
+ raise ValueError("'cicy_id' is required for dataset='cicy'.")
1449
+
1450
+ def _identifiers_to_list(
1451
+ self, identifiers: Any
1452
+ ) -> List[Tuple[Optional[int], Optional[int], Optional[int],
1453
+ Optional[int], Optional[int]]]:
1454
+ r"""
1455
+ **Description:**
1456
+ Normalise ``identifiers`` to a list of
1457
+ ``(ks_id, triang_id, cicy_id, h11, h12)`` quintuples.
1458
+
1459
+ Accepted input formats:
1460
+
1461
+ - ``pandas.DataFrame`` with columns ``ks_id, triang_id`` (and
1462
+ optionally ``h11``, ``h12``) or ``cicy_id``.
1463
+ - List of ``(ks_id, triang_id)`` 2-tuples (for ``"tdf"``).
1464
+ - List of ``(h11, h12, ks_id, triang_id)`` 4-tuples (for ``"tdf"``,
1465
+ recommended to avoid ambiguity).
1466
+ - List of ``int`` values (for ``"cicy"``).
1467
+
1468
+ Args:
1469
+ identifiers: See above.
1470
+
1471
+ Returns:
1472
+ list of ``(ks_id, triang_id, cicy_id, h11, h12)`` quintuples.
1473
+ """
1474
+ pd = _require_pandas()
1475
+ result = []
1476
+ if isinstance(identifiers, pd.DataFrame):
1477
+ for _, row in identifiers.iterrows():
1478
+ if self.dataset == "tdf":
1479
+ h11 = int(row["h11"]) if "h11" in row.index else None
1480
+ h12 = int(row["h12"]) if "h12" in row.index else None
1481
+ result.append((int(row["ks_id"]), int(row["triang_id"]),
1482
+ None, h11, h12))
1483
+ else:
1484
+ result.append((None, None, int(row["cicy_id"]), None, None))
1485
+ elif isinstance(identifiers, (list, tuple)):
1486
+ for item in identifiers:
1487
+ if isinstance(item, (list, tuple)) and len(item) == 4:
1488
+ # (h11, h12, ks_id, triang_id)
1489
+ result.append((int(item[2]), int(item[3]), None,
1490
+ int(item[0]), int(item[1])))
1491
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
1492
+ # (ks_id, triang_id) — legacy format
1493
+ result.append((int(item[0]), int(item[1]), None, None, None))
1494
+ elif isinstance(item, (int, np.integer)):
1495
+ result.append((None, None, int(item), None, None))
1496
+ else:
1497
+ raise ValueError(f"Cannot interpret identifier: {item!r}")
1498
+ else:
1499
+ raise TypeError(
1500
+ f"'identifiers' must be a DataFrame or a list of tuples/ints, "
1501
+ f"got {type(identifiers).__name__}."
1502
+ )
1503
+ return result
1504
+
1505
+ @property
1506
+ def _vacua_dir(self) -> Path:
1507
+ r"""Root directory for vacua storage."""
1508
+ return self.cache_dir / "vacua"
1509
+
1510
+ def _ensure_vacua_catalog(self) -> None:
1511
+ r"""Load (or reload) the vacua catalog from disk.
1512
+
1513
+ Reloads when the on-disk catalog has been modified since the
1514
+ cached copy was loaded — keeps freshly-written runs visible to
1515
+ readers in the same Python session. Tracks the file's
1516
+ modification time on ``self._vacua_catalog_mtime``.
1517
+ """
1518
+ pd = _require_pandas()
1519
+ catalog_path = self._vacua_dir / "vacua_catalog.parquet"
1520
+ if not catalog_path.exists():
1521
+ if self._vacua_catalog is None:
1522
+ self._vacua_catalog = pd.DataFrame()
1523
+ return
1524
+ cur_mtime = catalog_path.stat().st_mtime
1525
+ cached_mtime = getattr(self, "_vacua_catalog_mtime", None)
1526
+ if self._vacua_catalog is not None and cached_mtime == cur_mtime:
1527
+ return
1528
+ self._vacua_catalog = pd.read_parquet(catalog_path)
1529
+ self._vacua_catalog_mtime = cur_mtime
1530
+
1531
+ @property
1532
+ def _designated_dir(self) -> Path:
1533
+ r"""
1534
+ Description:
1535
+ Root directory for designated (permanent) vacua storage.
1536
+
1537
+ Resolves to the project-local ``vacua_vault/`` directory (see
1538
+ :func:`_resolve_vault_dir`). Falls back to the legacy
1539
+ ``<cache_dir>/designated_vacua/`` location only when a user has
1540
+ pre-existing data there and the vault directory is empty — this
1541
+ preserves backwards compatibility without silent duplication.
1542
+ """
1543
+ vault = _resolve_vault_dir()
1544
+ legacy = self.cache_dir / "designated_vacua"
1545
+ # Prefer vault unless only legacy has data (one-time migration hint).
1546
+ if (not vault.exists()) and legacy.exists() and any(legacy.iterdir()):
1547
+ return legacy
1548
+ return vault
1549
+
1550
+ # `_resolve_vacua_dir` was moved to stringforge.vacua_writer.VacuaWriter —
1551
+ # it depends on `_extract_model_identity`, which reads `lcs_tree`
1552
+ # attributes and therefore cannot live in this jaxvacua-dep-free layer.
1553
+ # Callers that used to do `db._resolve_vacua_dir(model=...)` should use
1554
+ # `VacuaWriter(db)._resolve_vacua_dir(model=...)` instead. The delegated
1555
+ # method on LCSDatabase (stringforge/lcs_database.py) still exposes it
1556
+ # for convenience.
1557
+
1558
+ def _ensure_designated_catalog(self) -> None:
1559
+ r"""Load designated vacua catalog from disk if not yet in memory."""
1560
+ if self._designated_catalog is not None:
1561
+ return
1562
+ pd = _require_pandas()
1563
+ catalog_path = self._designated_dir / "designated_vacua_catalog.parquet"
1564
+ if catalog_path.exists():
1565
+ self._designated_catalog = pd.read_parquet(catalog_path)
1566
+ else:
1567
+ self._designated_catalog = pd.DataFrame()
1568
+
1569
+
1570
+ class TDFDatabase(CYDatabase):
1571
+ r"""
1572
+ **Description:**
1573
+ Convenience subclass of :class:`CYDatabase` pre-configured for the
1574
+ ``"tdf"`` sub-dataset (toric models from the Kreuzer-Skarke list).
1575
+
1576
+ Models are identified by ``(ks_id, triang_id)`` in catalogue convention.
1577
+
1578
+ Example usage::
1579
+
1580
+ db = TDFDatabase()
1581
+ rows = db.query(h11=2, has_conifolds=True)
1582
+ poly = db.get_polytope(ks_id=int(rows.iloc[0]["ks_id"]), h11=2)
1583
+ """
1584
+
1585
+ # Consumed by :meth:`CYDatabase.from_local` so that
1586
+ # ``TDFDatabase.from_local(path)`` infers ``dataset="tdf"``.
1587
+ _DATASET = "tdf"
1588
+
1589
+ def __init__(
1590
+ self,
1591
+ hf_repo: str = HF_REPO_ID,
1592
+ cache_dir: Optional[str] = None,
1593
+ offline: bool = False,
1594
+ cache_mode: str = "persistent",
1595
+ shard_cache_size: int = 32,
1596
+ dataset: Optional[str] = None,
1597
+ ) -> None:
1598
+ r"""Initialise a :class:`TDFDatabase` instance.
1599
+
1600
+ The ``dataset`` kwarg is accepted but must equal ``"tdf"`` if
1601
+ provided — it exists so that :meth:`CYDatabase.from_local` (which
1602
+ forwards ``dataset=...`` generically) can be called as
1603
+ ``TDFDatabase.from_local(...)``.
1604
+ """
1605
+ if dataset is not None and dataset != "tdf":
1606
+ raise ValueError(
1607
+ f"TDFDatabase requires dataset='tdf'; got {dataset!r}"
1608
+ )
1609
+ super().__init__(
1610
+ dataset="tdf",
1611
+ hf_repo=hf_repo,
1612
+ cache_dir=cache_dir,
1613
+ offline=offline,
1614
+ shard_cache_size=shard_cache_size,
1615
+ cache_mode=cache_mode,
1616
+ )
1617
+
1618
+
1619
+ class CICYDatabase(CYDatabase):
1620
+ r"""
1621
+ **Description:**
1622
+ Convenience subclass of :class:`CYDatabase` pre-configured for the
1623
+ ``"cicy"`` sub-dataset (Complete Intersection Calabi-Yau models).
1624
+
1625
+ Models are identified by ``cicy_id`` in catalogue convention.
1626
+
1627
+ Example usage::
1628
+
1629
+ db = CICYDatabase()
1630
+ rows = db.query(h11=1)
1631
+ """
1632
+
1633
+ # Consumed by :meth:`CYDatabase.from_local` so that
1634
+ # ``CICYDatabase.from_local(path)`` infers ``dataset="cicy"``.
1635
+ _DATASET = "cicy"
1636
+
1637
+ def __init__(
1638
+ self,
1639
+ hf_repo: str = HF_REPO_ID,
1640
+ cache_dir: Optional[str] = None,
1641
+ offline: bool = False,
1642
+ cache_mode: str = "persistent",
1643
+ shard_cache_size: int = 32,
1644
+ dataset: Optional[str] = None,
1645
+ ) -> None:
1646
+ r"""Initialise a :class:`CICYDatabase` instance.
1647
+
1648
+ The ``dataset`` kwarg is accepted but must equal ``"cicy"`` if
1649
+ provided — it exists so that :meth:`CYDatabase.from_local` (which
1650
+ forwards ``dataset=...`` generically) can be called as
1651
+ ``CICYDatabase.from_local(...)``.
1652
+ """
1653
+ if dataset is not None and dataset != "cicy":
1654
+ raise ValueError(
1655
+ f"CICYDatabase requires dataset='cicy'; got {dataset!r}"
1656
+ )
1657
+ super().__init__(
1658
+ dataset="cicy",
1659
+ hf_repo=hf_repo,
1660
+ cache_dir=cache_dir,
1661
+ offline=offline,
1662
+ shard_cache_size=shard_cache_size,
1663
+ cache_mode=cache_mode,
1664
+ )
1665
+
1666
+
1667
+ def query_models(
1668
+ dataset: str = "tdf",
1669
+ h11: Optional[int] = None,
1670
+ h12: Optional[int] = None,
1671
+ has_conifolds: Optional[bool] = None,
1672
+ n_conifolds_min: Optional[int] = None,
1673
+ n_conifolds_max: Optional[int] = None,
1674
+ has_gv: Optional[bool] = None,
1675
+ D3_tadpole_max: Optional[int] = None,
1676
+ cache_dir: str = DEFAULT_CACHE_DIR,
1677
+ **filters: Any,
1678
+ ) -> Any:
1679
+ r"""
1680
+ **Description:**
1681
+ Query the catalog of a sub-dataset and return matching rows as a
1682
+ ``pandas.DataFrame``, without instantiating a :class:`CYDatabase`
1683
+ explicitly.
1684
+
1685
+ Args:
1686
+ dataset (str): Sub-dataset identifier (``"tdf"`` or ``"cicy"``).
1687
+ h11 (int | None): Filter by :math:`h^{1,1}`.
1688
+ h12 (int | None): Filter by :math:`h^{1,2}`.
1689
+ has_conifolds (bool | None): Filter by conifold availability.
1690
+ n_conifolds_min (int | None): Minimum number of conifold limits.
1691
+ n_conifolds_max (int | None): Maximum number of conifold limits.
1692
+ has_gv (bool | None): Filter by GV availability.
1693
+ D3_tadpole_max (int | None): Upper bound on the D3-tadpole.
1694
+ cache_dir (str): Local cache directory.
1695
+ **filters: Additional exact-match column filters.
1696
+
1697
+ Returns:
1698
+ pandas.DataFrame: Matching rows from the catalog.
1699
+ """
1700
+ db = CYDatabase(dataset=dataset, cache_dir=cache_dir)
1701
+ return db.query(
1702
+ h11=h11, h12=h12,
1703
+ has_conifolds=has_conifolds,
1704
+ n_conifolds_min=n_conifolds_min,
1705
+ n_conifolds_max=n_conifolds_max,
1706
+ has_gv=has_gv,
1707
+ D3_tadpole_max=D3_tadpole_max,
1708
+ **filters,
1709
+ )
1710
+
1711
+
1712
+ def load_catalog(
1713
+ path: Union[str, "Path", None] = None,
1714
+ dataset: str = "tdf",
1715
+ catalog: str = "catalog",
1716
+ cache_dir: str = DEFAULT_CACHE_DIR,
1717
+ ) -> Any:
1718
+ r"""
1719
+ **Description:**
1720
+ Load a catalog as a ``pandas.DataFrame`` from either a local database
1721
+ directory or the default HuggingFace cache.
1722
+
1723
+ This is a lightweight entry point — it reads only the catalog parquet
1724
+ file, not any geometry data.
1725
+
1726
+ Args:
1727
+ path (str | Path | None): Path to a local database. Can point to
1728
+ the root (containing the ``tdf/`` or ``cicy/`` sub-folder) or
1729
+ directly to the sub-dataset folder. If ``None``, the catalog
1730
+ is loaded from (or downloaded to) the default HuggingFace cache.
1731
+ dataset (str): Sub-dataset identifier (``"tdf"`` or ``"cicy"``).
1732
+ Defaults to ``"tdf"``.
1733
+ catalog (str): Which catalog to load. One of:
1734
+
1735
+ - ``"catalog"`` — main model catalog (default)
1736
+ - ``"conifold_catalog"`` — conifold sub-catalog
1737
+ - ``"designated_vacua_catalog"`` — designated (Tier 2) solutions
1738
+
1739
+ cache_dir (str): Cache directory when ``path`` is ``None``.
1740
+
1741
+ Returns:
1742
+ pandas.DataFrame: The requested catalog.
1743
+
1744
+ Example::
1745
+
1746
+ # From a local build
1747
+ cat = load_catalog("/data/mydb")
1748
+ cf = load_catalog("/data/mydb", catalog="conifold_catalog")
1749
+
1750
+ # From the online / cached HuggingFace repo
1751
+ cat = load_catalog()
1752
+ """
1753
+ if path is not None:
1754
+ db = CYDatabase.from_local(path, dataset=dataset)
1755
+ else:
1756
+ db = CYDatabase(dataset=dataset, cache_dir=cache_dir)
1757
+
1758
+ if catalog == "catalog":
1759
+ db._ensure_catalog()
1760
+ return db._catalog
1761
+ elif catalog == "conifold_catalog":
1762
+ db._ensure_conifold_catalog()
1763
+ return db._conifold_catalog
1764
+ elif catalog == "designated_vacua_catalog":
1765
+ db._ensure_designated_catalog()
1766
+ return db._designated_catalog
1767
+ else:
1768
+ raise ValueError(
1769
+ f"Unknown catalog '{catalog}'. Choose one of: "
1770
+ "'catalog', 'conifold_catalog', 'designated_vacua_catalog'."
1771
+ )
1772
+
1773
+
1774
+
1775
+
1776
+ __all__ = [
1777
+ # ----- constants & exceptions --------------------------------------------
1778
+ "HF_REPO_ID", "DEFAULT_CACHE_DIR", "VAULT_DIRNAME", "DEFAULT_VAULT_REPO",
1779
+ "SCHEMA_VERSION", "SCHEMA_CHANGELOG",
1780
+ "SchemaVersionError", "ValidationError",
1781
+ # ----- parsing helpers ---------------------------------------------------
1782
+ "_decode_array", "_parse_gv_row", "_parse_conifold_rows", "_parse_polytope_row",
1783
+ # ----- classes -----------------------------------------------------------
1784
+ "CYDatabase", "TDFDatabase", "CICYDatabase",
1785
+ # ----- module-level convenience ------------------------------------------
1786
+ "load_catalog", "query_models",
1787
+ ]