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,1223 @@
1
+ # ==============================================================================
2
+ # stringforge / lcs_database
3
+ #
4
+ # LCSDatabase — extends cy_io.CYDatabase with:
5
+ #
6
+ # (a) methods that construct :class:`jaxvacua.lcs.lcs_tree` objects and
7
+ # :class:`jaxvacua.flux_vacua_finder.FluxVacuaFinder` instances from
8
+ # parquet-row data (load, load_from_conifold_row, load_model, load_batch,
9
+ # iter_batch, sample, plus the batch-model variants load_model_batch
10
+ # and iter_model_batch);
11
+ #
12
+ # (b) a filter-keyed cache of the last constructed batch of FluxVacuaFinder
13
+ # instances (cached_models property, clear_cached_models method);
14
+ #
15
+ # (c) vacua-persistence delegation — `db.designate_vacua(...)` and friends
16
+ # forward to a lazily-built :class:`stringforge.vacua_writer.VacuaWriter`
17
+ # held on the instance.
18
+ # ==============================================================================
19
+
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import warnings
26
+ from collections import deque
27
+ from concurrent.futures import ThreadPoolExecutor, as_completed
28
+ from pathlib import Path
29
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
30
+
31
+ import numpy as np
32
+
33
+ from .cy_io import (
34
+ CYDatabase,
35
+ SCHEMA_VERSION,
36
+ SchemaVersionError,
37
+ ValidationError,
38
+ DEFAULT_CACHE_DIR,
39
+ _DATASET_CONFIGS,
40
+ _decode_array,
41
+ _parse_gv_row,
42
+ _parse_conifold_rows,
43
+ _parse_polytope_row,
44
+ _safe_concat,
45
+ _require_pandas,
46
+ _require_pyarrow,
47
+ )
48
+
49
+ from .vacua_writer import VacuaWriter
50
+
51
+
52
+ def _swap_h_columns(df: Any) -> Any:
53
+ r"""Relabel the ``h11`` and ``h12`` columns of *df*.
54
+
55
+ Used by :class:`LCSDatabase` to convert between the catalog-convention
56
+ DataFrames returned by :class:`CYDatabase` and the mirror-convention
57
+ surface presented by :class:`LCSDatabase`. The swap is symmetric, so
58
+ applying it twice returns the original DataFrame.
59
+ """
60
+ return df.rename(columns={"h11": "h12", "h12": "h11"})
61
+
62
+
63
+ def _parse_lcs_row(row: Any, dataset: str) -> Dict[str, Any]:
64
+ r"""
65
+ **Description:**
66
+ Convert a single row from the ``lcs_data`` parquet split into a keyword-
67
+ argument dictionary suitable for constructing an :class:`~jaxvacua.lcs.lcs_tree`.
68
+
69
+ The expected column names in the parquet row are:
70
+
71
+ .. code-block:: text
72
+
73
+ h11, h12, chi,
74
+ intnums_coo_i, intnums_coo_j, intnums_coo_k, intnums_coo_v,
75
+ c2, a_matrix,
76
+ hyperplanes, kahler_generators, kahler_rays, mori_rays,
77
+ polytope_points, # tdf only
78
+ heights, # tdf only
79
+ extra_data # JSON string
80
+
81
+ Args:
82
+ row: A ``pandas.Series`` corresponding to one row of the parquet file.
83
+ dataset (str): Sub-dataset identifier (``"tdf"`` or ``"cicy"``).
84
+
85
+ Returns:
86
+ Dict[str, Any]: Keyword arguments for ``lcs_tree.__init__``.
87
+ """
88
+ # ---- Reconstruct sparse intersection-number array (COO format) ----------
89
+ coo_i = _decode_array(row.get("intnums_coo_i"))
90
+ coo_j = _decode_array(row.get("intnums_coo_j"))
91
+ coo_k = _decode_array(row.get("intnums_coo_k"))
92
+ coo_v = _decode_array(row.get("intnums_coo_v"))
93
+
94
+ if all(x is not None for x in (coo_i, coo_j, coo_k, coo_v)):
95
+ intnums_coo = np.stack([coo_i, coo_j, coo_k, coo_v], axis=1)
96
+ else:
97
+ intnums_coo = None
98
+
99
+ # ---- Parse extra_data JSON string ---------------------------------------
100
+ raw_extra = row.get("extra_data")
101
+ if isinstance(raw_extra, str):
102
+ try:
103
+ extra_data = json.loads(raw_extra)
104
+ except json.JSONDecodeError:
105
+ extra_data = {}
106
+ elif isinstance(raw_extra, dict):
107
+ extra_data = raw_extra
108
+ else:
109
+ extra_data = {}
110
+
111
+ # ---- Inject primary-key fields into extra_data -------------------------
112
+ if dataset == "tdf":
113
+ extra_data.setdefault("ks_id", int(row.get("ks_id", -1)))
114
+ extra_data.setdefault("triang_id", int(row.get("triang_id", 0)))
115
+ model_ID = int(row.get("ks_id", -1))
116
+ else:
117
+ extra_data.setdefault("cicy_id", int(row.get("cicy_id", -1)))
118
+ model_ID = int(row.get("cicy_id", -1))
119
+
120
+ kwargs = dict(
121
+ h11 = int(row["h11"]),
122
+ h12 = int(row["h12"]),
123
+ #chi = int(row["chi"]) if "chi" in row.index else None,
124
+ intnums_coo = intnums_coo,
125
+ c2 = _decode_array(row.get("c2")),
126
+ a_matrix = _decode_array(row.get("a_matrix")),
127
+ hyperplanes = _decode_array(row.get("hyperplanes")),
128
+ kahler_generators = _decode_array(row.get("kahler_generators")),
129
+ kahler_rays = _decode_array(row.get("kahler_rays")),
130
+ mori_rays = _decode_array(row.get("mori_rays")),
131
+ tip_skc = _decode_array(row.get("tip_skc")),
132
+ model_type = _DATASET_CONFIGS[dataset],
133
+ model_ID = model_ID,
134
+ extra_data = extra_data or None,
135
+ )
136
+
137
+ # KS-specific fields
138
+ if dataset == "tdf":
139
+ kwargs["polytope_points"] = _decode_array(row.get("polytope_points"))
140
+ kwargs["heights"] = _decode_array(row.get("heights"))
141
+
142
+ return kwargs
143
+
144
+
145
+
146
+ class LCSDatabase(CYDatabase):
147
+ """Database layer that bridges cached geometry rows into JAXVacua.
148
+
149
+ ``LCSDatabase`` extends the pure-I/O :class:`CYDatabase` with
150
+ ``lcs_tree`` and ``FluxVacuaFinder`` construction, batch loading, sampling,
151
+ and delegation to :class:`stringforge.vacua_writer.VacuaWriter` for vacua
152
+ persistence. It owns the data/convention boundary; the physical
153
+ computations performed by returned models are owned by JAXVacua.
154
+ """
155
+
156
+ def __new__(cls, *args: Any, **kwargs: Any) -> "LCSDatabase":
157
+ r"""Factory dispatch.
158
+
159
+ When the user constructs ``LCSDatabase(dataset="kklt")`` or
160
+ ``LCSDatabase("kklt")`` directly, return a
161
+ :class:`~stringforge.kklt_database.KKLTDatabase` instance instead.
162
+ Python then calls
163
+ :meth:`KKLTDatabase.__init__` on the returned object (because
164
+ ``isinstance(returned, LCSDatabase)``), so the dispatch is
165
+ transparent to callers.
166
+ """
167
+ dataset = kwargs.get("dataset")
168
+ if dataset is None and args:
169
+ dataset = args[0]
170
+ if cls is LCSDatabase and dataset == "kklt":
171
+ from .kklt_database import KKLTDatabase
172
+ return object.__new__(KKLTDatabase)
173
+ return super().__new__(cls)
174
+
175
+ def __init__(self, *args, **kwargs):
176
+ super().__init__(*args, **kwargs)
177
+ # Filter-keyed cache populated by load_model_batch
178
+ self._cached_models: Optional[List[Any]] = None
179
+ self._cached_filter_key: Optional[Tuple[Any, ...]] = None
180
+
181
+ # ------------------------------------------------------------------
182
+ # Mirror-convention wrappers
183
+ #
184
+ # `LCSDatabase` exposes h11/h12 in the *mirror* convention used by
185
+ # `lcs_tree` / jaxvacua, whereas the underlying cy-database catalog
186
+ # stores them in the *catalog* convention (typically small h11, large
187
+ # h12). Every public method that accepts or returns h11/h12 swaps at
188
+ # the boundary so the inside of the class continues to operate on
189
+ # catalog-convention values. See :func:`_swap_h_columns`.
190
+ # ------------------------------------------------------------------
191
+ def query(
192
+ self,
193
+ h11: Optional[int] = None,
194
+ h12: Optional[int] = None,
195
+ has_conifolds: Optional[bool] = None,
196
+ n_conifolds_min: Optional[int] = None,
197
+ n_conifolds_max: Optional[int] = None,
198
+ has_gv: Optional[bool] = None,
199
+ D3_tadpole_max: Optional[int] = None,
200
+ **filters: Any,
201
+ ) -> Any:
202
+ r"""Filter the catalog and return matching models in mirror convention.
203
+
204
+ Same semantics as :meth:`CYDatabase.query`, except both the
205
+ ``h11`` / ``h12`` *filter kwargs* and the ``h11`` / ``h12``
206
+ *columns of the returned DataFrame* are interpreted in the mirror
207
+ (jaxvacua) convention. In particular::
208
+
209
+ LCSDatabase(...).query(h12=2)
210
+
211
+ returns the same rows as ``CYDatabase(...).query(h11=2)``, with
212
+ the two Hodge-number columns relabelled accordingly.
213
+
214
+ The catalog ``chi`` column is dropped from the returned DataFrame:
215
+ the catalog's :math:`\chi = 2(h^{1,1}_{\text{cat}} - h^{1,2}_{\text{cat}})`
216
+ flips sign under the mirror swap, so exposing it here would be
217
+ misleading. This mirrors the ``chi=None`` line in :meth:`load`.
218
+ """
219
+ df = super().query(
220
+ h11=h12,
221
+ h12=h11,
222
+ has_conifolds=has_conifolds,
223
+ n_conifolds_min=n_conifolds_min,
224
+ n_conifolds_max=n_conifolds_max,
225
+ has_gv=has_gv,
226
+ D3_tadpole_max=D3_tadpole_max,
227
+ **filters,
228
+ )
229
+ return _swap_h_columns(df).drop(columns=["chi"], errors="ignore")
230
+
231
+ def query_conifolds(
232
+ self,
233
+ h11: Optional[int] = None,
234
+ h12: Optional[int] = None,
235
+ ncf: Optional[int] = None,
236
+ conifold_id: Optional[int] = None,
237
+ **filters: Any,
238
+ ) -> Any:
239
+ r"""Filter the conifold sub-catalog in mirror convention.
240
+
241
+ Mirror-convention wrapper around :meth:`CYDatabase.query_conifolds`.
242
+ See :meth:`query` for the convention. The catalog ``chi`` column
243
+ is dropped from the returned DataFrame for the same reason as in
244
+ :meth:`query` (sign flip under the mirror swap).
245
+ """
246
+ df = super().query_conifolds(
247
+ h11=h12,
248
+ h12=h11,
249
+ ncf=ncf,
250
+ conifold_id=conifold_id,
251
+ **filters,
252
+ )
253
+ return _swap_h_columns(df).drop(columns=["chi"], errors="ignore")
254
+
255
+ def get_polytope( # type: ignore[override]
256
+ self,
257
+ ks_id: int,
258
+ h11: Optional[int] = None,
259
+ h12: Optional[int] = None,
260
+ ) -> Dict[str, Any]:
261
+ r"""Fetch polytope data for a model in mirror convention.
262
+
263
+ Mirror-convention wrapper around :meth:`CYDatabase.get_polytope`.
264
+ The parent's primary discriminator is the *catalog* ``h11``
265
+ (typically small). In mirror convention this is the user-supplied
266
+ ``h12``, which is therefore required here even though both
267
+ Hodge-number arguments are typed ``Optional`` to keep the keyword
268
+ order consistent with the rest of the mirror-convention surface.
269
+
270
+ Raises:
271
+ ValueError: If ``h12`` is omitted.
272
+ """
273
+ if h12 is None:
274
+ raise ValueError(
275
+ "LCSDatabase.get_polytope requires `h12` "
276
+ "(= catalog h11, the primary discriminator)."
277
+ )
278
+ return super().get_polytope(ks_id, h11=h12, h12=h11)
279
+
280
+ def info(self) -> None:
281
+ r"""Print summary of available models, with Hodge ranges in mirror convention."""
282
+ self._ensure_catalog()
283
+ cat = self._catalog
284
+ assert cat is not None # populated by _ensure_catalog
285
+ n_total = len(cat)
286
+ h11_min, h11_max = int(cat["h11"].min()), int(cat["h11"].max())
287
+ h12_min, h12_max = int(cat["h12"].min()), int(cat["h12"].max())
288
+ n_gv = int(cat["has_gv"].sum()) if "has_gv" in cat.columns else -1
289
+ n_cf = int((cat["n_conifolds"] > 0).sum()) if "n_conifolds" in cat.columns else -1
290
+
291
+ print(f"LCSDatabase — sub-dataset: '{self.dataset}' (mirror convention)")
292
+ print(f" Total models : {n_total:,}")
293
+ # Mirror convention: catalog h12 is reported as h11, and vice versa.
294
+ print(f" h11 range : {h12_min} – {h12_max}")
295
+ print(f" h12 range : {h11_min} – {h11_max}")
296
+ if n_gv >= 0:
297
+ print(f" With GV data : {n_gv:,} ({100*n_gv/n_total:.1f}%)")
298
+ if n_cf >= 0:
299
+ print(f" With conifolds: {n_cf:,} ({100*n_cf/n_total:.1f}%)")
300
+ print(f" Cache dir : {self.cache_dir}")
301
+
302
+ # ------------------------------------------------------------------
303
+ # lcs_tree / FluxVacuaFinder construction — method bodies below were
304
+ # copied verbatim from the original CYDatabase (except `load_model`
305
+ # which now returns FluxVacuaFinder instead of FluxEFT).
306
+ # ------------------------------------------------------------------
307
+ def load(
308
+ self,
309
+ ks_id: Optional[int] = None,
310
+ triang_id: Optional[int] = None,
311
+ cicy_id: Optional[int] = None,
312
+ h11: Optional[int] = None,
313
+ h12: Optional[int] = None,
314
+ include_gv: bool = False,
315
+ include_conifolds: Union[bool, str] = False,
316
+ conifold_id: Optional[int] = None,
317
+ conifold_basis: bool = True,
318
+ include_extra_data: bool = True,
319
+ include_polytope: bool = False,
320
+ extra_fields: Optional[List[str]] = None,
321
+ maximum_degree: Optional[int] = None,
322
+ ) -> Any:
323
+ r"""
324
+ **Description:**
325
+ Load a single Calabi-Yau model from the database and return it as an
326
+ :class:`~jaxvacua.lcs.lcs_tree` object.
327
+
328
+ For ``tdf`` models the full primary key is
329
+ ``(h11, h12, ks_id, triang_id)``. When ``h11`` and ``h12`` are
330
+ omitted the lookup falls back to ``(ks_id, triang_id)``; if that
331
+ combination is ambiguous a ``ValueError`` is raised asking you to
332
+ supply the Hodge numbers.
333
+
334
+ For ``cicy`` models, only ``cicy_id`` is required.
335
+
336
+ Args:
337
+ ks_id (int | None): Kreuzer-Skarke polytope index (required for
338
+ ``dataset="tdf"``).
339
+ triang_id (int | None): Triangulation index (required for
340
+ ``dataset="tdf"``).
341
+ cicy_id (int | None): CICY model index (required for
342
+ ``dataset="cicy"``).
343
+ h11 (int | None): Mirror :math:`h^{1,1}` (= catalog
344
+ :math:`h^{1,2}`). Recommended for ``dataset="tdf"`` to
345
+ ensure a unique match.
346
+ h12 (int | None): Mirror :math:`h^{1,2}` (= catalog
347
+ :math:`h^{1,1}`). Recommended for ``dataset="tdf"`` to
348
+ ensure a unique match.
349
+ include_gv (bool): If ``True``, fetch and attach Gopakumar-Vafa
350
+ and Gromov-Witten invariants. Defaults to ``False``.
351
+ include_conifolds (bool | str): If ``True``, fetch all available
352
+ conifold limits and populate ``lcs_tree.conifold`` (the
353
+ active :class:`~jaxvacua.conifold_utils.Conifold`) from the
354
+ selected conifold (controlled by ``conifold_id``; defaults
355
+ to 0). Pass ``"all"`` to obtain a list of trees, one per
356
+ conifold. Defaults to ``False``.
357
+ conifold_id (int | None): Index of the conifold limit to use when
358
+ ``include_conifolds=True``. Ignored when
359
+ ``include_conifolds="all"``. Defaults to ``0``.
360
+ conifold_basis (bool): If ``True``, rotate to the basis defined by
361
+ the conifold curve when ``include_conifolds`` is active.
362
+ Defaults to ``True``.
363
+ include_extra_data (bool): If ``True``, populate
364
+ ``lcs_tree.extra_data`` from the ``extra`` split (merged with
365
+ the identifier fields always stored there). Defaults to
366
+ ``True``.
367
+ include_polytope (bool): If ``True``, fetch the ``polytope`` split
368
+ and attach ``polytope_points`` (and any extra polytope-level
369
+ fields) to the returned tree. Only meaningful for
370
+ ``dataset="tdf"``. Defaults to ``False``.
371
+ extra_fields (list[str] | None): Subset of columns to load from
372
+ the ``extra`` split when ``include_extra_data=True``. If
373
+ ``None``, all available columns are loaded.
374
+ maximum_degree (int | None): If ``include_gv=True``, truncate GV
375
+ invariants to at most this degree. ``None`` keeps all stored
376
+ invariants.
377
+
378
+ Returns:
379
+ lcs_tree | list[lcs_tree]: A single tree, or a list when
380
+ ``include_conifolds="all"``.
381
+
382
+ Raises:
383
+ KeyError: If the requested model is not in the catalog.
384
+ ValueError: If required primary-key arguments are missing, or if
385
+ the ``(ks_id, triang_id)`` pair matches multiple models and
386
+ ``h11``/``h12`` were not supplied.
387
+
388
+ Notes:
389
+ ``h11`` / ``h12`` are interpreted in the *mirror* (jaxvacua)
390
+ convention. They are translated to the underlying catalog
391
+ convention here at the API boundary; the post-fetch swap that
392
+ puts the values back into mirror convention for ``lcs_tree``
393
+ is done further down (see the ``# Flip Hodge numbers for input``
394
+ block).
395
+ """
396
+ # Mirror -> catalog: the underlying catalog and `_lookup`/shard paths
397
+ # use the catalog convention, so swap the user-supplied Hodge numbers
398
+ # before any further processing. The post-fetch swap further down
399
+ # restores mirror convention for the kwargs handed to `lcs_tree`.
400
+ h11, h12 = h12, h11
401
+
402
+ self._check_cache_size()
403
+ self._validate_key(ks_id, triang_id, cicy_id)
404
+ entry = self._lookup(ks_id, triang_id, cicy_id, h11=h11, h12=h12)
405
+
406
+ # ---- Fetch LCS geometry data ----------------------------------------
407
+ h11 = int(entry["h11"])
408
+ if self.cache_mode == "persistent":
409
+ lcs_shard = self._fetch_shard(
410
+ f"lcs_data/h11_{h11}", int(entry["lcs_shard_id"])
411
+ )
412
+ lcs_row = lcs_shard.iloc[int(entry["lcs_row_index"])]
413
+ else:
414
+ lcs_row = self._fetch_row(
415
+ f"lcs_data/h11_{h11}",
416
+ int(entry["lcs_shard_id"]),
417
+ int(entry["lcs_row_index"]),
418
+ )
419
+ kwargs = _parse_lcs_row(lcs_row, self.dataset)
420
+
421
+ # ---- Optionally fetch extra data ------------------------------------
422
+ if include_extra_data and "extra_shard_id" in entry.index:
423
+ if self.cache_mode == "persistent":
424
+ extra_shard = self._fetch_shard("extra", int(entry["extra_shard_id"]))
425
+ extra_row = extra_shard.iloc[int(entry["extra_row_index"])]
426
+ else:
427
+ extra_row = self._fetch_row(
428
+ "extra", int(entry["extra_shard_id"]),
429
+ int(entry["extra_row_index"]),
430
+ )
431
+ extra = dict(extra_row)
432
+ if extra_fields is not None:
433
+ extra = {k: v for k, v in extra.items() if k in extra_fields}
434
+ existing = kwargs.get("extra_data") or {}
435
+ kwargs["extra_data"] = {**existing, **extra}
436
+
437
+ # ---- Optionally fetch polytope data (tdf only) ----------------------
438
+ if include_polytope and "polytope_shard_id" in entry.index:
439
+ _psid = entry["polytope_shard_id"]
440
+ _prid = entry["polytope_row_index"]
441
+ _has_poly = False
442
+ try:
443
+ import pandas as pd
444
+ _has_poly = _psid is not None and not pd.isna(_psid)
445
+ except (TypeError, ValueError):
446
+ _has_poly = _psid is not None
447
+ if _has_poly:
448
+ if self.cache_mode == "persistent":
449
+ poly_shard = self._fetch_shard("polytope", int(_psid))
450
+ poly_row = poly_shard.iloc[int(_prid)]
451
+ else:
452
+ poly_row = self._fetch_row("polytope", int(_psid), int(_prid))
453
+ poly_data = _parse_polytope_row(poly_row)
454
+ kwargs["polytope_points"] = poly_data["polytope_points"]
455
+ if "polytope_data" in poly_data:
456
+ existing = kwargs.get("extra_data") or {}
457
+ kwargs["extra_data"] = {**existing, "polytope_data": poly_data["polytope_data"]}
458
+
459
+ # ---- Optionally fetch GV invariants --------------------------------
460
+ gvs, gws, grading_vec = None, None, None
461
+ if include_gv and entry.get("has_gv", False):
462
+ _gv_split = f"gv/h11_{h11}"
463
+ if self.cache_mode == "persistent":
464
+ gv_shard = self._fetch_shard(_gv_split, int(entry["gv_shard_id"]))
465
+ gv_row = gv_shard.iloc[int(entry["gv_row_index"])]
466
+ else:
467
+ gv_row = self._fetch_row(
468
+ _gv_split, int(entry["gv_shard_id"]),
469
+ int(entry["gv_row_index"]),
470
+ )
471
+ gv_data = _parse_gv_row(gv_row)
472
+ gvs = gv_data["GVs"]
473
+ gws = gv_data["GWs"]
474
+ grading_vec = gv_data["grading_vector"]
475
+ if maximum_degree is not None:
476
+ gvs, gws = self._truncate_gv(gvs, gws, grading_vec,maximum_degree)
477
+ kwargs["gvs"] = gvs
478
+ kwargs["gws"] = gws
479
+ kwargs["grading_vector"] = grading_vec
480
+
481
+
482
+ # Flip Hodge numbers for input
483
+ h11 = kwargs["h11"]
484
+ h12 = kwargs["h12"]
485
+ kwargs["h11"] = h12
486
+ kwargs["h12"] = h11
487
+ kwargs["chi"] = None
488
+
489
+ if h11 == 0 or h12 == 0:
490
+ warnings.warn(
491
+ "One of the Hodge numbers is zero, which may lead to "
492
+ "unexpected behavior in some JAXVacua computations. "
493
+ "Proceed with caution."
494
+ )
495
+
496
+ # ---- Optionally fetch conifold data --------------------------------
497
+ # Conifold shards are sharded by *catalog* h11 (the on-disk
498
+ # convention), so use the entry's original h11 before the mirror
499
+ # swap performed above.
500
+ _cat_h11 = int(entry["h11"])
501
+ conifold_list = []
502
+ if include_conifolds and int(entry.get("n_conifolds", 0)) > 0:
503
+ _cf_shard_id = int(entry["conifold_shard_id"])
504
+ _cf_split = f"conifolds/h11_{_cat_h11}"
505
+ if self.cache_mode == "persistent":
506
+ cf_shard = self._fetch_shard(_cf_split, _cf_shard_id)
507
+ else:
508
+ # For conifolds we need the full shard to filter by model
509
+ # ID, so use _fetch_rows with a mask function.
510
+ if self.dataset == "tdf":
511
+ def _cf_mask(df):
512
+ m = (df["ks_id"] == ks_id) & (df["triang_id"] == triang_id)
513
+ if "h11" in df.columns:
514
+ m = m & (df["h11"] == _cat_h11)
515
+ return m
516
+ else:
517
+ _cf_mask = lambda df: df["cicy_id"] == cicy_id
518
+ cf_rows = self._fetch_rows(_cf_split, _cf_shard_id, _cf_mask)
519
+ conifold_list = _parse_conifold_rows(cf_rows)
520
+
521
+ if self.cache_mode == "persistent":
522
+ if self.dataset == "tdf":
523
+ mask = (
524
+ (cf_shard["ks_id"] == ks_id) &
525
+ (cf_shard["triang_id"] == triang_id)
526
+ )
527
+ if "h11" in cf_shard.columns:
528
+ mask = mask & (cf_shard["h11"] == _cat_h11)
529
+ cf_rows = cf_shard[mask]
530
+ else:
531
+ cf_rows = cf_shard[cf_shard["cicy_id"] == cicy_id]
532
+ conifold_list = _parse_conifold_rows(cf_rows)
533
+
534
+ # ---- Construct lcs_tree --------------------------------------------
535
+ from jaxvacua.lcs import lcs_tree
536
+
537
+ _CF_EXTRA_KEYS = ("flop_edge", "one_face_divisors")
538
+
539
+ if include_conifolds == "all" and conifold_list:
540
+ trees = []
541
+ for cf in conifold_list:
542
+ kw = {
543
+ **kwargs,
544
+ "ncf": cf["ncf"],
545
+ "conifold_curve": cf["conifold_curve"],
546
+ "conifold_basis": conifold_basis,
547
+ "limit": "coniLCS",
548
+ }
549
+ if conifold_basis and cf.get("basis_change") is not None:
550
+ kw["basis_change"] = cf["basis_change"]
551
+ if include_extra_data:
552
+ cf_extra = {k: cf[k] for k in _CF_EXTRA_KEYS if cf.get(k) is not None}
553
+ if cf_extra:
554
+ kw["extra_data"] = {**(kw.get("extra_data") or {}), **cf_extra}
555
+ trees.append(lcs_tree.from_dict(kw))
556
+ return trees
557
+
558
+ if conifold_list:
559
+ # Select the requested conifold; fall back to id=0 if not found.
560
+ _target_id = conifold_id if conifold_id is not None else 0
561
+ _matches = [cf for cf in conifold_list if cf["conifold_id"] == _target_id]
562
+ if not _matches:
563
+ raise KeyError(
564
+ f"conifold_id={_target_id} not found for this model. "
565
+ f"Available ids: {[cf['conifold_id'] for cf in conifold_list]}"
566
+ )
567
+ cf = _matches[0]
568
+ kwargs["ncf"] = cf["ncf"]
569
+ kwargs["conifold_curve"] = cf["conifold_curve"]
570
+ kwargs["conifold_basis"] = conifold_basis
571
+ kwargs["limit"] = "coniLCS"
572
+ if conifold_basis and cf.get("basis_change") is not None:
573
+ kwargs["basis_change"] = cf["basis_change"]
574
+ if include_extra_data:
575
+ cf_extra = {k: cf[k] for k in _CF_EXTRA_KEYS if cf.get(k) is not None}
576
+ if cf_extra:
577
+ kwargs["extra_data"] = {**(kwargs.get("extra_data") or {}), **cf_extra}
578
+
579
+ # Pass ``maximum_degree`` through as an int; 0 means no
580
+ # instanton-degree cutoff.
581
+ kwargs["maximum_degree"] = (
582
+ int(maximum_degree) if maximum_degree is not None else 0
583
+ )
584
+
585
+ return lcs_tree.from_dict(kwargs)
586
+
587
+ def load_from_conifold_row(
588
+ self,
589
+ row: Any,
590
+ include_gv: bool = False,
591
+ conifold_basis: bool = True,
592
+ include_extra_data: bool = True,
593
+ include_polytope: bool = False,
594
+ maximum_degree: Optional[int] = None,
595
+ ) -> Any:
596
+ r"""
597
+ **Description:**
598
+ Load the model corresponding to a single row from
599
+ :meth:`query_conifolds` and return it as an
600
+ :class:`~jaxvacua.lcs.lcs_tree` with that conifold limit active.
601
+
602
+ Example::
603
+
604
+ rows = db.query_conifolds(h11=2, ncf=2)
605
+ tree = db.load_from_conifold_row(rows.iloc[0])
606
+
607
+ Args:
608
+ row: A single-row result from :meth:`query_conifolds` (a
609
+ ``pandas.Series``).
610
+ include_gv (bool): Attach GV invariants. Defaults to ``False``.
611
+ conifold_basis (bool): Rotate to the conifold basis. Defaults to
612
+ ``True``.
613
+ include_extra_data (bool): Populate ``extra_data``. Defaults to
614
+ ``True``.
615
+ include_polytope (bool): Attach polytope data. Defaults to
616
+ ``False``.
617
+ maximum_degree (int | None): GV truncation degree.
618
+
619
+ Returns:
620
+ lcs_tree: The requested model with the selected conifold active.
621
+ """
622
+ return self.load(
623
+ ks_id=int(row["ks_id"]) if self.dataset == "tdf" else None,
624
+ triang_id=int(row["triang_id"]) if self.dataset == "tdf" else None,
625
+ cicy_id=int(row["cicy_id"]) if self.dataset == "cicy" else None,
626
+ include_conifolds=True,
627
+ conifold_id=int(row["conifold_id"]),
628
+ conifold_basis=conifold_basis,
629
+ include_gv=include_gv,
630
+ include_extra_data=include_extra_data,
631
+ include_polytope=include_polytope,
632
+ maximum_degree=maximum_degree,
633
+ )
634
+
635
+ def load_model(
636
+ self,
637
+ ks_id: Optional[int] = None,
638
+ triang_id: Optional[int] = None,
639
+ cicy_id: Optional[int] = None,
640
+ h11: Optional[int] = None,
641
+ h12: Optional[int] = None,
642
+ include_gv: bool = False,
643
+ include_conifolds: Union[bool, str] = False,
644
+ maximum_degree: int = 0,
645
+ **model_kwargs: Any,
646
+ ) -> Any:
647
+ r"""
648
+ **Description:**
649
+ Load a model from the database and return it as a fully initialised
650
+ :class:`~jaxvacua.flux_vacua_finder.FluxVacuaFinder` object.
651
+
652
+ This is a convenience wrapper around :meth:`load` followed by
653
+ construction of a
654
+ :class:`~jaxvacua.flux_vacua_finder.FluxVacuaFinder` with
655
+ ``lcs_tree_input``. The returned object includes the period,
656
+ complex-structure-sector, flux-EFT, and vacuum-finding layers.
657
+
658
+ Args:
659
+ ks_id (int | None): Kreuzer-Skarke polytope index (tdf only).
660
+ triang_id (int | None): Triangulation index (tdf only).
661
+ cicy_id (int | None): CICY index (cicy only).
662
+ h11 (int | None): Mirror :math:`h^{1,1}` (= catalog
663
+ :math:`h^{1,2}`; tdf only).
664
+ h12 (int | None): Mirror :math:`h^{1,2}` (= catalog
665
+ :math:`h^{1,1}`; tdf only).
666
+ include_gv (bool): Attach GV invariants. Defaults to ``False``.
667
+ include_conifolds (bool): Attach conifold data. Defaults to
668
+ ``False``.
669
+ maximum_degree (int): Maximum instanton degree; passed to
670
+ :class:`~jaxvacua.flux_vacua_finder.FluxVacuaFinder`.
671
+ Defaults to ``0`` (instanton corrections disabled).
672
+ **model_kwargs: Additional keyword arguments forwarded to
673
+ :class:`~jaxvacua.flux_vacua_finder.FluxVacuaFinder`,
674
+ e.g. ``Q``, ``limit``, ``gauge_choice``.
675
+
676
+ Returns:
677
+ FluxVacuaFinder: Initialised JAXVacua model.
678
+
679
+ Raises:
680
+ KeyError: If the requested model is not in the catalog.
681
+ """
682
+ from jaxvacua.flux_vacua_finder import FluxVacuaFinder
683
+
684
+ tree = self.load(
685
+ ks_id=ks_id,
686
+ triang_id=triang_id,
687
+ cicy_id=cicy_id,
688
+ h11=h11,
689
+ h12=h12,
690
+ include_gv=include_gv,
691
+ include_conifolds=include_conifolds,
692
+ maximum_degree=maximum_degree if include_gv else None,
693
+ )
694
+ return FluxVacuaFinder(
695
+ lcs_tree_input=tree,
696
+ maximum_degree=maximum_degree,
697
+ **model_kwargs,
698
+ )
699
+
700
+ def load_batch(
701
+ self,
702
+ identifiers: Any = None,
703
+ include_gv: bool = False,
704
+ include_conifolds: Union[bool, str] = False,
705
+ conifold_id: Optional[int] = None,
706
+ conifold_basis: bool = True,
707
+ include_extra_data: bool = True,
708
+ include_polytope: bool = False,
709
+ maximum_degree: Optional[int] = None,
710
+ parallel: bool = True,
711
+ n_workers: Optional[int] = None,
712
+ **query_filters: Any,
713
+ ) -> List[Any]:
714
+ r"""
715
+ **Description:**
716
+ Load multiple models and return them as a list of
717
+ :class:`~jaxvacua.lcs.lcs_tree` objects.
718
+
719
+ By default shard I/O is parallelised across a thread pool so that
720
+ models in different shards are fetched concurrently. Results are
721
+ always returned in the same order as ``identifiers``.
722
+
723
+ Can be called in two ways:
724
+
725
+ 1. **With explicit identifiers:**
726
+ ``db.load_batch(df)`` or ``db.load_batch([(ks_id, triang_id), ...])``
727
+ 2. **With query filters** (same kwargs as :meth:`query`):
728
+ ``db.load_batch(h11=2)`` or ``db.load_batch(ks_id=12345)``
729
+
730
+ When query filters are used, :meth:`query` is called first and
731
+ the matching catalog entries are loaded.
732
+
733
+ Args:
734
+ identifiers: Either a ``pandas.DataFrame`` with columns
735
+ ``ks_id`` and ``triang_id`` (or ``cicy_id``), or a list of
736
+ ``(ks_id, triang_id)`` tuples for ``"tdf"``, or a list of
737
+ ``cicy_id`` integers for ``"cicy"``. If ``None``, the
738
+ ``**query_filters`` are used instead.
739
+ include_gv (bool): Attach GV invariants to each model.
740
+ include_conifolds (bool | str): Attach conifold data.
741
+ conifold_id (int | None): Index of the conifold limit to use.
742
+ Defaults to ``0``. Ignored when ``include_conifolds="all"``.
743
+ conifold_basis (bool): Rotate to the conifold basis when
744
+ ``include_conifolds`` is active. Defaults to ``True``.
745
+ include_extra_data (bool): Populate ``extra_data`` field.
746
+ include_polytope (bool): Attach polytope data from the polytope split.
747
+ maximum_degree (int | None): GV truncation degree.
748
+ parallel (bool): If ``False``, load models sequentially (no thread
749
+ pool). Useful when the caller is already inside a parallel
750
+ context or when debugging. Defaults to ``True``.
751
+ n_workers (int | None): Number of threads when ``parallel=True``.
752
+ ``None`` uses ``min(len(identifiers), 8)``.
753
+ **query_filters: Keyword arguments forwarded to :meth:`query`
754
+ when ``identifiers`` is ``None``. Common filters:
755
+ ``h11``, ``h12``, ``ks_id``, ``has_conifolds``, ``has_gv``.
756
+
757
+ Returns:
758
+ list[lcs_tree]: Loaded trees in the same order as ``identifiers``
759
+ (or in catalog order when using query filters).
760
+ """
761
+ _require_pandas()
762
+
763
+ if identifiers is None:
764
+ if not query_filters:
765
+ raise ValueError(
766
+ "Either pass identifiers (DataFrame / list) or "
767
+ "query filters (e.g. h11=2, ks_id=12345)."
768
+ )
769
+ identifiers = self.query(**query_filters)
770
+ if len(identifiers) == 0:
771
+ warnings.warn("Query returned no models.")
772
+ return []
773
+
774
+ rows = self._identifiers_to_list(identifiers)
775
+
776
+ if not rows:
777
+ return []
778
+
779
+ workers = 1 if not parallel else (min(len(rows), 8) if n_workers is None else n_workers)
780
+
781
+ def _load_one(row):
782
+ """Load a single model from an identifier row."""
783
+ ks_id, triang_id, cicy_id, h11, h12 = row
784
+ return self.load(
785
+ ks_id=ks_id,
786
+ triang_id=triang_id,
787
+ cicy_id=cicy_id,
788
+ h11=h11,
789
+ h12=h12,
790
+ include_gv=include_gv,
791
+ include_conifolds=include_conifolds,
792
+ conifold_id=conifold_id,
793
+ conifold_basis=conifold_basis,
794
+ include_extra_data=include_extra_data,
795
+ include_polytope=include_polytope,
796
+ maximum_degree=maximum_degree,
797
+ )
798
+
799
+ if workers == 1:
800
+ return [_load_one(row) for row in rows]
801
+
802
+ # Submit all jobs, preserving insertion order via index.
803
+ with ThreadPoolExecutor(max_workers=workers) as executor:
804
+ future_to_idx = {
805
+ executor.submit(_load_one, row): i
806
+ for i, row in enumerate(rows)
807
+ }
808
+ results = [None] * len(rows)
809
+ for future in as_completed(future_to_idx):
810
+ idx = future_to_idx[future]
811
+ results[idx] = future.result() # re-raises any exception
812
+
813
+ return results
814
+
815
+ def iter_batch(
816
+ self,
817
+ identifiers: Any,
818
+ include_gv: bool = False,
819
+ include_conifolds: Union[bool, str] = False,
820
+ conifold_id: Optional[int] = None,
821
+ conifold_basis: bool = True,
822
+ include_extra_data: bool = True,
823
+ include_polytope: bool = False,
824
+ maximum_degree: Optional[int] = None,
825
+ prefetch: int = 4,
826
+ ) -> Iterator[Any]:
827
+ r"""
828
+ **Description:**
829
+ Yield models one at a time from a (potentially large) set of
830
+ identifiers, keeping memory usage constant regardless of the total
831
+ number of models requested.
832
+
833
+ Unlike :meth:`load_batch`, which loads all models into a list before
834
+ returning, ``iter_batch`` is a generator: it yields each
835
+ :class:`~jaxvacua.lcs.lcs_tree` as soon as it is ready, so the
836
+ caller can begin processing immediately and only one model needs to be
837
+ in memory at a time.
838
+
839
+ A sliding prefetch window of size ``prefetch`` submits the next
840
+ ``prefetch`` loads to a background thread pool while the caller
841
+ processes the current model, keeping disk I/O overlapped with
842
+ computation. Set ``prefetch=1`` (or ``prefetch=0``) to disable
843
+ parallelism and load strictly one model at a time.
844
+
845
+ Example::
846
+
847
+ df = db.query(h11=3)
848
+ for tree in db.iter_batch(df, prefetch=8):
849
+ result = analyse(tree) # memory: ~1 model at a time
850
+
851
+ Args:
852
+ identifiers: Either a ``pandas.DataFrame`` with columns
853
+ ``ks_id`` and ``triang_id`` (or ``cicy_id``), or a list of
854
+ ``(ks_id, triang_id)`` tuples for ``"tdf"``, or a list of
855
+ ``cicy_id`` integers for ``"cicy"``.
856
+ include_gv (bool): Attach GV invariants to each model.
857
+ include_conifolds (bool | str): Attach conifold data.
858
+ conifold_id (int | None): Index of the conifold limit to use.
859
+ Defaults to ``0``. Ignored when ``include_conifolds="all"``.
860
+ conifold_basis (bool): Rotate to the conifold basis when
861
+ ``include_conifolds`` is active. Defaults to ``True``.
862
+ include_extra_data (bool): Populate ``extra_data`` field.
863
+ include_polytope (bool): Attach polytope data.
864
+ maximum_degree (int | None): GV truncation degree.
865
+ prefetch (int): Number of models to load ahead in background
866
+ threads. Defaults to ``4``. Set to ``0`` or ``1`` for
867
+ strictly sequential loading.
868
+
869
+ Yields:
870
+ lcs_tree: One loaded model per iteration, in the same order as
871
+ ``identifiers``.
872
+ """
873
+ _require_pandas()
874
+ rows = self._identifiers_to_list(identifiers)
875
+
876
+ if not rows:
877
+ return
878
+
879
+ def _load_one(row):
880
+ """Load a single model from an identifier row for iteration."""
881
+ ks_id, triang_id, cicy_id, h11, h12 = row
882
+ return self.load(
883
+ ks_id=ks_id,
884
+ triang_id=triang_id,
885
+ cicy_id=cicy_id,
886
+ h11=h11,
887
+ h12=h12,
888
+ include_gv=include_gv,
889
+ include_conifolds=include_conifolds,
890
+ conifold_id=conifold_id,
891
+ conifold_basis=conifold_basis,
892
+ include_extra_data=include_extra_data,
893
+ include_polytope=include_polytope,
894
+ maximum_degree=maximum_degree,
895
+ )
896
+
897
+ # Sequential path — no thread pool overhead.
898
+ if prefetch <= 1:
899
+ for row in rows:
900
+ yield _load_one(row)
901
+ return
902
+
903
+ # Prefetch path — sliding window of futures keeps I/O and computation
904
+ # overlapped. The window size is capped to the number of rows.
905
+ window = min(prefetch, len(rows))
906
+ executor = ThreadPoolExecutor(max_workers=window)
907
+ pending: deque = deque()
908
+
909
+ try:
910
+ # Prime the window with the first `window` rows.
911
+ for i in range(window):
912
+ pending.append(executor.submit(_load_one, rows[i]))
913
+
914
+ # For each remaining row, pop the oldest future (blocking until
915
+ # done), yield it, then immediately submit the next row so the
916
+ # window stays full.
917
+ for i in range(window, len(rows)):
918
+ pending.append(executor.submit(_load_one, rows[i]))
919
+ yield pending.popleft().result()
920
+
921
+ # Drain the window.
922
+ while pending:
923
+ yield pending.popleft().result()
924
+
925
+ finally:
926
+ # Cancel any still-pending futures if the caller broke out of the
927
+ # loop early, then shut down the executor cleanly.
928
+ for f in pending:
929
+ f.cancel()
930
+ executor.shutdown(wait=False)
931
+
932
+ def sample(
933
+ self,
934
+ n: int,
935
+ h11: Optional[int] = None,
936
+ h12: Optional[int] = None,
937
+ has_conifolds: Optional[bool] = None,
938
+ has_gv: Optional[bool] = None,
939
+ seed: Optional[int] = None,
940
+ include_gv: bool = False,
941
+ include_conifolds: Union[bool, str] = False,
942
+ conifold_id: Optional[int] = None,
943
+ conifold_basis: bool = True,
944
+ include_extra_data: bool = True,
945
+ include_polytope: bool = False,
946
+ maximum_degree: Optional[int] = None,
947
+ parallel: bool = True,
948
+ n_workers: Optional[int] = None,
949
+ ) -> List[Any]:
950
+ r"""
951
+ **Description:**
952
+ Draw a random sample of models from the database and return them as a
953
+ list of :class:`~jaxvacua.lcs.lcs_tree` objects.
954
+
955
+ Args:
956
+ n (int): Number of models to draw.
957
+ h11 (int | None): Restrict sample to models with this mirror
958
+ :math:`h^{1,1}` (= catalog :math:`h^{1,2}`).
959
+ h12 (int | None): Restrict sample to models with this mirror
960
+ :math:`h^{1,2}` (= catalog :math:`h^{1,1}`). This is the
961
+ primary discriminator of small-modulus models.
962
+ has_conifolds (bool | None): Restrict to models with conifold data.
963
+ has_gv (bool | None): Restrict to models with GV invariants.
964
+ seed (int | None): Random seed for reproducibility.
965
+ include_gv (bool): Attach GV invariants to each sampled model.
966
+ include_conifolds (bool | str): Attach conifold data.
967
+ conifold_id (int | None): Index of the conifold limit to use.
968
+ Defaults to ``0``. Ignored when ``include_conifolds="all"``.
969
+ conifold_basis (bool): Rotate to the conifold basis when
970
+ ``include_conifolds`` is active. Defaults to ``True``.
971
+ include_extra_data (bool): Populate ``extra_data`` field.
972
+ include_polytope (bool): Attach polytope data from the polytope split.
973
+ maximum_degree (int | None): GV truncation degree.
974
+ parallel (bool): If ``False``, load models sequentially. See
975
+ :meth:`load_batch`.
976
+ n_workers (int | None): Number of parallel threads. See
977
+ :meth:`load_batch`.
978
+
979
+ Returns:
980
+ list[lcs_tree]: ``n`` randomly drawn trees.
981
+
982
+ Raises:
983
+ ValueError: If the filtered catalog contains fewer than ``n``
984
+ models.
985
+ """
986
+ subset = self.query(
987
+ h11=h11, h12=h12,
988
+ has_conifolds=has_conifolds,
989
+ has_gv=has_gv,
990
+ )
991
+ if len(subset) < n:
992
+ raise ValueError(
993
+ f"Requested {n} models but only {len(subset)} match the filter."
994
+ )
995
+ sampled = subset.sample(n=n, random_state=seed)
996
+ return self.load_batch(
997
+ sampled,
998
+ include_gv=include_gv,
999
+ include_conifolds=include_conifolds,
1000
+ conifold_id=conifold_id,
1001
+ conifold_basis=conifold_basis,
1002
+ include_extra_data=include_extra_data,
1003
+ include_polytope=include_polytope,
1004
+ maximum_degree=maximum_degree,
1005
+ parallel=parallel,
1006
+ n_workers=n_workers,
1007
+ )
1008
+
1009
+ @staticmethod
1010
+ def _truncate_gv(
1011
+ gvs: Dict[str, Any],
1012
+ gws: Dict[str, Any],
1013
+ grading_vec: Optional[np.ndarray],
1014
+ maximum_degree: int,
1015
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
1016
+ r"""
1017
+ **Description:**
1018
+ Truncate Gopakumar-Vafa and Gromov-Witten invariants to a maximum
1019
+ total degree.
1020
+
1021
+ The total degree of a curve with charge vector ``q`` is taken to be
1022
+ ``q.sum()``. Entries with total degree greater than ``maximum_degree``
1023
+ are removed.
1024
+
1025
+ Args:
1026
+ gvs (dict): GV data with keys ``"charges"`` and ``"invariants"``.
1027
+ gws (dict): GW data with keys ``"charges"`` and ``"invariants"``.
1028
+ maximum_degree (int): Maximum allowed total degree.
1029
+
1030
+ Returns:
1031
+ Tuple[dict, dict]: Truncated ``(gvs, gws)``.
1032
+ """
1033
+ def _trunc(data: Dict[str, Any]) -> Dict[str, Any]:
1034
+ """Truncate data arrays to entries within the maximum degree."""
1035
+ charges = data.get("charges")
1036
+ invs = data.get("invariants")
1037
+ if charges is None or invs is None or grading_vec is None:
1038
+ return data
1039
+ charges = np.asarray([np.array(c).astype(int) for c in charges])
1040
+ invs = np.asarray(invs)
1041
+ deg = charges@grading_vec
1042
+ if np.any(deg < 0):
1043
+ raise ValueError("Found negative curve degrees. Grading vector may be incorrect.")
1044
+ mask = deg <= maximum_degree
1045
+ return {"charges": charges[mask], "invariants": invs[mask]}
1046
+
1047
+ return _trunc(gvs), _trunc(gws)
1048
+
1049
+
1050
+ # ------------------------------------------------------------------
1051
+ # NEW — batch-model methods + filter-keyed cache
1052
+ # ------------------------------------------------------------------
1053
+
1054
+ @staticmethod
1055
+ def _filter_cache_key(filters: Dict[str, Any]) -> Optional[Tuple[Any, ...]]:
1056
+ """Return a hashable tuple summarising `filters`, or None if any value
1057
+ isn't hashable (e.g. a DataFrame passed as an entire filter argument).
1058
+ Callers treat a ``None`` key as "bypass cache"."""
1059
+ try:
1060
+ return tuple(sorted((k, v) for k, v in filters.items()))
1061
+ except TypeError:
1062
+ return None
1063
+
1064
+ def load_model_batch(self, **filters) -> List[Any]:
1065
+ """Eager ensemble load — returns a list of FluxVacuaFinder instances.
1066
+
1067
+ Filter-keyed cache: repeated calls with the same ``**filters`` return
1068
+ the same cached list object without rebuilding. Calling with a
1069
+ different filter set rebuilds and replaces the cache. Unhashable
1070
+ filters bypass the cache transparently (always rebuild).
1071
+
1072
+ See `iter_model_batch` for a lazy alternative that does not retain
1073
+ constructed models.
1074
+ """
1075
+ from jaxvacua.flux_vacua_finder import FluxVacuaFinder
1076
+ key = self._filter_cache_key(filters)
1077
+ if key is not None and key == self._cached_filter_key:
1078
+ return self._cached_models
1079
+ trees = self.load_batch(**filters)
1080
+ models = [FluxVacuaFinder(lcs_tree_input=t) for t in trees]
1081
+ self._cached_models = models
1082
+ self._cached_filter_key = key
1083
+ return models
1084
+
1085
+ # kwargs `iter_batch` accepts directly (pass through); anything else is
1086
+ # treated as a catalog filter and routed through `self.query(**filters)`.
1087
+ _ITER_BATCH_KWARGS = frozenset((
1088
+ "include_gv", "include_conifolds", "conifold_id", "conifold_basis",
1089
+ "include_extra_data", "include_polytope", "maximum_degree", "prefetch",
1090
+ ))
1091
+
1092
+ def iter_model_batch(self, identifiers: Any = None, **kwargs) -> Iterator[Any]:
1093
+ """Lazy ensemble iterator over FluxVacuaFinder instances.
1094
+
1095
+ Yields one FluxVacuaFinder at a time without retaining prior models.
1096
+ **Intended for cluster runs and million-model scans** where holding
1097
+ the full batch in RAM is prohibitive — each yielded instance is
1098
+ constructed fresh from shard data, and the previous instance becomes
1099
+ eligible for GC once the user moves on. No filter caching (unlike
1100
+ `load_model_batch`); re-iterating the same filter set rebuilds every
1101
+ FluxVacuaFinder from scratch. Shard-level caching (the LRU on
1102
+ CYDatabase) still applies, so re-iteration is cheaper than a cold
1103
+ run.
1104
+
1105
+ Accepts either a pre-built `identifiers` (DataFrame / list), or catalog
1106
+ filter kwargs (e.g. ``h11=3, has_conifolds=True``) — matching the
1107
+ ergonomics of ``load_batch``. ``iter_batch``-specific kwargs
1108
+ (``include_gv``, ``include_conifolds``, ``maximum_degree`` …) are
1109
+ forwarded to the underlying :meth:`iter_batch`.
1110
+
1111
+ Use `load_model_batch` instead if the batch fits in memory and you
1112
+ want cached O(1) re-access via ``db.cached_models``.
1113
+ """
1114
+ from jaxvacua.flux_vacua_finder import FluxVacuaFinder
1115
+ iter_kw = {k: kwargs.pop(k) for k in list(kwargs) if k in self._ITER_BATCH_KWARGS}
1116
+ if identifiers is None:
1117
+ if not kwargs:
1118
+ raise ValueError(
1119
+ "iter_model_batch requires either `identifiers` or catalog filter kwargs"
1120
+ )
1121
+ identifiers = self.query(**kwargs)
1122
+ elif kwargs:
1123
+ raise TypeError(
1124
+ f"iter_model_batch got unexpected kwargs with identifiers already given: {list(kwargs)}"
1125
+ )
1126
+ for tree in self.iter_batch(identifiers, **iter_kw):
1127
+ yield FluxVacuaFinder(lcs_tree_input=tree)
1128
+
1129
+ @property
1130
+ def cached_models(self) -> Optional[List[Any]]:
1131
+ """The FluxVacuaFinder batch most recently produced by
1132
+ ``load_model_batch``, or ``None`` if ``load_model_batch`` has never
1133
+ been called (or was just cleared). Read-only; identical to the list
1134
+ returned by the most recent ``load_model_batch(**filters)`` call.
1135
+ """
1136
+ return self._cached_models
1137
+
1138
+ def clear_cached_models(self) -> None:
1139
+ """Drop the cached model batch (releases the FluxVacuaFinder list)."""
1140
+ self._cached_models = None
1141
+ self._cached_filter_key = None
1142
+
1143
+ # ------------------------------------------------------------------
1144
+ # Vacua delegation — forwards to a lazily-built VacuaWriter(self).
1145
+ # Method names match the originals on CYDatabase.
1146
+ # ------------------------------------------------------------------
1147
+
1148
+ @property
1149
+ def _vw(self) -> "VacuaWriter":
1150
+ vw = self.__dict__.get("_vw_cached")
1151
+ if vw is None:
1152
+ vw = VacuaWriter(self)
1153
+ self.__dict__["_vw_cached"] = vw
1154
+ return vw
1155
+
1156
+ def designate_vacua(self, *args, **kwargs): return self._vw.designate_vacua(*args, **kwargs)
1157
+ def retract_designated(self, *args, **kwargs): return self._vw.retract_designated(*args, **kwargs)
1158
+ def purge_retracted(self, *args, **kwargs): return self._vw.purge_retracted(*args, **kwargs)
1159
+ def query_designated(self, *args, **kwargs): return self._vw.query_designated(*args, **kwargs)
1160
+ def load_designated(self, *args, **kwargs): return self._vw.load_designated(*args, **kwargs)
1161
+ def load_local_vacua(self, *args, **kwargs): return self._vw.load_local_vacua(*args, **kwargs)
1162
+ def push_vacua_to_hub(self, *args, **kwargs): return self._vw.push_vacua_to_hub(*args, **kwargs)
1163
+ def fetch_vacua_from_hub(self, *args, **kwargs):return self._vw.fetch_vacua_from_hub(*args, **kwargs)
1164
+ def list_hub_vacua(self, *args, **kwargs): return self._vw.list_hub_vacua(*args, **kwargs)
1165
+ def validate_vacua(self, *args, **kwargs): return self._vw.validate_vacua(*args, **kwargs)
1166
+ def complete_missing(self, *args, **kwargs): return self._vw.complete_missing(*args, **kwargs)
1167
+ def delete_vacua(self, *args, **kwargs): return self._vw.delete_vacua(*args, **kwargs)
1168
+ def vacua_writer(self, *args, **kwargs): return self._vw.vacua_writer(*args, **kwargs)
1169
+ def designated_info(self, *args, **kwargs): return self._vw.designated_info(*args, **kwargs)
1170
+ def _resolve_vacua_dir(self, *args, **kwargs): return self._vw._resolve_vacua_dir(*args, **kwargs)
1171
+ def query_vacua(self, *args, **kwargs): return self._vw.query_vacua(*args, **kwargs)
1172
+ def load_vacua(self, *args, **kwargs): return self._vw.load_vacua(*args, **kwargs)
1173
+ def solution_exists(self, *args, **kwargs): return self._vw.solution_exists(*args, **kwargs)
1174
+ def find_similar_vacua(self, *args, **kwargs): return self._vw.find_similar_vacua(*args, **kwargs)
1175
+ def vacua_info(self, *args, **kwargs): return self._vw.vacua_info(*args, **kwargs)
1176
+
1177
+
1178
+ # ==========================================================================
1179
+ # Module-level one-shot shortcuts
1180
+ # ==========================================================================
1181
+
1182
+ def load_tdf_model(
1183
+ ks_id: int,
1184
+ triang_id: int,
1185
+ include_gv: bool = False,
1186
+ include_conifolds: Union[bool, str] = False,
1187
+ maximum_degree: Optional[int] = None,
1188
+ cache_dir: str = DEFAULT_CACHE_DIR,
1189
+ ) -> Any:
1190
+ r"""Load a single TDF (toric Kreuzer-Skarke) model as an
1191
+ :class:`~jaxvacua.lcs.lcs_tree` without instantiating a database
1192
+ explicitly. Equivalent to
1193
+ ``LCSDatabase(dataset="tdf", cache_dir=cache_dir).load(ks_id=..., triang_id=..., ...)``.
1194
+ """
1195
+ db = LCSDatabase(dataset="tdf", cache_dir=cache_dir)
1196
+ return db.load(
1197
+ ks_id=ks_id,
1198
+ triang_id=triang_id,
1199
+ include_gv=include_gv,
1200
+ include_conifolds=include_conifolds,
1201
+ maximum_degree=maximum_degree,
1202
+ )
1203
+
1204
+
1205
+ def load_cicy_model(
1206
+ cicy_id: int,
1207
+ include_gv: bool = False,
1208
+ maximum_degree: Optional[int] = None,
1209
+ cache_dir: str = DEFAULT_CACHE_DIR,
1210
+ ) -> Any:
1211
+ r"""Load a single CICY model as an :class:`~jaxvacua.lcs.lcs_tree` without
1212
+ instantiating a database explicitly. Equivalent to
1213
+ ``LCSDatabase(dataset="cicy", cache_dir=cache_dir).load(cicy_id=..., ...)``.
1214
+ """
1215
+ db = LCSDatabase(dataset="cicy", cache_dir=cache_dir)
1216
+ return db.load(
1217
+ cicy_id=cicy_id,
1218
+ include_gv=include_gv,
1219
+ maximum_degree=maximum_degree,
1220
+ )
1221
+
1222
+
1223
+ __all__ = ["LCSDatabase", "load_tdf_model", "load_cicy_model", "_parse_lcs_row"]