levich-sdk 1.0.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.
- levich_sdk/__init__.py +92 -0
- levich_sdk/builder.py +464 -0
- levich_sdk/runner.py +375 -0
- levich_sdk/verifier.py +248 -0
- levich_sdk-1.0.0.dist-info/METADATA +40 -0
- levich_sdk-1.0.0.dist-info/RECORD +8 -0
- levich_sdk-1.0.0.dist-info/WHEEL +5 -0
- levich_sdk-1.0.0.dist-info/top_level.txt +1 -0
levich_sdk/__init__.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Copyright 2026 Coffenova Research Group (https://coffenova.com)
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""
|
|
4
|
+
`levich_sdk` — Public Thin Python Orchestration Client for LEVICH.
|
|
5
|
+
|
|
6
|
+
Contains ZERO solver physics and ZERO parameter weights. Provides:
|
|
7
|
+
- `builder`: Type-safe, unit-checked `.lev` input generation (compact & expert modes)
|
|
8
|
+
and `.xyz` / ASE-compatible geometry serialization.
|
|
9
|
+
- `runner`: Thin subprocess wrapper around `levich check` / `levich run` / `--hostid` /
|
|
10
|
+
`--verify-install`, `.out` polarization table parser, and Slurm job generator.
|
|
11
|
+
- `verifier`: Detached `.levsig` RFC 8785 JCS & `.out` `LEVICH-ATTEST-v1` metadata parser
|
|
12
|
+
and offline `levich verify` wrapper.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from .builder import (
|
|
16
|
+
AttestConfig,
|
|
17
|
+
CompactLevSpec,
|
|
18
|
+
EdlConfig,
|
|
19
|
+
ElectronicConfig,
|
|
20
|
+
ExpertLevSpec,
|
|
21
|
+
KineticsConfig,
|
|
22
|
+
LatticeBox,
|
|
23
|
+
LevBuilder,
|
|
24
|
+
PotentialSweepSpec,
|
|
25
|
+
ProtonConfig,
|
|
26
|
+
ReservoirConfig,
|
|
27
|
+
TransferAtoms,
|
|
28
|
+
VALID_BASES,
|
|
29
|
+
VALID_ISOTOPES,
|
|
30
|
+
VALID_TASKS,
|
|
31
|
+
VALID_THEORIES,
|
|
32
|
+
write_xyz,
|
|
33
|
+
)
|
|
34
|
+
from .runner import (
|
|
35
|
+
CheckResult,
|
|
36
|
+
LevichRunner,
|
|
37
|
+
PhiPointRecord,
|
|
38
|
+
RunSummary,
|
|
39
|
+
SlurmConfig,
|
|
40
|
+
discover_levich_binary,
|
|
41
|
+
generate_slurm_script,
|
|
42
|
+
parse_out_table,
|
|
43
|
+
)
|
|
44
|
+
from .verifier import (
|
|
45
|
+
LevichVerifier,
|
|
46
|
+
LevsigMetadata,
|
|
47
|
+
OutProvenanceFooter,
|
|
48
|
+
VerifyResult,
|
|
49
|
+
compute_out_body_sha256,
|
|
50
|
+
parse_levsig_file,
|
|
51
|
+
parse_levsig_json,
|
|
52
|
+
parse_out_provenance,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
__version__ = "1.0.0"
|
|
56
|
+
|
|
57
|
+
__all__ = [
|
|
58
|
+
"__version__",
|
|
59
|
+
"AttestConfig",
|
|
60
|
+
"CheckResult",
|
|
61
|
+
"CompactLevSpec",
|
|
62
|
+
"EdlConfig",
|
|
63
|
+
"ElectronicConfig",
|
|
64
|
+
"ExpertLevSpec",
|
|
65
|
+
"KineticsConfig",
|
|
66
|
+
"LatticeBox",
|
|
67
|
+
"LevBuilder",
|
|
68
|
+
"LevichRunner",
|
|
69
|
+
"LevichVerifier",
|
|
70
|
+
"LevsigMetadata",
|
|
71
|
+
"OutProvenanceFooter",
|
|
72
|
+
"PhiPointRecord",
|
|
73
|
+
"PotentialSweepSpec",
|
|
74
|
+
"ProtonConfig",
|
|
75
|
+
"ReservoirConfig",
|
|
76
|
+
"RunSummary",
|
|
77
|
+
"SlurmConfig",
|
|
78
|
+
"TransferAtoms",
|
|
79
|
+
"VALID_BASES",
|
|
80
|
+
"VALID_ISOTOPES",
|
|
81
|
+
"VALID_TASKS",
|
|
82
|
+
"VALID_THEORIES",
|
|
83
|
+
"VerifyResult",
|
|
84
|
+
"compute_out_body_sha256",
|
|
85
|
+
"discover_levich_binary",
|
|
86
|
+
"generate_slurm_script",
|
|
87
|
+
"parse_levsig_file",
|
|
88
|
+
"parse_levsig_json",
|
|
89
|
+
"parse_out_provenance",
|
|
90
|
+
"parse_out_table",
|
|
91
|
+
"write_xyz",
|
|
92
|
+
]
|
levich_sdk/builder.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
# Copyright 2026 Coffenova Research Group (https://coffenova.com)
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""
|
|
4
|
+
Programmatic `.lev` (Levich Interface Specification) DSL builder and `.xyz` serializer.
|
|
5
|
+
|
|
6
|
+
Strictly a thin declarative orchestration layer — contains ZERO solver physics.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Iterable, Optional, Sequence, Tuple, Union
|
|
14
|
+
|
|
15
|
+
VALID_THEORIES: Tuple[str, ...] = (
|
|
16
|
+
"gc-xtb",
|
|
17
|
+
"gc-dftb3",
|
|
18
|
+
"rpbe-d3",
|
|
19
|
+
"pbe-d3",
|
|
20
|
+
"beef-vdw",
|
|
21
|
+
"optb88-vdw",
|
|
22
|
+
"r2scan-d4",
|
|
23
|
+
"pbe+u",
|
|
24
|
+
"r2scan+u",
|
|
25
|
+
"hse06-d4",
|
|
26
|
+
"pbe0-d4",
|
|
27
|
+
"pbe0-d3",
|
|
28
|
+
"wb97x-d4",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
VALID_BASES: Tuple[str, ...] = (
|
|
32
|
+
"pw50",
|
|
33
|
+
"pw65",
|
|
34
|
+
"pw80",
|
|
35
|
+
"pw100",
|
|
36
|
+
"sz",
|
|
37
|
+
"dzp",
|
|
38
|
+
"tzp",
|
|
39
|
+
"tzvp+d",
|
|
40
|
+
"qzvp",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
VALID_TASKS: Tuple[str, ...] = (
|
|
44
|
+
"gc_scf",
|
|
45
|
+
"hybridization",
|
|
46
|
+
"proton_3d",
|
|
47
|
+
"edl_sample",
|
|
48
|
+
"kinetics",
|
|
49
|
+
"anshs_pcet",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
VALID_ISOTOPES: Tuple[str, ...] = ("H", "D", "T")
|
|
53
|
+
VALID_SPIN_MODES: Tuple[str, ...] = ("auto", "restricted", "collinear", "noncollinear")
|
|
54
|
+
VALID_SOC_MODES: Tuple[str, ...] = ("sr", "zora2c", "fr_nc")
|
|
55
|
+
VALID_REF_ELECTRODES: Tuple[str, ...] = ("RHE", "SHE")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _escape_lev_str(s: str) -> str:
|
|
59
|
+
if '"' in s or "\n" in s or "\r" in s:
|
|
60
|
+
raise ValueError(f"String literal contains invalid characters: {s!r}")
|
|
61
|
+
return s
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class TransferAtoms:
|
|
66
|
+
"""1-based atom indices for `transfer: H(66) from O(65) -> Pt(49)`."""
|
|
67
|
+
|
|
68
|
+
proton_element: str
|
|
69
|
+
proton_index: int
|
|
70
|
+
donor_element: str
|
|
71
|
+
donor_index: int
|
|
72
|
+
acceptor_element: str
|
|
73
|
+
acceptor_index: int
|
|
74
|
+
|
|
75
|
+
def __post_init__(self) -> None:
|
|
76
|
+
for role, elem, idx in (
|
|
77
|
+
("proton", self.proton_element, self.proton_index),
|
|
78
|
+
("donor", self.donor_element, self.donor_index),
|
|
79
|
+
("acceptor", self.acceptor_element, self.acceptor_index),
|
|
80
|
+
):
|
|
81
|
+
if not elem or not elem.isalpha():
|
|
82
|
+
raise ValueError(f"Invalid {role} element symbol: {elem!r}")
|
|
83
|
+
if idx < 1:
|
|
84
|
+
raise ValueError(f"1-based {role} index must be >= 1, got {idx}")
|
|
85
|
+
|
|
86
|
+
def to_lev(self) -> str:
|
|
87
|
+
return (
|
|
88
|
+
f"{self.proton_element}({self.proton_index}) "
|
|
89
|
+
f"from {self.donor_element}({self.donor_index}) "
|
|
90
|
+
f"-> {self.acceptor_element}({self.acceptor_index})"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class PotentialSweepSpec:
|
|
96
|
+
"""Electrode potential range vs RHE or SHE."""
|
|
97
|
+
|
|
98
|
+
start_v: float
|
|
99
|
+
end_v: float
|
|
100
|
+
step_mv: Optional[float] = None
|
|
101
|
+
reference: str = "RHE"
|
|
102
|
+
|
|
103
|
+
def __post_init__(self) -> None:
|
|
104
|
+
if self.reference not in VALID_REF_ELECTRODES:
|
|
105
|
+
raise ValueError(
|
|
106
|
+
f"Invalid reference electrode {self.reference!r}; expected one of {VALID_REF_ELECTRODES}"
|
|
107
|
+
)
|
|
108
|
+
if self.step_mv is not None and self.step_mv <= 0.0:
|
|
109
|
+
raise ValueError(f"step_mv must be > 0, got {self.step_mv}")
|
|
110
|
+
|
|
111
|
+
def to_lev(self, explicit_sweep: bool = False) -> str:
|
|
112
|
+
if explicit_sweep or self.step_mv is not None:
|
|
113
|
+
step = self.step_mv if self.step_mv is not None else 50.0
|
|
114
|
+
return (
|
|
115
|
+
f"sweep({self.start_v:.2f} V .. {self.end_v:.2f} V, "
|
|
116
|
+
f"step: {step:g} mV) vs {self.reference}"
|
|
117
|
+
)
|
|
118
|
+
return f"{self.start_v:.2f} V .. {self.end_v:.2f} V vs {self.reference}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True)
|
|
122
|
+
class LatticeBox:
|
|
123
|
+
"""Periodic supercell `lattice: [a A, b A, c A] @ [alpha deg, beta deg, gamma deg]`."""
|
|
124
|
+
|
|
125
|
+
lengths_a: Tuple[float, float, float]
|
|
126
|
+
angles_deg: Tuple[float, float, float] = (90.0, 90.0, 90.0)
|
|
127
|
+
|
|
128
|
+
def __post_init__(self) -> None:
|
|
129
|
+
if len(self.lengths_a) != 3 or any(L <= 0.0 for L in self.lengths_a):
|
|
130
|
+
raise ValueError(f"Invalid lattice lengths (A): {self.lengths_a}")
|
|
131
|
+
if len(self.angles_deg) != 3 or any(a <= 0.0 or a >= 180.0 for a in self.angles_deg):
|
|
132
|
+
raise ValueError(f"Invalid lattice angles (deg): {self.angles_deg}")
|
|
133
|
+
|
|
134
|
+
def to_lev(self) -> str:
|
|
135
|
+
a, b, c = self.lengths_a
|
|
136
|
+
al, be, ga = self.angles_deg
|
|
137
|
+
return f"[{a:.3f} A, {b:.3f} A, {c:.3f} A] @ [{al:g} deg, {be:g} deg, {ga:g} deg]"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True)
|
|
141
|
+
class ReservoirConfig:
|
|
142
|
+
"""Spatially partitioned continuum `reservoir: { mode: esm_mpb, mpb_onset: z >= 12.0 A, steric: 3.20 A }`."""
|
|
143
|
+
|
|
144
|
+
mode: str = "esm_mpb"
|
|
145
|
+
mpb_onset_a: float = 12.0
|
|
146
|
+
steric_a: float = 3.20
|
|
147
|
+
|
|
148
|
+
def __post_init__(self) -> None:
|
|
149
|
+
if self.mpb_onset_a <= 0.0:
|
|
150
|
+
raise ValueError(f"mpb_onset_a must be > 0 A, got {self.mpb_onset_a}")
|
|
151
|
+
if self.steric_a <= 0.0:
|
|
152
|
+
raise ValueError(f"steric_a must be > 0 A, got {self.steric_a}")
|
|
153
|
+
|
|
154
|
+
def to_lev(self) -> str:
|
|
155
|
+
return (
|
|
156
|
+
f"{{ mode: {self.mode}, mpb_onset: z >= {self.mpb_onset_a:.2f} A, "
|
|
157
|
+
f"steric: {self.steric_a:.2f} A }}"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass(frozen=True)
|
|
162
|
+
class ElectronicConfig:
|
|
163
|
+
"""GC-SCF settings `electronic: { kmesh: 4x4x1, smearing: 50 meV, dOmega: 1e-7 Ha, dMu: 0.1 meV }`."""
|
|
164
|
+
|
|
165
|
+
kmesh: Tuple[int, int, int] = (4, 4, 1)
|
|
166
|
+
smearing_mev: float = 50.0
|
|
167
|
+
d_omega_ha: float = 1e-7
|
|
168
|
+
d_mu_mev: float = 0.1
|
|
169
|
+
|
|
170
|
+
def __post_init__(self) -> None:
|
|
171
|
+
if len(self.kmesh) != 3 or any(k < 1 for k in self.kmesh):
|
|
172
|
+
raise ValueError(f"Invalid kmesh: {self.kmesh}")
|
|
173
|
+
if self.smearing_mev <= 0.0 or self.d_omega_ha <= 0.0 or self.d_mu_mev <= 0.0:
|
|
174
|
+
raise ValueError("Electronic smearing and tolerances must be > 0")
|
|
175
|
+
|
|
176
|
+
def to_lev(self) -> str:
|
|
177
|
+
kx, ky, kz = self.kmesh
|
|
178
|
+
return (
|
|
179
|
+
f"{{ kmesh: {kx}x{ky}x{kz}, smearing: {self.smearing_mev:g} meV, "
|
|
180
|
+
f"dOmega: {self.d_omega_ha:g} Ha, dMu: {self.d_mu_mev:g} meV }}"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass(frozen=True)
|
|
185
|
+
class ProtonConfig:
|
|
186
|
+
"""3D Sinc-DVR settings `proton: { box: 2.2 A x 1.8 A x 1.8 A, dvr_grid: 24x24x24, states: 25, non_condon: on }`."""
|
|
187
|
+
|
|
188
|
+
box_a: Tuple[float, float, float] = (2.2, 1.8, 1.8)
|
|
189
|
+
dvr_grid: Tuple[int, int, int] = (24, 24, 24)
|
|
190
|
+
states: int = 25
|
|
191
|
+
non_condon: bool = True
|
|
192
|
+
|
|
193
|
+
def __post_init__(self) -> None:
|
|
194
|
+
if len(self.box_a) != 3 or any(b <= 0.0 for b in self.box_a):
|
|
195
|
+
raise ValueError(f"Invalid proton box_a: {self.box_a}")
|
|
196
|
+
if len(self.dvr_grid) != 3 or any(g < 4 for g in self.dvr_grid):
|
|
197
|
+
raise ValueError(f"Invalid dvr_grid: {self.dvr_grid}")
|
|
198
|
+
if self.states < 1:
|
|
199
|
+
raise ValueError(f"states must be >= 1, got {self.states}")
|
|
200
|
+
|
|
201
|
+
def to_lev(self) -> str:
|
|
202
|
+
bx, by, bz = self.box_a
|
|
203
|
+
gx, gy, gz = self.dvr_grid
|
|
204
|
+
nc = "on" if self.non_condon else "off"
|
|
205
|
+
return (
|
|
206
|
+
f"{{ box: {bx:g} A x {by:g} A x {bz:g} A, "
|
|
207
|
+
f"dvr_grid: {gx}x{gy}x{gz}, states: {self.states}, non_condon: {nc} }}"
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@dataclass(frozen=True)
|
|
212
|
+
class EdlConfig:
|
|
213
|
+
"""Potential-dependent EDL sampling block."""
|
|
214
|
+
|
|
215
|
+
mlip: Optional[str] = None
|
|
216
|
+
time_ns: float = 3.0
|
|
217
|
+
seam_kbt: float = 5.0
|
|
218
|
+
fep_frames: int = 200
|
|
219
|
+
|
|
220
|
+
def __post_init__(self) -> None:
|
|
221
|
+
if self.time_ns <= 0.0 or self.seam_kbt <= 0.0 or self.fep_frames < 0:
|
|
222
|
+
raise ValueError("Invalid EdlConfig parameters")
|
|
223
|
+
|
|
224
|
+
def to_lev(self) -> str:
|
|
225
|
+
parts = []
|
|
226
|
+
if self.mlip is not None:
|
|
227
|
+
parts.append(f'mlip: "{_escape_lev_str(self.mlip)}"')
|
|
228
|
+
parts.append(f"time: {self.time_ns:g} ns")
|
|
229
|
+
parts.append(f"seam: {self.seam_kbt:g} kBT")
|
|
230
|
+
parts.append(f"fep: {self.fep_frames}")
|
|
231
|
+
return "{ " + ", ".join(parts) + " }"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@dataclass(frozen=True)
|
|
235
|
+
class KineticsConfig:
|
|
236
|
+
"""ANSHS spectral quadrature & friction turnover block."""
|
|
237
|
+
|
|
238
|
+
quadrature: str = "adaptive_tanh_sinh"
|
|
239
|
+
friction: str = "bcme_grote_hynes"
|
|
240
|
+
regime: str = "steady_state"
|
|
241
|
+
|
|
242
|
+
def to_lev(self) -> str:
|
|
243
|
+
return (
|
|
244
|
+
f"{{ quadrature: {self.quadrature}, friction: {self.friction}, "
|
|
245
|
+
f"regime: {self.regime} }}"
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@dataclass(frozen=True)
|
|
250
|
+
class AttestConfig:
|
|
251
|
+
"""Post-quantum provenance signing block (`LEVICH-ATTEST-v1`)."""
|
|
252
|
+
|
|
253
|
+
sign: bool = True
|
|
254
|
+
tsa: Optional[str] = None
|
|
255
|
+
|
|
256
|
+
def to_lev(self) -> str:
|
|
257
|
+
s_flag = "true" if self.sign else "false"
|
|
258
|
+
if self.tsa:
|
|
259
|
+
return f'{{ sign: {s_flag}, tsa: "{_escape_lev_str(self.tsa)}" }}'
|
|
260
|
+
return f"{{ sign: {s_flag} }}"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _validate_theory_basis_ph_temp(
|
|
264
|
+
theory: str, basis: Optional[str], ph: float, temperature_k: Optional[float] = None
|
|
265
|
+
) -> None:
|
|
266
|
+
if theory not in VALID_THEORIES:
|
|
267
|
+
raise ValueError(f"Unsupported theory {theory!r}; valid theories: {VALID_THEORIES}")
|
|
268
|
+
if basis is not None and basis not in VALID_BASES:
|
|
269
|
+
raise ValueError(f"Unsupported basis {basis!r}; valid bases: {VALID_BASES}")
|
|
270
|
+
if not (0.0 <= ph <= 14.0):
|
|
271
|
+
raise ValueError(f"pH must be within [0.0, 14.0], got {ph}")
|
|
272
|
+
if temperature_k is not None and temperature_k <= 0.0:
|
|
273
|
+
raise ValueError(f"Temperature must be > 0 K, got {temperature_k}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@dataclass(frozen=True)
|
|
277
|
+
class CompactLevSpec:
|
|
278
|
+
"""8-line compact `.lev` specification with smart defaults."""
|
|
279
|
+
|
|
280
|
+
title: str
|
|
281
|
+
structure: str
|
|
282
|
+
transfer: TransferAtoms
|
|
283
|
+
potential: PotentialSweepSpec
|
|
284
|
+
ph: float = 13.0
|
|
285
|
+
theory: str = "gc-xtb"
|
|
286
|
+
basis: Optional[str] = None
|
|
287
|
+
header_comment: Optional[str] = None
|
|
288
|
+
|
|
289
|
+
def __post_init__(self) -> None:
|
|
290
|
+
_validate_theory_basis_ph_temp(self.theory, self.basis, self.ph)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@dataclass(frozen=True)
|
|
294
|
+
class ExpertLevSpec:
|
|
295
|
+
"""Full expert override `.lev` specification."""
|
|
296
|
+
|
|
297
|
+
title: str
|
|
298
|
+
potential: PotentialSweepSpec
|
|
299
|
+
ph: float = 13.0
|
|
300
|
+
theory: str = "gc-xtb"
|
|
301
|
+
basis: Optional[str] = None
|
|
302
|
+
structure: Optional[str] = None
|
|
303
|
+
transfer: Optional[TransferAtoms] = None
|
|
304
|
+
temperature_k: Optional[float] = None
|
|
305
|
+
task: Optional[str] = None
|
|
306
|
+
resume: Optional[str] = None
|
|
307
|
+
spin: Optional[str] = None
|
|
308
|
+
soc: Optional[str] = None
|
|
309
|
+
lattice: Optional[LatticeBox] = None
|
|
310
|
+
electrolyte: Sequence[Tuple[float, str]] = field(default_factory=tuple)
|
|
311
|
+
reservoir: Optional[ReservoirConfig] = None
|
|
312
|
+
isotopes: Sequence[str] = field(default_factory=tuple)
|
|
313
|
+
electronic: Optional[ElectronicConfig] = None
|
|
314
|
+
proton: Optional[ProtonConfig] = None
|
|
315
|
+
edl: Optional[EdlConfig] = None
|
|
316
|
+
kinetics: Optional[KineticsConfig] = None
|
|
317
|
+
attest: Optional[AttestConfig] = None
|
|
318
|
+
schema_version: Optional[str] = None
|
|
319
|
+
header_comment: Optional[str] = None
|
|
320
|
+
|
|
321
|
+
def __post_init__(self) -> None:
|
|
322
|
+
_validate_theory_basis_ph_temp(self.theory, self.basis, self.ph, self.temperature_k)
|
|
323
|
+
if self.task is not None and self.task not in VALID_TASKS:
|
|
324
|
+
raise ValueError(f"Invalid task {self.task!r}; expected one of {VALID_TASKS}")
|
|
325
|
+
if self.spin is not None and self.spin not in VALID_SPIN_MODES:
|
|
326
|
+
raise ValueError(f"Invalid spin {self.spin!r}; expected one of {VALID_SPIN_MODES}")
|
|
327
|
+
if self.soc is not None and self.soc not in VALID_SOC_MODES:
|
|
328
|
+
raise ValueError(f"Invalid soc {self.soc!r}; expected one of {VALID_SOC_MODES}")
|
|
329
|
+
for iso in self.isotopes:
|
|
330
|
+
if iso not in VALID_ISOTOPES:
|
|
331
|
+
raise ValueError(f"Invalid isotope {iso!r}; expected one of {VALID_ISOTOPES}")
|
|
332
|
+
for conc_m, sp in self.electrolyte:
|
|
333
|
+
if conc_m < 0.0:
|
|
334
|
+
raise ValueError(f"Electrolyte concentration must be >= 0 M, got {conc_m}")
|
|
335
|
+
_escape_lev_str(sp)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class LevBuilder:
|
|
339
|
+
"""Render compact or expert `.lev` files from validated Python specifications."""
|
|
340
|
+
|
|
341
|
+
@staticmethod
|
|
342
|
+
def render_compact(spec: CompactLevSpec) -> str:
|
|
343
|
+
lines = []
|
|
344
|
+
if spec.header_comment:
|
|
345
|
+
for c_line in spec.header_comment.splitlines():
|
|
346
|
+
lines.append(f"// {c_line}")
|
|
347
|
+
theory_str = f"{spec.theory} / {spec.basis}" if spec.basis else spec.theory
|
|
348
|
+
lines.append(f'run "{_escape_lev_str(spec.title)}" {{')
|
|
349
|
+
lines.append(f" theory: {theory_str}")
|
|
350
|
+
lines.append(f' structure: "{_escape_lev_str(spec.structure)}"')
|
|
351
|
+
lines.append(f" transfer: {spec.transfer.to_lev()}")
|
|
352
|
+
lines.append(f" potential: {spec.potential.to_lev(explicit_sweep=False)}")
|
|
353
|
+
lines.append(f" pH: {spec.ph:.1f}")
|
|
354
|
+
lines.append("}")
|
|
355
|
+
return "\n".join(lines) + "\n"
|
|
356
|
+
|
|
357
|
+
@staticmethod
|
|
358
|
+
def render_expert(spec: ExpertLevSpec) -> str:
|
|
359
|
+
lines = []
|
|
360
|
+
if spec.header_comment:
|
|
361
|
+
for c_line in spec.header_comment.splitlines():
|
|
362
|
+
lines.append(f"// {c_line}")
|
|
363
|
+
if spec.schema_version is not None:
|
|
364
|
+
lines.append(f"schema: {spec.schema_version}")
|
|
365
|
+
theory_str = f"{spec.theory} / {spec.basis}" if spec.basis else spec.theory
|
|
366
|
+
lines.append(f'run "{_escape_lev_str(spec.title)}" {{')
|
|
367
|
+
lines.append(f" theory: {theory_str}")
|
|
368
|
+
if spec.task is not None:
|
|
369
|
+
lines.append(f" task: {spec.task}")
|
|
370
|
+
if spec.resume is not None:
|
|
371
|
+
lines.append(f' resume: "{_escape_lev_str(spec.resume)}"')
|
|
372
|
+
if spec.structure is not None:
|
|
373
|
+
lines.append(f' structure: "{_escape_lev_str(spec.structure)}"')
|
|
374
|
+
if spec.transfer is not None:
|
|
375
|
+
lines.append(f" transfer: {spec.transfer.to_lev()}")
|
|
376
|
+
lines.append(f" potential: {spec.potential.to_lev(explicit_sweep=True)}")
|
|
377
|
+
lines.append(f" pH: {spec.ph:.1f}")
|
|
378
|
+
if spec.temperature_k is not None:
|
|
379
|
+
lines.append(f" temperature: {spec.temperature_k:g} K")
|
|
380
|
+
if spec.spin is not None:
|
|
381
|
+
lines.append(f" spin: {spec.spin}")
|
|
382
|
+
if spec.soc is not None:
|
|
383
|
+
lines.append(f" soc: {spec.soc}")
|
|
384
|
+
if spec.lattice is not None:
|
|
385
|
+
lines.append(f" lattice: {spec.lattice.to_lev()}")
|
|
386
|
+
if spec.electrolyte:
|
|
387
|
+
items = ", ".join(
|
|
388
|
+
f'{conc:.2f} M "{_escape_lev_str(sp)}"' for conc, sp in spec.electrolyte
|
|
389
|
+
)
|
|
390
|
+
lines.append(f" electrolyte: [{items}]")
|
|
391
|
+
if spec.reservoir is not None:
|
|
392
|
+
lines.append(f" reservoir: {spec.reservoir.to_lev()}")
|
|
393
|
+
if spec.isotopes:
|
|
394
|
+
lines.append(f" isotopes: [{', '.join(spec.isotopes)}]")
|
|
395
|
+
if spec.electronic is not None:
|
|
396
|
+
lines.append(f" electronic: {spec.electronic.to_lev()}")
|
|
397
|
+
if spec.proton is not None:
|
|
398
|
+
lines.append(f" proton: {spec.proton.to_lev()}")
|
|
399
|
+
if spec.edl is not None:
|
|
400
|
+
lines.append(f" edl: {spec.edl.to_lev()}")
|
|
401
|
+
if spec.kinetics is not None:
|
|
402
|
+
lines.append(f" kinetics: {spec.kinetics.to_lev()}")
|
|
403
|
+
if spec.attest is not None:
|
|
404
|
+
lines.append(f" attest: {spec.attest.to_lev()}")
|
|
405
|
+
lines.append("}")
|
|
406
|
+
return "\n".join(lines) + "\n"
|
|
407
|
+
|
|
408
|
+
@classmethod
|
|
409
|
+
def write(
|
|
410
|
+
cls,
|
|
411
|
+
spec: Union[CompactLevSpec, ExpertLevSpec],
|
|
412
|
+
path: Union[str, Path],
|
|
413
|
+
) -> Path:
|
|
414
|
+
out_path = Path(path)
|
|
415
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
416
|
+
content = (
|
|
417
|
+
cls.render_compact(spec)
|
|
418
|
+
if isinstance(spec, CompactLevSpec)
|
|
419
|
+
else cls.render_expert(spec)
|
|
420
|
+
)
|
|
421
|
+
out_path.write_text(content, encoding="utf-8")
|
|
422
|
+
return out_path
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def write_xyz(
|
|
426
|
+
atoms: Iterable[Tuple[str, float, float, float]],
|
|
427
|
+
path: Union[str, Path],
|
|
428
|
+
comment: str = "Generated by levich-sdk",
|
|
429
|
+
lattice_vectors_a: Optional[Sequence[Sequence[float]]] = None,
|
|
430
|
+
) -> Path:
|
|
431
|
+
"""
|
|
432
|
+
Write standard or extended `.xyz` coordinates (in Angstrom).
|
|
433
|
+
Also accepts ASE-like `Atoms` objects if passed directly as `atoms` via duck typing.
|
|
434
|
+
"""
|
|
435
|
+
if hasattr(atoms, "get_chemical_symbols") and hasattr(atoms, "get_positions"):
|
|
436
|
+
syms = atoms.get_chemical_symbols() # type: ignore[attr-defined]
|
|
437
|
+
pos = atoms.get_positions() # type: ignore[attr-defined]
|
|
438
|
+
atom_list = [(str(s), float(r[0]), float(r[1]), float(r[2])) for s, r in zip(syms, pos)]
|
|
439
|
+
if lattice_vectors_a is None and hasattr(atoms, "get_cell"):
|
|
440
|
+
cell = atoms.get_cell() # type: ignore[attr-defined]
|
|
441
|
+
if cell is not None and len(cell) == 3:
|
|
442
|
+
lattice_vectors_a = [[float(v) for v in row] for row in cell]
|
|
443
|
+
else:
|
|
444
|
+
atom_list = [(str(s), float(x), float(y), float(z)) for s, x, y, z in atoms]
|
|
445
|
+
|
|
446
|
+
if not atom_list:
|
|
447
|
+
raise ValueError("Cannot write empty .xyz structure")
|
|
448
|
+
|
|
449
|
+
header_comment = comment.replace("\n", " ").strip()
|
|
450
|
+
if lattice_vectors_a is not None:
|
|
451
|
+
flat = [float(x) for row in lattice_vectors_a for x in row]
|
|
452
|
+
if len(flat) != 9:
|
|
453
|
+
raise ValueError("lattice_vectors_a must be a 3x3 matrix (9 floats)")
|
|
454
|
+
lat_str = " ".join(f"{v:.6f}" for v in flat)
|
|
455
|
+
header_comment = f'Lattice="{lat_str}" {header_comment}'.strip()
|
|
456
|
+
|
|
457
|
+
lines = [str(len(atom_list)), header_comment]
|
|
458
|
+
for sym, x, y, z in atom_list:
|
|
459
|
+
lines.append(f"{sym:<3s} {x:14.8f} {y:14.8f} {z:14.8f}")
|
|
460
|
+
|
|
461
|
+
out_path = Path(path)
|
|
462
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
463
|
+
out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
464
|
+
return out_path
|
levich_sdk/runner.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
# Copyright 2026 Coffenova Research Group (https://coffenova.com)
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""
|
|
4
|
+
Thin execution orchestrator wrapping the `levich` CLI (`check`, `run`, `--hostid`,
|
|
5
|
+
`--verify-install`), `.out` polarization table parsing, and Slurm job script generation.
|
|
6
|
+
|
|
7
|
+
Contains ZERO solver physics.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import List, Optional, Sequence, Union
|
|
18
|
+
|
|
19
|
+
EDITION_BINARIES = (
|
|
20
|
+
"levich",
|
|
21
|
+
"levich-enterprise",
|
|
22
|
+
"levich-sovereign",
|
|
23
|
+
"levich-common",
|
|
24
|
+
"levich-academic",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def discover_levich_binary(
|
|
29
|
+
preferred_edition: Optional[str] = None,
|
|
30
|
+
search_Hint: Optional[Union[str, Path]] = None,
|
|
31
|
+
) -> Path:
|
|
32
|
+
"""
|
|
33
|
+
Locate an installed or locally built `levich-*` executable.
|
|
34
|
+
Checks `LEVICH_BIN`, explicit search directory, monorepo `target/release/`, and `PATH`.
|
|
35
|
+
"""
|
|
36
|
+
env_bin = os.environ.get("LEVICH_BIN")
|
|
37
|
+
if env_bin:
|
|
38
|
+
p = Path(env_bin)
|
|
39
|
+
if p.is_file() and os.access(p, os.X_OK):
|
|
40
|
+
return p.resolve()
|
|
41
|
+
|
|
42
|
+
names: List[str] = []
|
|
43
|
+
if preferred_edition:
|
|
44
|
+
ed = preferred_edition.removeprefix("levich-")
|
|
45
|
+
names.append(f"levich-{ed}")
|
|
46
|
+
for b in EDITION_BINARIES:
|
|
47
|
+
if b not in names:
|
|
48
|
+
names.append(b)
|
|
49
|
+
|
|
50
|
+
repo_root = Path(__file__).resolve().parents[3]
|
|
51
|
+
candidate_dirs: List[Path] = []
|
|
52
|
+
if search_Hint is not None:
|
|
53
|
+
candidate_dirs.append(Path(search_Hint))
|
|
54
|
+
candidate_dirs.extend(
|
|
55
|
+
[
|
|
56
|
+
repo_root / "target" / "release",
|
|
57
|
+
repo_root / "target" / "debug",
|
|
58
|
+
]
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
for d in candidate_dirs:
|
|
62
|
+
for name in names:
|
|
63
|
+
cand = d / name
|
|
64
|
+
if cand.is_file() and os.access(cand, os.X_OK):
|
|
65
|
+
return cand.resolve()
|
|
66
|
+
|
|
67
|
+
for name in names:
|
|
68
|
+
found = shutil.which(name)
|
|
69
|
+
if found:
|
|
70
|
+
return Path(found).resolve()
|
|
71
|
+
|
|
72
|
+
raise FileNotFoundError(
|
|
73
|
+
"Could not find any `levich` binary (`levich-academic`, `levich-common`, "
|
|
74
|
+
"`levich-enterprise`, `levich-sovereign`). Set LEVICH_BIN or pass binary_path."
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class CheckResult:
|
|
80
|
+
"""Structured result of `levich check <file.lev>`."""
|
|
81
|
+
|
|
82
|
+
passed: bool
|
|
83
|
+
has_warnings: bool
|
|
84
|
+
returncode: int
|
|
85
|
+
stdout: str
|
|
86
|
+
stderr: str
|
|
87
|
+
warnings: List[str] = field(default_factory=list)
|
|
88
|
+
errors: List[str] = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class PhiPointRecord:
|
|
93
|
+
"""Parsed observable row from a converged `.out` polarization sweep."""
|
|
94
|
+
|
|
95
|
+
potential_v: float
|
|
96
|
+
omega_ha: float
|
|
97
|
+
sigma_uc_cm2: float
|
|
98
|
+
c_diff_uf_cm2: float
|
|
99
|
+
xi_ad: float
|
|
100
|
+
kappa_tot: float
|
|
101
|
+
k_red_s: float
|
|
102
|
+
j_ma_cm2: float
|
|
103
|
+
tafel_mv_dec: float
|
|
104
|
+
alpha: float
|
|
105
|
+
kie_hd: float
|
|
106
|
+
route: str
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class RunSummary:
|
|
111
|
+
"""Result of executing `levich run <file.lev>`."""
|
|
112
|
+
|
|
113
|
+
succeeded: bool
|
|
114
|
+
returncode: int
|
|
115
|
+
out_path: Path
|
|
116
|
+
checkpoint_path: Optional[Path]
|
|
117
|
+
sig_path: Optional[Path]
|
|
118
|
+
points: List[PhiPointRecord]
|
|
119
|
+
stdout: str
|
|
120
|
+
stderr: str
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True)
|
|
124
|
+
class SlurmConfig:
|
|
125
|
+
"""Slurm batch job parameters for HPC / workstation execution."""
|
|
126
|
+
|
|
127
|
+
job_name: str
|
|
128
|
+
lev_file: str
|
|
129
|
+
nodes: int = 1
|
|
130
|
+
ntasks_per_node: int = 1
|
|
131
|
+
cpus_per_task: int = 8
|
|
132
|
+
gpus_per_node: int = 0
|
|
133
|
+
partition: str = "compute"
|
|
134
|
+
walltime: str = "02:00:00"
|
|
135
|
+
mem_gb: int = 8
|
|
136
|
+
edition_binary: str = "levich-enterprise"
|
|
137
|
+
out_file: Optional[str] = None
|
|
138
|
+
checkpoint_file: Optional[str] = None
|
|
139
|
+
sig_file: Optional[str] = None
|
|
140
|
+
license_file: Optional[str] = None
|
|
141
|
+
account: Optional[str] = None
|
|
142
|
+
modules: Sequence[str] = field(default_factory=tuple)
|
|
143
|
+
|
|
144
|
+
def __post_init__(self) -> None:
|
|
145
|
+
if self.nodes < 1 or self.ntasks_per_node < 1 or self.cpus_per_task < 1:
|
|
146
|
+
raise ValueError("Slurm node/task/cpu counts must be >= 1")
|
|
147
|
+
if self.gpus_per_node < 0 or self.mem_gb < 1:
|
|
148
|
+
raise ValueError("Invalid GPU or memory specification")
|
|
149
|
+
if self.edition_binary == "levich-academic" and self.nodes > 4:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"levich-academic is hard-capped at max_nodes <= 4 (requested {self.nodes})"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def parse_out_table(out_text: str) -> List[PhiPointRecord]:
|
|
156
|
+
"""Parse polarization sweep rows from a LEVICH `.out` report."""
|
|
157
|
+
records: List[PhiPointRecord] = []
|
|
158
|
+
in_table = False
|
|
159
|
+
for raw_line in out_text.splitlines():
|
|
160
|
+
line = raw_line.strip()
|
|
161
|
+
if not line:
|
|
162
|
+
continue
|
|
163
|
+
if (line.startswith("V_RHE") or line.startswith("V_SHE")) and "Omega(Ha)" in line:
|
|
164
|
+
in_table = True
|
|
165
|
+
continue
|
|
166
|
+
if in_table:
|
|
167
|
+
if line.startswith("---"):
|
|
168
|
+
break
|
|
169
|
+
parts = line.split()
|
|
170
|
+
if len(parts) >= 12:
|
|
171
|
+
try:
|
|
172
|
+
records.append(
|
|
173
|
+
PhiPointRecord(
|
|
174
|
+
potential_v=float(parts[0]),
|
|
175
|
+
omega_ha=float(parts[1]),
|
|
176
|
+
sigma_uc_cm2=float(parts[2]),
|
|
177
|
+
c_diff_uf_cm2=float(parts[3]),
|
|
178
|
+
xi_ad=float(parts[4]),
|
|
179
|
+
kappa_tot=float(parts[5]),
|
|
180
|
+
k_red_s=float(parts[6]),
|
|
181
|
+
j_ma_cm2=float(parts[7]),
|
|
182
|
+
tafel_mv_dec=float(parts[8]),
|
|
183
|
+
alpha=float(parts[9]),
|
|
184
|
+
kie_hd=float(parts[10]),
|
|
185
|
+
route=parts[11],
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
except ValueError:
|
|
189
|
+
continue
|
|
190
|
+
return records
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def generate_slurm_script(cfg: SlurmConfig) -> str:
|
|
194
|
+
"""Generate a reproducible Slurm `sbatch` submission script for LEVICH."""
|
|
195
|
+
stem = Path(cfg.lev_file).stem
|
|
196
|
+
out_f = cfg.out_file or f"{stem}.out"
|
|
197
|
+
chk_f = cfg.checkpoint_file or f"{stem}.levchk"
|
|
198
|
+
sig_f = cfg.sig_file or f"{stem}.levsig"
|
|
199
|
+
|
|
200
|
+
lines = [
|
|
201
|
+
"#!/usr/bin/env bash",
|
|
202
|
+
f"#SBATCH --job-name={cfg.job_name}",
|
|
203
|
+
f"#SBATCH --partition={cfg.partition}",
|
|
204
|
+
f"#SBATCH --nodes={cfg.nodes}",
|
|
205
|
+
f"#SBATCH --ntasks-per-node={cfg.ntasks_per_node}",
|
|
206
|
+
f"#SBATCH --cpus-per-task={cfg.cpus_per_task}",
|
|
207
|
+
f"#SBATCH --mem={cfg.mem_gb}G",
|
|
208
|
+
f"#SBATCH --time={cfg.walltime}",
|
|
209
|
+
f"#SBATCH --output={cfg.job_name}.%j.slurm.log",
|
|
210
|
+
]
|
|
211
|
+
if cfg.gpus_per_node > 0:
|
|
212
|
+
lines.append(f"#SBATCH --gpus-per-node={cfg.gpus_per_node}")
|
|
213
|
+
if cfg.account:
|
|
214
|
+
lines.append(f"#SBATCH --account={cfg.account}")
|
|
215
|
+
|
|
216
|
+
lines.extend(
|
|
217
|
+
[
|
|
218
|
+
"",
|
|
219
|
+
"set -euo pipefail",
|
|
220
|
+
f"export OMP_NUM_THREADS={cfg.cpus_per_task}",
|
|
221
|
+
]
|
|
222
|
+
)
|
|
223
|
+
for mod in cfg.modules:
|
|
224
|
+
lines.append(f"module load {mod}")
|
|
225
|
+
|
|
226
|
+
cmd_parts = [
|
|
227
|
+
"srun",
|
|
228
|
+
cfg.edition_binary,
|
|
229
|
+
"run",
|
|
230
|
+
cfg.lev_file,
|
|
231
|
+
"--out",
|
|
232
|
+
out_f,
|
|
233
|
+
"--checkpoint",
|
|
234
|
+
chk_f,
|
|
235
|
+
"--sig",
|
|
236
|
+
sig_f,
|
|
237
|
+
"--nodes",
|
|
238
|
+
str(cfg.nodes),
|
|
239
|
+
]
|
|
240
|
+
if cfg.license_file:
|
|
241
|
+
cmd_parts.extend(["--license", cfg.license_file])
|
|
242
|
+
|
|
243
|
+
lines.append("")
|
|
244
|
+
lines.append(" \\\n ".join(cmd_parts))
|
|
245
|
+
lines.append("")
|
|
246
|
+
return "\n".join(lines)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class LevichRunner:
|
|
250
|
+
"""Thin Python client driving local `levich` CLI subcommands."""
|
|
251
|
+
|
|
252
|
+
def __init__(
|
|
253
|
+
self,
|
|
254
|
+
binary_path: Optional[Union[str, Path]] = None,
|
|
255
|
+
preferred_edition: Optional[str] = None,
|
|
256
|
+
) -> None:
|
|
257
|
+
self._binary_path = Path(binary_path) if binary_path is not None else None
|
|
258
|
+
self._preferred_edition = preferred_edition
|
|
259
|
+
|
|
260
|
+
def resolve_binary(self) -> Path:
|
|
261
|
+
if self._binary_path is not None:
|
|
262
|
+
return self._binary_path
|
|
263
|
+
return discover_levich_binary(preferred_edition=self._preferred_edition)
|
|
264
|
+
|
|
265
|
+
def hostid(self, timeout_s: float = 10.0) -> str:
|
|
266
|
+
proc = subprocess.run(
|
|
267
|
+
[str(self.resolve_binary()), "--hostid"],
|
|
268
|
+
capture_output=True,
|
|
269
|
+
text=True,
|
|
270
|
+
timeout=timeout_s,
|
|
271
|
+
check=True,
|
|
272
|
+
)
|
|
273
|
+
return proc.stdout.strip()
|
|
274
|
+
|
|
275
|
+
def verify_install(
|
|
276
|
+
self, license_path: Optional[Union[str, Path]] = None, timeout_s: float = 15.0
|
|
277
|
+
) -> subprocess.CompletedProcess[str]:
|
|
278
|
+
cmd = [str(self.resolve_binary()), "--verify-install"]
|
|
279
|
+
if license_path is not None:
|
|
280
|
+
cmd.extend(["--license", str(license_path)])
|
|
281
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s, check=False)
|
|
282
|
+
|
|
283
|
+
def keygen_dev_license(
|
|
284
|
+
self,
|
|
285
|
+
out_path: Union[str, Path],
|
|
286
|
+
edition: Optional[str] = None,
|
|
287
|
+
max_nodes: Optional[int] = None,
|
|
288
|
+
org: str = "coffenova-dev",
|
|
289
|
+
timeout_s: float = 15.0,
|
|
290
|
+
) -> Path:
|
|
291
|
+
out_p = Path(out_path)
|
|
292
|
+
cmd = [str(self.resolve_binary()), "keygen-dev-license", "--out", str(out_p), "--org", org]
|
|
293
|
+
if edition is not None:
|
|
294
|
+
cmd.extend(["--edition", edition])
|
|
295
|
+
if max_nodes is not None:
|
|
296
|
+
cmd.extend(["--max-nodes", str(max_nodes)])
|
|
297
|
+
subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s, check=True)
|
|
298
|
+
return out_p
|
|
299
|
+
|
|
300
|
+
def check(self, lev_path: Union[str, Path], timeout_s: float = 15.0) -> CheckResult:
|
|
301
|
+
proc = subprocess.run(
|
|
302
|
+
[str(self.resolve_binary()), "check", str(lev_path)],
|
|
303
|
+
capture_output=True,
|
|
304
|
+
text=True,
|
|
305
|
+
timeout=timeout_s,
|
|
306
|
+
check=False,
|
|
307
|
+
)
|
|
308
|
+
combined = f"{proc.stdout}\n{proc.stderr}"
|
|
309
|
+
warnings = [
|
|
310
|
+
ln.strip()
|
|
311
|
+
for ln in combined.splitlines()
|
|
312
|
+
if "[WARNING]" in ln or "WARNING:" in ln
|
|
313
|
+
]
|
|
314
|
+
errors = [
|
|
315
|
+
ln.strip()
|
|
316
|
+
for ln in combined.splitlines()
|
|
317
|
+
if "[ERROR]" in ln or "Syntax/Unit Error" in ln
|
|
318
|
+
]
|
|
319
|
+
return CheckResult(
|
|
320
|
+
passed=(proc.returncode == 0),
|
|
321
|
+
has_warnings=bool(warnings) or ("PASSED WITH WARNINGS" in proc.stdout),
|
|
322
|
+
returncode=proc.returncode,
|
|
323
|
+
stdout=proc.stdout,
|
|
324
|
+
stderr=proc.stderr,
|
|
325
|
+
warnings=warnings,
|
|
326
|
+
errors=errors,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
def run(
|
|
330
|
+
self,
|
|
331
|
+
lev_path: Union[str, Path],
|
|
332
|
+
out_path: Optional[Union[str, Path]] = None,
|
|
333
|
+
checkpoint_path: Optional[Union[str, Path]] = None,
|
|
334
|
+
sig_path: Optional[Union[str, Path]] = None,
|
|
335
|
+
license_path: Optional[Union[str, Path]] = None,
|
|
336
|
+
nodes: int = 1,
|
|
337
|
+
timeout_s: float = 300.0,
|
|
338
|
+
) -> RunSummary:
|
|
339
|
+
lev_p = Path(lev_path)
|
|
340
|
+
resolved_out = Path(out_path) if out_path is not None else lev_p.with_suffix(".out")
|
|
341
|
+
resolved_chk = Path(checkpoint_path) if checkpoint_path is not None else None
|
|
342
|
+
resolved_sig = Path(sig_path) if sig_path is not None else lev_p.with_suffix(".levsig")
|
|
343
|
+
|
|
344
|
+
cmd = [str(self.resolve_binary()), "run", str(lev_p), "--out", str(resolved_out)]
|
|
345
|
+
if resolved_chk is not None:
|
|
346
|
+
cmd.extend(["--checkpoint", str(resolved_chk)])
|
|
347
|
+
if sig_path is not None:
|
|
348
|
+
cmd.extend(["--sig", str(resolved_sig)])
|
|
349
|
+
if license_path is not None:
|
|
350
|
+
cmd.extend(["--license", str(license_path)])
|
|
351
|
+
if nodes != 1:
|
|
352
|
+
cmd.extend(["--nodes", str(nodes)])
|
|
353
|
+
|
|
354
|
+
proc = subprocess.run(
|
|
355
|
+
cmd,
|
|
356
|
+
capture_output=True,
|
|
357
|
+
text=True,
|
|
358
|
+
timeout=timeout_s,
|
|
359
|
+
check=False,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
points: List[PhiPointRecord] = []
|
|
363
|
+
if proc.returncode == 0 and resolved_out.is_file():
|
|
364
|
+
points = parse_out_table(resolved_out.read_text(encoding="utf-8"))
|
|
365
|
+
|
|
366
|
+
return RunSummary(
|
|
367
|
+
succeeded=(proc.returncode == 0),
|
|
368
|
+
returncode=proc.returncode,
|
|
369
|
+
out_path=resolved_out,
|
|
370
|
+
checkpoint_path=resolved_chk,
|
|
371
|
+
sig_path=resolved_sig if resolved_sig.is_file() else None,
|
|
372
|
+
points=points,
|
|
373
|
+
stdout=proc.stdout,
|
|
374
|
+
stderr=proc.stderr,
|
|
375
|
+
)
|
levich_sdk/verifier.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# Copyright 2026 Coffenova Research Group (https://coffenova.com)
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""
|
|
4
|
+
Offline provenance inspection & `levich verify` CLI wrapper for `LEVICH-ATTEST-v1`.
|
|
5
|
+
|
|
6
|
+
Parses RFC 8785 JCS `.levsig` certificates and `.out` provenance footers, and delegates
|
|
7
|
+
cryptographic Hybrid Ed25519 + Hedged-Randomized ML-DSA-87 verification to the `levich` binary.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import subprocess
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, Optional, Union
|
|
18
|
+
|
|
19
|
+
from .runner import discover_levich_binary
|
|
20
|
+
|
|
21
|
+
ATTEST_BANNER_LINE = "LEVICH PROVENANCE & REPRODUCIBILITY ATTESTATION (LEVICH-ATTEST-v1)"
|
|
22
|
+
SEPARATOR_80 = "-" * 80
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class LevsigMetadata:
|
|
27
|
+
"""Structured metadata parsed from a detached `.levsig` RFC 8785 JCS document."""
|
|
28
|
+
|
|
29
|
+
schema: str
|
|
30
|
+
attest_version: str
|
|
31
|
+
software: str
|
|
32
|
+
edition: str
|
|
33
|
+
tier: str
|
|
34
|
+
license_id: str
|
|
35
|
+
user_key_id: str
|
|
36
|
+
user_salt_hex: str
|
|
37
|
+
watermark: Optional[str]
|
|
38
|
+
input_sha256: str
|
|
39
|
+
results_sha256: str
|
|
40
|
+
out_body_sha256: str
|
|
41
|
+
completed_utc: str
|
|
42
|
+
tsa_status: str
|
|
43
|
+
signature_context: Optional[str]
|
|
44
|
+
has_ed25519: bool
|
|
45
|
+
has_mldsa87: bool
|
|
46
|
+
audit_metrics: Dict[str, Any] = field(default_factory=dict)
|
|
47
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class OutProvenanceFooter:
|
|
52
|
+
"""Metadata extracted from the human-readable `LEVICH-ATTEST-v1` footer inside `.out`."""
|
|
53
|
+
|
|
54
|
+
body_sha256: str
|
|
55
|
+
fields: Dict[str, str]
|
|
56
|
+
signature_armor: Optional[str]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class VerifyResult:
|
|
61
|
+
"""Outcome of invoking `levich verify <out> --sig <levsig>`."""
|
|
62
|
+
|
|
63
|
+
verified: bool
|
|
64
|
+
returncode: int
|
|
65
|
+
stdout: str
|
|
66
|
+
stderr: str
|
|
67
|
+
metadata: Optional[LevsigMetadata] = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def compute_out_body_sha256(out_text: Union[str, bytes]) -> str:
|
|
71
|
+
"""
|
|
72
|
+
Compute lowercase hex SHA-256 over the exact `.out` body strictly preceding the
|
|
73
|
+
`LEVICH-ATTEST-v1` provenance banner (matching `levich-auth` pre-footer splitting).
|
|
74
|
+
"""
|
|
75
|
+
text = out_text.decode("utf-8") if isinstance(out_text, bytes) else out_text
|
|
76
|
+
full_banner = f"{SEPARATOR_80}\n{ATTEST_BANNER_LINE}\n{SEPARATOR_80}"
|
|
77
|
+
idx = text.find(full_banner)
|
|
78
|
+
if idx != -1:
|
|
79
|
+
body = text[:idx]
|
|
80
|
+
else:
|
|
81
|
+
idx_line = text.find(ATTEST_BANNER_LINE)
|
|
82
|
+
body = text[:idx_line] if idx_line != -1 else text
|
|
83
|
+
return hashlib.sha256(body.encode("utf-8")).hexdigest()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse_out_provenance(out_text: str) -> OutProvenanceFooter:
|
|
87
|
+
"""Extract key-value fields and ASCII-armored signature block from a `.out` file."""
|
|
88
|
+
body_sha = compute_out_body_sha256(out_text)
|
|
89
|
+
idx = out_text.find(ATTEST_BANNER_LINE)
|
|
90
|
+
fields: Dict[str, str] = {}
|
|
91
|
+
armor_lines = []
|
|
92
|
+
in_sig = False
|
|
93
|
+
|
|
94
|
+
if idx != -1:
|
|
95
|
+
footer_part = out_text[idx:]
|
|
96
|
+
for raw_line in footer_part.splitlines():
|
|
97
|
+
line = raw_line.strip()
|
|
98
|
+
if line.startswith("-----BEGIN LEVICH PROVENANCE SIGNATURE-----"):
|
|
99
|
+
in_sig = True
|
|
100
|
+
continue
|
|
101
|
+
if line.startswith("-----END LEVICH PROVENANCE SIGNATURE-----"):
|
|
102
|
+
in_sig = False
|
|
103
|
+
continue
|
|
104
|
+
if in_sig:
|
|
105
|
+
armor_lines.append(line)
|
|
106
|
+
elif ":" in line and not line.startswith("---"):
|
|
107
|
+
k, v = line.split(":", 1)
|
|
108
|
+
fields[k.strip()] = v.strip()
|
|
109
|
+
|
|
110
|
+
return OutProvenanceFooter(
|
|
111
|
+
body_sha256=body_sha,
|
|
112
|
+
fields=fields,
|
|
113
|
+
signature_armor="\n".join(armor_lines) if armor_lines else None,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def parse_levsig_json(raw_json: str) -> LevsigMetadata:
|
|
118
|
+
"""Parse a `.levsig` canonical JSON string into `LevsigMetadata`."""
|
|
119
|
+
doc = json.loads(raw_json)
|
|
120
|
+
if not isinstance(doc, dict):
|
|
121
|
+
raise ValueError(".levsig root must be a JSON object")
|
|
122
|
+
|
|
123
|
+
payload = doc.get("payload", doc)
|
|
124
|
+
if not isinstance(payload, dict):
|
|
125
|
+
raise ValueError(".levsig 'payload' must be a JSON object")
|
|
126
|
+
|
|
127
|
+
sig = doc.get("signature", {}) if isinstance(doc.get("signature"), dict) else {}
|
|
128
|
+
|
|
129
|
+
in_dig = payload.get("input_digest", {})
|
|
130
|
+
input_sha = (
|
|
131
|
+
in_dig.get("sha256", "")
|
|
132
|
+
if isinstance(in_dig, dict)
|
|
133
|
+
else str(payload.get("input_sha256", in_dig))
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
res_dig = payload.get("results_digest", {})
|
|
137
|
+
results_sha = (
|
|
138
|
+
res_dig.get("sha256", "")
|
|
139
|
+
if isinstance(res_dig, dict)
|
|
140
|
+
else str(payload.get("results_sha256", res_dig))
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
has_ed = bool(
|
|
144
|
+
sig.get("ed25519_sig_b64")
|
|
145
|
+
or sig.get("ed25519_sig_hex")
|
|
146
|
+
or sig.get("ed25519")
|
|
147
|
+
)
|
|
148
|
+
has_pq = bool(
|
|
149
|
+
sig.get("mldsa87_sig_b64")
|
|
150
|
+
or sig.get("mldsa87_sig_hex")
|
|
151
|
+
or sig.get("ml_dsa_87_sig_b64")
|
|
152
|
+
or sig.get("mldsa87")
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
return LevsigMetadata(
|
|
156
|
+
schema=str(doc.get("schema", payload.get("attest_version", "LEVICH-ATTEST-v1"))),
|
|
157
|
+
attest_version=str(payload.get("attest_version", "LEVICH-ATTEST-v1")),
|
|
158
|
+
software=str(payload.get("software", "")),
|
|
159
|
+
edition=str(payload.get("edition", "")),
|
|
160
|
+
tier=str(payload.get("tier", "")),
|
|
161
|
+
license_id=str(payload.get("license_id", "")),
|
|
162
|
+
user_key_id=str(payload.get("user_key_id", "")),
|
|
163
|
+
user_salt_hex=str(payload.get("user_salt_hex", "")),
|
|
164
|
+
watermark=payload.get("watermark"),
|
|
165
|
+
input_sha256=str(input_sha),
|
|
166
|
+
results_sha256=str(results_sha),
|
|
167
|
+
out_body_sha256=str(payload.get("out_body_sha256", "")),
|
|
168
|
+
completed_utc=str(payload.get("completed_utc", "")),
|
|
169
|
+
tsa_status=str(payload.get("tsa_status", "")),
|
|
170
|
+
signature_context=sig.get("context") or sig.get("domain_context"),
|
|
171
|
+
has_ed25519=has_ed,
|
|
172
|
+
has_mldsa87=has_pq,
|
|
173
|
+
audit_metrics=dict(payload.get("audit_metrics") or {}),
|
|
174
|
+
raw=doc,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parse_levsig_file(sig_path: Union[str, Path]) -> LevsigMetadata:
|
|
179
|
+
"""Read and parse a `.levsig` file from disk."""
|
|
180
|
+
text = Path(sig_path).read_text(encoding="utf-8")
|
|
181
|
+
return parse_levsig_json(text)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class LevichVerifier:
|
|
185
|
+
"""Wrapper around `levich verify` and offline `.levsig` / `.out` pre-checks."""
|
|
186
|
+
|
|
187
|
+
def __init__(self, binary_path: Optional[Union[str, Path]] = None) -> None:
|
|
188
|
+
self._binary_path = Path(binary_path) if binary_path is not None else None
|
|
189
|
+
|
|
190
|
+
def resolve_binary(self) -> Path:
|
|
191
|
+
if self._binary_path is not None:
|
|
192
|
+
return self._binary_path
|
|
193
|
+
return discover_levich_binary()
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def quick_check_digest_match(
|
|
197
|
+
out_path: Union[str, Path], sig_path: Union[str, Path]
|
|
198
|
+
) -> Tuple[bool, LevsigMetadata]:
|
|
199
|
+
"""
|
|
200
|
+
Fast Python pre-check verifying that the `.out` pre-footer SHA-256 matches
|
|
201
|
+
`out_body_sha256` inside `.levsig` (full PQ signature verification requires `verify()`).
|
|
202
|
+
"""
|
|
203
|
+
meta = parse_levsig_file(sig_path)
|
|
204
|
+
out_bytes = Path(out_path).read_bytes()
|
|
205
|
+
actual_sha = compute_out_body_sha256(out_bytes)
|
|
206
|
+
ok = bool(meta.out_body_sha256) and (actual_sha.lower() == meta.out_body_sha256.lower())
|
|
207
|
+
return ok, meta
|
|
208
|
+
|
|
209
|
+
def verify(
|
|
210
|
+
self,
|
|
211
|
+
out_path: Union[str, Path],
|
|
212
|
+
sig_path: Union[str, Path],
|
|
213
|
+
require_tier: Optional[str] = None,
|
|
214
|
+
timeout_s: float = 30.0,
|
|
215
|
+
) -> VerifyResult:
|
|
216
|
+
"""
|
|
217
|
+
Invoke `levich verify <out> --sig <sig> [--require-tier <TIER>]` for full offline
|
|
218
|
+
Hybrid Ed25519 + Hedged-Randomized ML-DSA-87 verification.
|
|
219
|
+
"""
|
|
220
|
+
bin_path = self.resolve_binary()
|
|
221
|
+
out_p = Path(out_path)
|
|
222
|
+
sig_p = Path(sig_path)
|
|
223
|
+
|
|
224
|
+
meta: Optional[LevsigMetadata] = None
|
|
225
|
+
if sig_p.is_file():
|
|
226
|
+
try:
|
|
227
|
+
meta = parse_levsig_file(sig_p)
|
|
228
|
+
except (ValueError, OSError):
|
|
229
|
+
meta = None
|
|
230
|
+
|
|
231
|
+
cmd = [str(bin_path), "verify", str(out_p), "--sig", str(sig_p)]
|
|
232
|
+
if require_tier is not None:
|
|
233
|
+
cmd.extend(["--require-tier", require_tier])
|
|
234
|
+
|
|
235
|
+
proc = subprocess.run(
|
|
236
|
+
cmd,
|
|
237
|
+
capture_output=True,
|
|
238
|
+
text=True,
|
|
239
|
+
timeout=timeout_s,
|
|
240
|
+
check=False,
|
|
241
|
+
)
|
|
242
|
+
return VerifyResult(
|
|
243
|
+
verified=(proc.returncode == 0),
|
|
244
|
+
returncode=proc.returncode,
|
|
245
|
+
stdout=proc.stdout,
|
|
246
|
+
stderr=proc.stderr,
|
|
247
|
+
metadata=meta,
|
|
248
|
+
)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: levich-sdk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Thin Apache-2.0 Python orchestration SDK for LEVICH (.lev builder, CLI/Slurm runner, and .levsig provenance verifier — zero solver physics)
|
|
5
|
+
Author-email: Coffenova Research Group <licensing@coffenova.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://coffenova.com
|
|
8
|
+
Project-URL: Portal, https://levich.coffenova.com
|
|
9
|
+
Project-URL: Repository, https://github.com/iehoshva/levich-sdk
|
|
10
|
+
Keywords: electrochemistry,pcet,grand-canonical,levich,hpc,slurm
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Chemistry
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# `levich-sdk`
|
|
24
|
+
|
|
25
|
+
**Official Thin Python Orchestration SDK for `LEVICH`**
|
|
26
|
+
*Coffenova Research Group (`https://coffenova.com` | `https://levich.coffenova.com`)*
|
|
27
|
+
|
|
28
|
+
`levich-sdk` is the public, Apache-2.0 Python client for **LEVICH** (*Level-broadened Electron–Vibronic Interfacial Continuum Hamiltonian*). It provides:
|
|
29
|
+
|
|
30
|
+
- **Programmatic `.lev` Builder (`LevBuilder`)**: Type-safe, unit-aware generation of `.lev` (*Levich Interface Specification*) protocols and `.xyz` / extended-XYZ structures (with ASE duck-typing support).
|
|
31
|
+
- **Execution & Slurm Wrapper (`LevichRunner`)**: Subprocess wrapper for `levich check` / `levich run` and Slurm HPC batch script generation.
|
|
32
|
+
- **Provenance & Output Parser (`LevichVerifier`)**: Parses `.out` polarization/KIE tables and inspects `LEVICH-ATTEST-v1` Post-Quantum (`Hybrid Ed25519 + ML-DSA-87`) `.levsig` provenance manifests.
|
|
33
|
+
|
|
34
|
+
> **Note:** `levich-sdk` contains **zero solver physics** and **zero proprietary parameter weights**. To execute simulations, install a licensed `LEVICH` binary from **[https://levich.coffenova.com](https://levich.coffenova.com)**.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install levich-sdk
|
|
40
|
+
```
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
levich_sdk/__init__.py,sha256=_gdtVBDcU_nB4GpNu9HNdWyi4vY8Y2p-KTK9-kYKdho,2263
|
|
2
|
+
levich_sdk/builder.py,sha256=yOpZryZPxw2Pm0bdbKVF-nKw0CjHCIAwTcmZqsQZKx0,17139
|
|
3
|
+
levich_sdk/runner.py,sha256=fxjH3GZm-YShz56pRsOBgJSo_QhY9C8bvyt7iCZGph4,12107
|
|
4
|
+
levich_sdk/verifier.py,sha256=Wf-t7CHgEQCx01NypbLPjGvGnGl5vWZepY_ancZJJI8,8336
|
|
5
|
+
levich_sdk-1.0.0.dist-info/METADATA,sha256=tEhQnNMok9fyQ72bYY3RyF4kcE5EoZzT0Csj-f9oiAE,2211
|
|
6
|
+
levich_sdk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
levich_sdk-1.0.0.dist-info/top_level.txt,sha256=4oSSyVRM8YYmhrYYKsPZuv-ufh7DU7dhaDVU7gsej2Y,11
|
|
8
|
+
levich_sdk-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
levich_sdk
|