optivibe-reference 0.2.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.
- optivibe_reference/__init__.py +14 -0
- optivibe_reference/_envelope.py +19 -0
- optivibe_reference/_paths.py +66 -0
- optivibe_reference/_probe_common.py +142 -0
- optivibe_reference/build_data.py +271 -0
- optivibe_reference/build_steps.py +182 -0
- optivibe_reference/catalog_build.py +1138 -0
- optivibe_reference/data/operand_semantics.json +2192 -0
- optivibe_reference/data/operand_synonyms.json +1687 -0
- optivibe_reference/data/provenance_grants.txt +5 -0
- optivibe_reference/data/tolerance_operand_synonyms.json +307 -0
- optivibe_reference/errors.py +57 -0
- optivibe_reference/glass_build.py +433 -0
- optivibe_reference/glass_dispersion.py +207 -0
- optivibe_reference/glass_math.py +383 -0
- optivibe_reference/glass_parse.py +168 -0
- optivibe_reference/manual_build.py +672 -0
- optivibe_reference/manual_enrich.py +490 -0
- optivibe_reference/probe_operands.py +226 -0
- optivibe_reference/probe_tolerances.py +371 -0
- optivibe_reference/server.py +547 -0
- optivibe_reference/tolerance_build.py +554 -0
- optivibe_reference/tools/__init__.py +5 -0
- optivibe_reference/tools/_glass_common.py +137 -0
- optivibe_reference/tools/_glass_kind.py +133 -0
- optivibe_reference/tools/_query_params.py +57 -0
- optivibe_reference/tools/_rag_match.py +92 -0
- optivibe_reference/tools/find_glass_pair.py +574 -0
- optivibe_reference/tools/find_glasses.py +339 -0
- optivibe_reference/tools/lookup_glass.py +262 -0
- optivibe_reference/tools/lookup_operand.py +463 -0
- optivibe_reference/tools/search_reference.py +321 -0
- optivibe_reference-0.2.0.dist-info/METADATA +44 -0
- optivibe_reference-0.2.0.dist-info/RECORD +37 -0
- optivibe_reference-0.2.0.dist-info/WHEEL +5 -0
- optivibe_reference-0.2.0.dist-info/entry_points.txt +2 -0
- optivibe_reference-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"""glass_build.py — build the glass catalog (JSON + SQLite). Mirrors catalog_build.
|
|
2
|
+
|
|
3
|
+
Pipeline (§5/§6/§8), mirroring ``catalog_build.py``:
|
|
4
|
+
|
|
5
|
+
1. ``build_glass_catalog_json(glasscat_dir, provenance_md)`` — assert the
|
|
6
|
+
``.agf``-derivation grant row is on file FIRST (fail-closed
|
|
7
|
+
``ProvenanceGateError``), then parse every shipped ``.agf`` record, slice the
|
|
8
|
+
leading ``FORMULA_CD_COUNT[formula]`` CD coeffs, recompute the cardinal indices
|
|
9
|
+
(nd/ng/nF/nC), apply the §5 in-band validity guard, and store ``delta_pg_f``
|
|
10
|
+
VERBATIM (ED token 4). ``provenance='agf_recompute'``.
|
|
11
|
+
2. ``write_glass_catalog_json`` — persist normalized-LF / ``ensure_ascii`` /
|
|
12
|
+
``indent=2`` (the same idiom as ``catalog_build.write_catalog_json``) so the
|
|
13
|
+
forbidden-token scanner sees it and the drift hash is over THIS file.
|
|
14
|
+
3. ``build_glass_db`` / ``open_glass_catalog`` — build a keyed ``glass`` table
|
|
15
|
+
(``PRIMARY KEY(catalog, name)``) from the committed JSON. EXACT-ONLY, NO FTS5.
|
|
16
|
+
|
|
17
|
+
THE CARDINAL DEFENSE (§5): a computed cardinal is stored ONLY when its line is
|
|
18
|
+
in-band; otherwise the field is ``null`` and the ``*_valid`` flag is ``False`` —
|
|
19
|
+
so an out-of-band IR glass (KRS5) NEVER returns a plausible-but-meaningless Pg,F.
|
|
20
|
+
``assert_glass_provenance_invariants`` enforces the value<->flag parity.
|
|
21
|
+
|
|
22
|
+
PROVENANCE (§8): no raw ``.agf`` is ever committed; only OUR computed/parsed
|
|
23
|
+
numbers + factual glass names land in ``glass_catalog.json``. The build fails
|
|
24
|
+
CLOSED unless the ``.agf``-derivation ledger row is on file in ``PROVENANCE.md``.
|
|
25
|
+
"""
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import sqlite3
|
|
29
|
+
|
|
30
|
+
from . import _paths
|
|
31
|
+
from .errors import ProvenanceGateError
|
|
32
|
+
from .glass_dispersion import (
|
|
33
|
+
FORMULA_CD_COUNT,
|
|
34
|
+
FORMULA_NAMES,
|
|
35
|
+
LINE_C,
|
|
36
|
+
LINE_F,
|
|
37
|
+
LINE_d,
|
|
38
|
+
LINE_g,
|
|
39
|
+
abbe_vd,
|
|
40
|
+
index_at,
|
|
41
|
+
partial_pgf,
|
|
42
|
+
)
|
|
43
|
+
from .glass_parse import find_catalogs, iter_glass_records
|
|
44
|
+
|
|
45
|
+
SCHEMA_VERSION = 1
|
|
46
|
+
BUILDER_VERSION = 1
|
|
47
|
+
|
|
48
|
+
# A computed value whose |nF-nC| denominator is below this floor is a near-flat-
|
|
49
|
+
# dispersion artifact (e.g. a Conrady adhesive or a VACUUM row with nF~nC): BOTH
|
|
50
|
+
# the Abbe number Vd = (nd-1)/(nF-nC) AND the partial Pg,F = (ng-nF)/(nF-nC)
|
|
51
|
+
# divide by that same denominator, so a machine-noise denominator makes BOTH
|
|
52
|
+
# numerically meaningless. ONE source of truth — vd AND pg_f are nulled when
|
|
53
|
+
# |nF-nC| <= _DENOM_FLOOR even when the lines are in-band (§5 / gate 1).
|
|
54
|
+
#
|
|
55
|
+
# The VALUE is set from the measured split of the installed catalogs: the
|
|
56
|
+
# noise rows sit at |nF-nC| <= 3.1e-6 (four VACUUM rows; a constant-index model glass at
|
|
57
|
+
# exactly 0) and the smallest REAL material at 0.00285 (a liquid), with nothing between.
|
|
58
|
+
# 1e-4 is the geometric middle of that gap. The earlier 0.005 sat INSIDE the real
|
|
59
|
+
# materials: it blanked calcium fluoride, the FPL53 / FCD100 / FK95 class and the other
|
|
60
|
+
# lowest-dispersion glasses (nF-nC about 0.0046, Abbe number about 95), 60 rows in all,
|
|
61
|
+
# so no Abbe or partial-dispersion search could return them. An absolute floor, not one
|
|
62
|
+
# relative to nd-1: a vacuum row has nd below 1 and overlaps the real rows on that scale.
|
|
63
|
+
_DENOM_FLOOR = 1e-4
|
|
64
|
+
# Back-compat alias (the floor was historically named for vd only).
|
|
65
|
+
_VD_DENOM_FLOOR = _DENOM_FLOOR
|
|
66
|
+
|
|
67
|
+
# Path anchors (package-relative, NOT cwd-relative — agent cwd resets, §5).
|
|
68
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
69
|
+
DATA_DIR = os.path.join(_HERE, "data")
|
|
70
|
+
GLASS_CATALOG_JSON = os.path.join(DATA_DIR, "glass_catalog.json")
|
|
71
|
+
# The ledger the gate reads: the repo-root PROVENANCE.md in a source checkout, the
|
|
72
|
+
# shipped data/provenance_grants.txt marker in an installed package (``_paths``).
|
|
73
|
+
PROVENANCE_PATH = _paths.provenance_ledger_path()
|
|
74
|
+
|
|
75
|
+
# The PROVENANCE ledger-row marker that must be on file before .agf derivation.
|
|
76
|
+
# ASCII substring of the committed row ("Glass catalog (Nd/Vd/coeffs/...)").
|
|
77
|
+
_LEDGER_ROW_MARKER = "Glass catalog (Nd/Vd/coeffs"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# --- provenance fail-closed gate (mirrors manual_build.assert_manual_grant) -
|
|
81
|
+
def assert_agf_grant_on_file(provenance_path=PROVENANCE_PATH):
|
|
82
|
+
"""Fail CLOSED unless the .agf-derivation ledger row is on file (§8).
|
|
83
|
+
|
|
84
|
+
Reads ``PROVENANCE.md`` and requires the ledger-row marker. Raises
|
|
85
|
+
``ProvenanceGateError`` if the file is missing or the row is absent — guarding
|
|
86
|
+
against a future deletion of the grant silently re-enabling .agf-derived
|
|
87
|
+
commits. Mirrors ``manual_build.assert_manual_grant_on_file``.
|
|
88
|
+
"""
|
|
89
|
+
try:
|
|
90
|
+
with open(provenance_path, "r", encoding="utf-8") as fh:
|
|
91
|
+
text = fh.read()
|
|
92
|
+
except OSError as exc:
|
|
93
|
+
raise ProvenanceGateError(
|
|
94
|
+
f"PROVENANCE ledger not readable at {provenance_path!r}: {exc}"
|
|
95
|
+
)
|
|
96
|
+
if _LEDGER_ROW_MARKER not in text:
|
|
97
|
+
raise ProvenanceGateError(
|
|
98
|
+
".agf-derivation grant row "
|
|
99
|
+
f"({_LEDGER_ROW_MARKER!r}) not on file in PROVENANCE.md — "
|
|
100
|
+
"glass-catalog .agf derivation fails closed until the ledger row "
|
|
101
|
+
"is recorded"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def in_band(min_wave, max_wave, line):
|
|
106
|
+
"""True iff ``line`` (µm) lies within ``[min_wave, max_wave]`` (both present)."""
|
|
107
|
+
return (min_wave is not None and max_wave is not None
|
|
108
|
+
and min_wave <= line <= max_wave)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _build_row(rec):
|
|
112
|
+
"""Recompute one parsed record into a committed-JSON row dict (§5/§6)."""
|
|
113
|
+
formula = rec["formula"]
|
|
114
|
+
need = FORMULA_CD_COUNT.get(formula, 0)
|
|
115
|
+
# Slice the LEADING need coeffs; a short CD list is tolerated (recompute then
|
|
116
|
+
# yields None -> null fields, never a raise).
|
|
117
|
+
cd = (rec["cd"] or [])[:need]
|
|
118
|
+
|
|
119
|
+
nd = index_at(formula, cd, LINE_d)
|
|
120
|
+
ng = index_at(formula, cd, LINE_g)
|
|
121
|
+
nf = index_at(formula, cd, LINE_F)
|
|
122
|
+
nc = index_at(formula, cd, LINE_C)
|
|
123
|
+
|
|
124
|
+
min_wave = rec["min_wave"]
|
|
125
|
+
max_wave = rec["max_wave"]
|
|
126
|
+
# Band membership of each cardinal line (the §5 in-band guard input).
|
|
127
|
+
d_in_band = in_band(min_wave, max_wave, LINE_d)
|
|
128
|
+
pg_f_in_band = (in_band(min_wave, max_wave, LINE_g)
|
|
129
|
+
and in_band(min_wave, max_wave, LINE_F)
|
|
130
|
+
and in_band(min_wave, max_wave, LINE_C))
|
|
131
|
+
|
|
132
|
+
vd = abbe_vd(nd, nf, nc)
|
|
133
|
+
pg_f = partial_pgf(ng, nf, nc)
|
|
134
|
+
|
|
135
|
+
# The validity FLAG means "in-band AND the value was actually computed" — so a
|
|
136
|
+
# band-OK glass whose recompute fell over (short CD -> None, or a degenerate
|
|
137
|
+
# flat index nF==nC -> partial_pgf None) carries flag=False, not a True flag
|
|
138
|
+
# over a null value. This keeps the §6 value<->flag biconditional EXACT (an
|
|
139
|
+
# in-band-but-null pg_f, e.g. MISC.AGF N15 with a constant 1.5 index, would
|
|
140
|
+
# otherwise break it) while still NEVER emitting an out-of-band number.
|
|
141
|
+
nd_valid = d_in_band and nd is not None
|
|
142
|
+
# pg_f = (ng-nF)/(nF-nC): meaningless when nF~nC even if the lines are in-band
|
|
143
|
+
# (a VACUUM-style row has |nF-nC|~3e-6 -> a noise pg_f~0.556). The SAME
|
|
144
|
+
# denominator floor vd carries (one source of truth, _DENOM_FLOOR) gates pg_f.
|
|
145
|
+
pg_f_valid = (pg_f_in_band and pg_f is not None
|
|
146
|
+
and nf is not None and nc is not None
|
|
147
|
+
and abs(nf - nc) > _DENOM_FLOOR)
|
|
148
|
+
# vd is meaningless when nF~nC even if d is in-band (near-flat dispersion).
|
|
149
|
+
vd_ok = (d_in_band and vd is not None and nf is not None and nc is not None
|
|
150
|
+
and abs(nf - nc) > _DENOM_FLOOR)
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
"catalog": rec["catalog"],
|
|
154
|
+
"name": rec["name"],
|
|
155
|
+
"formula": formula,
|
|
156
|
+
"formula_name": FORMULA_NAMES.get(formula),
|
|
157
|
+
"cd": cd,
|
|
158
|
+
"min_wave": min_wave,
|
|
159
|
+
"max_wave": max_wave,
|
|
160
|
+
"nd_stored": rec["nd_stored"],
|
|
161
|
+
"vd_stored": rec["vd_stored"],
|
|
162
|
+
"delta_pg_f": rec["dpgf"], # VERBATIM ED[4]; no re-derivation (§5 R3)
|
|
163
|
+
"nd": nd if nd_valid else None,
|
|
164
|
+
"ng": ng if pg_f_valid else None,
|
|
165
|
+
"nf": nf if pg_f_valid else None,
|
|
166
|
+
"nc": nc if pg_f_valid else None,
|
|
167
|
+
"vd": vd if vd_ok else None,
|
|
168
|
+
"pg_f": pg_f if pg_f_valid else None,
|
|
169
|
+
"nd_valid": nd_valid,
|
|
170
|
+
"pg_f_valid": pg_f_valid,
|
|
171
|
+
"provenance": "agf_recompute",
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _completeness_score(row):
|
|
176
|
+
"""Count the structurally-load-bearing fields present on a parsed row.
|
|
177
|
+
|
|
178
|
+
Used by the dedupe (H-2): on a within-catalog duplicate (catalog, name) key, we
|
|
179
|
+
keep the MORE structurally-complete record rather than blindly last-wins, so a
|
|
180
|
+
truncated bare ``NM DUP`` (formula/cd/min_wave/max_wave all None) can never
|
|
181
|
+
overwrite the complete first record. The score counts the four fields that a
|
|
182
|
+
truncation drops; genuine near-identical dups (e.g. two full records) tie and
|
|
183
|
+
fall back to the documented OpticStudio last-wins behavior.
|
|
184
|
+
"""
|
|
185
|
+
return sum(
|
|
186
|
+
1 for k in ("formula", "cd", "min_wave", "max_wave")
|
|
187
|
+
if row.get(k) is not None
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def assert_glass_provenance_invariants(rows):
|
|
192
|
+
"""Assert the §6 value<->flag parity over the catalog rows (never disagree).
|
|
193
|
+
|
|
194
|
+
- non-null ``pg_f`` <=> ``pg_f_valid is True``;
|
|
195
|
+
- non-null ``nd`` <=> ``nd_valid is True``;
|
|
196
|
+
- every row's ``provenance`` is ``'agf_recompute'``.
|
|
197
|
+
|
|
198
|
+
Raises ``AssertionError`` on any violation. Used by the build and the tests.
|
|
199
|
+
"""
|
|
200
|
+
for row in rows:
|
|
201
|
+
key = (row.get("catalog"), row.get("name"))
|
|
202
|
+
assert (row["pg_f"] is not None) == bool(row["pg_f_valid"]), (
|
|
203
|
+
f"{key}: pg_f value<->pg_f_valid flag mismatch"
|
|
204
|
+
)
|
|
205
|
+
assert (row["nd"] is not None) == bool(row["nd_valid"]), (
|
|
206
|
+
f"{key}: nd value<->nd_valid flag mismatch"
|
|
207
|
+
)
|
|
208
|
+
assert row["provenance"] == "agf_recompute", (
|
|
209
|
+
f"{key}: bad provenance {row['provenance']!r}"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def build_glass_catalog_json(glasscat_dir, provenance_md=PROVENANCE_PATH):
|
|
214
|
+
"""Build the normalized glass-catalog dict from the shipped .agf set (§5/§8).
|
|
215
|
+
|
|
216
|
+
START GATE: ``assert_agf_grant_on_file`` is the FIRST action (fail-closed). Then
|
|
217
|
+
every record in every catalog is parsed + recomputed into a row (§6 schema).
|
|
218
|
+
``agf_glass_count`` counts EVERY parsed record (in-band or not).
|
|
219
|
+
"""
|
|
220
|
+
assert_agf_grant_on_file(provenance_md)
|
|
221
|
+
# ``agf_glass_count`` counts every RAW parsed record. A handful of shipped
|
|
222
|
+
# catalogs carry a same-name DUPLICATE entry (e.g. HIKARI.AGF E-F2 appears
|
|
223
|
+
# twice with near-identical coeffs) — the composite (catalog, name) PRIMARY KEY
|
|
224
|
+
# cannot hold both, so we DEDUPE keeping the LAST occurrence (OpticStudio's own
|
|
225
|
+
# loader is last-wins) and emit one row per key. The raw count is preserved in
|
|
226
|
+
# ``agf_glass_count`` so the offline-repro drift gate still pins the true record
|
|
227
|
+
# tally; the Nd checksum is over the (deterministic) deduped row set.
|
|
228
|
+
by_key = {}
|
|
229
|
+
count = 0
|
|
230
|
+
quarantined = 0
|
|
231
|
+
empty_catalogs = []
|
|
232
|
+
for path in find_catalogs(glasscat_dir):
|
|
233
|
+
# Per-catalog record count: a shipped .agf that parses to ZERO records is a
|
|
234
|
+
# hard build failure, NEVER a silent drop. ~11 install catalogs ship
|
|
235
|
+
# UTF-16-LE; a decode-encoding regression there yields zero records and
|
|
236
|
+
# would silently shrink the catalog (the SILENT-DATA-LOSS defect this guard
|
|
237
|
+
# closes). The load-bearing guard: assert every enumerated catalog >= 1.
|
|
238
|
+
per_catalog = 0
|
|
239
|
+
for rec in iter_glass_records(path):
|
|
240
|
+
count += 1
|
|
241
|
+
per_catalog += 1
|
|
242
|
+
row = _build_row(rec)
|
|
243
|
+
# M-1: a record with no NM name token yields name=None — that can never
|
|
244
|
+
# be a real keyed glass (it would land a junk (catalog, None) PRIMARY
|
|
245
|
+
# KEY). QUARANTINE it (skip + tally), but NOT a record that merely lacks
|
|
246
|
+
# optical data (formula None with a valid name is a safe-null row that
|
|
247
|
+
# stays). A blank/whitespace name is treated the same as None.
|
|
248
|
+
name = row["name"]
|
|
249
|
+
if name is None or (isinstance(name, str) and not name.strip()):
|
|
250
|
+
quarantined += 1
|
|
251
|
+
continue
|
|
252
|
+
key = (row["catalog"], name)
|
|
253
|
+
# H-2: on a duplicate key, keep the MORE structurally-complete row. A
|
|
254
|
+
# within-catalog dup whose SECOND record is truncated (bare "NM DUP"
|
|
255
|
+
# with formula/cd None) must NOT overwrite the complete first row with a
|
|
256
|
+
# null-filled one. Only when the two are EQUALLY complete do we fall
|
|
257
|
+
# back to last-wins (the documented OpticStudio behavior for genuine
|
|
258
|
+
# near-identical dups like a doubled full record).
|
|
259
|
+
prev = by_key.get(key)
|
|
260
|
+
if prev is None or _completeness_score(row) >= _completeness_score(prev):
|
|
261
|
+
by_key[key] = row
|
|
262
|
+
if per_catalog == 0:
|
|
263
|
+
empty_catalogs.append(os.path.basename(path))
|
|
264
|
+
if empty_catalogs:
|
|
265
|
+
raise ValueError(
|
|
266
|
+
"glass-catalog build: %d enumerated .agf catalog(s) parsed to ZERO "
|
|
267
|
+
"records (a silently-empty catalog is now a hard build failure, not a "
|
|
268
|
+
"silent drop) — check the file encoding (UTF-16 catalogs need BOM "
|
|
269
|
+
"decode): %s" % (len(empty_catalogs), ", ".join(sorted(empty_catalogs)))
|
|
270
|
+
)
|
|
271
|
+
rows = [by_key[k] for k in sorted(by_key)]
|
|
272
|
+
assert_glass_provenance_invariants(rows)
|
|
273
|
+
return {
|
|
274
|
+
"schema_version": SCHEMA_VERSION,
|
|
275
|
+
"builder_version": BUILDER_VERSION,
|
|
276
|
+
"agf_glass_count": count,
|
|
277
|
+
"quarantined_count": quarantined,
|
|
278
|
+
"row_count": len(rows),
|
|
279
|
+
"rows": rows,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def write_glass_catalog_json(out_path, catalog):
|
|
284
|
+
"""Write ``catalog`` as normalized-LF, indent=2 JSON (reuse §2 idiom).
|
|
285
|
+
|
|
286
|
+
``newline="\n"`` forces LF on every platform so the committed artifact is
|
|
287
|
+
byte-stable and the reproducibility hash is over THIS file (§8). Mirrors
|
|
288
|
+
``catalog_build.write_catalog_json``.
|
|
289
|
+
"""
|
|
290
|
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
|
291
|
+
text = json.dumps(catalog, indent=2, ensure_ascii=True)
|
|
292
|
+
with open(out_path, "w", encoding="utf-8", newline="\n") as fh:
|
|
293
|
+
fh.write(text)
|
|
294
|
+
fh.write("\n")
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _load_json(path):
|
|
298
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
299
|
+
return json.load(fh)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# --- SQLite schema (§6) — keyed, EXACT-ONLY, NO FTS5 -----------------------
|
|
303
|
+
_CREATE_GLASS = """
|
|
304
|
+
CREATE TABLE glass (
|
|
305
|
+
catalog TEXT NOT NULL,
|
|
306
|
+
name TEXT NOT NULL,
|
|
307
|
+
formula INTEGER,
|
|
308
|
+
formula_name TEXT,
|
|
309
|
+
cd TEXT,
|
|
310
|
+
min_wave REAL,
|
|
311
|
+
max_wave REAL,
|
|
312
|
+
nd_stored REAL,
|
|
313
|
+
vd_stored REAL,
|
|
314
|
+
delta_pg_f REAL,
|
|
315
|
+
nd REAL,
|
|
316
|
+
ng REAL,
|
|
317
|
+
nf REAL,
|
|
318
|
+
nc REAL,
|
|
319
|
+
vd REAL,
|
|
320
|
+
pg_f REAL,
|
|
321
|
+
nd_valid INTEGER NOT NULL,
|
|
322
|
+
pg_f_valid INTEGER NOT NULL,
|
|
323
|
+
provenance TEXT,
|
|
324
|
+
PRIMARY KEY (catalog, name)
|
|
325
|
+
)
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# A stored ΔPg,F beyond this reads as missing (the owner's choice). The
|
|
330
|
+
# vendor field holds a few impossible values (HIKARI Q-LASFH59S -81.0); the largest real one in
|
|
331
|
+
# the shipped catalogs is about 0.072. The committed JSON keeps the vendor's value.
|
|
332
|
+
DELTA_PG_F_LIMIT = 0.1
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _plausible_delta_pg_f(value):
|
|
336
|
+
"""Return ``value``, or None when it is absent or its magnitude is above DELTA_PG_F_LIMIT."""
|
|
337
|
+
if value is None or abs(value) > DELTA_PG_F_LIMIT:
|
|
338
|
+
return None
|
|
339
|
+
return value
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def build_glass_db(catalog_json_path, conn):
|
|
343
|
+
"""Build the keyed ``glass`` table from the committed JSON (NO FTS5).
|
|
344
|
+
|
|
345
|
+
ONE-SHOT: ``build_glass_db`` creates the ``glass`` table on a FRESH connection.
|
|
346
|
+
It is NOT idempotent against a persistent path — a second call on a connection
|
|
347
|
+
that already holds a ``glass`` table raises a clear ``RuntimeError`` (GLASS-3)
|
|
348
|
+
rather than the cryptic ``sqlite3.OperationalError: table glass already
|
|
349
|
+
exists``. The runtime dispatch path uses ``:memory:`` (a fresh table per open),
|
|
350
|
+
so this never bites at runtime; the guard makes a developer's accidental reuse
|
|
351
|
+
of a persistent path fail clearly. Pass a fresh ``:memory:`` db or a new path to
|
|
352
|
+
rebuild. We deliberately do NOT add ``IF NOT EXISTS`` (that would silently REUSE
|
|
353
|
+
a stale table) or any version-reconcile machinery (no persistent-reuse path is
|
|
354
|
+
in use — YAGNI).
|
|
355
|
+
|
|
356
|
+
The SQL ``PRIMARY KEY (catalog, name)`` raises ``IntegrityError`` on a
|
|
357
|
+
duplicate (the storage-layer dedupe). ``cd`` is stored as a JSON string. The
|
|
358
|
+
``*_valid`` flags are stored as 0/1 INTEGERs. Returns ``conn``.
|
|
359
|
+
"""
|
|
360
|
+
# One-shot precondition: a pre-existing ``glass`` table means this connection
|
|
361
|
+
# was already built — reject reuse with a clear message (not the cryptic
|
|
362
|
+
# "table glass already exists" OperationalError that CREATE TABLE would raise).
|
|
363
|
+
existing = conn.execute(
|
|
364
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='glass'"
|
|
365
|
+
).fetchone()
|
|
366
|
+
if existing is not None:
|
|
367
|
+
raise RuntimeError(
|
|
368
|
+
"glass table already exists; open_glass_catalog/build_glass_db is "
|
|
369
|
+
"one-shot — pass a fresh :memory: db or a new path"
|
|
370
|
+
)
|
|
371
|
+
catalog = _load_json(catalog_json_path)
|
|
372
|
+
conn.execute(_CREATE_GLASS)
|
|
373
|
+
for row in catalog["rows"]:
|
|
374
|
+
conn.execute(
|
|
375
|
+
"INSERT INTO glass (catalog, name, formula, formula_name, cd, "
|
|
376
|
+
"min_wave, max_wave, nd_stored, vd_stored, delta_pg_f, nd, ng, nf, "
|
|
377
|
+
"nc, vd, pg_f, nd_valid, pg_f_valid, provenance) "
|
|
378
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
379
|
+
(
|
|
380
|
+
row["catalog"],
|
|
381
|
+
row["name"],
|
|
382
|
+
row.get("formula"),
|
|
383
|
+
row.get("formula_name"),
|
|
384
|
+
json.dumps(row.get("cd")),
|
|
385
|
+
row.get("min_wave"),
|
|
386
|
+
row.get("max_wave"),
|
|
387
|
+
row.get("nd_stored"),
|
|
388
|
+
row.get("vd_stored"),
|
|
389
|
+
_plausible_delta_pg_f(row.get("delta_pg_f")),
|
|
390
|
+
row.get("nd"),
|
|
391
|
+
row.get("ng"),
|
|
392
|
+
row.get("nf"),
|
|
393
|
+
row.get("nc"),
|
|
394
|
+
row.get("vd"),
|
|
395
|
+
row.get("pg_f"),
|
|
396
|
+
1 if row.get("nd_valid") else 0,
|
|
397
|
+
1 if row.get("pg_f_valid") else 0,
|
|
398
|
+
row.get("provenance"),
|
|
399
|
+
),
|
|
400
|
+
)
|
|
401
|
+
conn.commit()
|
|
402
|
+
return conn
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def open_glass_catalog(db_path=":memory:", json_path=None, check_same_thread=False):
|
|
406
|
+
"""Open a glass-catalog connection, building the keyed table from committed JSON.
|
|
407
|
+
|
|
408
|
+
The DB is ALWAYS built from the committed normalized-LF JSON (the binary
|
|
409
|
+
``.db`` is never committed — §8). The JSON path resolves via a package-relative
|
|
410
|
+
anchor. ``check_same_thread=False`` mirrors ``open_catalog`` (the runtime path
|
|
411
|
+
is READ-ONLY and may be used from an async MCP worker thread).
|
|
412
|
+
|
|
413
|
+
ONE-SHOT: each call builds the ``glass`` table on a FRESH connection. The
|
|
414
|
+
default ``:memory:`` path gives a fresh table every open; reusing the SAME
|
|
415
|
+
persistent ``db_path`` raises a clear ``RuntimeError`` (GLASS-3) because the
|
|
416
|
+
table already exists — open a fresh connection (a new path or ``:memory:``) per
|
|
417
|
+
catalog. No persistent-reuse / version-reconcile path is supported (YAGNI).
|
|
418
|
+
|
|
419
|
+
Returns a ``sqlite3.Connection``. The caller owns closing it.
|
|
420
|
+
"""
|
|
421
|
+
if json_path is None:
|
|
422
|
+
json_path = GLASS_CATALOG_JSON
|
|
423
|
+
conn = sqlite3.connect(db_path, check_same_thread=check_same_thread)
|
|
424
|
+
try:
|
|
425
|
+
build_glass_db(json_path, conn)
|
|
426
|
+
except Exception:
|
|
427
|
+
# build_glass_db RAISES (one-shot guard) on a pre-existing ``glass``
|
|
428
|
+
# table BEFORE we can return ``conn`` — the just-opened connection would
|
|
429
|
+
# leak (on Windows it can retain a file handle). The raise path must own
|
|
430
|
+
# the conn it opened: close it, then re-raise unchanged.
|
|
431
|
+
conn.close()
|
|
432
|
+
raise
|
|
433
|
+
return conn
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""glass_dispersion.py — the .agf dispersion engine (PURE math; lifted verbatim).
|
|
2
|
+
|
|
3
|
+
Lifted VERBATIM from the live probe (``scripts/probe_glass.py``): the 13 ``_n_*``
|
|
4
|
+
dispersion forms + the ``DISPERSION`` dispatch dict + ``index_at`` / ``abbe_vd`` /
|
|
5
|
+
``partial_pgf`` + ``FORMULA_NAMES`` / ``FORMULA_CD_COUNT`` + the 4 cardinal-line
|
|
6
|
+
µm constants. The recompute IS the provenance — the probe's recomputed Nd matched
|
|
7
|
+
the ``.agf``-stored Nd to <=2e-6 AND matched the live engine INDX to full double
|
|
8
|
+
precision (N-BK7 Pg,F engine-vs-ours delta = 0.0). See §4.
|
|
9
|
+
|
|
10
|
+
Zero I/O, zero engine dependency. ``index_at`` returns ``None`` on an
|
|
11
|
+
unimplemented formula or any raised math error; ``abbe_vd`` / ``partial_pgf``
|
|
12
|
+
return ``None`` on a ``None`` input or a zero ``nF-nC``.
|
|
13
|
+
|
|
14
|
+
Equation FORMS are written in our own notation (local authorship: NOT pasted manual
|
|
15
|
+
prose; the manual equation glyphs render as images and do not extract as text).
|
|
16
|
+
Formulas #4 (Sellmeier2) and #10 (Extended) are absent from the v1 battery but
|
|
17
|
+
implemented for forward-compat (§4).
|
|
18
|
+
"""
|
|
19
|
+
import math
|
|
20
|
+
|
|
21
|
+
# --- cardinal spectral lines (micrometers) --------------------------------
|
|
22
|
+
LINE_d = 0.5875618 # d (He yellow) -- the Nd reference line
|
|
23
|
+
LINE_g = 0.4358343 # g (Hg blue)
|
|
24
|
+
LINE_F = 0.4861327 # F (H blue)
|
|
25
|
+
LINE_C = 0.6562725 # C (H red)
|
|
26
|
+
|
|
27
|
+
# --- authoritative .agf NM-field dispersion-formula numbering -------------
|
|
28
|
+
FORMULA_NAMES = {
|
|
29
|
+
1: "Schott",
|
|
30
|
+
2: "Sellmeier1",
|
|
31
|
+
3: "Herzberger",
|
|
32
|
+
4: "Sellmeier2",
|
|
33
|
+
5: "Conrady",
|
|
34
|
+
6: "Sellmeier3",
|
|
35
|
+
7: "Handbook1",
|
|
36
|
+
8: "Handbook2",
|
|
37
|
+
9: "Sellmeier4",
|
|
38
|
+
10: "Extended",
|
|
39
|
+
11: "Sellmeier5",
|
|
40
|
+
12: "Extended2",
|
|
41
|
+
13: "Extended3",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
# How many CD coefficients each formula's n(lambda) equation consumes. The .agf CD
|
|
45
|
+
# line is right-padded with zeros (commonly to 10 fields) so the field COUNT on the
|
|
46
|
+
# line is NOT the equation's coefficient count -- this is the equation count.
|
|
47
|
+
FORMULA_CD_COUNT = {
|
|
48
|
+
1: 6, # Schott: a0,a1,a2,a3,a4,a5
|
|
49
|
+
2: 6, # Sellmeier1: K1,L1,K2,L2,K3,L3
|
|
50
|
+
3: 6, # Herzberger: A,B,C,D,E,F
|
|
51
|
+
4: 5, # Sellmeier2: A,B1,L1,B2,L2
|
|
52
|
+
5: 3, # Conrady: n0,A,B
|
|
53
|
+
6: 8, # Sellmeier3: K1,L1,K2,L2,K3,L3,K4,L4
|
|
54
|
+
7: 4, # Handbook1: A,B,C,D
|
|
55
|
+
8: 4, # Handbook2: A,B,C,D
|
|
56
|
+
9: 5, # Sellmeier4: A,B,C,D,E
|
|
57
|
+
10: 8, # Extended: a0..a7
|
|
58
|
+
11: 10, # Sellmeier5: K1,L1,...,K5,L5
|
|
59
|
+
12: 8, # Extended2: a0..a7 (last two terms use lambda^+4,+6)
|
|
60
|
+
13: 9, # Extended3: a0..a8
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ==========================================================================
|
|
65
|
+
# DISPERSION FORMULAS -- n(lambda), lambda in micrometers.
|
|
66
|
+
# ==========================================================================
|
|
67
|
+
def _n_schott(c, w):
|
|
68
|
+
# n^2 = a0 + a1 w^2 + a2 w^-2 + a3 w^-4 + a4 w^-6 + a5 w^-8
|
|
69
|
+
w2 = w * w
|
|
70
|
+
n2 = (c[0] + c[1] * w2 + c[2] / w2 + c[3] / w2**2
|
|
71
|
+
+ c[4] / w2**3 + c[5] / w2**4)
|
|
72
|
+
return math.sqrt(n2)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _n_sellmeier1(c, w):
|
|
76
|
+
# n^2 - 1 = sum_i K_i w^2 / (w^2 - L_i) (3 terms)
|
|
77
|
+
w2 = w * w
|
|
78
|
+
s = sum(c[2 * i] * w2 / (w2 - c[2 * i + 1]) for i in range(3))
|
|
79
|
+
return math.sqrt(1.0 + s)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _n_herzberger(c, w):
|
|
83
|
+
# n = A + B*L + C*L^2 + D w^2 + E w^4 + F w^6, L = 1/(w^2 - 0.028)
|
|
84
|
+
w2 = w * w
|
|
85
|
+
L = 1.0 / (w2 - 0.028)
|
|
86
|
+
return (c[0] + c[1] * L + c[2] * L * L
|
|
87
|
+
+ c[3] * w2 + c[4] * w2**2 + c[5] * w2**3)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _n_sellmeier2(c, w):
|
|
91
|
+
# n^2 - 1 = A + B1 w^2/(w^2 - L1^2) + B2 w^2/(w^2 - L2^2)
|
|
92
|
+
# agf coeff order: A, B1, L1, B2, L2 (L stored as wavelength, squared here)
|
|
93
|
+
w2 = w * w
|
|
94
|
+
A, B1, L1, B2, L2 = c[0], c[1], c[2], c[3], c[4]
|
|
95
|
+
s = A + B1 * w2 / (w2 - L1 * L1) + B2 * w2 / (w2 - L2 * L2)
|
|
96
|
+
return math.sqrt(1.0 + s)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _n_conrady(c, w):
|
|
100
|
+
# n = n0 + A/w + B/w^3.5
|
|
101
|
+
return c[0] + c[1] / w + c[2] / w**3.5
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _n_sellmeier3(c, w):
|
|
105
|
+
# n^2 - 1 = sum_i K_i w^2/(w^2 - L_i) (4 terms)
|
|
106
|
+
w2 = w * w
|
|
107
|
+
s = sum(c[2 * i] * w2 / (w2 - c[2 * i + 1]) for i in range(4))
|
|
108
|
+
return math.sqrt(1.0 + s)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _n_handbook1(c, w):
|
|
112
|
+
# n^2 = A + B/(w^2 - C) - D w^2
|
|
113
|
+
w2 = w * w
|
|
114
|
+
return math.sqrt(c[0] + c[1] / (w2 - c[2]) - c[3] * w2)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _n_handbook2(c, w):
|
|
118
|
+
# n^2 = A + B w^2/(w^2 - C) - D w^2
|
|
119
|
+
w2 = w * w
|
|
120
|
+
return math.sqrt(c[0] + c[1] * w2 / (w2 - c[2]) - c[3] * w2)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _n_sellmeier4(c, w):
|
|
124
|
+
# n^2 = A + B w^2/(w^2 - C) + D w^2/(w^2 - E)
|
|
125
|
+
w2 = w * w
|
|
126
|
+
A, B, C, D, E = c[0], c[1], c[2], c[3], c[4]
|
|
127
|
+
return math.sqrt(A + B * w2 / (w2 - C) + D * w2 / (w2 - E))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _n_extended(c, w):
|
|
131
|
+
# n^2 = a0 + a1 w^2 + a2 w^-2 + a3 w^-4 + a4 w^-6 + a5 w^-8
|
|
132
|
+
# + a6 w^-10 + a7 w^-12
|
|
133
|
+
w2 = w * w
|
|
134
|
+
return math.sqrt(c[0] + c[1] * w2 + c[2] / w2 + c[3] / w2**2
|
|
135
|
+
+ c[4] / w2**3 + c[5] / w2**4 + c[6] / w2**5
|
|
136
|
+
+ c[7] / w2**6)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _n_sellmeier5(c, w):
|
|
140
|
+
# n^2 - 1 = sum_i K_i w^2/(w^2 - L_i) (5 terms)
|
|
141
|
+
w2 = w * w
|
|
142
|
+
s = sum(c[2 * i] * w2 / (w2 - c[2 * i + 1]) for i in range(5))
|
|
143
|
+
return math.sqrt(1.0 + s)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _n_extended2(c, w):
|
|
147
|
+
# n^2 = a0 + a1 w^2 + a2 w^-2 + a3 w^-4 + a4 w^-6 + a5 w^-8
|
|
148
|
+
# + a6 w^4 + a7 w^6 (last two terms: POSITIVE powers of w)
|
|
149
|
+
w2 = w * w
|
|
150
|
+
return math.sqrt(c[0] + c[1] * w2 + c[2] / w2 + c[3] / w2**2
|
|
151
|
+
+ c[4] / w2**3 + c[5] / w2**4
|
|
152
|
+
+ c[6] * w2**2 + c[7] * w2**3)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _n_extended3(c, w):
|
|
156
|
+
# n^2 = a0 + a1 w^2 + a2 w^4 + a3 w^-2 + a4 w^-4 + a5 w^-6
|
|
157
|
+
# + a6 w^-8 + a7 w^-10 + a8 w^-12
|
|
158
|
+
w2 = w * w
|
|
159
|
+
return math.sqrt(c[0] + c[1] * w2 + c[2] * w2**2 + c[3] / w2
|
|
160
|
+
+ c[4] / w2**2 + c[5] / w2**3 + c[6] / w2**4
|
|
161
|
+
+ c[7] / w2**5 + c[8] / w2**6)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
DISPERSION = {
|
|
165
|
+
1: _n_schott,
|
|
166
|
+
2: _n_sellmeier1,
|
|
167
|
+
3: _n_herzberger,
|
|
168
|
+
4: _n_sellmeier2,
|
|
169
|
+
5: _n_conrady,
|
|
170
|
+
6: _n_sellmeier3,
|
|
171
|
+
7: _n_handbook1,
|
|
172
|
+
8: _n_handbook2,
|
|
173
|
+
9: _n_sellmeier4,
|
|
174
|
+
10: _n_extended,
|
|
175
|
+
11: _n_sellmeier5,
|
|
176
|
+
12: _n_extended2,
|
|
177
|
+
13: _n_extended3,
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def index_at(formula, coeffs, w):
|
|
182
|
+
"""n(w) for a formula; returns None if unimplemented or it raises."""
|
|
183
|
+
fn = DISPERSION.get(formula)
|
|
184
|
+
if fn is None:
|
|
185
|
+
return None
|
|
186
|
+
try:
|
|
187
|
+
return fn(coeffs, w)
|
|
188
|
+
except Exception: # noqa: BLE001
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def abbe_vd(nd, nf, nc):
|
|
193
|
+
if nf is None or nc is None or nd is None:
|
|
194
|
+
return None
|
|
195
|
+
denom = nf - nc
|
|
196
|
+
if denom == 0:
|
|
197
|
+
return None
|
|
198
|
+
return (nd - 1.0) / denom
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def partial_pgf(ng, nf, nc):
|
|
202
|
+
if None in (ng, nf, nc):
|
|
203
|
+
return None
|
|
204
|
+
denom = nf - nc
|
|
205
|
+
if denom == 0:
|
|
206
|
+
return None
|
|
207
|
+
return (ng - nf) / denom
|