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,3079 @@
1
+ # ==============================================================================
2
+ # stringforge / vacua_writer
3
+ #
4
+ # Vacua persistence layer — writes designated vacua to disk, retracts/purges
5
+ # them, uploads and fetches from the community HuggingFace vault, and runs
6
+ # physics validation. The `VacuaWriter` class wraps a `CYDatabase` instance
7
+ # and forwards any attribute not defined locally to the wrapped database via
8
+ # `__getattr__`, so method bodies that read `self.cache_dir`, `self._fetch_*`,
9
+ # `self._catalog`, etc. keep working unchanged.
10
+ #
11
+ # Method names are kept identical to the originals on `CYDatabase` (e.g.
12
+ # `designate_vacua`, `push_vacua_to_hub`). The `LCSDatabase` layer in
13
+ # `lcs_database.py` forwards its own methods of the same names to these.
14
+ #
15
+ # No imports from `lcs_tree` / `flux_eft` / `flux_vacua_finder` at module
16
+ # load — any physics dependency is imported lazily inside the method that
17
+ # needs it.
18
+ # ==============================================================================
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import threading
27
+ import uuid
28
+ import warnings
29
+ from collections import OrderedDict, deque
30
+ from concurrent.futures import ThreadPoolExecutor, as_completed
31
+ from contextlib import contextmanager
32
+ from importlib.metadata import PackageNotFoundError, version
33
+ from pathlib import Path
34
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
35
+
36
+ import numpy as np
37
+
38
+ # The vacua layer depends on the pure-I/O layer for constants, exceptions and
39
+ # helpers (all of which live in stringforge.cy_io after the 2026-04-30 split).
40
+ # We re-import the ones the method bodies reference.
41
+ from .cy_io import (
42
+ SCHEMA_VERSION,
43
+ SchemaVersionError,
44
+ ValidationError,
45
+ _decode_array,
46
+ _require_pandas,
47
+ _require_pyarrow,
48
+ _require_hf_hub,
49
+ _require_hf_api,
50
+ _safe_concat,
51
+ _resolve_vault_repo,
52
+ _resolve_vault_dir,
53
+ VAULT_DIRNAME,
54
+ DEFAULT_VAULT_REPO,
55
+ HF_REPO_ID,
56
+ )
57
+
58
+
59
+ @contextmanager
60
+ def _file_lock(path: Path):
61
+ r"""
62
+ **Description:**
63
+ Advisory exclusive lock on a sibling ``.lock`` file. Used to
64
+ serialise multi-process appends to the designated-vacua catalog so
65
+ that concurrent ``designate_vacua`` calls do not allocate
66
+ overlapping ``designated_id`` ranges.
67
+
68
+ Falls back to a no-op on platforms without :mod:`fcntl` (Windows).
69
+ """
70
+ try:
71
+ import fcntl
72
+ except ImportError:
73
+ yield
74
+ return
75
+ lock_path = path.with_suffix(path.suffix + ".lock")
76
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
77
+ fh = open(lock_path, "a+")
78
+ try:
79
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
80
+ yield
81
+ finally:
82
+ try:
83
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
84
+ finally:
85
+ fh.close()
86
+
87
+
88
+ def _compute_model_hash(tree: Any) -> str:
89
+ r"""
90
+ **Description:**
91
+ Compute a deterministic SHA-256 hash of the geometric fingerprint of an
92
+ ``lcs_tree``. The fingerprint consists of ``(h11, h12, chi, intnums_coo,
93
+ c2)`` — the minimal set of invariants that uniquely identify the geometry.
94
+
95
+ Args:
96
+ tree: An ``lcs_tree`` instance (or any object exposing ``h11``,
97
+ ``h12``, ``chi``, ``intnums_coo``, ``c2`` attributes).
98
+
99
+ Returns:
100
+ str: Hex-encoded SHA-256 hash string.
101
+ """
102
+ h = hashlib.sha256()
103
+ h.update(f"h11={tree.h11}".encode())
104
+ h.update(f"h12={tree.h12}".encode())
105
+ h.update(f"chi={tree.chi}".encode())
106
+ if tree.intnums_coo is not None:
107
+ h.update(np.asarray(tree.intnums_coo).tobytes())
108
+ if tree.c2 is not None:
109
+ h.update(np.asarray(tree.c2).tobytes())
110
+ return h.hexdigest()
111
+
112
+
113
+ def _extract_model_identity(
114
+ model: Any = None,
115
+ h11: Optional[int] = None,
116
+ h12: Optional[int] = None,
117
+ ks_id: Optional[int] = None,
118
+ triang_id: Optional[int] = None,
119
+ conifold_id: int = -1,
120
+ cicy_id: Optional[int] = None,
121
+ model_name: Optional[str] = None,
122
+ ) -> Dict[str, Any]:
123
+ r"""
124
+ **Description:**
125
+ Extract or assemble model identity fields. If *model* is provided
126
+ (a ``FluxVacuaFinder``, ``FluxEFT``, or ``lcs_tree``), identity is read
127
+ from the tree; explicit keyword arguments override.
128
+
129
+ Returns:
130
+ Dict with keys ``h11``, ``h12``, ``ks_id``, ``triang_id``,
131
+ ``conifold_id``, ``cicy_id``, ``model_hash``, ``model_name``.
132
+ """
133
+ tree = None
134
+ if model is not None:
135
+ # Accept JAXVacua model objects (with .periods.lcs_tree) or lcs_tree.
136
+ tree = getattr(getattr(model, "periods", None), "lcs_tree", model)
137
+
138
+ _h11 = h11 if h11 is not None else (getattr(tree, "h11", None) if tree else None)
139
+ _h12 = h12 if h12 is not None else (getattr(tree, "h12", None) if tree else None)
140
+
141
+ # Try to get ks_id/triang_id from tree.extra_data
142
+ _extra = getattr(tree, "extra_data", None) or {}
143
+ _ks = ks_id if ks_id is not None else _extra.get("ks_id", -1)
144
+ _tr = triang_id if triang_id is not None else _extra.get("triang_id", -1)
145
+ _cid = cicy_id if cicy_id is not None else _extra.get("cicy_id", -1)
146
+
147
+ # conifold_id: check tree.limit and conifold metadata
148
+ _cf = conifold_id
149
+ if _cf == -1 and tree is not None:
150
+ limit = getattr(tree, "limit", None)
151
+ if limit is not None and "coni" in str(limit).lower():
152
+ _cf = _extra.get("conifold_id", 0)
153
+
154
+ _hash = _compute_model_hash(tree) if tree is not None else ""
155
+ _name = model_name
156
+
157
+ # For local models loaded via model_ID, auto-generate a model_name
158
+ # so they are human-readable in queries.
159
+ if _name is None and _ks == -1 and tree is not None:
160
+ _mid = getattr(tree, "model_ID", None)
161
+ if _mid is not None:
162
+ _name = f"local_h12_{_h12}_ID_{_mid}"
163
+
164
+ if _h11 is None or _h12 is None:
165
+ raise ValueError(
166
+ "Cannot determine h11/h12. Pass them explicitly or provide a model."
167
+ )
168
+
169
+ return {
170
+ "h11": int(_h11),
171
+ "h12": int(_h12),
172
+ "ks_id": int(_ks),
173
+ "triang_id": int(_tr),
174
+ "conifold_id": int(_cf),
175
+ "cicy_id": int(_cid),
176
+ "model_hash": _hash,
177
+ "model_name": _name,
178
+ }
179
+
180
+
181
+ # Catalog columns that are *run-level* and should not be smeared
182
+ # onto every loaded row. ``n_vacua`` is a count of the run, not a
183
+ # per-row property; ``file_path`` is internal provenance.
184
+ _RUN_FIELDS_SKIP_ON_LOAD: frozenset[str] = frozenset({"n_vacua", "file_path"})
185
+
186
+
187
+ def _propagate_run_fields(df: Any, run_row: Any) -> Any:
188
+ r"""
189
+ **Description:**
190
+ Copy the run-level fields from a vacua-catalog row onto every row
191
+ of a freshly-loaded vacua DataFrame. Lets callers do
192
+ ``df.groupby("method")``, ``df.query("created > '2026-04-01'")``,
193
+ or ``df["model_hash"]`` without re-joining against the catalog.
194
+
195
+ Skips columns in :data:`_RUN_FIELDS_SKIP_ON_LOAD` (``n_vacua`` and
196
+ ``file_path``) and leaves existing columns on ``df`` untouched.
197
+
198
+ Args:
199
+ df: A pandas DataFrame as just loaded from a run's parquet.
200
+ run_row: The matching catalog row (a pandas Series).
201
+
202
+ Returns:
203
+ The same DataFrame (mutated in place); also returned for
204
+ chaining.
205
+ """
206
+ for col in run_row.index:
207
+ if col in _RUN_FIELDS_SKIP_ON_LOAD:
208
+ continue
209
+ if col not in df.columns:
210
+ df[col] = run_row[col]
211
+ return df
212
+
213
+
214
+ def _synthesize_complex_columns(df: Any) -> Any:
215
+ r"""
216
+ **Description:**
217
+ Add convenience complex-valued ``moduli`` and ``tau`` columns to a
218
+ freshly-loaded vacua DataFrame, derived from the stored
219
+ ``moduli_re`` / ``moduli_im`` and ``tau_re`` / ``tau_im`` float
220
+ columns.
221
+
222
+ The on-disk parquet keeps real and imaginary parts as separate
223
+ columns (parquet has no native complex dtype, and ``moduli`` is a
224
+ variable-length vector per row). Synthesising the complex form
225
+ on read lets callers write the natural ``df["moduli"]`` /
226
+ ``df["tau"]`` patterns. Existing complex columns (e.g. on a
227
+ re-load) are left untouched.
228
+
229
+ Args:
230
+ df: A pandas DataFrame as just loaded from a run's parquet.
231
+
232
+ Returns:
233
+ The same DataFrame (mutated in place); also returned for
234
+ chaining.
235
+ """
236
+ if ("moduli" not in df.columns
237
+ and "moduli_re" in df.columns and "moduli_im" in df.columns):
238
+ df["moduli"] = [
239
+ np.asarray(re, dtype=np.float64) + 1j * np.asarray(im, dtype=np.float64)
240
+ for re, im in zip(df["moduli_re"], df["moduli_im"])
241
+ ]
242
+ if ("tau" not in df.columns
243
+ and "tau_re" in df.columns and "tau_im" in df.columns):
244
+ df["tau"] = df["tau_re"].astype(np.float64) + 1j * df["tau_im"].astype(np.float64)
245
+ return df
246
+
247
+
248
+ def _vacua_row_from_dict(
249
+ result: dict,
250
+ vacuum_id: int,
251
+ tags: Optional[Any] = None,
252
+ extra_data: Optional[dict] = None,
253
+ ) -> dict:
254
+ r"""
255
+ Normalise a single result dict (as returned by ``enumerate_fluxes`` or
256
+ ``sample_bounded_fluxes``) into a flat row matching the vacua parquet
257
+ schema.
258
+
259
+ Args:
260
+ result: Dict with keys ``"flux"``, ``"moduli"``, ``"tau"``, and
261
+ optionally ``"residual"``, ``"is_susy"``, ``"N_flux"``, ``"W"``,
262
+ ``"F_terms"``.
263
+ vacuum_id: 0-based index within the run.
264
+ tags: String or list of strings.
265
+ extra_data: Optional dict of arbitrary metadata.
266
+
267
+ Returns:
268
+ dict: Flat row dict ready for DataFrame construction.
269
+ """
270
+ flux = np.asarray(result["flux"], dtype=np.int32)
271
+ moduli = np.asarray(result["moduli"], dtype=np.complex128)
272
+ tau = complex(result["tau"])
273
+
274
+ # Normalise tags
275
+ if tags is None:
276
+ tags_json = "[]"
277
+ elif isinstance(tags, str):
278
+ tags_json = json.dumps([tags])
279
+ else:
280
+ tags_json = json.dumps(list(tags))
281
+
282
+ row = {
283
+ "vacuum_id": vacuum_id,
284
+ "flux": flux.tolist(),
285
+ "moduli_re": moduli.real.tolist(),
286
+ "moduli_im": moduli.imag.tolist(),
287
+ "tau_re": tau.real,
288
+ "tau_im": tau.imag,
289
+ "W_re": None,
290
+ "W_im": None,
291
+ "F_terms_re": None,
292
+ "F_terms_im": None,
293
+ "N_flux": result.get("N_flux"),
294
+ "residual": result.get("residual"),
295
+ "is_susy": result.get("is_susy", False),
296
+ "tags": tags_json,
297
+ "extra_data": json.dumps(extra_data) if extra_data else None,
298
+ "timestamp": datetime.datetime.now(datetime.timezone.utc),
299
+ }
300
+
301
+ # Optional pre-computed derived quantities
302
+ W = result.get("W")
303
+ if W is not None:
304
+ W = complex(W)
305
+ row["W_re"] = W.real
306
+ row["W_im"] = W.imag
307
+
308
+ F = result.get("F_terms")
309
+ if F is not None:
310
+ F = np.asarray(F, dtype=np.complex128)
311
+ row["F_terms_re"] = F.real.tolist()
312
+ row["F_terms_im"] = F.imag.tolist()
313
+
314
+ return row
315
+
316
+
317
+ def _vacua_rows_from_batch(
318
+ moduli: Any,
319
+ tau: Any,
320
+ fluxes: Any,
321
+ tags: Optional[Any] = None,
322
+ id_offset: int = 0,
323
+ **extra_fields: Any,
324
+ ) -> List[dict]:
325
+ r"""
326
+ **Description:**
327
+ Convert batched arrays (as returned by ``initial_guesses_ISD``) into a
328
+ list of row dicts matching the vacua parquet schema.
329
+
330
+ Args:
331
+ moduli: Array shape ``(N, h12)``, complex.
332
+ tau: Array shape ``(N,)``, complex.
333
+ fluxes: Array shape ``(N, 2*n_fluxes)``, int.
334
+ tags: String or list of strings applied to all rows.
335
+ id_offset: Starting vacuum_id.
336
+ **extra_fields: Additional per-vacuum arrays of length N (e.g.
337
+ ``residual``, ``N_flux``).
338
+
339
+ Returns:
340
+ List[dict]: One row dict per vacuum.
341
+ """
342
+ moduli_np = np.asarray(moduli, dtype=np.complex128)
343
+ tau_np = np.asarray(tau, dtype=np.complex128)
344
+ fluxes_np = np.asarray(fluxes, dtype=np.int32)
345
+ N = len(fluxes_np)
346
+
347
+ # Normalise tags once
348
+ if tags is None:
349
+ tags_json = "[]"
350
+ elif isinstance(tags, str):
351
+ tags_json = json.dumps([tags])
352
+ else:
353
+ tags_json = json.dumps(list(tags))
354
+
355
+ rows = []
356
+ for i in range(N):
357
+ row = {
358
+ "vacuum_id": id_offset + i,
359
+ "flux": fluxes_np[i].tolist(),
360
+ "moduli_re": moduli_np[i].real.tolist(),
361
+ "moduli_im": moduli_np[i].imag.tolist(),
362
+ "tau_re": float(tau_np[i].real),
363
+ "tau_im": float(tau_np[i].imag),
364
+ "W_re": None,
365
+ "W_im": None,
366
+ "F_terms_re": None,
367
+ "F_terms_im": None,
368
+ "N_flux": float(extra_fields["N_flux"][i]) if "N_flux" in extra_fields else None,
369
+ "residual": float(extra_fields["residual"][i]) if "residual" in extra_fields else None,
370
+ "is_susy": bool(extra_fields["is_susy"][i]) if "is_susy" in extra_fields else False,
371
+ "tags": tags_json,
372
+ "extra_data": None,
373
+ "timestamp": datetime.datetime.now(datetime.timezone.utc),
374
+ }
375
+ rows.append(row)
376
+ return rows
377
+
378
+
379
+ def _is_missing(v: Any) -> bool:
380
+ r"""True if a DataFrame cell is absent (``None`` / ``NaN``). List- and
381
+ array-valued cells (``flux``, ``F_terms_*``, ``mass2``) always count as
382
+ present (``pd.isna`` on them is ambiguous)."""
383
+ if v is None:
384
+ return True
385
+ try:
386
+ res = _require_pandas().isna(v)
387
+ except (ValueError, TypeError):
388
+ return False
389
+ return bool(res) if np.ndim(res) == 0 else False
390
+
391
+
392
+ def _mass2_from_matrix(MM: Any) -> list:
393
+ r"""Sorted (ascending) real mass-squared spectrum from the canonically
394
+ normalised mass matrix. For a valid vacuum the matrix is Hermitian, so the
395
+ eigenvalues are real; the real part is taken to drop numerical noise."""
396
+ return [float(x) for x in np.sort(np.linalg.eigvals(np.asarray(MM)).real)]
397
+
398
+
399
+ def _masses_one(model: Any, z: Any, t: complex, fl: Any, W: Any = None):
400
+ r"""``(mass2, m_gravitino)`` for a single vacuum, or ``(None, None)`` if the
401
+ model call fails. Kept separate so the loop and the vmap path share the
402
+ same mass computation (the eigendecomposition runs on the host)."""
403
+ try:
404
+ zc = np.conj(z); tc = np.conj(t)
405
+ mass2 = _mass2_from_matrix(model.mass_matrix(
406
+ z, zc, t, tc, fl, mode=None, noscale=True))
407
+ KP = float(np.real(model.kahler_potential(z, zc, t, tc)))
408
+ if W is None:
409
+ W = complex(model.superpotential(z, t, fl))
410
+ return mass2, float(np.exp(KP / 2.0) * abs(W))
411
+ except Exception:
412
+ return None, None
413
+
414
+
415
+ def _derived_loop(model: Any, moduli: list, tau: list, flux: list,
416
+ with_masses: bool):
417
+ r"""Per-row evaluation of ``W``, ``DW``, ``N_flux`` and (optionally) the
418
+ mass spectrum + gravitino mass. Returns five length-``n`` lists; a row
419
+ whose model call raises is left as ``None`` in every output. This is the
420
+ default path -- it re-uses the model's own cached ``jit``, so it is fast
421
+ and is the only path that works for non-jax models."""
422
+ n = len(moduli)
423
+ W = [None] * n; DW = [None] * n; Nflux = [None] * n
424
+ mass2 = [None] * n; mgrav = [None] * n
425
+ for i in range(n):
426
+ try:
427
+ z = moduli[i]; t = complex(tau[i]); fl = np.asarray(flux[i])
428
+ zc = np.conj(z); tc = np.conj(t)
429
+ Nflux[i] = float(np.real(model.tadpole(fl)))
430
+ W[i] = complex(model.superpotential(z, t, fl))
431
+ DW[i] = np.asarray(model.DW(z, zc, t, tc, fl), dtype=np.complex128)
432
+ except Exception:
433
+ continue
434
+ if with_masses:
435
+ mass2[i], mgrav[i] = _masses_one(model, z, t, fl, W[i])
436
+ return W, DW, Nflux, mass2, mgrav
437
+
438
+
439
+ def _derived_vmap(model: Any, moduli: list, tau: list, flux: list,
440
+ vmap_dim: int, with_masses: bool):
441
+ r"""Vectorised evaluation of ``W`` / ``DW`` / ``N_flux``: a single
442
+ ``jax.jit(jax.vmap(...))`` kernel computes them for a whole batch on the
443
+ accelerator. Batches are padded to a constant ``vmap_dim`` so the kernel
444
+ compiles once and is re-used, amortising the compilation over a large
445
+ table; a batch that raises (e.g. a non-jax model) falls back to
446
+ :func:`_derived_loop`.
447
+
448
+ The mass spectrum + gravitino mass are computed per row (the
449
+ eigendecomposition stays on the host). ``vmap_dim`` is opt-in: it pays off
450
+ only for large tables, since for small ones the per-row loop already re-uses
451
+ the model's cached ``jit``."""
452
+ import jax
453
+ import jax.numpy as jnp
454
+
455
+ n = len(moduli)
456
+ Zall = jnp.asarray(np.stack([np.asarray(z) for z in moduli]))
457
+ Tall = jnp.asarray(np.asarray(tau, dtype=np.complex128))
458
+ Fall = jnp.asarray(np.stack([np.asarray(f) for f in flux]))
459
+
460
+ def _cheap(z, t, fl):
461
+ zc = jnp.conj(z); tc = jnp.conj(t)
462
+ return (model.superpotential(z, t, fl),
463
+ model.DW(z, zc, t, tc, fl),
464
+ jnp.real(model.tadpole(fl)))
465
+
466
+ fn = jax.jit(jax.vmap(_cheap))
467
+
468
+ W = [None] * n; DW = [None] * n; Nflux = [None] * n
469
+ mass2 = [None] * n; mgrav = [None] * n
470
+ bs = max(1, int(vmap_dim))
471
+ for s in range(0, n, bs):
472
+ e = min(s + bs, n)
473
+ zb, tb, fb = Zall[s:e], Tall[s:e], Fall[s:e]
474
+ pad = bs - (e - s)
475
+ if pad: # pad to a constant batch size so the kernel compiles once
476
+ zb = jnp.concatenate([zb, jnp.broadcast_to(zb[-1:], (pad,) + zb.shape[1:])], 0)
477
+ tb = jnp.concatenate([tb, jnp.broadcast_to(tb[-1:], (pad,))], 0)
478
+ fb = jnp.concatenate([fb, jnp.broadcast_to(fb[-1:], (pad,) + fb.shape[1:])], 0)
479
+ try:
480
+ Wb, DWb, Nfb = fn(zb, tb, fb)
481
+ Wb = np.asarray(Wb); DWb = np.asarray(DWb); Nfb = np.asarray(Nfb).real
482
+ for j in range(e - s):
483
+ idx = s + j
484
+ W[idx] = complex(Wb[j]); DW[idx] = DWb[j]; Nflux[idx] = float(Nfb[j])
485
+ except Exception:
486
+ wB, dB, nB, _, _ = _derived_loop(
487
+ model, moduli[s:e], tau[s:e], flux[s:e], False)
488
+ W[s:e], DW[s:e], Nflux[s:e] = wB, dB, nB
489
+
490
+ if with_masses: # per row (eigendecomposition on the host)
491
+ for i in range(n):
492
+ if W[i] is None:
493
+ continue
494
+ z = moduli[i]; t = complex(tau[i]); fl = np.asarray(flux[i])
495
+ mass2[i], mgrav[i] = _masses_one(model, z, t, fl, W[i])
496
+ return W, DW, Nflux, mass2, mgrav
497
+
498
+
499
+ def _compute_derived(
500
+ df: Any,
501
+ model: Any,
502
+ fill_missing_only: bool = False,
503
+ with_masses: bool = False,
504
+ vmap_dim: Optional[int] = None,
505
+ enrich: bool = False,
506
+ ) -> Any:
507
+ r"""
508
+ **Description:**
509
+ Complete a per-vacuum table: starting from *df* (all input columns are
510
+ preserved), fill in the derived quantities computed from *model* and --
511
+ when *enrich* is set -- back-fill the standard identity / convenience
512
+ columns, so the result carries the same schema as :meth:`query_vacua` /
513
+ :meth:`load_vacua` with every column populated.
514
+
515
+ Derived physics: superpotential ``W_re``/``W_im``, F-terms
516
+ ``F_terms_re``/``F_terms_im``, tadpole ``N_flux``, ``is_susy``, the string
517
+ coupling ``g_s`` (:math:`= 1/\mathrm{Im}\,\tau`), and -- when *with_masses*
518
+ -- the scalar mass spectrum ``mass2`` and the gravitino mass
519
+ ``m_gravitino``. Backfilled columns: the complex ``moduli`` / ``tau``
520
+ convenience columns and the model-identity columns ``h11``, ``h12``,
521
+ ``ks_id``, ``triang_id``, ``conifold_id``, ``cicy_id``, ``model_hash``,
522
+ ``model_name`` (constant for a given *model*).
523
+
524
+ The mass spectrum ``mass2`` is the sorted list of real eigenvalues of the
525
+ canonically-normalised mass matrix of the **no-scale** scalar potential
526
+ (:func:`FluxEFT.mass_matrix` with ``mode=None, noscale=True``);
527
+ sign-carrying (negative entries are tachyonic). ``m_gravitino`` is
528
+ :math:`m_{3/2}=e^{K/2}|W|`.
529
+
530
+ .. warning::
531
+ ``mass2`` and ``m_gravitino`` are in the **FluxEFT no-scale
532
+ normalisation, NOT in** :math:`M_\mathrm{Pl}`. The FluxEFT Kähler
533
+ potential :math:`K=-\log[-i(\tau-\bar\tau)]-\log\mathcal{A}(z,\bar z)`
534
+ omits the :math:`-2\log\mathcal{V}_E` term, because the overall CY
535
+ (Einstein-frame) volume :math:`\mathcal{V}_E` -- a function of the
536
+ Kähler moduli -- is not stabilised at this level. The physical values
537
+ therefore carry an unfixed overall volume factor,
538
+ :math:`m^2_\mathrm{phys}=\mathcal{V}_E^{-2}\times` ``mass2`` and
539
+ :math:`m_{3/2,\mathrm{phys}}=\mathcal{V}_E^{-1}\times`
540
+ ``m_gravitino``. Only the **ratio** :math:`m/m_{3/2}` (in which
541
+ :math:`\mathcal{V}_E` cancels) is volume-independent and physical.
542
+
543
+ Args:
544
+ df: DataFrame with at least ``flux``, ``moduli_re``,
545
+ ``moduli_im``, ``tau_re``, ``tau_im``. Tables without those
546
+ columns (e.g. a run-level catalog) are returned unchanged.
547
+ model: A JAXVacua ``FluxEFT`` / ``FluxVacuaFinder`` model.
548
+ fill_missing_only (bool): if ``True``, only populate cells that are
549
+ currently ``None`` / ``NaN`` (idempotent autocomplete); existing
550
+ values are left untouched. If ``False`` (default), ``W``, the
551
+ F-terms and ``is_susy`` are recomputed unconditionally.
552
+ with_masses (bool): if ``True``, also compute ``mass2`` and
553
+ ``m_gravitino``. Off by default because the mass matrix costs an
554
+ :math:`O((h^{1,2}+1)^3)` eigendecomposition per row.
555
+ vmap_dim (int | None): if set, evaluate ``W`` / ``DW`` / ``N_flux``
556
+ (and the masses) with :func:`jax.vmap` in batches of this many
557
+ rows instead of a Python loop -- much faster for large tables.
558
+ ``None`` (default) keeps the per-row path (also the only path that
559
+ works for non-jax models).
560
+ enrich (bool): if ``True``, also add the complex ``moduli`` / ``tau``
561
+ columns and back-fill the model-identity columns (``h11``,
562
+ ``h12``, ``ks_id``, ...). Off by default because those complex
563
+ columns cannot be serialised to parquet; :meth:`complete_missing`
564
+ sets it for in-memory completion.
565
+
566
+ Returns:
567
+ pandas.DataFrame: *df* with the derived + backfilled columns populated.
568
+ """
569
+ pd = _require_pandas()
570
+ out = df.copy()
571
+ n = len(out)
572
+ if n == 0:
573
+ return out
574
+
575
+ # Per-vacuum inputs. If absent (e.g. a run-level catalog without a
576
+ # ``flux`` column) there is nothing to complete -- return df unchanged.
577
+ try:
578
+ moduli = [np.asarray(out["moduli_re"].iloc[i], dtype=float)
579
+ + 1j * np.asarray(out["moduli_im"].iloc[i], dtype=float)
580
+ for i in range(n)]
581
+ tau = [complex(out["tau_re"].iloc[i]) + 1j * complex(out["tau_im"].iloc[i])
582
+ for i in range(n)]
583
+ flux = [np.asarray(out["flux"].iloc[i]) for i in range(n)]
584
+ except (KeyError, TypeError, ValueError):
585
+ return out
586
+
587
+ def _fill(col: str, values: list) -> None:
588
+ """Assign *values* (length n, positional) into *col*, honouring
589
+ fill_missing_only. Scalar columns keep their natural (numeric) dtype;
590
+ list-valued columns (F_terms, mass2) are stored as object so pandas
591
+ does not try to broadcast them."""
592
+ if fill_missing_only and col in out.columns:
593
+ cur = list(out[col])
594
+ values = [values[i] if _is_missing(cur[i]) else cur[i]
595
+ for i in range(n)]
596
+ listlike = any(isinstance(v, (list, tuple, np.ndarray)) for v in values)
597
+ out[col] = pd.Series(values, index=out.index,
598
+ dtype=object if listlike else None)
599
+
600
+ # Identity + convenience-column back-fill (``enrich``). Off by default
601
+ # because the complex ``moduli`` / ``tau`` columns cannot be serialised to
602
+ # parquet -- this path is only for in-memory results (``complete_missing``).
603
+ # query_vacua / load_vacua already carry these columns, so a written shard
604
+ # never needs them.
605
+ if enrich:
606
+ # Convenience complex columns (parity with query_vacua / load_vacua).
607
+ if "moduli" not in out.columns:
608
+ out["moduli"] = pd.Series(moduli, index=out.index, dtype=object)
609
+ if "tau" not in out.columns:
610
+ out["tau"] = pd.Series(tau, index=out.index, dtype=object)
611
+
612
+ # Model-identity columns (constant per model; skipped if the model has
613
+ # no extractable identity, e.g. a bare test stub).
614
+ try:
615
+ ident = _extract_model_identity(model=model)
616
+ except Exception:
617
+ ident = {}
618
+ for k in ("h11", "h12", "ks_id", "triang_id", "conifold_id",
619
+ "cicy_id", "model_hash", "model_name"):
620
+ if k not in ident:
621
+ continue
622
+ if k not in out.columns:
623
+ out[k] = ident[k]
624
+ elif fill_missing_only:
625
+ cur = list(out[k])
626
+ out[k] = [cur[i] if not _is_missing(cur[i]) else ident[k]
627
+ for i in range(n)]
628
+
629
+ # String coupling g_s = 1 / Im(tau).
630
+ _fill("g_s", [(1.0 / float(np.imag(tau[i])))
631
+ if np.imag(tau[i]) != 0.0 else None for i in range(n)])
632
+
633
+ # Physics: vmapped batches or per-row.
634
+ if vmap_dim:
635
+ W, DW, Nflux, mass2, mgrav = _derived_vmap(
636
+ model, moduli, tau, flux, int(vmap_dim), with_masses)
637
+ else:
638
+ W, DW, Nflux, mass2, mgrav = _derived_loop(
639
+ model, moduli, tau, flux, with_masses)
640
+
641
+ _fill("N_flux", [None if x is None else float(x) for x in Nflux])
642
+ _fill("W_re", [None if w is None else float(np.real(w)) for w in W])
643
+ _fill("W_im", [None if w is None else float(np.imag(w)) for w in W])
644
+ _fill("F_terms_re",
645
+ [None if d is None else np.asarray(d).real.tolist() for d in DW])
646
+ _fill("F_terms_im",
647
+ [None if d is None else np.asarray(d).imag.tolist() for d in DW])
648
+ _fill("is_susy",
649
+ [None if d is None else bool(np.max(np.abs(np.asarray(d))) < 1e-6)
650
+ for d in DW])
651
+ if with_masses:
652
+ _fill("mass2", mass2)
653
+ _fill("m_gravitino", [None if x is None else float(x) for x in mgrav])
654
+ return out
655
+
656
+
657
+ class _VacuaStreamWriter:
658
+ r"""
659
+ Context manager for buffered writing of vacuum solutions to local parquet
660
+ storage. Intended to be created via :meth:`CYDatabase.vacua_writer`.
661
+
662
+ Usage::
663
+
664
+ with db.vacua_writer(model=my_model) as writer:
665
+ for result in results:
666
+ writer.append(result, tags=["PFV"])
667
+ # flushes to disk on __exit__
668
+
669
+ Args:
670
+ vacua_dir (Path): Root directory for vacua storage.
671
+ identity (dict): Model identity fields (h11, h12, ks_id, ...).
672
+ run_id (str): UUID of this run.
673
+ method (str): Sampling method label.
674
+ metadata (dict | None): Arbitrary run-level metadata (JSON-serialisable).
675
+ model: Optional JAXVacua model for derived-quantity computation.
676
+ compute_derived (bool): If True and *model* is set, compute W, DW,
677
+ N_flux at flush time.
678
+ filter_fn: Optional callable ``result_dict → bool``.
679
+ deduplicate (bool): If True, skip flux vectors already stored for
680
+ this model.
681
+ map_to_fd (bool): If True and *model* has ``map_to_FD``, map each
682
+ vacuum to the fundamental domain before storing and deduplicating.
683
+ """
684
+
685
+ def __init__(
686
+ self,
687
+ vacua_dir: Path,
688
+ identity: Dict[str, Any],
689
+ run_id: str,
690
+ method: str = "manual",
691
+ metadata: Optional[dict] = None,
692
+ model: Any = None,
693
+ compute_derived: bool = False,
694
+ filter_fn: Any = None,
695
+ deduplicate: bool = True,
696
+ map_to_fd: bool = False,
697
+ ) -> None:
698
+ """Initialise the vacua writer for a given model identity and run."""
699
+ self._vacua_dir = vacua_dir
700
+ self._identity = identity
701
+ self._run_id = run_id
702
+ self._method = method
703
+ self._metadata = metadata
704
+ self._model = model
705
+ self._compute_derived = compute_derived
706
+ self._filter_fn = filter_fn
707
+ self._deduplicate = deduplicate
708
+ self._map_to_fd = map_to_fd and model is not None and hasattr(model, 'map_to_FD')
709
+
710
+ self._buffer: List[dict] = []
711
+ self._flushed_count: int = 0
712
+ self._n_duplicates_skipped: int = 0
713
+ self._seen_fluxes: set = set()
714
+
715
+ # Determine output path
716
+ h11 = identity["h11"]
717
+ h12 = identity["h12"]
718
+ ks = identity["ks_id"]
719
+ tr = identity["triang_id"]
720
+ if ks >= 0 and tr >= 0:
721
+ self._run_dir = (
722
+ vacua_dir / f"h11_{h11}_h12_{h12}_ksid_{ks}" / f"triang_{tr}"
723
+ )
724
+ else:
725
+ mhash = identity["model_hash"]
726
+ self._run_dir = vacua_dir / "custom" / mhash
727
+ self._run_path = self._run_dir / f"run_{self._run_id}.parquet"
728
+
729
+ def __enter__(self) -> "_VacuaStreamWriter":
730
+ """Enter context manager, loading existing fluxes if deduplicating."""
731
+ if self._deduplicate:
732
+ self._load_existing_fluxes()
733
+ return self
734
+
735
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
736
+ """Exit context manager, flushing buffered rows and updating the catalog."""
737
+ if self._buffer:
738
+ self.flush()
739
+ # Update catalog regardless (even if 0 new vacua, to record the run)
740
+ if self._flushed_count > 0:
741
+ self._update_catalog()
742
+
743
+ # ------------------------------------------------------------------
744
+ # Public API
745
+ # ------------------------------------------------------------------
746
+
747
+ def append(
748
+ self,
749
+ result: Any,
750
+ tags: Optional[Any] = None,
751
+ extra_data: Optional[dict] = None,
752
+ ) -> None:
753
+ r"""
754
+ **Description:**
755
+ Append a single vacuum solution.
756
+
757
+ Args:
758
+ result: Either a dict ``{"flux", "moduli", "tau", ...}`` (as
759
+ returned by ``enumerate_fluxes``) or a tuple
760
+ ``(moduli, tau, flux)``.
761
+ tags: String or list of tag strings.
762
+ extra_data: Optional dict of arbitrary per-vacuum metadata.
763
+ """
764
+ if isinstance(result, (tuple, list)) and not isinstance(result, dict):
765
+ moduli, tau, flux = result
766
+ result = {"moduli": moduli, "tau": tau, "flux": flux}
767
+
768
+ # Map to fundamental domain (monodromy + SL(2,Z))
769
+ if self._map_to_fd:
770
+ import jax.numpy as jnp
771
+ moduli_fd, tau_fd, fluxes_fd = self._model.map_to_FD(
772
+ jnp.asarray(result["moduli"]),
773
+ complex(result["tau"]),
774
+ jnp.asarray(result["flux"]),
775
+ )
776
+ result = {**result, "moduli": moduli_fd, "tau": tau_fd, "flux": fluxes_fd}
777
+
778
+ # Filter
779
+ if self._filter_fn is not None and not self._filter_fn(result):
780
+ return
781
+
782
+ # Dedup
783
+ if self._deduplicate:
784
+ flux_key = tuple(int(x) for x in np.asarray(result["flux"]))
785
+ if flux_key in self._seen_fluxes:
786
+ self._n_duplicates_skipped += 1
787
+ return
788
+ self._seen_fluxes.add(flux_key)
789
+
790
+ vid = self._flushed_count + len(self._buffer)
791
+ self._buffer.append(_vacua_row_from_dict(result, vid, tags, extra_data))
792
+
793
+ def append_batch(
794
+ self,
795
+ moduli: Any,
796
+ tau: Any,
797
+ fluxes: Any,
798
+ tags: Optional[Any] = None,
799
+ **extra_fields: Any,
800
+ ) -> None:
801
+ r"""
802
+ **Description:**
803
+ Append a batch of vacuum solutions from array data.
804
+
805
+ Args:
806
+ moduli: Array shape ``(N, h12)``, complex.
807
+ tau: Array shape ``(N,)``, complex.
808
+ fluxes: Array shape ``(N, 2*n_fluxes)``, int.
809
+ tags: String or list applied to all rows.
810
+ **extra_fields: Per-vacuum arrays of length N (``residual``,
811
+ ``N_flux``, ``is_susy``).
812
+ """
813
+ # Strip any zero-magnitude imaginary part on the input fluxes
814
+ # (JAX → numpy roundoff on the upstream solver) before casting
815
+ # to int32; assert it's negligible so we never silently round
816
+ # away a meaningful complex value.
817
+ fluxes_arr = np.asarray(fluxes)
818
+ if np.iscomplexobj(fluxes_arr):
819
+ max_im = float(np.max(np.abs(fluxes_arr.imag)))
820
+ assert max_im < 1e-9, (
821
+ f"fluxes have non-negligible imaginary part "
822
+ f"(max |imag|={max_im:.3e}) — should be a real integer "
823
+ f"array."
824
+ )
825
+ fluxes_arr = fluxes_arr.real
826
+ fluxes_np = np.asarray(fluxes_arr, dtype=np.int32)
827
+ moduli_np = np.asarray(moduli, dtype=np.complex128)
828
+ tau_np = np.asarray(tau, dtype=np.complex128)
829
+ N = len(fluxes_np)
830
+
831
+ # Map to fundamental domain (monodromy + SL(2,Z))
832
+ if self._map_to_fd:
833
+ import jax.numpy as jnp
834
+ for i in range(N):
835
+ m_fd, t_fd, f_fd = self._model.map_to_FD(
836
+ jnp.asarray(moduli_np[i]),
837
+ complex(tau_np[i]),
838
+ jnp.asarray(fluxes_np[i]),
839
+ )
840
+ moduli_np[i] = np.asarray(m_fd)
841
+ tau_np[i] = complex(t_fd)
842
+ fluxes_np[i] = np.asarray(f_fd, dtype=np.int32)
843
+
844
+ # Build keep mask for dedup + filter
845
+ keep = np.ones(N, dtype=bool)
846
+ if self._deduplicate:
847
+ for i in range(N):
848
+ flux_key = tuple(int(x) for x in fluxes_np[i])
849
+ if flux_key in self._seen_fluxes:
850
+ keep[i] = False
851
+ self._n_duplicates_skipped += 1
852
+ else:
853
+ self._seen_fluxes.add(flux_key)
854
+
855
+ if self._filter_fn is not None:
856
+ for i in range(N):
857
+ if keep[i]:
858
+ r = {"flux": fluxes_np[i], "moduli": moduli_np[i], "tau": tau_np[i]}
859
+ if not self._filter_fn(r):
860
+ keep[i] = False
861
+
862
+ # Subset arrays
863
+ idx = np.where(keep)[0]
864
+ if len(idx) == 0:
865
+ return
866
+
867
+ sub_moduli = moduli_np[idx]
868
+ sub_tau = tau_np[idx]
869
+ sub_fluxes = fluxes_np[idx]
870
+ sub_extra = {
871
+ k: np.asarray(v)[idx]
872
+ for k, v in extra_fields.items()
873
+ }
874
+
875
+ vid_offset = self._flushed_count + len(self._buffer)
876
+ rows = _vacua_rows_from_batch(
877
+ sub_moduli, sub_tau, sub_fluxes,
878
+ tags=tags, id_offset=vid_offset, **sub_extra,
879
+ )
880
+ self._buffer.extend(rows)
881
+
882
+ def flush(self) -> None:
883
+ r"""Write buffered rows to the run parquet file."""
884
+ if not self._buffer:
885
+ return
886
+
887
+ pd = _require_pandas()
888
+ df = pd.DataFrame(self._buffer)
889
+
890
+ # Optional derived-quantity computation
891
+ if self._compute_derived and self._model is not None:
892
+ df = self._compute_derived_quantities(df)
893
+
894
+ # Write (append to existing file if present from prior flush)
895
+ self._run_dir.mkdir(parents=True, exist_ok=True)
896
+ if self._run_path.exists():
897
+ existing = pd.read_parquet(self._run_path)
898
+ df = _safe_concat([existing, df], ignore_index=True)
899
+ df.to_parquet(self._run_path, index=False)
900
+
901
+ self._flushed_count += len(self._buffer)
902
+ self._buffer.clear()
903
+
904
+ @property
905
+ def count(self) -> int:
906
+ r"""Total number of vacua accepted (buffered + flushed)."""
907
+ return self._flushed_count + len(self._buffer)
908
+
909
+ @property
910
+ def n_duplicates_skipped(self) -> int:
911
+ r"""Number of duplicate flux vectors skipped."""
912
+ return self._n_duplicates_skipped
913
+
914
+ @property
915
+ def run_id(self) -> str:
916
+ r"""UUID of this run (matches the ``run_id`` column on every
917
+ appended row). Use this to query back the written rows via
918
+ :meth:`VacuaWriter.query_vacua(run_id=writer.run_id)`."""
919
+ return self._run_id
920
+
921
+ # ------------------------------------------------------------------
922
+ # Private helpers
923
+ # ------------------------------------------------------------------
924
+
925
+ def _load_existing_fluxes(self) -> None:
926
+ r"""Load all flux vectors from prior runs for this model into the
927
+ dedup set."""
928
+ pd = _require_pandas()
929
+ if not self._run_dir.exists():
930
+ return
931
+ for f in self._run_dir.glob("run_*.parquet"):
932
+ try:
933
+ df = pd.read_parquet(f, columns=["flux"])
934
+ for flux_list in df["flux"]:
935
+ self._seen_fluxes.add(tuple(int(x) for x in flux_list))
936
+ except Exception:
937
+ pass # skip corrupt files
938
+
939
+ def _update_catalog(self) -> None:
940
+ r"""Append this run to the vacua catalog."""
941
+ pd = _require_pandas()
942
+ catalog_path = self._vacua_dir / "vacua_catalog.parquet"
943
+
944
+ new_row = {
945
+ "run_id": self._run_id,
946
+ "h11": self._identity["h11"],
947
+ "h12": self._identity["h12"],
948
+ "ks_id": self._identity["ks_id"],
949
+ "triang_id": self._identity["triang_id"],
950
+ "conifold_id": self._identity["conifold_id"],
951
+ "cicy_id": self._identity["cicy_id"],
952
+ "model_hash": self._identity["model_hash"],
953
+ "model_name": self._identity["model_name"],
954
+ "n_vacua": self._flushed_count,
955
+ "method": self._method,
956
+ "created": datetime.datetime.now(datetime.timezone.utc),
957
+ "metadata": json.dumps(self._metadata) if self._metadata else None,
958
+ "file_path": str(self._run_path.relative_to(self._vacua_dir)),
959
+ }
960
+
961
+ self._vacua_dir.mkdir(parents=True, exist_ok=True)
962
+ if catalog_path.exists():
963
+ existing = pd.read_parquet(catalog_path)
964
+ catalog = _safe_concat([existing, pd.DataFrame([new_row])], ignore_index=True)
965
+ else:
966
+ catalog = pd.DataFrame([new_row])
967
+ catalog.to_parquet(catalog_path, index=False)
968
+
969
+ def _compute_derived_quantities(self, df: Any) -> Any:
970
+ r"""Compute W, DW, N_flux (and ``g_s``) for all rows in *df* using
971
+ ``self._model``. Thin wrapper around the module-level
972
+ :func:`_compute_derived` (masses are not computed at session-flush
973
+ time -- they are added on designation / via
974
+ :meth:`VacuaWriter.complete_missing`)."""
975
+ return _compute_derived(df, self._model)
976
+
977
+
978
+
979
+ class VacuaWriter:
980
+ """Vacua persistence / HuggingFace-upload handler.
981
+
982
+ Wraps a :class:`stringforge.cy_io.CYDatabase` (or any subclass) and delegates
983
+ all data-access calls — catalog reads, shard fetches, path resolution — to
984
+ the wrapped instance via :meth:`__getattr__`. This keeps the extracted
985
+ method bodies untouched from their original `CYDatabase` form.
986
+
987
+ Construct with ``VacuaWriter(db)`` where ``db`` is an instance of
988
+ :class:`stringforge.cy_io.CYDatabase` (or any class implementing the same
989
+ I/O surface — e.g. :class:`stringforge.lcs_database.LCSDatabase`).
990
+ """
991
+
992
+ # Attribute names that live on the VacuaWriter itself rather than being
993
+ # forwarded to the wrapped database.
994
+ _VW_OWN_ATTRS = frozenset({"db", "_vault_dir_override"})
995
+
996
+ def __init__(self, db, *, vault_dir: Optional[Path] = None):
997
+ object.__setattr__(self, "db", db)
998
+ object.__setattr__(self, "_vault_dir_override", Path(vault_dir) if vault_dir is not None else None)
999
+
1000
+ # ----- Attribute proxy -------------------------------------------------
1001
+ # Method bodies were copied verbatim from CYDatabase, so they use `self.X`
1002
+ # for attributes that actually belong to the wrapped database (the shard
1003
+ # cache, schema state, per-model vault subdir, etc.). Both __getattr__
1004
+ # *and* __setattr__ forward to self.db so reads and writes land on the
1005
+ # same object — otherwise state set on the VacuaWriter would shadow but
1006
+ # never update the db, and methods like _ensure_designated_catalog(self)
1007
+ # (which dispatches on db) would never see the update.
1008
+ def __getattr__(self, name: str):
1009
+ if name.startswith("__") and name.endswith("__"):
1010
+ raise AttributeError(name)
1011
+ return getattr(self.db, name)
1012
+
1013
+ def __setattr__(self, name: str, value) -> None:
1014
+ if name in self._VW_OWN_ATTRS:
1015
+ object.__setattr__(self, name, value)
1016
+ else:
1017
+ setattr(self.db, name, value)
1018
+
1019
+ # ------------------------------------------------------------------
1020
+ # Vault-path resolution. Moved here from CYDatabase because it depends
1021
+ # on `_extract_model_identity`, which reads `lcs_tree` attributes and
1022
+ # therefore cannot live in the pure-I/O layer.
1023
+ # ------------------------------------------------------------------
1024
+ def _resolve_vacua_dir(self, model: Any = None, **identity_kwargs: Any) -> Path:
1025
+ r"""Return the per-model subdirectory inside the vault for designated
1026
+ vacua belonging to *model*.
1027
+
1028
+ Path layout:
1029
+
1030
+ - Local KS models (bundled; loaded via ``(h12, model_ID)``) →
1031
+ ``<vault>/KS/h12_{h12}_model_{model_ID}/``.
1032
+ - HF-downloaded TDF models →
1033
+ ``<vault>/tdf/h11_{h11}_h12_{h12}/ks_{ks_id}_tri_{triang_id}/``.
1034
+ - HF-downloaded CICY models → ``<vault>/cicy/cicy_{cicy_id}/``.
1035
+ - Fallback (custom model) → ``<vault>/custom/{model_hash}/``.
1036
+ """
1037
+ vault = _resolve_vault_dir()
1038
+ ident = _extract_model_identity(model=model, **identity_kwargs)
1039
+
1040
+ ks = ident.get("ks_id", -1)
1041
+ tr = ident.get("triang_id", -1)
1042
+ cicy_id = ident.get("cicy_id", -1)
1043
+ h11 = ident.get("h11")
1044
+ h12 = ident.get("h12")
1045
+ name = ident.get("model_name") or ""
1046
+ mhash = ident.get("model_hash") or ""
1047
+
1048
+ if ks >= 0 and tr >= 0:
1049
+ return (
1050
+ vault
1051
+ / "tdf"
1052
+ / f"h11_{h11}_h12_{h12}"
1053
+ / f"ks_{ks}_tri_{tr}"
1054
+ )
1055
+ if cicy_id >= 0:
1056
+ return vault / "cicy" / f"cicy_{cicy_id}"
1057
+
1058
+ model_ID = None
1059
+ if name.startswith("local_h12_") and "_ID_" in name:
1060
+ try:
1061
+ model_ID = int(name.split("_ID_")[-1])
1062
+ except ValueError:
1063
+ model_ID = None
1064
+
1065
+ if h12 is not None and model_ID is not None:
1066
+ return vault / "KS" / f"h12_{h12}_model_{model_ID}"
1067
+
1068
+ return vault / "custom" / (mhash or "unknown")
1069
+
1070
+ def vacua_writer(
1071
+ self,
1072
+ model: Any = None,
1073
+ h11: Optional[int] = None,
1074
+ h12: Optional[int] = None,
1075
+ ks_id: Optional[int] = None,
1076
+ triang_id: Optional[int] = None,
1077
+ conifold_id: int = -1,
1078
+ cicy_id: Optional[int] = None,
1079
+ model_name: Optional[str] = None,
1080
+ run_id: Optional[str] = None,
1081
+ method: str = "manual",
1082
+ compute_derived: bool = False,
1083
+ filter_fn: Any = None,
1084
+ deduplicate: bool = True,
1085
+ map_to_fd: bool = False,
1086
+ metadata: Optional[dict] = None,
1087
+ tags: Optional[list] = None,
1088
+ ) -> "_VacuaStreamWriter":
1089
+ r"""
1090
+ **Description:**
1091
+ Return a context manager for writing vacuum solutions to local
1092
+ parquet storage.
1093
+
1094
+ Identity fields (``h11``, ``h12``, ``ks_id``, ``triang_id``,
1095
+ ``conifold_id``) are extracted from *model* when available; explicit
1096
+ keyword arguments override. For custom models (no database entry),
1097
+ set ``model_name`` for human-readable identification.
1098
+
1099
+ Args:
1100
+ model: A JAXVacua model or ``lcs_tree`` instance. Used both
1101
+ for identity extraction and (if *compute_derived* is True)
1102
+ for computing W, DW, N_flux.
1103
+ h11 (int | None): Override :math:`h^{1,1}`.
1104
+ h12 (int | None): Override :math:`h^{1,2}`.
1105
+ ks_id (int | None): Override Kreuzer-Skarke polytope index.
1106
+ triang_id (int | None): Override triangulation index.
1107
+ conifold_id (int): Conifold index (-1 for LCS).
1108
+ cicy_id (int | None): Override CICY index.
1109
+ model_name (str | None): Human-readable label for custom models.
1110
+ run_id (str | None): UUID for this run. Auto-generated if None.
1111
+ method (str): Sampling method label. Defaults to ``"manual"``.
1112
+ compute_derived (bool): Compute W, DW, N_flux at flush time.
1113
+ filter_fn: Optional callable ``result_dict → bool``.
1114
+ deduplicate (bool): Skip duplicate flux vectors. Defaults to
1115
+ ``True``.
1116
+ map_to_fd (bool): If True and *model* has ``map_to_FD``, map each
1117
+ vacuum to the fundamental domain (SL(2,Z) for tau, monodromy
1118
+ for z) before storing and deduplicating. Defaults to ``False``.
1119
+ metadata (dict | None): Arbitrary JSON-serialisable run metadata.
1120
+ tags (list | None): Searchable tags folded into *metadata* under
1121
+ the ``"tags"`` key. Accepted so callers that pass ``tags=``
1122
+ (e.g. :func:`jaxvacua.flux_bounding.bounded_fluxes.merge_cluster_results`)
1123
+ don't raise ``TypeError``.
1124
+
1125
+ Returns:
1126
+ _VacuaStreamWriter: A context manager. Use with ``with`` statement.
1127
+
1128
+ Example::
1129
+
1130
+ with db.vacua_writer(model=my_model, method="enumerate") as w:
1131
+ for result in results:
1132
+ w.append(result, tags=["PFV"])
1133
+ print(f"Stored {w.count} vacua, skipped {w.n_duplicates_skipped}")
1134
+ """
1135
+ self._check_cache_size()
1136
+ identity = _extract_model_identity(
1137
+ model=model, h11=h11, h12=h12, ks_id=ks_id,
1138
+ triang_id=triang_id, conifold_id=conifold_id,
1139
+ cicy_id=cicy_id, model_name=model_name,
1140
+ )
1141
+ _run_id = run_id or str(uuid.uuid4())
1142
+
1143
+ # Fold `tags` into metadata so we don't need to thread an extra
1144
+ # kwarg through _VacuaStreamWriter.
1145
+ if tags is not None:
1146
+ metadata = dict(metadata) if metadata else {}
1147
+ metadata.setdefault("tags", list(tags))
1148
+
1149
+ return _VacuaStreamWriter(
1150
+ vacua_dir=self._vacua_dir,
1151
+ identity=identity,
1152
+ run_id=_run_id,
1153
+ method=method,
1154
+ metadata=metadata,
1155
+ model=model,
1156
+ compute_derived=compute_derived,
1157
+ filter_fn=filter_fn,
1158
+ deduplicate=deduplicate,
1159
+ map_to_fd=map_to_fd,
1160
+ )
1161
+ def query_vacua(
1162
+ self,
1163
+ h11: Optional[int] = None,
1164
+ h12: Optional[int] = None,
1165
+ ks_id: Optional[int] = None,
1166
+ triang_id: Optional[int] = None,
1167
+ conifold_id: Optional[int] = None,
1168
+ cicy_id: Optional[int] = None,
1169
+ model_hash: Optional[str] = None,
1170
+ run_id: Optional[str] = None,
1171
+ is_susy: Optional[bool] = None,
1172
+ N_flux_max: Optional[float] = None,
1173
+ tags: Optional[Any] = None,
1174
+ method: Optional[str] = None,
1175
+ limit: Optional[int] = None,
1176
+ ) -> Any:
1177
+ r"""
1178
+ **Description:**
1179
+ Query stored vacua and return matching rows as a ``pandas.DataFrame``.
1180
+
1181
+ Filtering proceeds in two stages:
1182
+
1183
+ 1. **Catalog stage** — filter ``vacua_catalog.parquet`` by model
1184
+ identity and run-level fields (fast, in-memory).
1185
+ 2. **Data stage** — for matching runs, load parquet files and apply
1186
+ row-level filters (``is_susy``, ``N_flux_max``, ``tags``).
1187
+
1188
+ Args:
1189
+ h11, h12, ks_id, triang_id, conifold_id, cicy_id: Model identity
1190
+ filters (exact match).
1191
+ model_hash (str | None): Filter by geometric fingerprint hash.
1192
+ run_id (str | None): Filter by run UUID.
1193
+ is_susy (bool | None): Filter by SUSY flag.
1194
+ N_flux_max (float | None): Maximum tadpole value.
1195
+ tags: String or list of strings. Rows must contain **all**
1196
+ specified tags.
1197
+ method (str | None): Filter by sampling method.
1198
+ limit (int | None): Maximum number of rows to return.
1199
+
1200
+ Returns:
1201
+ pandas.DataFrame: Matching vacuum rows with ``run_id`` column
1202
+ injected.
1203
+ """
1204
+ pd = _require_pandas()
1205
+ self._ensure_vacua_catalog()
1206
+ cat = self._vacua_catalog
1207
+ if cat is None or len(cat) == 0:
1208
+ return pd.DataFrame()
1209
+
1210
+ # Stage 1: catalog-level filters
1211
+ mask = np.ones(len(cat), dtype=bool)
1212
+ if h11 is not None:
1213
+ mask &= (cat["h11"] == h11).values
1214
+ if h12 is not None:
1215
+ mask &= (cat["h12"] == h12).values
1216
+ if ks_id is not None:
1217
+ mask &= (cat["ks_id"] == ks_id).values
1218
+ if triang_id is not None:
1219
+ mask &= (cat["triang_id"] == triang_id).values
1220
+ if conifold_id is not None:
1221
+ mask &= (cat["conifold_id"] == conifold_id).values
1222
+ if cicy_id is not None:
1223
+ mask &= (cat["cicy_id"] == cicy_id).values
1224
+ if model_hash is not None:
1225
+ mask &= (cat["model_hash"] == model_hash).values
1226
+ if run_id is not None:
1227
+ mask &= (cat["run_id"] == run_id).values
1228
+ if method is not None:
1229
+ mask &= (cat["method"] == method).values
1230
+
1231
+ matching = cat[mask]
1232
+ if len(matching) == 0:
1233
+ return pd.DataFrame()
1234
+
1235
+ # Stage 2: load and filter data files
1236
+ frames = []
1237
+ for _, run_row in matching.iterrows():
1238
+ path = self._vacua_dir / run_row["file_path"]
1239
+ if not path.exists():
1240
+ continue
1241
+ df = pd.read_parquet(path)
1242
+ # Propagate run-level catalog fields onto each row, then
1243
+ # synthesise convenience complex columns.
1244
+ df = _propagate_run_fields(df, run_row)
1245
+ df = _synthesize_complex_columns(df)
1246
+
1247
+ if is_susy is not None and "is_susy" in df.columns:
1248
+ df = df[df["is_susy"] == is_susy]
1249
+ if N_flux_max is not None and "N_flux" in df.columns:
1250
+ df = df[df["N_flux"].notna() & (df["N_flux"] <= N_flux_max)]
1251
+ if tags is not None:
1252
+ if isinstance(tags, str):
1253
+ tags = [tags]
1254
+ def _has_all_tags(tags_json, required=tags):
1255
+ """Check whether tags_json contains all required tags."""
1256
+ try:
1257
+ stored = json.loads(tags_json) if isinstance(tags_json, str) else []
1258
+ except (json.JSONDecodeError, TypeError):
1259
+ stored = []
1260
+ return all(t in stored for t in required)
1261
+ if "tags" in df.columns:
1262
+ df = df[df["tags"].apply(_has_all_tags)]
1263
+
1264
+ frames.append(df)
1265
+
1266
+ if not frames:
1267
+ return pd.DataFrame()
1268
+ result = _safe_concat(frames, ignore_index=True)
1269
+ if limit is not None:
1270
+ result = result.head(limit)
1271
+ return result
1272
+ def load_vacua(self, run_id: str) -> Any:
1273
+ r"""
1274
+ **Description:**
1275
+ Load all vacuum solutions from a specific run.
1276
+
1277
+ Args:
1278
+ run_id (str): UUID of the run.
1279
+
1280
+ Returns:
1281
+ pandas.DataFrame: All rows from the run's parquet file.
1282
+
1283
+ Raises:
1284
+ KeyError: If the run is not found in the catalog.
1285
+ """
1286
+ pd = _require_pandas()
1287
+ self._ensure_vacua_catalog()
1288
+ cat = self._vacua_catalog
1289
+ if cat is None or len(cat) == 0:
1290
+ raise KeyError(f"Run '{run_id}' not found — vacua catalog is empty.")
1291
+ matches = cat[cat["run_id"] == run_id]
1292
+ if len(matches) == 0:
1293
+ raise KeyError(f"Run '{run_id}' not found in vacua catalog.")
1294
+ row = matches.iloc[0]
1295
+ path = self._vacua_dir / row["file_path"]
1296
+ if not path.exists():
1297
+ raise FileNotFoundError(f"Run file not found: {path}")
1298
+ df = pd.read_parquet(path)
1299
+ df = _propagate_run_fields(df, row)
1300
+ df = _synthesize_complex_columns(df)
1301
+ return df
1302
+ def solution_exists(
1303
+ self,
1304
+ flux: Any,
1305
+ h11: Optional[int] = None,
1306
+ h12: Optional[int] = None,
1307
+ ks_id: Optional[int] = None,
1308
+ triang_id: Optional[int] = None,
1309
+ model: Any = None,
1310
+ ) -> bool:
1311
+ r"""
1312
+ **Description:**
1313
+ Check whether a vacuum with the given flux vector is already stored
1314
+ for this model. Uses exact integer comparison.
1315
+
1316
+ Args:
1317
+ flux: Integer array of length ``2 * n_fluxes``.
1318
+ h11, h12, ks_id, triang_id: Model identity (used to filter runs).
1319
+ model: Alternative — extract identity from a JAXVacua model or
1320
+ ``lcs_tree``.
1321
+
1322
+ Returns:
1323
+ bool: True if the flux vector is found in any stored run.
1324
+ """
1325
+ pd = _require_pandas()
1326
+ identity = _extract_model_identity(
1327
+ model=model, h11=h11, h12=h12, ks_id=ks_id, triang_id=triang_id,
1328
+ )
1329
+ flux_key = tuple(int(x) for x in np.asarray(flux))
1330
+
1331
+ self._ensure_vacua_catalog()
1332
+ cat = self._vacua_catalog
1333
+ if cat is None or len(cat) == 0:
1334
+ return False
1335
+
1336
+ # Filter catalog to this model
1337
+ mask = np.ones(len(cat), dtype=bool)
1338
+ if identity["ks_id"] >= 0:
1339
+ mask &= (cat["ks_id"] == identity["ks_id"]).values
1340
+ mask &= (cat["triang_id"] == identity["triang_id"]).values
1341
+ if "h11" in cat.columns:
1342
+ mask &= (cat["h11"] == identity["h11"]).values
1343
+ elif identity["model_hash"]:
1344
+ mask &= (cat["model_hash"] == identity["model_hash"]).values
1345
+
1346
+ for _, run_row in cat[mask].iterrows():
1347
+ path = self._vacua_dir / run_row["file_path"]
1348
+ if not path.exists():
1349
+ continue
1350
+ df = pd.read_parquet(path, columns=["flux"])
1351
+ for stored_flux in df["flux"]:
1352
+ if tuple(int(x) for x in stored_flux) == flux_key:
1353
+ return True
1354
+ return False
1355
+ def find_similar_vacua(
1356
+ self,
1357
+ moduli: Any = None,
1358
+ tau: Any = None,
1359
+ flux: Any = None,
1360
+ h11: Optional[int] = None,
1361
+ h12: Optional[int] = None,
1362
+ ks_id: Optional[int] = None,
1363
+ triang_id: Optional[int] = None,
1364
+ model: Any = None,
1365
+ flux_tol: int = 0,
1366
+ moduli_tol: float = 1e-6,
1367
+ tau_tol: float = 1e-6,
1368
+ ) -> Any:
1369
+ r"""
1370
+ **Description:**
1371
+ Find stored vacua that are similar to the given point within
1372
+ specified tolerances.
1373
+
1374
+ Args:
1375
+ moduli: Complex array of length h12 (optional).
1376
+ tau: Complex scalar (optional).
1377
+ flux: Integer array (optional). Compared with L∞ tolerance.
1378
+ h11, h12, ks_id, triang_id: Model identity filters.
1379
+ model: Alternative — extract identity from a model object.
1380
+ flux_tol (int): L∞ tolerance on flux vector (0 = exact match).
1381
+ moduli_tol (float): Relative tolerance on moduli.
1382
+ tau_tol (float): Relative tolerance on tau.
1383
+
1384
+ Returns:
1385
+ pandas.DataFrame: Matching vacuum rows.
1386
+ """
1387
+ pd = _require_pandas()
1388
+ identity = _extract_model_identity(
1389
+ model=model, h11=h11, h12=h12, ks_id=ks_id, triang_id=triang_id,
1390
+ )
1391
+
1392
+ self._ensure_vacua_catalog()
1393
+ cat = self._vacua_catalog
1394
+ if cat is None or len(cat) == 0:
1395
+ return pd.DataFrame()
1396
+
1397
+ # Filter catalog to this model
1398
+ mask = np.ones(len(cat), dtype=bool)
1399
+ if identity["ks_id"] >= 0:
1400
+ mask &= (cat["ks_id"] == identity["ks_id"]).values
1401
+ mask &= (cat["triang_id"] == identity["triang_id"]).values
1402
+ if "h11" in cat.columns:
1403
+ mask &= (cat["h11"] == identity["h11"]).values
1404
+ elif identity["model_hash"]:
1405
+ mask &= (cat["model_hash"] == identity["model_hash"]).values
1406
+
1407
+ matching_runs = cat[mask]
1408
+ if len(matching_runs) == 0:
1409
+ return pd.DataFrame()
1410
+
1411
+ # Prepare query values
1412
+ flux_q = np.asarray(flux, dtype=np.int32) if flux is not None else None
1413
+ moduli_q = np.asarray(moduli, dtype=np.complex128) if moduli is not None else None
1414
+ tau_q = complex(tau) if tau is not None else None
1415
+
1416
+ frames = []
1417
+ for _, run_row in matching_runs.iterrows():
1418
+ path = self._vacua_dir / run_row["file_path"]
1419
+ if not path.exists():
1420
+ continue
1421
+ df = pd.read_parquet(path)
1422
+ keep = np.ones(len(df), dtype=bool)
1423
+
1424
+ if flux_q is not None and "flux" in df.columns:
1425
+ for i, stored in enumerate(df["flux"]):
1426
+ stored_arr = np.array(stored, dtype=np.int32)
1427
+ if np.max(np.abs(stored_arr - flux_q)) > flux_tol:
1428
+ keep[i] = False
1429
+
1430
+ if moduli_q is not None and "moduli_re" in df.columns:
1431
+ for i in range(len(df)):
1432
+ if not keep[i]:
1433
+ continue
1434
+ stored_z = (
1435
+ np.array(df.iloc[i]["moduli_re"])
1436
+ + 1j * np.array(df.iloc[i]["moduli_im"])
1437
+ )
1438
+ denom = np.abs(stored_z)
1439
+ denom = np.where(denom > 0, denom, 1.0)
1440
+ if np.max(np.abs(stored_z - moduli_q) / denom) > moduli_tol:
1441
+ keep[i] = False
1442
+
1443
+ if tau_q is not None and "tau_re" in df.columns:
1444
+ for i in range(len(df)):
1445
+ if not keep[i]:
1446
+ continue
1447
+ stored_tau = df.iloc[i]["tau_re"] + 1j * df.iloc[i]["tau_im"]
1448
+ denom = abs(stored_tau) if abs(stored_tau) > 0 else 1.0
1449
+ if abs(stored_tau - tau_q) / denom > tau_tol:
1450
+ keep[i] = False
1451
+
1452
+ df = df[keep]
1453
+ if len(df) > 0:
1454
+ df = _propagate_run_fields(df, run_row)
1455
+ df = _synthesize_complex_columns(df)
1456
+ frames.append(df)
1457
+
1458
+ if not frames:
1459
+ return pd.DataFrame()
1460
+ return _safe_concat(frames, ignore_index=True)
1461
+ def vacua_info(self) -> None:
1462
+ r"""
1463
+ **Description:**
1464
+ Print a summary of stored vacua.
1465
+ """
1466
+ self._ensure_vacua_catalog()
1467
+ cat = self._vacua_catalog
1468
+ if cat is None or len(cat) == 0:
1469
+ print("No vacua stored.")
1470
+ return
1471
+
1472
+ n_runs = len(cat)
1473
+ n_vacua = int(cat["n_vacua"].sum())
1474
+ n_models = len(cat.groupby(["ks_id", "triang_id", "model_hash"]))
1475
+ methods = cat["method"].value_counts().to_dict()
1476
+
1477
+ print(f"Vacua storage: {n_vacua} vacua across {n_runs} run(s), "
1478
+ f"{n_models} distinct model(s)")
1479
+ if methods:
1480
+ print(f" Methods: {methods}")
1481
+
1482
+ # Show per-model summary
1483
+ groups = cat.groupby(["h11", "ks_id", "triang_id"]).agg(
1484
+ n_runs=("run_id", "count"),
1485
+ n_vacua=("n_vacua", "sum"),
1486
+ ).reset_index()
1487
+ if len(groups) <= 20:
1488
+ print(f"\n{'h11':>4} {'ks_id':>6} {'trid':>5} {'runs':>5} {'vacua':>7}")
1489
+ for _, g in groups.iterrows():
1490
+ print(f"{g['h11']:4d} {g['ks_id']:6d} {g['triang_id']:5d} "
1491
+ f"{g['n_runs']:5d} {g['n_vacua']:7d}")
1492
+ else:
1493
+ print(f" (showing {len(groups)} models — use query_vacua() for details)")
1494
+ def delete_vacua(
1495
+ self,
1496
+ run_id: Optional[str] = None,
1497
+ ks_id: Optional[int] = None,
1498
+ triang_id: Optional[int] = None,
1499
+ ) -> int:
1500
+ r"""
1501
+ **Description:**
1502
+ Delete stored vacua matching the given filter.
1503
+
1504
+ Args:
1505
+ run_id (str | None): Delete a specific run.
1506
+ ks_id (int | None): Delete all runs for this model.
1507
+ triang_id (int | None): Narrow by triangulation (with ks_id).
1508
+
1509
+ Returns:
1510
+ int: Number of runs deleted.
1511
+ """
1512
+ pd = _require_pandas()
1513
+ self._ensure_vacua_catalog()
1514
+ cat = self._vacua_catalog
1515
+ if cat is None or len(cat) == 0:
1516
+ return 0
1517
+
1518
+ mask = np.ones(len(cat), dtype=bool)
1519
+ if run_id is not None:
1520
+ mask &= (cat["run_id"] == run_id).values
1521
+ if ks_id is not None:
1522
+ mask &= (cat["ks_id"] == ks_id).values
1523
+ if triang_id is not None:
1524
+ mask &= (cat["triang_id"] == triang_id).values
1525
+
1526
+ to_delete = cat[mask]
1527
+ n_deleted = 0
1528
+ for _, row in to_delete.iterrows():
1529
+ path = self._vacua_dir / row["file_path"]
1530
+ if path.exists():
1531
+ path.unlink()
1532
+ n_deleted += 1
1533
+
1534
+ # Update catalog
1535
+ self._vacua_catalog = cat[~mask].reset_index(drop=True)
1536
+ catalog_path = self._vacua_dir / "vacua_catalog.parquet"
1537
+ if len(self._vacua_catalog) > 0:
1538
+ self._vacua_catalog.to_parquet(catalog_path, index=False)
1539
+ elif catalog_path.exists():
1540
+ catalog_path.unlink()
1541
+
1542
+ return n_deleted
1543
+ def validate_vacua(
1544
+ self,
1545
+ vacua_df: Any,
1546
+ model: Any = None,
1547
+ F_term_tol: float = 1e-8,
1548
+ check_tadpole: bool = True,
1549
+ check_physics: bool = True,
1550
+ check_duplicates: bool = True,
1551
+ identity: Optional[Dict[str, Any]] = None,
1552
+ ) -> List[dict]:
1553
+ r"""
1554
+ **Description:**
1555
+ Validate vacuum solutions before designation. Each solution is
1556
+ checked for schema conformance, deduplication against already
1557
+ designated solutions, and (optionally) physics consistency.
1558
+
1559
+ Can be called standalone or is invoked automatically inside
1560
+ :meth:`designate_vacua`.
1561
+
1562
+ Args:
1563
+ vacua_df: ``pandas.DataFrame`` of vacuum rows (as returned by
1564
+ :meth:`query_vacua`).
1565
+ model: Optional JAXVacua model for physics re-verification.
1566
+ When provided, F-terms and tadpole are recomputed from the
1567
+ stored flux and moduli vectors.
1568
+ F_term_tol (float): Maximum allowed ``|F_i|`` for a solution to
1569
+ pass the physics check. Defaults to ``1e-8``.
1570
+ check_tadpole (bool): Verify ``N_flux ≤ D3_tadpole``.
1571
+ check_physics (bool): Recompute F-terms from stored data
1572
+ (requires *model*).
1573
+ check_duplicates (bool): Check flux vectors against existing
1574
+ designated solutions.
1575
+ identity (dict | None): Optional model identity used to scope
1576
+ duplicate checks. When provided, a flux vector only counts
1577
+ as duplicate if it is already designated for the same model.
1578
+
1579
+ Returns:
1580
+ List[dict]: One report entry per row with keys ``"index"``,
1581
+ ``"passed"`` (bool), and ``"errors"`` (list of strings).
1582
+ """
1583
+ pd = _require_pandas()
1584
+ report: List[dict] = []
1585
+
1586
+ # Required columns
1587
+ required = {"flux", "moduli_re", "moduli_im", "tau_re", "tau_im"}
1588
+
1589
+ # Load existing designated catalog for dedup
1590
+ existing_fluxes: set = set()
1591
+ if check_duplicates:
1592
+ self._ensure_designated_catalog()
1593
+ dcat = self._designated_catalog
1594
+ if (
1595
+ identity is not None
1596
+ and dcat is not None
1597
+ and len(dcat) > 0
1598
+ ):
1599
+ mask = np.ones(len(dcat), dtype=bool)
1600
+ for key in (
1601
+ "h11", "h12", "ks_id", "triang_id",
1602
+ "conifold_id", "cicy_id", "model_hash", "model_name",
1603
+ ):
1604
+ if key not in dcat.columns or key not in identity:
1605
+ continue
1606
+ value = identity.get(key)
1607
+ if value is None or value == "":
1608
+ continue
1609
+ mask &= (dcat[key] == value).values
1610
+ dcat = dcat[mask]
1611
+ if dcat is not None and len(dcat) > 0 and "flux" in dcat.columns:
1612
+ for fl in dcat["flux"]:
1613
+ existing_fluxes.add(tuple(int(x) for x in fl))
1614
+
1615
+ for idx in range(len(vacua_df)):
1616
+ row = vacua_df.iloc[idx]
1617
+ errors: List[str] = []
1618
+
1619
+ # Schema check
1620
+ for col in required:
1621
+ if col not in vacua_df.columns:
1622
+ errors.append(f"Missing required column: {col}")
1623
+ else:
1624
+ val = row.get(col)
1625
+ if val is None:
1626
+ errors.append(f"Missing required column: {col}")
1627
+ elif not hasattr(val, '__len__') and pd.isna(val):
1628
+ errors.append(f"Missing required column: {col}")
1629
+
1630
+ # Dedup check
1631
+ if check_duplicates and "flux" in vacua_df.columns:
1632
+ try:
1633
+ flux_key = tuple(int(x) for x in row["flux"])
1634
+ if flux_key in existing_fluxes:
1635
+ errors.append("Flux vector already designated")
1636
+ except (TypeError, ValueError):
1637
+ errors.append("Invalid flux vector format")
1638
+
1639
+ # Physics check (requires model)
1640
+ if check_physics and model is not None and not errors:
1641
+ try:
1642
+ flux = np.array(row["flux"], dtype=np.int32)
1643
+ moduli = (np.array(row["moduli_re"])
1644
+ + 1j * np.array(row["moduli_im"]))
1645
+ tau = row["tau_re"] + 1j * row["tau_im"]
1646
+ tau_c = np.conj(tau)
1647
+ moduli_c = np.conj(moduli)
1648
+
1649
+ DW = np.asarray(
1650
+ model.DW(moduli, moduli_c, tau, tau_c, flux),
1651
+ dtype=np.complex128,
1652
+ )
1653
+ max_F = float(np.max(np.abs(DW)))
1654
+ if max_F > F_term_tol:
1655
+ errors.append(
1656
+ f"F-term residual too large: max|F_i| = {max_F:.2e} "
1657
+ f"> {F_term_tol:.0e}"
1658
+ )
1659
+ except Exception as e:
1660
+ errors.append(f"Physics check failed: {e}")
1661
+
1662
+ # Tadpole check
1663
+ if check_tadpole and model is not None and not errors:
1664
+ try:
1665
+ flux = np.array(row["flux"], dtype=np.int32)
1666
+ N = float(model.tadpole(flux))
1667
+ D3 = getattr(model, "D3_tadpole", None)
1668
+ if D3 is not None and N > float(D3):
1669
+ errors.append(
1670
+ f"Tadpole violation: N_flux={N:.1f} > "
1671
+ f"D3_tadpole={float(D3):.1f}"
1672
+ )
1673
+ except Exception as e:
1674
+ errors.append(f"Tadpole check failed: {e}")
1675
+
1676
+ report.append({
1677
+ "index": idx,
1678
+ "passed": len(errors) == 0,
1679
+ "errors": errors,
1680
+ })
1681
+
1682
+ return report
1683
+ def _validate_for_upload(
1684
+ self,
1685
+ vacua_df: Any,
1686
+ label: str,
1687
+ committed_by: str,
1688
+ model: Any = None,
1689
+ F_term_tol: float = 1e-6,
1690
+ check_remote: bool = True,
1691
+ repo_id: Optional[str] = None,
1692
+ ) -> dict:
1693
+ r"""
1694
+ **Description:**
1695
+ Upload-specific validation wrapper around :meth:`validate_vacua`.
1696
+ Runs the standard physics/dedup checks plus extras required for
1697
+ pushing to a HuggingFace dataset repo:
1698
+
1699
+ - ``label`` matches the filesystem-safe slug regex.
1700
+ - ``committed_by`` is non-empty.
1701
+ - Schema version of this package matches the remote repo's
1702
+ ``schema.json`` (when *check_remote* is True and the package
1703
+ is online).
1704
+ - Optional remote duplicate check against the remote catalog.
1705
+
1706
+ Args:
1707
+ vacua_df: Vacuum rows to upload.
1708
+ label (str): Dataset label (filesystem-safe).
1709
+ committed_by (str): Contributor identifier.
1710
+ model: Optional JAXVacua model for F-term re-verification.
1711
+ F_term_tol (float): F-term tolerance. Defaults to ``1e-6``.
1712
+ check_remote (bool): Check schema + catalog on the remote
1713
+ repo. Requires network; skipped automatically when
1714
+ ``self.offline`` is True.
1715
+ repo_id (str | None): Override target repo. Defaults to the
1716
+ package-wide vault repo (see :func:`set_vault_repo`).
1717
+
1718
+ Returns:
1719
+ dict: ``{"passed": bool, "errors": list, "warnings": list,
1720
+ "per_row_report": list}``. Suitable for including in a PR
1721
+ summary comment.
1722
+ """
1723
+ import re
1724
+ errors: List[str] = []
1725
+ warnings_: List[str] = []
1726
+
1727
+ # 1. Upload-specific bookkeeping
1728
+ if not label or not label.strip():
1729
+ errors.append("label must be non-empty")
1730
+ else:
1731
+ slug = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
1732
+ if not slug.match(label):
1733
+ errors.append(
1734
+ f"label {label!r} is not a valid slug "
1735
+ f"(must match {slug.pattern})"
1736
+ )
1737
+ if not committed_by or not committed_by.strip():
1738
+ errors.append("committed_by must be non-empty")
1739
+
1740
+ # 2. Remote schema + catalogue checks
1741
+ if check_remote and not self.offline:
1742
+ try:
1743
+ repo = repo_id or _resolve_vault_repo()
1744
+ hf_download = _require_hf_hub()
1745
+ schema_path = hf_download(
1746
+ repo_id=repo,
1747
+ filename="schema.json",
1748
+ repo_type="dataset",
1749
+ )
1750
+ with open(schema_path) as f:
1751
+ remote_schema = json.load(f)
1752
+ remote_ver = int(remote_schema.get("schema_version", -1))
1753
+ if remote_ver != SCHEMA_VERSION:
1754
+ errors.append(
1755
+ f"Schema version mismatch: remote={remote_ver}, "
1756
+ f"local={SCHEMA_VERSION}. Upgrade your local "
1757
+ f"`jaxvacua` package or coordinate with the repo "
1758
+ f"maintainer."
1759
+ )
1760
+ except Exception as e:
1761
+ # Remote schema may not exist yet (fresh repo) — warn only.
1762
+ warnings_.append(f"Could not fetch remote schema: {e}")
1763
+
1764
+ # 3. Row-level validation (reuses existing validate_vacua)
1765
+ per_row = self.validate_vacua(
1766
+ vacua_df, model=model, F_term_tol=F_term_tol,
1767
+ check_tadpole=True,
1768
+ check_physics=(model is not None),
1769
+ check_duplicates=True,
1770
+ )
1771
+ n_failed = sum(1 for r in per_row if not r["passed"])
1772
+ if n_failed > 0:
1773
+ errors.append(
1774
+ f"{n_failed}/{len(per_row)} rows failed per-row validation"
1775
+ )
1776
+
1777
+ return {
1778
+ "passed": len(errors) == 0,
1779
+ "errors": errors,
1780
+ "warnings": warnings_,
1781
+ "per_row_report": per_row,
1782
+ }
1783
+ def push_vacua_to_hub(
1784
+ self,
1785
+ vacua_df: Any,
1786
+ label: str,
1787
+ committed_by: str,
1788
+ model: Any,
1789
+ tags: Optional[list] = None,
1790
+ notes: str = "",
1791
+ repo_id: Optional[str] = None,
1792
+ create_pr: bool = True,
1793
+ partial_failure: str = "strict",
1794
+ if_exists: str = "error",
1795
+ check_remote: bool = True,
1796
+ token: Optional[str] = None,
1797
+ classification: Optional[dict] = None,
1798
+ ) -> dict:
1799
+ r"""
1800
+ **Description:**
1801
+ Upload a batch of vacuum solutions to the HuggingFace
1802
+ ``aschachner/vacua_vault`` dataset repository (or an override
1803
+ via *repo_id* / ``STRINGFORGE_VAULT_REPO``).
1804
+
1805
+ The upload lands inside the target model's ``community/``
1806
+ directory: ``tdf/h12_{N}/ks_{X}_tri_{Y}/community/{hf_username}_{label}.parquet``
1807
+ (or the analogous CICY ``cicy/cicy_{X}/…`` or local-model
1808
+ ``local/h12_{N}/model_{M}/…`` path). Filesystem-free-form labels
1809
+ (see §5.6 of the vacua-storage plan) mean classification
1810
+ (``susy``, ``method``, ``nmax``, ``qualifiers``) is stored as
1811
+ parquet-level key-value metadata and extracted by the remote
1812
+ catalogue rebuild on merge.
1813
+
1814
+ Args:
1815
+ vacua_df: Rows to upload. Must include at least ``flux``,
1816
+ ``moduli_re``, ``moduli_im``, ``tau_re``, ``tau_im``.
1817
+ label (str): Filesystem-safe slug for the output file.
1818
+ committed_by (str): Contributor identifier (ORCID preferred;
1819
+ HF username accepted).
1820
+ model: Required JAXVacua model for identity extraction and
1821
+ physics validation.
1822
+ tags (list | None): Free-form tags attached to the dataset.
1823
+ notes (str): Free-text annotation.
1824
+ repo_id (str | None): Target dataset repo. Defaults to
1825
+ :func:`_resolve_vault_repo`.
1826
+ create_pr (bool): If ``True`` (default), open a pull
1827
+ request rather than pushing directly to ``main``.
1828
+ partial_failure (str): ``"strict"`` (default, refuse the
1829
+ upload if any rows fail validation) or ``"split"``
1830
+ (valid rows go to the main file; failing rows go to
1831
+ ``_rejected/{filename}.rejected.parquet``).
1832
+ if_exists (str): Behaviour on filename collision in the
1833
+ target repo. ``"error"`` (default), ``"append"``, or
1834
+ ``"new_version"`` (auto-suffix ``_v2``, ``_v3``, ...).
1835
+ ``"append"`` is only supported with
1836
+ ``create_pr=False`` because it requires a read-modify-
1837
+ write round-trip.
1838
+ check_remote (bool): Perform remote schema check during
1839
+ validation. Requires network access.
1840
+ token (str | None): Optional HF access token. Falls back
1841
+ to the token cached by ``huggingface-cli login`` and
1842
+ then to ``HF_TOKEN``.
1843
+ classification (dict | None): Optional parquet-level
1844
+ metadata to attach to the uploaded file. Expected
1845
+ keys: ``susy`` (``"SUSY"`` | ``"nonSUSY"`` | ``"mixed"``),
1846
+ ``method`` (str), ``nmax`` (int), and ``qualifiers``
1847
+ (dict). When omitted, sensible defaults are inferred.
1848
+
1849
+ Returns:
1850
+ dict: ``{"pr_url": str | None, "commit_url": str,
1851
+ "file_path": str, "n_uploaded": int, "n_rejected": int,
1852
+ "report": ValidationReport}``.
1853
+
1854
+ Raises:
1855
+ RuntimeError: If ``self.offline=True``.
1856
+ ValidationError: If validation fails and
1857
+ ``partial_failure="strict"``.
1858
+ FileExistsError: If the target filename exists and
1859
+ ``if_exists="error"``.
1860
+ """
1861
+ if self.offline:
1862
+ raise RuntimeError(
1863
+ "push_vacua_to_hub requires network access "
1864
+ "(self.offline=True)."
1865
+ )
1866
+ if partial_failure not in ("strict", "split"):
1867
+ raise ValueError(
1868
+ f"partial_failure must be 'strict' or 'split', "
1869
+ f"got {partial_failure!r}"
1870
+ )
1871
+ if if_exists not in ("error", "append", "new_version"):
1872
+ raise ValueError(
1873
+ f"if_exists must be 'error', 'append', or 'new_version', "
1874
+ f"got {if_exists!r}"
1875
+ )
1876
+ if if_exists == "append" and create_pr:
1877
+ raise ValueError(
1878
+ "if_exists='append' requires create_pr=False because it "
1879
+ "performs a read-modify-write upload."
1880
+ )
1881
+
1882
+ pd = _require_pandas()
1883
+ pq = _require_pyarrow()
1884
+ try:
1885
+ import pyarrow as pa # for Table-level metadata manipulation
1886
+ except ImportError as e:
1887
+ raise ImportError(
1888
+ "The 'pyarrow' package is required for push_vacua_to_hub."
1889
+ ) from e
1890
+ hf_api = _require_hf_api()
1891
+ hf_download = _require_hf_hub()
1892
+ repo = repo_id or _resolve_vault_repo()
1893
+
1894
+ # 1. Client-side validation
1895
+ report = self._validate_for_upload(
1896
+ vacua_df, label=label, committed_by=committed_by,
1897
+ model=model, check_remote=check_remote, repo_id=repo,
1898
+ )
1899
+
1900
+ # 2. Apply partial-failure policy
1901
+ n_total = len(vacua_df)
1902
+ passed_idx = [r["index"] for r in report["per_row_report"] if r["passed"]]
1903
+ failed_idx = [r["index"] for r in report["per_row_report"] if not r["passed"]]
1904
+
1905
+ if failed_idx and partial_failure == "strict":
1906
+ msg = (
1907
+ f"{len(failed_idx)}/{n_total} rows failed validation. "
1908
+ f"Use partial_failure='split' to upload only the valid rows."
1909
+ )
1910
+ raise ValidationError(msg, report=report["per_row_report"])
1911
+
1912
+ valid_df = vacua_df.iloc[passed_idx].reset_index(drop=True)
1913
+ rejected_df = vacua_df.iloc[failed_idx].reset_index(drop=True) if failed_idx else None
1914
+ if rejected_df is not None and len(rejected_df) > 0:
1915
+ # Attach per-row error strings
1916
+ errs = []
1917
+ for r in report["per_row_report"]:
1918
+ if not r["passed"]:
1919
+ errs.append("; ".join(r["errors"]))
1920
+ rejected_df = rejected_df.copy()
1921
+ rejected_df["error"] = errs
1922
+
1923
+ # Abort if nothing to upload
1924
+ if len(valid_df) == 0:
1925
+ raise ValidationError(
1926
+ "No valid rows to upload.", report=report["per_row_report"],
1927
+ )
1928
+
1929
+ # 3. Identify the authenticated HF user (for filename prefix)
1930
+ try:
1931
+ who = hf_api.whoami(token=token)
1932
+ hf_username = who.get("name") or who.get("username") or "anonymous"
1933
+ except Exception as e:
1934
+ raise RuntimeError(
1935
+ f"Could not identify HF user (check HF_TOKEN / huggingface-cli login): {e}"
1936
+ ) from e
1937
+
1938
+ # 4. Resolve remote paths
1939
+ identity = _extract_model_identity(model=model)
1940
+ model_dir_remote = self._remote_model_dir(identity)
1941
+ if model_dir_remote is None:
1942
+ raise ValueError(
1943
+ "Could not derive a remote model directory from the "
1944
+ "given model. Pass ks_id/triang_id or cicy_id "
1945
+ "explicitly."
1946
+ )
1947
+
1948
+ base_name = f"{hf_username}_{label}"
1949
+ ext = ".parquet"
1950
+ target_rel = f"{model_dir_remote}/community/{base_name}{ext}"
1951
+
1952
+ # 5. Handle filename collisions according to if_exists
1953
+ final_rel = self._resolve_remote_filename(
1954
+ hf_api, hf_download, repo, target_rel, if_exists=if_exists,
1955
+ token=token,
1956
+ )
1957
+
1958
+ # 6. Write the valid rows (plus pyarrow metadata) to a scratch
1959
+ # parquet file locally, then upload it.
1960
+ import tempfile, time
1961
+ cls_meta = classification or {}
1962
+ arrow_meta = {
1963
+ "schema_version": str(SCHEMA_VERSION),
1964
+ "susy": str(cls_meta.get("susy", "unknown")),
1965
+ "method": str(cls_meta.get("method", "unknown")),
1966
+ "nmax": str(cls_meta.get("nmax", "")),
1967
+ "qualifiers": json.dumps(cls_meta.get("qualifiers", {})),
1968
+ "label": label,
1969
+ "committed_by": committed_by,
1970
+ "notes": notes or "",
1971
+ "uploaded_at": datetime.datetime.now(
1972
+ datetime.timezone.utc).isoformat(),
1973
+ }
1974
+ if tags:
1975
+ arrow_meta["tags"] = json.dumps(list(tags))
1976
+
1977
+ def _write_with_metadata(df, path, meta):
1978
+ table = pa.Table.from_pandas(df, preserve_index=False)
1979
+ existing = dict(table.schema.metadata or {})
1980
+ existing.update({k.encode(): v.encode() for k, v in meta.items()})
1981
+ table = table.replace_schema_metadata(existing)
1982
+ pq.write_table(table, path)
1983
+
1984
+ result: Dict[str, Any] = {
1985
+ "pr_url": None,
1986
+ "commit_url": None,
1987
+ "file_path": final_rel,
1988
+ "n_uploaded": len(valid_df),
1989
+ "n_rejected": len(rejected_df) if rejected_df is not None else 0,
1990
+ "report": report,
1991
+ }
1992
+
1993
+ with tempfile.TemporaryDirectory() as tmpdir:
1994
+ if if_exists == "append":
1995
+ try:
1996
+ existing_path = hf_download(
1997
+ repo_id=repo,
1998
+ filename=final_rel,
1999
+ repo_type="dataset",
2000
+ local_dir=tmpdir,
2001
+ token=token,
2002
+ )
2003
+ existing_df = pd.read_parquet(existing_path)
2004
+ except Exception:
2005
+ existing_df = None
2006
+ if existing_df is not None and len(existing_df) > 0:
2007
+ valid_df = _safe_concat(
2008
+ [existing_df, valid_df], ignore_index=True,
2009
+ )
2010
+ result["n_uploaded"] = len(valid_df)
2011
+
2012
+ # Valid file
2013
+ local_main = os.path.join(tmpdir, os.path.basename(final_rel))
2014
+ _write_with_metadata(valid_df, local_main, arrow_meta)
2015
+
2016
+ # Optional rejected file
2017
+ local_rejected = None
2018
+ rejected_rel = None
2019
+ if rejected_df is not None and len(rejected_df) > 0:
2020
+ rej_name = (
2021
+ os.path.splitext(os.path.basename(final_rel))[0]
2022
+ + ".rejected" + ext
2023
+ )
2024
+ rejected_rel = f"{model_dir_remote}/community/_rejected/{rej_name}"
2025
+ local_rejected = os.path.join(tmpdir, rej_name)
2026
+ rej_meta = dict(arrow_meta)
2027
+ rej_meta["status"] = "rejected"
2028
+ _write_with_metadata(rejected_df, local_rejected, rej_meta)
2029
+
2030
+ # Upload
2031
+ commit_msg = f"add: {final_rel} (label={label}, by={committed_by})"
2032
+ operations = []
2033
+ operations.append(dict(
2034
+ local_path=local_main, path_in_repo=final_rel,
2035
+ ))
2036
+ if local_rejected is not None:
2037
+ operations.append(dict(
2038
+ local_path=local_rejected, path_in_repo=rejected_rel,
2039
+ ))
2040
+
2041
+ uploaded_paths = []
2042
+ for op in operations:
2043
+ ci = hf_api.upload_file(
2044
+ path_or_fileobj=op["local_path"],
2045
+ path_in_repo=op["path_in_repo"],
2046
+ repo_id=repo,
2047
+ repo_type="dataset",
2048
+ commit_message=commit_msg,
2049
+ token=token,
2050
+ create_pr=create_pr,
2051
+ )
2052
+ uploaded_paths.append(op["path_in_repo"])
2053
+ # huggingface_hub returns a CommitInfo for direct uploads
2054
+ # or a PR-related response when create_pr=True.
2055
+ if create_pr and result["pr_url"] is None:
2056
+ pr_url = getattr(ci, "pr_url", None) or getattr(ci, "url", None)
2057
+ result["pr_url"] = pr_url
2058
+ if not create_pr and result["commit_url"] is None:
2059
+ result["commit_url"] = getattr(ci, "commit_url", None) or getattr(ci, "oid", None)
2060
+
2061
+ result["file_path"] = uploaded_paths[0]
2062
+ result["rejected_path"] = uploaded_paths[1] if len(uploaded_paths) > 1 else None
2063
+
2064
+ return result
2065
+ def fetch_vacua_from_hub(
2066
+ self,
2067
+ model: Any = None,
2068
+ ks_id: Optional[int] = None,
2069
+ triang_id: Optional[int] = None,
2070
+ cicy_id: Optional[int] = None,
2071
+ label: Optional[str] = None,
2072
+ include_community: bool = False,
2073
+ include_retracted: bool = False,
2074
+ cache: bool = True,
2075
+ repo_id: Optional[str] = None,
2076
+ token: Optional[str] = None,
2077
+ ) -> Any:
2078
+ r"""
2079
+ **Description:**
2080
+ Download curated (and optionally community) vacuum solutions
2081
+ for a given model from the HuggingFace vacua repo.
2082
+
2083
+ Args:
2084
+ model: Optional JAXVacua model for identity extraction.
2085
+ ks_id, triang_id, cicy_id: Explicit identity overrides.
2086
+ label (str | None): If given, match only files whose name
2087
+ starts with this label (before any ``_v{n}`` suffix).
2088
+ include_community (bool): Also fetch files under
2089
+ ``community/``. Defaults to False.
2090
+ include_retracted (bool): Include rows flagged
2091
+ ``retracted=True`` in the returned DataFrame.
2092
+ cache (bool): Keep downloads in the HF cache (reserved for
2093
+ future use; ``hf_hub_download`` always caches).
2094
+ repo_id (str | None): Target dataset repo. Defaults to
2095
+ :func:`_resolve_vault_repo`.
2096
+ token (str | None): Optional HF access token.
2097
+
2098
+ Returns:
2099
+ pandas.DataFrame: Concatenated rows from all matching
2100
+ files, with an extra ``_source_path`` column identifying
2101
+ the origin file. Empty DataFrame if nothing matches.
2102
+ """
2103
+ if self.offline:
2104
+ raise RuntimeError(
2105
+ "fetch_vacua_from_hub requires network access "
2106
+ "(self.offline=True)."
2107
+ )
2108
+ pd = _require_pandas()
2109
+ hf_download = _require_hf_hub()
2110
+ hf_api = _require_hf_api()
2111
+ repo = repo_id or _resolve_vault_repo()
2112
+
2113
+ identity = _extract_model_identity(
2114
+ model=model, ks_id=ks_id, triang_id=triang_id,
2115
+ cicy_id=cicy_id,
2116
+ )
2117
+ model_dir = self._remote_model_dir(identity)
2118
+ if model_dir is None:
2119
+ raise ValueError(
2120
+ "Could not derive a remote model directory from the "
2121
+ "given model/identity."
2122
+ )
2123
+
2124
+ # List remote files under the model directory
2125
+ try:
2126
+ all_files = hf_api.list_repo_files(
2127
+ repo_id=repo, repo_type="dataset", token=token,
2128
+ )
2129
+ except Exception as e:
2130
+ raise RuntimeError(
2131
+ f"Could not list files in {repo}: {e}"
2132
+ ) from e
2133
+
2134
+ def _matches(path: str) -> bool:
2135
+ if not path.startswith(model_dir + "/"):
2136
+ return False
2137
+ if not path.endswith(".parquet"):
2138
+ return False
2139
+ # Curated files live directly in model_dir; community files
2140
+ # live in model_dir/community/; _rejected/ always excluded.
2141
+ rel = path[len(model_dir) + 1:]
2142
+ if rel.startswith("_rejected/"):
2143
+ return False
2144
+ is_community = rel.startswith("community/")
2145
+ if is_community and not include_community:
2146
+ return False
2147
+ if not is_community and "/" in rel:
2148
+ return False # nested file (shouldn't happen)
2149
+ # Label filter
2150
+ if label is not None:
2151
+ name = os.path.splitext(os.path.basename(path))[0]
2152
+ # Community files carry a "{hf_username}_" prefix; strip it
2153
+ if is_community and "_" in name:
2154
+ # Find the first underscore; the rest is {label}[_v{n}]
2155
+ name = name.split("_", 1)[1]
2156
+ # Accept exact label or label_v{n}
2157
+ import re
2158
+ if not re.match(rf"^{re.escape(label)}(_v\d+)?$", name):
2159
+ return False
2160
+ return True
2161
+
2162
+ matching = sorted(p for p in all_files if _matches(p))
2163
+ if not matching:
2164
+ return pd.DataFrame()
2165
+
2166
+ dfs = []
2167
+ for rp in matching:
2168
+ try:
2169
+ local = hf_download(
2170
+ repo_id=repo, filename=rp,
2171
+ repo_type="dataset", token=token,
2172
+ )
2173
+ except Exception as e:
2174
+ print(f"[fetch_vacua_from_hub] failed to download {rp}: {e}")
2175
+ continue
2176
+ try:
2177
+ df = pd.read_parquet(local)
2178
+ df["_source_path"] = rp
2179
+ dfs.append(df)
2180
+ except Exception as e:
2181
+ print(f"[fetch_vacua_from_hub] failed to parse {rp}: {e}")
2182
+
2183
+ if not dfs:
2184
+ return pd.DataFrame()
2185
+ out = _safe_concat(dfs, ignore_index=True)
2186
+ if not include_retracted and "retracted" in out.columns:
2187
+ out = out[~out["retracted"].fillna(False).astype(bool)].reset_index(drop=True)
2188
+ return out
2189
+ def list_hub_vacua(
2190
+ self,
2191
+ h11: Optional[int] = None,
2192
+ h12: Optional[int] = None,
2193
+ ks_id: Optional[int] = None,
2194
+ triang_id: Optional[int] = None,
2195
+ cicy_id: Optional[int] = None,
2196
+ label: Optional[str] = None,
2197
+ committed_by: Optional[str] = None,
2198
+ include_retracted: bool = False,
2199
+ limit: Optional[int] = None,
2200
+ repo_id: Optional[str] = None,
2201
+ token: Optional[str] = None,
2202
+ ) -> Any:
2203
+ r"""
2204
+ **Description:**
2205
+ Browse the remote vacua-vault catalogue. Downloads
2206
+ ``catalog.parquet`` from the target repo and applies boolean
2207
+ masks following the same filter API as
2208
+ :meth:`query_designated`.
2209
+
2210
+ Args:
2211
+ h11, h12, ks_id, triang_id, cicy_id: Identity filters.
2212
+ label (str | None): Filter by dataset label.
2213
+ committed_by (str | None): Filter by contributor.
2214
+ include_retracted (bool): Include retracted entries.
2215
+ limit (int | None): Return at most this many rows.
2216
+ repo_id (str | None): Target dataset repo.
2217
+ token (str | None): Optional HF access token.
2218
+
2219
+ Returns:
2220
+ pandas.DataFrame: Catalog rows matching the filters.
2221
+ Empty DataFrame if the remote catalog is empty or missing.
2222
+ """
2223
+ if self.offline:
2224
+ raise RuntimeError(
2225
+ "list_hub_vacua requires network access (offline=True)."
2226
+ )
2227
+ pd = _require_pandas()
2228
+ hf_download = _require_hf_hub()
2229
+ repo = repo_id or _resolve_vault_repo()
2230
+
2231
+ try:
2232
+ local = hf_download(
2233
+ repo_id=repo, filename="catalog.parquet",
2234
+ repo_type="dataset", token=token,
2235
+ )
2236
+ except Exception as e:
2237
+ # Catalog may not exist yet on a fresh repo.
2238
+ print(f"[list_hub_vacua] could not fetch remote catalog: {e}")
2239
+ return pd.DataFrame()
2240
+
2241
+ cat = pd.read_parquet(local)
2242
+ filters = {
2243
+ "h11": h11, "h12": h12, "ks_id": ks_id,
2244
+ "triang_id": triang_id, "cicy_id": cicy_id,
2245
+ "label": label, "committed_by": committed_by,
2246
+ }
2247
+ for col, val in filters.items():
2248
+ if val is not None and col in cat.columns:
2249
+ cat = cat[cat[col] == val]
2250
+
2251
+ if not include_retracted and "retracted" in cat.columns:
2252
+ cat = cat[~cat["retracted"].fillna(False).astype(bool)]
2253
+
2254
+ if limit is not None:
2255
+ cat = cat.head(limit)
2256
+
2257
+ return cat.reset_index(drop=True)
2258
+ @staticmethod
2259
+ def _remote_model_dir(identity: Dict[str, Any]) -> Optional[str]:
2260
+ r"""
2261
+ Derive the per-model subdirectory on the remote vault repo from
2262
+ an identity dict. Returns ``None`` if the identity doesn't
2263
+ provide enough information.
2264
+ """
2265
+ ks = identity.get("ks_id", -1)
2266
+ tr = identity.get("triang_id", -1)
2267
+ cic = identity.get("cicy_id", -1)
2268
+ h12 = identity.get("h12")
2269
+ if ks >= 0 and tr >= 0 and h12 is not None:
2270
+ return f"tdf/h12_{h12}/ks_{ks}_tri_{tr}"
2271
+ if cic >= 0:
2272
+ return f"cicy/cicy_{cic}"
2273
+ # Local JAXVacua models (loaded via h12 + model_ID) carry no
2274
+ # ks/triang/cicy id; ``_extract_model_identity`` assigns them a
2275
+ # synthetic name ``local_h12_{h12}_ID_{model_ID}``. They live in a
2276
+ # dedicated remote ``local/`` namespace (nested to match the
2277
+ # ``tdf/``/``cicy/`` two-level convention; the on-disk store uses the
2278
+ # flat ``KS/h12_{h12}_model_{model_ID}`` dir, see ``_resolve_vacua_dir``).
2279
+ name = identity.get("model_name") or ""
2280
+ if name.startswith("local_h12_") and "_ID_" in name and h12 is not None:
2281
+ mid = name.rsplit("_ID_", 1)[-1]
2282
+ return f"local/h12_{h12}/model_{mid}"
2283
+ return None
2284
+ @staticmethod
2285
+ def _resolve_remote_filename(
2286
+ hf_api: Any,
2287
+ hf_download: Any,
2288
+ repo: str,
2289
+ target_rel: str,
2290
+ if_exists: str,
2291
+ token: Optional[str] = None,
2292
+ ) -> str:
2293
+ r"""
2294
+ Implement the ``if_exists`` collision policy for a target remote
2295
+ filename. Returns the final ``path_in_repo`` to use.
2296
+
2297
+ - ``"error"``: raise if the file already exists.
2298
+ - ``"append"``: return the existing path (caller is responsible
2299
+ for appending — this helper just signals).
2300
+ - ``"new_version"``: auto-suffix ``_v2``, ``_v3``, ... until a
2301
+ free name is found.
2302
+ """
2303
+ # Probe existence by trying to download with a head-only call
2304
+ # (hf_hub_download returns file path if exists). List files
2305
+ # via HfApi for a cleaner existence check.
2306
+ try:
2307
+ files = set(hf_api.list_repo_files(repo_id=repo, repo_type="dataset",
2308
+ token=token))
2309
+ except Exception:
2310
+ # Could be empty / unreachable repo; treat as "no collision".
2311
+ files = set()
2312
+
2313
+ if target_rel not in files:
2314
+ return target_rel
2315
+
2316
+ if if_exists == "error":
2317
+ raise FileExistsError(
2318
+ f"{target_rel!r} already exists in {repo!r}. "
2319
+ f"Pick a different label or use "
2320
+ f"if_exists='new_version' (auto-suffix) or "
2321
+ f"if_exists='append' (merge)."
2322
+ )
2323
+ if if_exists == "append":
2324
+ return target_rel
2325
+ # "new_version" → find the first free _vN suffix
2326
+ import re
2327
+ stem, ext = os.path.splitext(target_rel)
2328
+ base_stem = re.sub(r"_v\d+$", "", stem) # strip any existing _vN
2329
+ n = 2
2330
+ while f"{base_stem}_v{n}{ext}" in files:
2331
+ n += 1
2332
+ return f"{base_stem}_v{n}{ext}"
2333
+ def complete_missing(
2334
+ self,
2335
+ df: Any,
2336
+ model: Any,
2337
+ with_masses: bool = True,
2338
+ vmap_dim: Optional[int] = None,
2339
+ ) -> Any:
2340
+ r"""
2341
+ **Description:**
2342
+ Return *df* completed to the full per-vacuum schema: every input
2343
+ column is preserved, the derived physics is filled in, and the
2344
+ standard identity / convenience columns are back-filled from *model*,
2345
+ so the result carries the same columns as :meth:`query_vacua` /
2346
+ :meth:`load_vacua` with everything populated. Only cells that are
2347
+ currently ``None`` / ``NaN`` are touched (idempotent), so it is safe
2348
+ on freshly-queried session vacua *or* on loaded designated vacua
2349
+ (which are stored with a reduced column set).
2350
+
2351
+ Fields completed: superpotential ``W_re``/``W_im``, F-terms
2352
+ ``F_terms_re``/``F_terms_im``, tadpole ``N_flux``, ``is_susy``, string
2353
+ coupling ``g_s`` (:math:`= 1/\mathrm{Im}\,\tau`), the complex
2354
+ ``moduli`` / ``tau`` columns, the identity columns (``h11``, ``h12``,
2355
+ ``ks_id``, ``triang_id``, ``conifold_id``, ``cicy_id``,
2356
+ ``model_hash``, ``model_name``) and -- when *with_masses* -- the mass
2357
+ spectrum ``mass2`` (sorted real mass-squared eigenvalues of the
2358
+ canonically-normalised no-scale mass matrix, sign-carrying) and the
2359
+ gravitino mass ``m_gravitino`` (:math:`m_{3/2}=e^{K/2}|W|`).
2360
+ ``mass2`` and ``m_gravitino`` are in the **FluxEFT no-scale
2361
+ normalisation, not** :math:`M_\mathrm{Pl}` -- they carry an unfixed
2362
+ overall CY-volume factor (only the ratio :math:`m/m_{3/2}` is
2363
+ volume-independent). See :func:`_compute_derived` for the exact
2364
+ conventions.
2365
+
2366
+ Args:
2367
+ df: DataFrame with at least ``flux``, ``moduli_re``,
2368
+ ``moduli_im``, ``tau_re``, ``tau_im`` (e.g. from
2369
+ :meth:`load_vacua` or :meth:`load_designated`).
2370
+ model: JAXVacua model whose geometry the rows belong to
2371
+ (required -- the writer does not hold a model).
2372
+ with_masses (bool): also compute the mass spectrum and
2373
+ gravitino mass. Defaults to ``True``.
2374
+ vmap_dim (int | None): if set, evaluate the physics with
2375
+ :func:`jax.vmap` in batches of this many rows (much faster
2376
+ for large tables). ``None`` (default) uses the per-row path.
2377
+
2378
+ Returns:
2379
+ pandas.DataFrame: the frame completed to the full schema.
2380
+ """
2381
+ if model is None:
2382
+ raise ValueError(
2383
+ "complete_missing requires a model to compute derived "
2384
+ "quantities (pass model=...)."
2385
+ )
2386
+ return _compute_derived(
2387
+ df, model, fill_missing_only=True, with_masses=with_masses,
2388
+ vmap_dim=vmap_dim, enrich=True,
2389
+ )
2390
+ def designate_vacua(
2391
+ self,
2392
+ vacua_df: Any,
2393
+ label: str,
2394
+ committed_by: str,
2395
+ model: Any = None,
2396
+ h11: Optional[int] = None,
2397
+ h12: Optional[int] = None,
2398
+ ks_id: Optional[int] = None,
2399
+ triang_id: Optional[int] = None,
2400
+ conifold_id: int = -1,
2401
+ cicy_id: Optional[int] = None,
2402
+ model_name: Optional[str] = None,
2403
+ tags: Optional[Any] = None,
2404
+ notes: str = "",
2405
+ validate: bool = True,
2406
+ force: bool = False,
2407
+ F_term_tol: float = 1e-8,
2408
+ vmap_dim: Optional[int] = None,
2409
+ ) -> List[int]:
2410
+ r"""
2411
+ **Description:**
2412
+ Designate vacuum solutions as permanent / curated. Solutions are
2413
+ written to the ``designated_vacua/`` directory with provenance
2414
+ metadata and added to the designated catalog.
2415
+
2416
+ By default, all solutions are validated before writing. Validation
2417
+ failures raise :class:`ValidationError` unless ``force=True``.
2418
+
2419
+ The input *vacua_df* can be a ``DataFrame`` from
2420
+ :meth:`query_vacua`, or any DataFrame with the standard vacuum
2421
+ columns (``flux``, ``moduli_re``, ``moduli_im``, ``tau_re``,
2422
+ ``tau_im``).
2423
+
2424
+ Args:
2425
+ vacua_df: ``pandas.DataFrame`` of vacuum rows.
2426
+ label (str): Human-readable label (e.g. ``"benchmark_ISD"``,
2427
+ ``"paper:2506.xxxxx"``).
2428
+ committed_by (str): Author identifier (name or ORCID).
2429
+ model: Optional JAXVacua model for identity extraction and
2430
+ physics validation.
2431
+ h11, h12, ks_id, triang_id, conifold_id, cicy_id: Explicit
2432
+ model identity overrides.
2433
+ model_name (str | None): Human-readable label for custom models.
2434
+ tags: String or list of tag strings applied to all solutions.
2435
+ notes (str): Free-text annotation.
2436
+ validate (bool): Run validation before designating.
2437
+ force (bool): Designate even if validation fails (failed
2438
+ solutions are skipped).
2439
+ F_term_tol (float): F-term tolerance for validation.
2440
+
2441
+ Returns:
2442
+ List[int]: ``designated_id`` values assigned to the new
2443
+ solutions.
2444
+
2445
+ Raises:
2446
+ ValidationError: If validation fails and ``force=False``.
2447
+ ValueError: If ``label`` or ``committed_by`` is empty.
2448
+ """
2449
+ pd = _require_pandas()
2450
+
2451
+ if not label or not label.strip():
2452
+ raise ValueError("label must be non-empty")
2453
+ if not committed_by or not committed_by.strip():
2454
+ raise ValueError("committed_by must be non-empty")
2455
+
2456
+ # Resolve model identity
2457
+ identity = _extract_model_identity(
2458
+ model=model, h11=h11, h12=h12, ks_id=ks_id,
2459
+ triang_id=triang_id, conifold_id=conifold_id,
2460
+ cicy_id=cicy_id, model_name=model_name,
2461
+ )
2462
+
2463
+ # Validation
2464
+ if validate:
2465
+ report = self.validate_vacua(
2466
+ vacua_df, model=model, F_term_tol=F_term_tol,
2467
+ identity=identity,
2468
+ )
2469
+ n_failed = sum(1 for r in report if not r["passed"])
2470
+ if n_failed > 0 and not force:
2471
+ msg_lines = [f"{n_failed}/{len(report)} solutions failed validation:"]
2472
+ for r in report:
2473
+ if not r["passed"]:
2474
+ msg_lines.append(f" row {r['index']}: {'; '.join(r['errors'])}")
2475
+ raise ValidationError("\n".join(msg_lines), report=report)
2476
+ # If force, keep only passing rows
2477
+ if force and n_failed > 0:
2478
+ keep_idx = [r["index"] for r in report if r["passed"]]
2479
+ vacua_df = vacua_df.iloc[keep_idx].reset_index(drop=True)
2480
+
2481
+ if len(vacua_df) == 0:
2482
+ return []
2483
+
2484
+ # Compute derived quantities -- including the mass spectrum (mass2)
2485
+ # and gravitino mass (m_gravitino), in the FluxEFT no-scale
2486
+ # normalisation (NOT M_Pl: the overall CY volume is unfixed here) --
2487
+ # so the permanent designated records carry them. Missing-only, so
2488
+ # values already on the rows are preserved.
2489
+ if model is not None:
2490
+ vacua_df = _compute_derived(
2491
+ vacua_df, model, fill_missing_only=True, with_masses=True,
2492
+ vmap_dim=vmap_dim,
2493
+ )
2494
+
2495
+ # Normalise tags
2496
+ if tags is None:
2497
+ tags_json = "[]"
2498
+ elif isinstance(tags, str):
2499
+ tags_json = json.dumps([tags])
2500
+ else:
2501
+ tags_json = json.dumps(list(tags))
2502
+
2503
+ try:
2504
+ _jv_version = version("jaxvacua")
2505
+ except PackageNotFoundError:
2506
+ _jv_version = "unknown"
2507
+
2508
+ now = datetime.datetime.now(datetime.timezone.utc)
2509
+ today = now.date().isoformat()
2510
+
2511
+ self._designated_dir.mkdir(parents=True, exist_ok=True)
2512
+ catalog_path = (
2513
+ self._designated_dir / "designated_vacua_catalog.parquet"
2514
+ )
2515
+
2516
+ # ``designate_vacua`` assigns a contiguous range of integer IDs
2517
+ # starting from ``max(existing) + 1``. Serialise the read of
2518
+ # the catalog, the ID allocation, and the write so concurrent
2519
+ # cluster workers cannot collide.
2520
+ with _file_lock(catalog_path):
2521
+ self._designated_catalog = None
2522
+ self._ensure_designated_catalog()
2523
+ dcat = self._designated_catalog
2524
+ if dcat is not None and len(dcat) > 0:
2525
+ next_id = int(dcat["designated_id"].max()) + 1
2526
+ else:
2527
+ next_id = 0
2528
+
2529
+ catalog_rows: List[Dict[str, Any]] = []
2530
+ data_rows: List[Dict[str, Any]] = []
2531
+ assigned_ids: List[int] = []
2532
+
2533
+ for i in range(len(vacua_df)):
2534
+ row = vacua_df.iloc[i]
2535
+ did = next_id + i
2536
+ assigned_ids.append(did)
2537
+
2538
+ existing_tags: List[str] = []
2539
+ if "tags" in vacua_df.columns:
2540
+ try:
2541
+ et = row["tags"]
2542
+ if isinstance(et, str):
2543
+ existing_tags = json.loads(et)
2544
+ except (json.JSONDecodeError, TypeError):
2545
+ pass
2546
+ new_tags = json.loads(tags_json)
2547
+ merged_tags = list(dict.fromkeys(existing_tags + new_tags))
2548
+
2549
+ source_run = (
2550
+ str(row.get("run_id", ""))
2551
+ if "run_id" in vacua_df.columns else ""
2552
+ )
2553
+
2554
+ catalog_rows.append({
2555
+ "designated_id": did,
2556
+ "h11": identity["h11"],
2557
+ "h12": identity["h12"],
2558
+ "ks_id": identity["ks_id"],
2559
+ "triang_id": identity["triang_id"],
2560
+ "conifold_id": identity["conifold_id"],
2561
+ "cicy_id": identity["cicy_id"],
2562
+ "model_hash": identity["model_hash"],
2563
+ "model_name": identity.get("model_name"),
2564
+ "flux": list(int(x) for x in row["flux"]),
2565
+ "N_flux": row.get("N_flux"),
2566
+ "is_susy": bool(row.get("is_susy", False)),
2567
+ "tags": json.dumps(merged_tags),
2568
+ "label": label,
2569
+ "notes": notes,
2570
+ "committed_by": committed_by,
2571
+ "commit_date": today,
2572
+ "jaxvacua_version": _jv_version,
2573
+ "source_run_id": source_run,
2574
+ "retracted": False,
2575
+ "retraction_reason": None,
2576
+ })
2577
+
2578
+ data_rows.append({
2579
+ "designated_id": did,
2580
+ "flux": list(int(x) for x in row["flux"]),
2581
+ "moduli_re": list(row["moduli_re"]) if "moduli_re" in vacua_df.columns else None,
2582
+ "moduli_im": list(row["moduli_im"]) if "moduli_im" in vacua_df.columns else None,
2583
+ "tau_re": row.get("tau_re"),
2584
+ "tau_im": row.get("tau_im"),
2585
+ "W_re": row.get("W_re"),
2586
+ "W_im": row.get("W_im"),
2587
+ "F_terms_re": row.get("F_terms_re"),
2588
+ "F_terms_im": row.get("F_terms_im"),
2589
+ "N_flux": row.get("N_flux"),
2590
+ "g_s": row.get("g_s"),
2591
+ "mass2": row.get("mass2"),
2592
+ "m_gravitino": row.get("m_gravitino"),
2593
+ "residual": row.get("residual"),
2594
+ "is_susy": bool(row.get("is_susy", False)),
2595
+ "tags": json.dumps(merged_tags),
2596
+ "extra_data": row.get("extra_data"),
2597
+ "label": label,
2598
+ "committed_by": committed_by,
2599
+ "commit_date": today,
2600
+ })
2601
+
2602
+ shard_dir = self._resolve_vacua_dir(model=model, **{
2603
+ k: identity[k] for k in (
2604
+ "h11", "h12", "ks_id", "triang_id",
2605
+ "conifold_id", "cicy_id", "model_name",
2606
+ ) if k in identity
2607
+ })
2608
+ shard_dir.mkdir(parents=True, exist_ok=True)
2609
+ shard_path = shard_dir / "shard_0.parquet"
2610
+
2611
+ data_df = pd.DataFrame(data_rows)
2612
+ if shard_path.exists():
2613
+ existing = pd.read_parquet(shard_path)
2614
+ data_df = _safe_concat([existing, data_df], ignore_index=True)
2615
+ data_df.to_parquet(shard_path, index=False)
2616
+
2617
+ catalog_df = pd.DataFrame(catalog_rows)
2618
+ if dcat is not None and len(dcat) > 0:
2619
+ catalog_df = _safe_concat(
2620
+ [dcat, catalog_df], ignore_index=True,
2621
+ )
2622
+ catalog_df.to_parquet(catalog_path, index=False)
2623
+ self._designated_catalog = catalog_df
2624
+
2625
+ return assigned_ids
2626
+ def query_designated(
2627
+ self,
2628
+ h11: Optional[int] = None,
2629
+ h12: Optional[int] = None,
2630
+ ks_id: Optional[int] = None,
2631
+ triang_id: Optional[int] = None,
2632
+ conifold_id: Optional[int] = None,
2633
+ cicy_id: Optional[int] = None,
2634
+ model_hash: Optional[str] = None,
2635
+ label: Optional[str] = None,
2636
+ committed_by: Optional[str] = None,
2637
+ is_susy: Optional[bool] = None,
2638
+ N_flux_max: Optional[float] = None,
2639
+ tags: Optional[Any] = None,
2640
+ include_retracted: bool = False,
2641
+ limit: Optional[int] = None,
2642
+ ) -> Any:
2643
+ r"""
2644
+ **Description:**
2645
+ Query designated (permanent) vacua from the catalog.
2646
+
2647
+ All filtering is done at the catalog level (one row per solution),
2648
+ so this is fast even for large collections.
2649
+
2650
+ Args:
2651
+ h11, h12, ks_id, triang_id, conifold_id, cicy_id: Model
2652
+ identity filters (exact match).
2653
+ model_hash (str | None): Filter by geometric fingerprint.
2654
+ label (str | None): Filter by label (exact match).
2655
+ committed_by (str | None): Filter by author.
2656
+ is_susy (bool | None): Filter by SUSY flag.
2657
+ N_flux_max (float | None): Maximum tadpole value.
2658
+ tags: String or list of strings. Rows must contain **all**
2659
+ specified tags.
2660
+ include_retracted (bool): Include retracted solutions.
2661
+ Defaults to ``False``.
2662
+ limit (int | None): Maximum number of rows to return.
2663
+
2664
+ Returns:
2665
+ pandas.DataFrame: Matching rows from the designated catalog.
2666
+ """
2667
+ pd = _require_pandas()
2668
+ self._ensure_designated_catalog()
2669
+ dcat = self._designated_catalog
2670
+ if dcat is None or len(dcat) == 0:
2671
+ return pd.DataFrame()
2672
+
2673
+ mask = np.ones(len(dcat), dtype=bool)
2674
+
2675
+ # Exclude retracted by default
2676
+ if not include_retracted and "retracted" in dcat.columns:
2677
+ mask &= ~dcat["retracted"].fillna(False).astype(bool).values
2678
+
2679
+ if h11 is not None:
2680
+ mask &= (dcat["h11"] == h11).values
2681
+ if h12 is not None:
2682
+ mask &= (dcat["h12"] == h12).values
2683
+ if ks_id is not None:
2684
+ mask &= (dcat["ks_id"] == ks_id).values
2685
+ if triang_id is not None:
2686
+ mask &= (dcat["triang_id"] == triang_id).values
2687
+ if conifold_id is not None:
2688
+ mask &= (dcat["conifold_id"] == conifold_id).values
2689
+ if cicy_id is not None:
2690
+ mask &= (dcat["cicy_id"] == cicy_id).values
2691
+ if model_hash is not None:
2692
+ mask &= (dcat["model_hash"] == model_hash).values
2693
+ if label is not None:
2694
+ mask &= (dcat["label"] == label).values
2695
+ if committed_by is not None:
2696
+ mask &= (dcat["committed_by"] == committed_by).values
2697
+ if is_susy is not None:
2698
+ mask &= (dcat["is_susy"] == is_susy).values
2699
+ if N_flux_max is not None and "N_flux" in dcat.columns:
2700
+ mask &= dcat["N_flux"].fillna(float("inf")).values <= N_flux_max
2701
+ if tags is not None:
2702
+ if isinstance(tags, str):
2703
+ tags = [tags]
2704
+ def _has_all_tags(tags_json, required=tags):
2705
+ """Check whether tags_json contains all required tags."""
2706
+ try:
2707
+ stored = json.loads(tags_json) if isinstance(tags_json, str) else []
2708
+ except (json.JSONDecodeError, TypeError):
2709
+ stored = []
2710
+ return all(t in stored for t in required)
2711
+ if "tags" in dcat.columns:
2712
+ mask &= dcat["tags"].apply(_has_all_tags).values
2713
+
2714
+ result = dcat[mask]
2715
+ if limit is not None:
2716
+ result = result.head(limit)
2717
+ return result.reset_index(drop=True)
2718
+ def load_designated(
2719
+ self,
2720
+ designated_ids: Optional[List[int]] = None,
2721
+ h11: Optional[int] = None,
2722
+ h12: Optional[int] = None,
2723
+ ks_id: Optional[int] = None,
2724
+ triang_id: Optional[int] = None,
2725
+ model_hash: Optional[str] = None,
2726
+ ) -> Any:
2727
+ r"""
2728
+ **Description:**
2729
+ Load full data (moduli, flux, derived quantities) for designated
2730
+ solutions.
2731
+
2732
+ Either specify ``designated_ids`` directly, or use model identity
2733
+ filters to select all designated solutions for a model.
2734
+
2735
+ Args:
2736
+ designated_ids (list[int] | None): Specific designated IDs.
2737
+ h11, h12, ks_id, triang_id: Model identity filters.
2738
+ model_hash (str | None): Filter by geometric fingerprint.
2739
+
2740
+ Returns:
2741
+ pandas.DataFrame: Full solution data with ``designated_id``.
2742
+ """
2743
+ pd = _require_pandas()
2744
+ self._ensure_designated_catalog()
2745
+ dcat = self._designated_catalog
2746
+ if dcat is None or len(dcat) == 0:
2747
+ return pd.DataFrame()
2748
+
2749
+ # Determine which shard directories to load
2750
+ if designated_ids is not None:
2751
+ subset = dcat[dcat["designated_id"].isin(designated_ids)]
2752
+ else:
2753
+ mask = np.ones(len(dcat), dtype=bool)
2754
+ if h11 is not None:
2755
+ mask &= (dcat["h11"] == h11).values
2756
+ if h12 is not None:
2757
+ mask &= (dcat["h12"] == h12).values
2758
+ if ks_id is not None:
2759
+ mask &= (dcat["ks_id"] == ks_id).values
2760
+ if triang_id is not None:
2761
+ mask &= (dcat["triang_id"] == triang_id).values
2762
+ if model_hash is not None:
2763
+ mask &= (dcat["model_hash"] == model_hash).values
2764
+ subset = dcat[mask]
2765
+
2766
+ if len(subset) == 0:
2767
+ return pd.DataFrame()
2768
+
2769
+ # Group by model to find shard paths
2770
+ target_ids = set(subset["designated_id"].values)
2771
+ frames = []
2772
+
2773
+ # Scan all shard files under designated_vacua/
2774
+ if self._designated_dir.exists():
2775
+ for shard_path in self._designated_dir.rglob("shard_*.parquet"):
2776
+ try:
2777
+ df = pd.read_parquet(shard_path)
2778
+ if "designated_id" in df.columns:
2779
+ matched = df[df["designated_id"].isin(target_ids)]
2780
+ if len(matched) > 0:
2781
+ frames.append(matched)
2782
+ except Exception:
2783
+ continue
2784
+
2785
+ if not frames:
2786
+ return pd.DataFrame()
2787
+ return _safe_concat(frames, ignore_index=True)
2788
+ def designated_info(self) -> None:
2789
+ r"""
2790
+ **Description:**
2791
+ Print a summary of designated (permanent) vacua.
2792
+ """
2793
+ self._ensure_designated_catalog()
2794
+ dcat = self._designated_catalog
2795
+ if dcat is None or len(dcat) == 0:
2796
+ print("No designated vacua stored.")
2797
+ return
2798
+
2799
+ # Filter active (non-retracted)
2800
+ if "retracted" in dcat.columns:
2801
+ active = dcat[~dcat["retracted"].fillna(False).astype(bool)]
2802
+ n_retracted = len(dcat) - len(active)
2803
+ else:
2804
+ active = dcat
2805
+ n_retracted = 0
2806
+
2807
+ n_total = len(active)
2808
+ n_models = len(active.groupby(["ks_id", "triang_id", "model_hash"]))
2809
+ labels = active["label"].value_counts().to_dict() if "label" in active.columns else {}
2810
+ authors = active["committed_by"].nunique() if "committed_by" in active.columns else 0
2811
+
2812
+ print(f"Designated vacua: {n_total} solution(s) across "
2813
+ f"{n_models} model(s), {authors} contributor(s)")
2814
+ if n_retracted > 0:
2815
+ print(f" ({n_retracted} retracted, excluded from counts)")
2816
+ if labels:
2817
+ print(f" Labels: {labels}")
2818
+
2819
+ # Per-model summary
2820
+ groups = active.groupby(["h11", "ks_id", "triang_id"]).agg(
2821
+ n_vacua=("designated_id", "count"),
2822
+ ).reset_index()
2823
+ if len(groups) <= 20:
2824
+ print(f"\n{'h11':>4} {'ks_id':>6} {'trid':>5} {'vacua':>7}")
2825
+ for _, g in groups.iterrows():
2826
+ print(f"{g['h11']:4d} {g['ks_id']:6d} {g['triang_id']:5d} "
2827
+ f"{g['n_vacua']:7d}")
2828
+ else:
2829
+ print(f" ({len(groups)} models — use query_designated() for details)")
2830
+ def load_local_vacua(
2831
+ self,
2832
+ model: Any = None,
2833
+ label: Optional[str] = None,
2834
+ include_retracted: bool = False,
2835
+ **identity_kwargs: Any,
2836
+ ) -> Any:
2837
+ r"""
2838
+ **Description:**
2839
+ Load designated vacua stored in the local ``vacua_vault/`` for a
2840
+ given model.
2841
+
2842
+ Convenience wrapper around :meth:`query_designated` that
2843
+ resolves the per-model vault subdirectory via
2844
+ :meth:`_resolve_vacua_dir` and returns any solutions previously
2845
+ designated for that model.
2846
+
2847
+ Args:
2848
+ model: Optional JAXVacua model or ``lcs_tree`` used for
2849
+ identity extraction.
2850
+ label (str | None): If given, filter by designation label.
2851
+ include_retracted (bool): Include retracted entries.
2852
+ Defaults to False.
2853
+ **identity_kwargs: Explicit identity overrides
2854
+ (``h11``, ``h12``, ``ks_id``, ``triang_id``,
2855
+ ``cicy_id``, ``model_name``).
2856
+
2857
+ Returns:
2858
+ pandas.DataFrame: Solutions with the standard vacuum
2859
+ columns. Empty DataFrame if no vacua are stored.
2860
+ """
2861
+ ident = _extract_model_identity(model=model, **identity_kwargs)
2862
+ query = {}
2863
+ if ident.get("h11") is not None: query["h11"] = ident["h11"]
2864
+ if ident.get("h12") is not None: query["h12"] = ident["h12"]
2865
+ if ident.get("ks_id", -1) >= 0: query["ks_id"] = ident["ks_id"]
2866
+ if ident.get("triang_id", -1) >= 0: query["triang_id"] = ident["triang_id"]
2867
+ if ident.get("cicy_id", -1) >= 0: query["cicy_id"] = ident["cicy_id"]
2868
+ if label is not None: query["label"] = label
2869
+
2870
+ try:
2871
+ df = self.query_designated(**query)
2872
+ except TypeError:
2873
+ # Fallback for a reduced query_designated signature: query
2874
+ # by label (if any) and filter remaining columns manually.
2875
+ df = self.query_designated(label=label) if label else self.query_designated()
2876
+ if df is not None and len(df) > 0:
2877
+ for col, val in query.items():
2878
+ if col in df.columns:
2879
+ df = df[df[col] == val]
2880
+ df = df.reset_index(drop=True)
2881
+
2882
+ if df is not None and len(df) > 0 and not include_retracted:
2883
+ if "retracted" in df.columns:
2884
+ df = df[~df["retracted"].fillna(False).astype(bool)].reset_index(drop=True)
2885
+ return df
2886
+ def retract_designated(
2887
+ self,
2888
+ designated_id: int,
2889
+ reason: str,
2890
+ retracted_by: Optional[str] = None,
2891
+ ) -> None:
2892
+ r"""
2893
+ **Description:**
2894
+ Retract a designated solution. The solution is **not** deleted —
2895
+ it remains in the catalog and shard with ``retracted=True``,
2896
+ ``retraction_reason``, and ``retracted_at`` (timestamp) set.
2897
+ Retracted solutions are excluded from :meth:`query_designated` by
2898
+ default.
2899
+
2900
+ A row is also appended to ``<vault>/retractions.parquet`` as a
2901
+ permanent audit trail that survives any future catalog rebuild.
2902
+
2903
+ Args:
2904
+ designated_id (int): The ID of the solution to retract.
2905
+ reason (str): Explanation for the retraction (e.g.
2906
+ ``"Bug in jaxvacua v0.3.1 period computation"``).
2907
+ retracted_by (str | None): Optional identifier of the
2908
+ person/agent performing the retraction (ORCID, HF
2909
+ username, email). Recorded in the audit trail only.
2910
+
2911
+ Raises:
2912
+ KeyError: If the designated_id is not found.
2913
+ ValueError: If *reason* is empty.
2914
+ """
2915
+ pd = _require_pandas()
2916
+ if not reason or not reason.strip():
2917
+ raise ValueError("retraction reason must be non-empty")
2918
+
2919
+ self._ensure_designated_catalog()
2920
+ dcat = self._designated_catalog
2921
+ if dcat is None or len(dcat) == 0:
2922
+ raise KeyError(f"Designated ID {designated_id} not found — catalog is empty.")
2923
+
2924
+ mask = dcat["designated_id"] == designated_id
2925
+ if not mask.any():
2926
+ raise KeyError(f"Designated ID {designated_id} not found in catalog.")
2927
+
2928
+ now = pd.Timestamp.now(tz="UTC")
2929
+ dcat.loc[mask, "retracted"] = True
2930
+ dcat.loc[mask, "retraction_reason"] = reason
2931
+ dcat.loc[mask, "retracted_at"] = now
2932
+
2933
+ catalog_path = self._designated_dir / "designated_vacua_catalog.parquet"
2934
+ dcat.to_parquet(catalog_path, index=False)
2935
+ self._designated_catalog = dcat
2936
+
2937
+ # Append to <vault>/retractions.parquet (audit trail)
2938
+ audit_row = {
2939
+ "designated_id": int(designated_id),
2940
+ "reason": reason,
2941
+ "retracted_at": now,
2942
+ "retracted_by": retracted_by or "",
2943
+ }
2944
+ audit_path = _resolve_vault_dir() / "retractions.parquet"
2945
+ audit_path.parent.mkdir(parents=True, exist_ok=True)
2946
+ if audit_path.exists():
2947
+ existing = pd.read_parquet(audit_path)
2948
+ audit_df = _safe_concat([existing, pd.DataFrame([audit_row])],
2949
+ ignore_index=True)
2950
+ else:
2951
+ audit_df = pd.DataFrame([audit_row])
2952
+ audit_df.to_parquet(audit_path, index=False)
2953
+ def purge_retracted(
2954
+ self,
2955
+ older_than: Optional[str] = "30d",
2956
+ dry_run: bool = True,
2957
+ confirm: bool = False,
2958
+ archive: bool = False,
2959
+ ) -> list:
2960
+ r"""
2961
+ **Description:**
2962
+ Irreversibly delete retracted designated solutions.
2963
+
2964
+ Selects rows in the designated catalog with ``retracted=True``
2965
+ and (if *older_than* is given) ``retracted_at`` older than the
2966
+ threshold. Prints a summary of what would be deleted; only acts
2967
+ if both ``dry_run=False`` and ``confirm=True``.
2968
+
2969
+ Args:
2970
+ older_than (str | None): Pandas timedelta string (e.g.
2971
+ ``"30d"``, ``"90d"``, ``"6h"``) or ``None`` to ignore
2972
+ age. Defaults to ``"30d"``.
2973
+ dry_run (bool): If True (default), print what would be
2974
+ deleted and return the catalog subset — no files are
2975
+ touched.
2976
+ confirm (bool): Must be True alongside ``dry_run=False`` to
2977
+ actually delete. Guardrail against accidental data
2978
+ loss.
2979
+ archive (bool): If True, copy each shard to
2980
+ ``<vault>/archive/`` before deletion. Defaults to
2981
+ False.
2982
+
2983
+ Returns:
2984
+ list: List of ``designated_id`` values selected for (or,
2985
+ actually, deleted in) the purge.
2986
+ """
2987
+ pd = _require_pandas()
2988
+ import shutil
2989
+
2990
+ self._ensure_designated_catalog()
2991
+ dcat = self._designated_catalog
2992
+ if dcat is None or len(dcat) == 0:
2993
+ print("[purge_retracted] No designated catalog entries.")
2994
+ return []
2995
+
2996
+ if "retracted" not in dcat.columns:
2997
+ print("[purge_retracted] Catalog has no 'retracted' column — nothing to purge.")
2998
+ return []
2999
+
3000
+ mask = dcat["retracted"].fillna(False).astype(bool)
3001
+ if older_than is not None and "retracted_at" in dcat.columns:
3002
+ cutoff = pd.Timestamp.now(tz="UTC") - pd.Timedelta(older_than)
3003
+ ts = pd.to_datetime(dcat["retracted_at"], errors="coerce", utc=True)
3004
+ mask = mask & (ts < cutoff)
3005
+
3006
+ selected = dcat[mask]
3007
+ if len(selected) == 0:
3008
+ print("[purge_retracted] No retracted entries match the criteria.")
3009
+ return []
3010
+
3011
+ ids = [int(x) for x in selected["designated_id"].tolist()]
3012
+ print(f"[purge_retracted] {len(selected)} entries selected for purge:")
3013
+ for _, row in selected.iterrows():
3014
+ print(f" id={row.get('designated_id')} label={row.get('label')!r} "
3015
+ f"retracted_at={row.get('retracted_at')}")
3016
+
3017
+ if dry_run:
3018
+ print("[purge_retracted] dry_run=True — no files touched. "
3019
+ "Pass dry_run=False, confirm=True to actually delete.")
3020
+ return ids
3021
+ if not confirm:
3022
+ raise RuntimeError(
3023
+ "purge_retracted refuses to run with dry_run=False "
3024
+ "unless confirm=True is passed explicitly."
3025
+ )
3026
+
3027
+ # Each shard may contain multiple designated rows; surgically
3028
+ # remove just the purged rows and rewrite (or delete) each shard.
3029
+ vault = _resolve_vault_dir()
3030
+ archive_dir = vault / "archive"
3031
+ if archive:
3032
+ archive_dir.mkdir(parents=True, exist_ok=True)
3033
+
3034
+ shard_to_ids: Dict[Path, List[int]] = {}
3035
+ for _, row in selected.iterrows():
3036
+ try:
3037
+ shard_dir = self._resolve_vacua_dir(
3038
+ h11 = row.get("h11"),
3039
+ h12 = row.get("h12"),
3040
+ ks_id = row.get("ks_id", -1),
3041
+ triang_id = row.get("triang_id", -1),
3042
+ cicy_id = row.get("cicy_id", -1),
3043
+ model_name= row.get("model_name"),
3044
+ )
3045
+ except Exception as e:
3046
+ print(f"[purge_retracted] could not resolve shard for id={row['designated_id']}: {e}")
3047
+ continue
3048
+ shard_path = shard_dir / "shard_0.parquet"
3049
+ shard_to_ids.setdefault(shard_path, []).append(int(row["designated_id"]))
3050
+
3051
+ deleted = []
3052
+ for shard_path, ids in shard_to_ids.items():
3053
+ if not shard_path.exists():
3054
+ continue
3055
+ if archive:
3056
+ rel = f"{shard_path.parent.name}__{shard_path.name}"
3057
+ shutil.copy2(shard_path, archive_dir / rel)
3058
+ shard_df = pd.read_parquet(shard_path)
3059
+ keep = ~shard_df["designated_id"].isin(ids)
3060
+ shard_df = shard_df[keep]
3061
+ if len(shard_df) > 0:
3062
+ shard_df.to_parquet(shard_path, index=False)
3063
+ else:
3064
+ shard_path.unlink()
3065
+ deleted.extend(ids)
3066
+
3067
+ # Drop purged rows from catalog
3068
+ dcat = dcat[~mask].reset_index(drop=True)
3069
+ catalog_path = self._designated_dir / "designated_vacua_catalog.parquet"
3070
+ dcat.to_parquet(catalog_path, index=False)
3071
+ self._designated_catalog = dcat
3072
+
3073
+ print(f"[purge_retracted] Purged {len(deleted)} entry(ies) across "
3074
+ f"{len(shard_to_ids)} shard(s). Audit trail remains in "
3075
+ f"{vault}/retractions.parquet")
3076
+ return deleted
3077
+
3078
+
3079
+ __all__ = ['VacuaWriter', '_VacuaStreamWriter']