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,459 @@
1
+ r"""
2
+ Schema constants and file-level validation helpers for the vault.
3
+
4
+ **Homogeneity invariant.** Each parquet file in the vault must
5
+ contain rows describing **exactly one model** — i.e. every row
6
+ shares the same ``(ks_id, triang_id)`` (TDF) or ``cicy_id`` (CICY).
7
+ The vault layout (``<dataset>/h12_N/<identifier>/<label>.parquet``)
8
+ makes one-file-per-model the natural unit. Mixed-model files
9
+ break the catalogue's identity assumptions and the auto-load path
10
+ in :func:`validate_parquet_file`; they are rejected with a
11
+ top-level error.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ from pathlib import Path
19
+ from typing import Any, Dict, List, Optional, Tuple
20
+
21
+ # Schema version of the vault parquet layout. Defined here as the
22
+ # canonical source; ``cy_io`` re-exports the same constant so callers
23
+ # can import either path. Bump alongside any change to
24
+ # ``REQUIRED_COLUMNS`` or to the parquet kv-metadata contract.
25
+ SCHEMA_VERSION: int = 1
26
+
27
+ #: Top-level filenames the vault treats as metadata (CI rejects uploads
28
+ #: whose basename matches one of these).
29
+ RESERVED_NAMES = {
30
+ "catalog.parquet",
31
+ "retractions.parquet",
32
+ "schema.json",
33
+ "README.md",
34
+ }
35
+
36
+ #: Slug regex for free-form labels (Option A in the vacua-storage plan).
37
+ LABEL_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*(?:_v\d+)?$")
38
+
39
+ #: Required columns for every vault parquet file.
40
+ REQUIRED_COLUMNS = (
41
+ "flux", "moduli_re", "moduli_im", "tau_re", "tau_im",
42
+ )
43
+
44
+
45
+ def _basename_is_reserved(path: str | Path) -> bool:
46
+ name = os.path.basename(str(path))
47
+ if name in RESERVED_NAMES:
48
+ return True
49
+ if name.startswith("_"):
50
+ return True
51
+ return False
52
+
53
+
54
+ def _parse_label_from_filename(filename: str) -> Optional[str]:
55
+ """Extract the label from a filename. Strips the optional
56
+ ``{hf_username}_`` community prefix when the caller passes a
57
+ community-path filename — but since we can't tell from the name
58
+ alone whether a prefix is present, this just returns the stem
59
+ (caller strips prefixes as needed).
60
+ """
61
+ stem = os.path.splitext(os.path.basename(filename))[0]
62
+ return stem or None
63
+
64
+
65
+ def _extract_identity_from_row(row: Any) -> Optional[Dict[str, Any]]:
66
+ r"""
67
+ **Description:**
68
+ Extract a canonical model-identity dict from a single vacua row.
69
+
70
+ Returns ``{"dataset": "tdf", "kwargs": {"ks_id": …, "triang_id": …}}``
71
+ when the row carries non-``-1`` ``ks_id`` and ``triang_id`` columns,
72
+ or ``{"dataset": "cicy", "kwargs": {"cicy_id": …}}`` for a non-``-1``
73
+ ``cicy_id``. Returns ``None`` for "custom" / "unrooted" models
74
+ (all identity columns are ``-1`` or missing) — auto-load can't help
75
+ those and the caller should skip the physics path with a warning.
76
+
77
+ Args:
78
+ row: A pandas Series (one row of the vacua table).
79
+
80
+ Returns:
81
+ dict | None: Identity record, or ``None`` if no identifier
82
+ is present.
83
+ """
84
+ def _get(name: str, default: int = -1) -> int:
85
+ try:
86
+ v = row.get(name, default)
87
+ except AttributeError:
88
+ v = row[name] if name in row else default
89
+ try:
90
+ return int(v)
91
+ except (TypeError, ValueError):
92
+ return default
93
+
94
+ ks = _get("ks_id")
95
+ tr = _get("triang_id")
96
+ cic = _get("cicy_id")
97
+
98
+ if ks >= 0 and tr >= 0:
99
+ return {"dataset": "tdf",
100
+ "kwargs": {"ks_id": ks, "triang_id": tr}}
101
+ if cic >= 0:
102
+ return {"dataset": "cicy", "kwargs": {"cicy_id": cic}}
103
+ return None
104
+
105
+
106
+ def _identity_from_row(df: Any) -> Optional[Dict[str, Any]]:
107
+ r"""
108
+ **Description:**
109
+ Extract a single canonical identity record from a homogeneous
110
+ vacua DataFrame. Reads the **first** row; the homogeneity
111
+ invariant (enforced upstream by
112
+ :func:`_check_identity_consistency`) guarantees the rest agree.
113
+
114
+ Returns ``None`` when the DataFrame is empty or its rows lack
115
+ identity columns.
116
+
117
+ Args:
118
+ df: A pandas DataFrame with vacua rows.
119
+ """
120
+ if df is None or len(df) == 0:
121
+ return None
122
+ return _extract_identity_from_row(df.iloc[0])
123
+
124
+
125
+ def _check_identity_consistency(df: Any) -> List[str]:
126
+ r"""
127
+ **Description:**
128
+ Verify the per-file homogeneity invariant: every row must
129
+ describe the same model. See the module docstring for context.
130
+
131
+ Returns a list of top-level error strings (empty list = OK).
132
+
133
+ Args:
134
+ df: A pandas DataFrame with vacua rows.
135
+ """
136
+ errors: List[str] = []
137
+ if df is None or len(df) == 0:
138
+ return errors
139
+ id_cols = [c for c in ("ks_id", "triang_id", "cicy_id") if c in df.columns]
140
+ if not id_cols:
141
+ # No identity columns at all — handled at auto-load stage as a
142
+ # warning, not as an inconsistency error.
143
+ return errors
144
+ distinct = df[id_cols].drop_duplicates()
145
+ if len(distinct) > 1:
146
+ errors.append(
147
+ f"file contains rows for {len(distinct)} distinct models "
148
+ f"(violates the one-model-per-file invariant). Identifier "
149
+ f"tuples found: {distinct.values.tolist()[:5]}"
150
+ f"{' …' if len(distinct) > 5 else ''}"
151
+ )
152
+ return errors
153
+
154
+
155
+ def validate_parquet_file(
156
+ path: str | Path,
157
+ *,
158
+ model: Any = None,
159
+ db: Any = None,
160
+ model_hash_fn: Optional[Any] = None,
161
+ physics_checks: str = "auto",
162
+ F_term_tol: float = 1e-6,
163
+ check_tadpole: bool = True,
164
+ expected_schema_version: int = SCHEMA_VERSION,
165
+ ) -> Dict[str, Any]:
166
+ r"""
167
+ **Description:**
168
+ Load a parquet file and validate it against the vault schema.
169
+
170
+ Performs the same row-level checks as
171
+ :meth:`stringforge.cy_io.CYDatabase.validate_vacua`, plus an
172
+ identity-homogeneity check (one model per file — see the module
173
+ docstring for context) and an optional auto-load path that
174
+ reconstructs the model from row identity when physics checks
175
+ are requested.
176
+
177
+ Three modes via ``physics_checks``:
178
+
179
+ * ``"off"`` — schema-only validation (no identity check, no
180
+ tadpole, no F-term).
181
+ * ``"auto"`` (default) — schema + identity homogeneity always.
182
+ If ``model`` is supplied, runs physics with it. Else if rows
183
+ carry identity AND ``db`` is supplied, attempts to auto-load
184
+ via ``db.load_model(...)``. Missing ``db`` / unrooted rows /
185
+ auto-load failure all degrade to **warnings**.
186
+ * ``"explicit"`` — same as ``"auto"`` but every degradation is a
187
+ top-level error. For users who *require* physics validation.
188
+
189
+ **Pure dependency injection**: this function never imports
190
+ jaxvacua (or any other downstream package). Callers that want
191
+ physics-aware validation must supply ``db=`` and (optionally)
192
+ ``model_hash_fn=`` themselves.
193
+
194
+ Args:
195
+ path: Path to the parquet file.
196
+ model: Optional pre-built ``FluxVacuaFinder``
197
+ for F-term + tadpole verification. Wins over ``db`` /
198
+ ``physics_checks`` auto-load: if supplied, no auto-load is
199
+ attempted.
200
+ db: Optional pre-built CYDatabase (or
201
+ subclass) instance with a ``load_model(**ident)`` method
202
+ taking ``ks_id``/``triang_id`` (TDF) or ``cicy_id`` (CICY)
203
+ kwargs. Required for the auto-load path; if ``None`` and
204
+ ``model`` is also missing, auto-load is skipped with a
205
+ warning (in ``"auto"`` mode) or error (``"explicit"``).
206
+ model_hash_fn: Optional callable
207
+ ``(lcs_tree) -> str`` that recomputes the model hash from
208
+ an ``lcs_tree``-like object. When supplied alongside a
209
+ ``model``, the rebuilt hash is compared to the row's
210
+ stored ``model_hash`` and a mismatch raises a top-level
211
+ error (catches incompatible jaxvacua-version uploads).
212
+ When ``None``, the check is silently skipped.
213
+ physics_checks: ``"off"`` | ``"auto"`` (default) |
214
+ ``"explicit"``. See above.
215
+ F_term_tol: F-term tolerance for SUSY rows.
216
+ check_tadpole: Verify ``|f^T σ h| ≤ D3`` (requires
217
+ ``model``).
218
+ expected_schema_version: Expected ``schema_version`` from
219
+ parquet key-value metadata.
220
+
221
+ Returns:
222
+ dict: ``{"passed": bool, "errors": list, "warnings": list,
223
+ "n_rows": int, "n_failed": int, "per_row_report": list,
224
+ "metadata": dict}``.
225
+ """
226
+ if physics_checks not in ("off", "auto", "explicit"):
227
+ raise ValueError(
228
+ f"physics_checks must be 'off', 'auto', or 'explicit'; "
229
+ f"got {physics_checks!r}"
230
+ )
231
+ import pandas as pd
232
+ import pyarrow.parquet as pq
233
+
234
+ errors: List[str] = []
235
+ warnings: List[str] = []
236
+ report: List[Dict[str, Any]] = []
237
+ p = Path(path)
238
+
239
+ # 1. Filename checks
240
+ if _basename_is_reserved(p):
241
+ errors.append(f"Reserved filename: {p.name}")
242
+
243
+ stem = os.path.splitext(p.name)[0]
244
+ # Strip a leading {hf_username}_ prefix for community files (best-effort).
245
+ parent = p.parent.name
246
+ if parent == "community":
247
+ # {hf_username}_{label}[_v{n}]: require at least one underscore.
248
+ if "_" not in stem:
249
+ errors.append(
250
+ f"community file {p.name!r} lacks a '{{hf_username}}_' prefix"
251
+ )
252
+ if not LABEL_SLUG_RE.match(stem):
253
+ errors.append(f"filename stem {stem!r} is not a valid slug")
254
+
255
+ # 2. Load parquet + metadata
256
+ try:
257
+ table = pq.read_table(p)
258
+ except Exception as e:
259
+ return {
260
+ "passed": False,
261
+ "errors": [f"Failed to read parquet: {e}"],
262
+ "warnings": warnings,
263
+ "n_rows": 0,
264
+ "n_failed": 0,
265
+ "per_row_report": [],
266
+ "metadata": {},
267
+ }
268
+
269
+ md_raw = table.schema.metadata or {}
270
+ metadata = {k.decode(): v.decode() for k, v in md_raw.items()
271
+ if isinstance(k, (bytes, bytearray))}
272
+
273
+ sv = metadata.get("schema_version")
274
+ if sv is None:
275
+ warnings.append("parquet has no 'schema_version' metadata")
276
+ else:
277
+ try:
278
+ sv_int = int(sv)
279
+ if sv_int != expected_schema_version:
280
+ errors.append(
281
+ f"schema_version mismatch: file={sv_int}, "
282
+ f"expected={expected_schema_version}"
283
+ )
284
+ except ValueError:
285
+ errors.append(f"unparseable schema_version: {sv!r}")
286
+
287
+ # 3. Required columns
288
+ df = table.to_pandas()
289
+ missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]
290
+ if missing:
291
+ errors.append(f"missing required columns: {missing}")
292
+
293
+ n_rows = len(df)
294
+ if n_rows == 0:
295
+ warnings.append("file has 0 rows")
296
+
297
+ # 3.5 Identity homogeneity (only relevant when physics_checks ≠ "off"
298
+ # so users who explicitly request schema-only get it).
299
+ if physics_checks != "off":
300
+ errors.extend(_check_identity_consistency(df))
301
+
302
+ # 3.7 Auto-load: pure dependency injection. We never import the
303
+ # downstream model layer ourselves — the caller supplies a
304
+ # ``db`` instance whose ``load_model(**ident)`` returns a model
305
+ # carrying the necessary lcs_tree. Missing identity / missing db
306
+ # / load failure all degrade to a warning in ``"auto"`` mode and
307
+ # to a top-level error in ``"explicit"``.
308
+ if model is None and physics_checks in ("auto", "explicit") and n_rows > 0:
309
+ ident = _identity_from_row(df)
310
+ if ident is None:
311
+ msg = ("rows carry no model identity; cannot auto-load. "
312
+ "Pass `model=` explicitly or set "
313
+ "physics_checks='off' to skip physics.")
314
+ (errors if physics_checks == "explicit" else warnings).append(msg)
315
+ elif db is None:
316
+ msg = ("auto-load requires `db=`; pass an LCSDatabase "
317
+ "(or any CYDatabase subclass with a "
318
+ "`load_model(**ident)` method) instance. Pass "
319
+ "`physics_checks='off'` to skip physics validation.")
320
+ (errors if physics_checks == "explicit" else warnings).append(msg)
321
+ else:
322
+ try:
323
+ model = db.load_model(**ident["kwargs"])
324
+ except Exception as e: # noqa: BLE001
325
+ msg = (f"auto-load failed for "
326
+ f"{ident['dataset']}/{ident['kwargs']}: "
327
+ f"{type(e).__name__}: {e}")
328
+ (errors if physics_checks == "explicit" else warnings).append(msg)
329
+ model = None
330
+
331
+ # 3.8 Model-hash round-trip — when we have a model, a caller-supplied
332
+ # ``model_hash_fn``, AND a stored ``model_hash`` on the rows, the
333
+ # reconstructed tree's hash must match. Catches incompatible
334
+ # uploads (basis-change drift, conifold convention changes, etc.).
335
+ # When ``model_hash_fn`` is ``None``, the check is silently
336
+ # skipped — this keeps schema.py free of jaxvacua-specific
337
+ # imports.
338
+ if (model is not None and physics_checks != "off"
339
+ and model_hash_fn is not None
340
+ and "model_hash" in df.columns and n_rows > 0):
341
+ stored = str(df.iloc[0].get("model_hash") or "")
342
+ if stored:
343
+ try:
344
+ tree = getattr(model, "lcs_tree", None) or getattr(
345
+ getattr(model, "periods", None), "lcs_tree", None,
346
+ )
347
+ if tree is None:
348
+ warnings.append("model has no lcs_tree; "
349
+ "skipping model_hash check")
350
+ else:
351
+ rebuilt = model_hash_fn(tree)
352
+ if rebuilt != stored:
353
+ errors.append(
354
+ f"model_hash mismatch: row={stored[:12]}…, "
355
+ f"reconstructed={rebuilt[:12]}… "
356
+ f"(incompatible package version / basis / "
357
+ f"conifold convention)"
358
+ )
359
+ except Exception as e: # noqa: BLE001
360
+ warnings.append(f"model_hash check failed: {e}")
361
+
362
+ # 4. Per-row validation: integer flux, tadpole, F-terms
363
+ n_failed = 0
364
+ for i, row in df.iterrows():
365
+ row_errors: List[str] = []
366
+ if "flux" in df.columns:
367
+ try:
368
+ fl = row["flux"]
369
+ ints = [int(x) for x in fl]
370
+ if any(abs(x - v) > 1e-6 for x, v in zip(ints, fl)):
371
+ row_errors.append("flux vector contains non-integer entries")
372
+ except (TypeError, ValueError):
373
+ row_errors.append("flux vector is not iterable of ints")
374
+
375
+ # Tadpole check (requires model)
376
+ if check_tadpole and model is not None and "flux" in df.columns:
377
+ try:
378
+ import jax.numpy as jnp
379
+ tad = abs(float(
380
+ (model.tadpole(jnp.array(list(row["flux"])))).real
381
+ if hasattr(model.tadpole(jnp.array(list(row["flux"]))), "real")
382
+ else model.tadpole(jnp.array(list(row["flux"])))
383
+ ))
384
+ D3 = getattr(
385
+ getattr(model, "lcs_tree", None), "D3_tadpole", None,
386
+ )
387
+ if D3 is not None and tad > float(D3) + 1e-9:
388
+ row_errors.append(
389
+ f"tadpole {tad:.2f} > D3={float(D3):.2f}"
390
+ )
391
+ except Exception as e:
392
+ row_errors.append(f"tadpole check failed: {e}")
393
+
394
+ # F-term check for SUSY-flagged rows
395
+ if model is not None and bool(row.get("is_susy", False)):
396
+ try:
397
+ import jax.numpy as jnp
398
+ flux = jnp.array(list(row["flux"]), dtype=float)
399
+ mod = jnp.array(
400
+ [r + 1j * im for r, im in zip(row["moduli_re"], row["moduli_im"])]
401
+ )
402
+ tau = complex(row["tau_re"] + 1j * row["tau_im"])
403
+ DW = model.DW_x(
404
+ model._convert_complex_to_real(mod, tau), flux,
405
+ )
406
+ maxDW = float(abs(DW).max())
407
+ if maxDW > F_term_tol:
408
+ row_errors.append(
409
+ f"|DW|={maxDW:.2e} > tol={F_term_tol:.0e}"
410
+ )
411
+ except Exception as e:
412
+ row_errors.append(f"F-term check failed: {e}")
413
+
414
+ passed = not row_errors
415
+ if not passed:
416
+ n_failed += 1
417
+ report.append({
418
+ "index": int(i),
419
+ "passed": passed,
420
+ "errors": row_errors,
421
+ })
422
+
423
+ if n_failed > 0:
424
+ errors.append(f"{n_failed}/{n_rows} rows failed row-level validation")
425
+
426
+ return {
427
+ "passed": len(errors) == 0,
428
+ "errors": errors,
429
+ "warnings": warnings,
430
+ "n_rows": n_rows,
431
+ "n_failed": n_failed,
432
+ "per_row_report": report,
433
+ "metadata": metadata,
434
+ }
435
+
436
+
437
+ def split_by_validation(
438
+ df: Any, per_row_report: List[Dict[str, Any]],
439
+ ) -> Tuple[Any, Any]:
440
+ r"""
441
+ **Description:**
442
+ Split a DataFrame into (valid, rejected) subsets based on a
443
+ per-row validation report. The rejected DataFrame gets an extra
444
+ ``error`` column containing the joined error strings.
445
+ """
446
+ import pandas as pd
447
+ ok_idx = [r["index"] for r in per_row_report if r["passed"]]
448
+ bad_idx = [r["index"] for r in per_row_report if not r["passed"]]
449
+ valid = df.iloc[ok_idx].reset_index(drop=True) if ok_idx else df.iloc[:0].copy()
450
+ if bad_idx:
451
+ rej = df.iloc[bad_idx].copy().reset_index(drop=True)
452
+ errs = []
453
+ for r in per_row_report:
454
+ if not r["passed"]:
455
+ errs.append("; ".join(r["errors"]))
456
+ rej["error"] = errs
457
+ else:
458
+ rej = df.iloc[:0].copy()
459
+ return valid, rej