levich-sdk 1.0.0__tar.gz

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,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,18 @@
1
+ # `levich-sdk`
2
+
3
+ **Official Thin Python Orchestration SDK for `LEVICH`**
4
+ *Coffenova Research Group (`https://coffenova.com` | `https://levich.coffenova.com`)*
5
+
6
+ `levich-sdk` is the public, Apache-2.0 Python client for **LEVICH** (*Level-broadened Electron–Vibronic Interfacial Continuum Hamiltonian*). It provides:
7
+
8
+ - **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).
9
+ - **Execution & Slurm Wrapper (`LevichRunner`)**: Subprocess wrapper for `levich check` / `levich run` and Slurm HPC batch script generation.
10
+ - **Provenance & Output Parser (`LevichVerifier`)**: Parses `.out` polarization/KIE tables and inspects `LEVICH-ATTEST-v1` Post-Quantum (`Hybrid Ed25519 + ML-DSA-87`) `.levsig` provenance manifests.
11
+
12
+ > **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)**.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install levich-sdk
18
+ ```
@@ -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
+ ]
@@ -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