From 1884846a37951ca2bc2a57b65612f0f973c3cfb1 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Wed, 11 Nov 2026 16:59:39 +0800 Subject: [PATCH 01/46] test(time,ida): add heterointerface BDF audit tests and fix IDA patch busy-guard count --- .../test_ida_observation.py | 64 ++-- .../solvers/time/test_cnd2_interface_audit.py | 307 ++++++++++++++++++ 2 files changed, 351 insertions(+), 20 deletions(-) create mode 100644 tests/unit/solvers/time/test_cnd2_interface_audit.py diff --git a/tests/numerical_contracts/test_ida_observation.py b/tests/numerical_contracts/test_ida_observation.py index f944f399..d559a765 100644 --- a/tests/numerical_contracts/test_ida_observation.py +++ b/tests/numerical_contracts/test_ida_observation.py @@ -61,10 +61,12 @@ def test_parent_frame_public_bridge_and_owner_refresh(self, builder, archive, tm for key, value in (("size", True), ("size", 2), ("frame_identity", "not-bound"), ("t0_hex", "nan"), ("t0_hex", "0x0p+0"), ("v0_words_hex", [zero]*5), ("extra", 0)): - changed = deepcopy(good); changed[key] = value + changed = deepcopy(good) + changed[key] = value with pytest.raises((ValueError, OverflowError)): validate(changed) - changed = deepcopy(good); changed["q0_words_hex"][1][0] = (1.0).hex() + changed = deepcopy(good) + changed["q0_words_hex"][1][0] = (1.0).hex() with pytest.raises(ValueError, match="unnormalized"): validate(changed) initial = code[code.index(" cdef _init_step("):code.index(" cdef _step(")] @@ -88,11 +90,15 @@ def test_exact_patch_and_unchanged_native_solve_calls(self, builder, archive, tm code = (source / "src/sksundae/_cy_ida.pyx").read_text() with tarfile.open(archive) as tar: original = tar.extractfile("scikit_sundae-1.1.3/src/sksundae/_cy_ida.pyx").read().decode() - calls = lambda text: [line.strip() for line in text.splitlines() if "flag = IDASolve(" in line] + + def calls(text: str) -> list[str]: + return [line.strip() for line in text.splitlines() if "flag = IDASolve(" in line] + assert len(calls(code)) == 3 assert calls(code) == calls(original) assert code.count("self._obs_after_step(observation_before,") == 3 - assert code.count("self._obs_busy = True") == 3 + assert code.count("self._obs_busy = True") == 4 + assert code.count("self._obs_busy = False") == 5 assert "_OBSERVATION_BUILD_ID = None" in code wrapper = ast.parse((source / "src/sksundae/ida/_solver.py").read_text()) public = next(node for node in wrapper.body if isinstance(node, ast.ClassDef) and node.name == "IDA") @@ -922,13 +928,19 @@ def test_segment_frame_native_application_and_lifetime(native): assert not target.exists() progress = target.with_suffix(".progress.jsonl") assert not progress.exists() - zero = np.zeros(45); q0 = np.full(45, 2.0**20); v0 = np.full(45, 2.0**10) - alpha = np.full(45, 2.0**-40); alpha[0] = 1.0 + zero = np.zeros(45) + q0 = np.full(45, 2.0**20) + v0 = np.full(45, 2.0**10) + alpha = np.full(45, 2.0**-40) + alpha[0] = 1.0 settings = dict(rtol=2.0**-50, atol=[2.0**-50]*45, first_step=2.0**-4, max_step=2.0**-4, max_order=3, nonlin_conv_coef=1.024e-5, nonlin_guard="first-correction-wrms-v1", nonlin_trace_capacity=4096, max_nonlin_iters=8) assert settings == spec["controls"] - hx = lambda row: [float(v).hex() for v in row] + + def hx(row): + return [float(v).hex() for v in row] + frame = {"schema": "sksundae.ida.parent-affine-weights.v1", "frame_identity": hashlib.sha256(b"fixture-frame-1").hexdigest(), "t0_hex": 0.0.hex(), "size": 45, "q0_words_hex": [hx(q0), hx(zero), hx(zero), hx(zero)], "v0_words_hex": [hx(v0), hx(zero), hx(zero), hx(zero)], @@ -948,18 +960,26 @@ def retain(name, solver): records.append(row) with progress.open("a") as output: output.write(json.dumps(observation_record(row))+"\n") - output.flush(); os.fsync(output.fileno()) + output.flush() + os.fsync(output.fileno()) try: plain = IDA(affine_residual, jacfn=jacobian, **settings) - owners.append(plain); refs.append(weakref.ref(plain)) - outcome["native_initializations"] += 1; assert plain.init_step(0.0, q0, v0).success - outcome["onestep_calls"] += 1; assert plain.step(1.0, method="onestep", tstop=1.0).success - plain_packet = plain.last_step_snapshot(); retain("default_off", plain) + owners.append(plain) + refs.append(weakref.ref(plain)) + outcome["native_initializations"] += 1 + assert plain.init_step(0.0, q0, v0).success + outcome["onestep_calls"] += 1 + assert plain.step(1.0, method="onestep", tstop=1.0).success + plain_packet = plain.last_step_snapshot() + retain("default_off", plain) assert "parent_weight_state" not in plain.statistics() solver = IDA(residual, jacfn=jacobian, parent_weight_frame=frame, **settings) - owners.append(solver); refs.append(weakref.ref(solver)) - outcome["native_initializations"] += 1; assert solver.init_step(0.0, zero, zero).success - initial = solver.statistics(); retain("frame_initialized", solver) + owners.append(solver) + refs.append(weakref.ref(solver)) + outcome["native_initializations"] += 1 + assert solver.init_step(0.0, zero, zero).success + initial = solver.statistics() + retain("frame_initialized", solver) assert initial["parent_weight_state"]["callback_calls"] == 0 previous_phi = zero.tobytes() for index in range(2): @@ -967,7 +987,8 @@ def retain(name, solver): returned = solver.step(1.0, method="onestep", tstop=1.0) retain("frame_onestep_"+str(index+1), solver) assert returned.success - packet = solver.last_step_snapshot(); records.append({"phase": "accepted_packet", "packet": packet}) + packet = solver.last_step_snapshot() + records.append({"phase": "accepted_packet", "packet": packet}) state = packet["parent_weight_state"] assert state["basis_u"] == previous_phi t = Fraction(float.fromhex(state["basis_time_hex"])) @@ -982,7 +1003,8 @@ def retain(name, solver): assert np.any(np.asarray(returned.y)[1:] != 0) assert np.all(np.abs(np.asarray(returned.y)[1:]) < np.spacing(q0[1:])) previous_phi = packet["basis"]["phi"][:45*8] - newer = deepcopy(frame); newer.update(t0_hex=0.25.hex(), frame_identity=hashlib.sha256(b"fixture-frame-2").hexdigest()) + newer = deepcopy(frame) + newer.update(t0_hex=0.25.hex(), frame_identity=hashlib.sha256(b"fixture-frame-2").hexdigest()) origin[0] = 0.25 outcome["native_initializations"] += 1 assert solver.init_step(0.25, zero, zero, parent_weight_frame=newer).success @@ -990,7 +1012,8 @@ def retain(name, solver): changed = solver.statistics()["parent_weight_state"] assert changed["frame_identity"] == newer["frame_identity"] and changed["generation"] == 2 assert changed["callback_calls"] == 0 and changed["t0_hex"] == 0.25.hex() - resized = deepcopy(newer); resized["size"] = 44 + resized = deepcopy(newer) + resized["size"] = 44 resized["q0_words_hex"] = [row[:44] for row in resized["q0_words_hex"]] resized["v0_words_hex"] = [row[:44] for row in resized["v0_words_hex"]] outcome["native_initializations"] += 1 @@ -1009,7 +1032,8 @@ def retain(name, solver): records.append({"phase": "failed_operation", "statistics_unavailable": str(unavailable)}) raise finally: - owners.clear(); plain = solver = None + owners.clear() + plain = solver = None gc.collect() outcome["python_owners_released"] = all(ref() is None for ref in refs) target.write_text(json.dumps(observation_record(outcome), indent=2)+"\n") @@ -1196,5 +1220,5 @@ def jacobian(t, y, yp, out, cj, jac): finish(False, first_error=failure, missing_native_fields_remain_absent=True) raise finally: - solver = None + solver = None # noqa: F841 gc.collect() diff --git a/tests/unit/solvers/time/test_cnd2_interface_audit.py b/tests/unit/solvers/time/test_cnd2_interface_audit.py new file mode 100644 index 00000000..1abae2e6 --- /dev/null +++ b/tests/unit/solvers/time/test_cnd2_interface_audit.py @@ -0,0 +1,307 @@ +"""Interface-trust and unified-assembler heterointerface conservation audit tests. + +Exercises the owned ``solarlab.solvers.time`` BDF1/BDF2 kernels and unified +``Assembler`` storage adapters (``AssembledStorage1D``, ``AssembledIonicStorage1D``) +across multilayer heterointerfaces, plus the Backward Euler public default guard +from ``docs/DevelopmentGuide.md``. +""" + +from __future__ import annotations + +import hashlib +import inspect +import json +from pathlib import Path + +import numpy as np + +from examples.research_1d.ionic_residual import prepare_single_ion_device +from examples.research_1d.ionic_steady import controls as steady_ionic_controls +from examples.research_1d.ionic_transient import controls as time_ionic_controls +from examples.research_1d.multiple_ionic_domains import ( + DOMAINS, + INTERVALS, + prepare_multiple_ionic_device, +) +from examples.research_1d.steady import load_device +from examples.research_1d.transient import controls, json_value +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.assembly.ionic_1d import AssembledMultipleIonic1DProblem +from solarlab.experiments.ionic_transient import ( + IonicTransientResult, + load_ionic_steady_initial, + solve_ionic_transient, +) +from solarlab.experiments.transient import ( + TransientProtocol, + TransientResult1D, + solve_transient, +) +from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state +from solarlab.solvers.time.assembled_ionic_bdf import ( + assembled_ionic_bdf_accounting, + assembled_ionic_bdf_seed, +) +from solarlab.solvers.time.assembled_storage import ( + AssembledIonicStorage1D, + AssembledStorage1D, +) +from solarlab.solvers.time.bdf import BDFOptions, BDFResult, BDFStep, HistoryPoint +from solarlab.solvers.time.bdf_1d import ElectronicStorage1D, bdf_accounting + + +def test_public_transient_entry_points_keep_backward_euler_default( + tmp_path: Path, +) -> None: + """Backward Euler remains the public default; BDF requires explicit opt-in.""" + electronic_sig = inspect.signature(solve_transient) + ionic_sig = inspect.signature(solve_ionic_transient) + assert electronic_sig.parameters["method"].default == "backward_euler" + assert electronic_sig.parameters["bdf_options"].default is None + assert ionic_sig.parameters["method"].default == "backward_euler" + assert ionic_sig.parameters["bdf_options"].default is None + + device = compile_device_1d(load_device(), intervals_per_layer=8) + steady_opts = SteadyOptions() + initial = solve_steady_state( + device, voltage_V=0.0, generation_scale=1.0, options=steady_opts + ) + assert initial.converged + protocol = TransientProtocol( + np.array([0.0, 1e-7, 2e-7]), + np.array([0.0, 0.0, 0.0]), + np.array([1.0, 1.002, 1.005]), + ) + + be_res = solve_transient( + device, initial, protocol, options=controls(), initial_options=steady_opts + ) + assert isinstance(be_res, TransientResult1D) + assert len(be_res.accepted_times_s) == 3 + + bdf_res = solve_transient( + device, + initial, + protocol, + options=controls(), + initial_options=steady_opts, + method="bdf", + bdf_options=BDFOptions(1e-7, adaptive=False, max_order=2), + ) + assert isinstance(bdf_res, BDFResult) + assert bdf_res.completed + + ionic_device = compile_ionic_device_1d( + prepare_single_ion_device(diffusion_only=True), intervals_per_layer=8 + ) + ionic_steady = steady_ionic_controls(ionic_device.ion_node_count) + point = solve_ionic_steady_state( + ionic_device, voltage_V=0.002, generation_scale=0.0, options=ionic_steady + ) + assert point.accepted + payload = json.dumps( + json_value( + { + "summary": { + "accepted": True, + "compiled_identity": ionic_device.identity, + "voltage_V": 0.002, + "generation_scale": 0.0, + }, + "result": point, + } + ), + allow_nan=False, + ).encode() + evidence_path = tmp_path / "initial_ionic.json" + evidence_path.write_bytes(payload) + ionic_initial = load_ionic_steady_initial( + ionic_device, + evidence_path, + hashlib.sha256(payload).hexdigest(), + controls=ionic_steady, + ) + ionic_protocol = TransientProtocol( + np.array([0.0, 0.25]), + np.array([0.002, 0.0025]), + np.array([0.0, 0.0]), + ) + ionic_be = solve_ionic_transient( + ionic_device, ionic_initial, ionic_protocol, options=time_ionic_controls() + ) + assert isinstance(ionic_be, IonicTransientResult) + + +def test_assembled_storage_1d_heterointerface_secant_bdf2_and_gauss_maxwell_closure() -> ( + None +): + """Verify expm1 storage secants, BDF2 weights, equilibrium SG flux, and Gauss-Maxwell closure.""" + device = compile_device_1d(load_device(), intervals_per_layer=8) + n_nodes = device.node_count + # Multilayer stack must expose distinct layer dielectric / band properties across interfaces. + assert len(device.geometry.interfaces) >= 2 + + # 1. Exact zero Scharfetter-Gummel carrier flux across heterointerfaces in dark equilibrium. + eq_problem = AssembledDC1DProblem(device, voltage_V=0.0, generation_scale=0.0) + eq_steady = solve_steady_state( + device, voltage_V=0.0, generation_scale=0.0, options=SteadyOptions() + ) + assert eq_steady.converged + eq_fluxes = eq_problem.fluxes(eq_steady.state.u) + assert np.max(np.abs(eq_fluxes.electron.flux)) < 1e-3 + assert np.max(np.abs(eq_fluxes.hole.flux)) < 1e-3 + + # 2. Cancellation-free expm1 secant vs tangent action under tiny heterointerface perturbations. + a0 = AssembledStorage1D( + AssembledDC1DProblem(device, voltage_V=0.0, generation_scale=1.0) + ) + a1 = AssembledStorage1D( + AssembledDC1DProblem(device, voltage_V=0.0, generation_scale=1.0) + ) + rng = np.random.default_rng(20261102) + u0 = eq_steady.state.u.copy() + delta = 1e-11 * rng.normal(size=u0.shape) + u1 = u0 + delta + actual_delta = u1 - u0 + secant = a1.storage_increment(u1, a0, u0) + midpoint_tangent = ( + 0.5 * (a1.storage_tangent(u1) + a0.storage_tangent(u0)) @ actual_delta + ) + row_roundoff = ( + 8.0 * np.finfo(float).eps * (abs(a0.storage_tangent(u0)) @ np.abs(actual_delta)) + ) + scale = np.maximum(np.abs(midpoint_tangent), 1e-30) + row_roundoff + mask = np.abs(midpoint_tangent) > 0.0 + assert np.max(np.abs(secant[mask] - midpoint_tangent[mask]) / scale[mask]) < 1e-8 + # Poisson rows are purely algebraic. + np.testing.assert_array_equal(secant[:n_nodes], np.zeros(n_nodes)) + + # 3. Variable-step BDF2 (step ratio r = 1.5 <= 2) across voltage & generation drive. + e0 = ElectronicStorage1D( + AssembledDC1DProblem(device, voltage_V=0.0, generation_scale=1.0) + ) + e1 = ElectronicStorage1D( + AssembledDC1DProblem(device, voltage_V=0.02, generation_scale=1.05) + ) + e2 = ElectronicStorage1D( + AssembledDC1DProblem(device, voltage_V=0.05, generation_scale=1.10) + ) + u_a = eq_steady.state.u.copy() + u_b = u_a + 1e-3 * rng.normal(size=u_a.shape) + u_c = u_b + 1.5e-3 * rng.normal(size=u_a.shape) + + h0 = HistoryPoint(0.0, u_a, e0.storage(u_a), e0) + h1 = HistoryPoint(1e-7, u_b, e1.storage(u_b), e1) + end2 = 2.5e-7 # dt1 = 1e-7, dt2 = 1.5e-7 -> step ratio r = 1.5 + step2 = BDFStep(e2, (h1, h0), end2, 2) + + r = 1.5 + expected_alpha = ((1.0 + 2.0 * r) / (1.0 + r), -(1.0 + r), (r * r) / (1.0 + r)) + np.testing.assert_allclose(step2.coefficients, expected_alpha, rtol=0.0, atol=1e-15) + assert abs(sum(step2.coefficients)) <= 2.0 * np.finfo(float).eps + + acc = bdf_accounting(step2, u_c) + disp = acc["bdf_displacement_rate_A_m2"] + q_rate = acc["charge_inventory_rate_A_m2"] + # Discrete Gauss closure at contact ports and interior heterointerface cells: + np.testing.assert_allclose( + disp[:-1] - disp[1:] + q_rate, + acc["stable_gauss_defect_rate_A_m2"], + rtol=0.0, + atol=1e-12, + ) + current_scale = max( + float(np.max(np.abs(acc["bdf_conduction_current_A_m2"]))), + float(np.max(np.abs(disp))), + 1.0, + ) + assert float(np.max(np.abs(acc["maxwell_identity_error_A_m2"]))) < ( + 64.0 * np.finfo(float).eps * current_scale + ) + + +def test_assembled_ionic_storage_1d_heterointerface_shared_node_charge_and_blocking_flux() -> ( + None +): + """Verify W_P / W_e shared heterointerface node charge projection and blocking ion endpoints.""" + device = compile_multiple_ionic_device_1d( + prepare_multiple_ionic_device(kind="shared"), + intervals_per_layer=INTERVALS, + ion_domains=DOMAINS, + ) + n_nodes = device.node_count + a0 = AssembledIonicStorage1D(AssembledMultipleIonic1DProblem(device, 0.002, 0.0)) + a1 = AssembledIonicStorage1D(AssembledMultipleIonic1DProblem(device, 0.004, 0.0)) + a2 = AssembledIonicStorage1D(AssembledMultipleIonic1DProblem(device, 0.007, 0.0)) + + u0 = np.zeros(device.state_size) + h0 = HistoryPoint(0.0, u0, a0.storage(u0), a0) + first = BDFStep(a1, (h0,), 0.2, 1) + u1 = assembled_ionic_bdf_seed(first) + u1[3 * n_nodes :] += 0.015 + h1 = HistoryPoint(0.2, u1, a1.storage(u1), a1) + step2 = BDFStep(a2, (h1, h0), 0.35, 2) + u2 = assembled_ionic_bdf_seed(step2) + u2[3 * n_nodes :] -= 0.008 + + # Check W_e * rho_ion == q * sum_domains W_P * delta_P at every heterointerface shared node. + state2 = device.state(u2, voltage_V=0.007) + _phi, n2, p2, populations = device.fields_by_domain(u2, voltage_V=0.007) + w_elec = device.electronic_component.geometry.cell_measures_m + base_rho = device.electronic_component.charge_ledger(n2, p2).space_charge_C_m3() + full_rho = device.charge_ledger(n2, p2, populations).space_charge_C_m3() + integrated_ion_charge_C_m2 = w_elec * (full_rho - base_rho) + + expected_ion_charge_C_m2 = np.zeros(n_nodes) + for idx, domain in enumerate(device.domains): + dom_state = state2.domain_component_states[idx] + w_ion = domain.ion_geometry.cell_measures_m + # Heterointerface boundary nodes use half-endpoint domain measures W_P < W_e. + elec_indices = domain.ion_node_indices + if elec_indices[0] > 0: + assert w_ion[0] < w_elec[elec_indices[0]] + if elec_indices[-1] < n_nodes - 1: + assert w_ion[-1] < w_elec[elec_indices[-1]] + delta_p = np.zeros_like(w_ion) + if "positive" in domain.ion_species_names: + delta_p += ( + dom_state.positive_ion_density_m3 - domain.positive_ion_reference_m3 + ) + if "negative" in domain.ion_species_names: + assert domain.negative_ion_reference_m3 is not None + assert dom_state.negative_ion_density_m3 is not None + delta_p -= ( + dom_state.negative_ion_density_m3 - domain.negative_ion_reference_m3 + ) + expected_ion_charge_C_m2[elec_indices] += Q * w_ion * delta_p + + charge_scale = max(float(np.max(np.abs(w_elec * full_rho))), 1e-12) + np.testing.assert_allclose( + integrated_ion_charge_C_m2, + expected_ion_charge_C_m2, + rtol=1e-12, + atol=float(16.0 * np.finfo(float).eps * charge_scale), + ) + + # Check blocking heterointerface fluxes and BDF2 Maxwell identity across domains. + acc = assembled_ionic_bdf_accounting(step2, u2) + for domain in device.domains: + dom_acc = acc["domains"][domain.domain_layer_id] + for species_record in dom_acc["species"].values(): + flux = species_record["domain_flux_m2_s"] + assert flux[0] == 0.0 + assert flux[-1] == 0.0 + + scale = max( + float(np.max(np.abs(acc["conduction_current_density_A_m2"]))), + float(np.max(np.abs(acc["bdf_displacement_rate_A_m2"]))), + 1.0, + ) + assert float(np.max(np.abs(acc["maxwell_identity_error_A_m2"]))) < ( + 64.0 * np.finfo(float).eps * scale + ) From 30ede5581af3657c4077f6fc4076e3604abee754 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Wed, 11 Nov 2026 18:12:11 +0800 Subject: [PATCH 02/46] feat(config): close P03-01/04/05/06/07 gaps for Gate G3 (M-only) - Surface declared vs historical-effective SCAPS and device optical coherence (inspect_scaps_optical_coherence, inspect_device_optical_coherence, BehaviorContext.optical_coherence_diagnostics, ConfigurationMigration.export, LegacyWire.export) with P08-04 ownership tag and zero optical physics or v2 PreparedDevice word changes (P03-04). - Represent complete AST-pinned R1 implicit material behavior flags in inspect_r1_material_behavior and BehaviorContext(driver="r1_material"), fixing MULTIVALENT_VERSION QF-DC detection and guarding LegacyExecutionContext, ExecutionEngine, and IdentityInputs to require R1ExecutionContext (P03-04, P03-05). - Propagate tandem subcell diagnostics in migrate_configuration and synchronize SCAPS bulk_defects / scaps_defect_metadata edits (single-field edits, singular-to-plural promotion, clear, N_peak_cm3 edits, and conflict guards) in prepare_legacy_wire (P03-06, P03-07). - Update PublicAPI.json for solarlab.config.behavior and add regression tests across behavior, migration/wire roundtrip, cache/binding invalidation, and target-profile release/historical provenance verification (P03-01..07). --- src/solarlab/config/behavior.py | 376 ++++++++++++------ src/solarlab/config/identity.py | 7 + src/solarlab/config/legacy_execution.py | 2 + src/solarlab/config/legacy_wire.py | 173 +++++++- src/solarlab/config/migration.py | 19 +- src/solarlab/reproducibility/PublicAPI.json | 8 +- tests/refactor/test_behavior_context.py | 111 +++++- tests/refactor/test_binding_identity.py | 41 ++ .../refactor/test_configuration_migration.py | 185 +++++++++ tests/refactor/test_release_bundle.py | 80 ++++ 10 files changed, 867 insertions(+), 135 deletions(-) diff --git a/src/solarlab/config/behavior.py b/src/solarlab/config/behavior.py index e45c241a..3f515fb8 100644 --- a/src/solarlab/config/behavior.py +++ b/src/solarlab/config/behavior.py @@ -22,14 +22,18 @@ from solarlab.config.model_parameters import device_topology from solarlab.config.resolve_device import resolve_device from solarlab.config.scaps_input import import_scaps_device +from solarlab.config.yaml import load_yaml_mapping +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.defects import MULTIVALENT_VERSION from solarlab.device.resolved import PreparedDevice from solarlab.materials.source import SourceDocument from solarlab.physics.selection import Selection __all__ = ["BehaviorContext", "CapturedPreparation", "behavior_source_requirements", - "inspect_historical_behavior", "inspect_r1_material_behavior"] + "inspect_device_optical_coherence", "inspect_historical_behavior", + "inspect_r1_material_behavior", "inspect_scaps_optical_coherence"] -Driver = Literal["scaps_transient", "scaps_steady_state", "ion_hysteresis"] +Driver = Literal["scaps_transient", "scaps_steady_state", "ion_hysteresis", "r1_material"] _SCHEMA = "solarlab.historical-behavior-preparation.v1" # Source identities of the inspected branches, not a table of physical defaults. _PINS = { @@ -306,8 +310,8 @@ def __post_init__(self) -> None: _verify_words(result, schema=result["schema"]) def inspect(self, driver: Driver, device: PreparedDevice, arguments: dict[str, Any]) -> dict[str, Any]: - if driver == "ion_hysteresis": - raise ValueError("SCAPS evidence cannot stand in for an ion trajectory") + if driver in {"ion_hysteresis", "r1_material"}: + raise ValueError("SCAPS evidence cannot stand in for an ion or R1 trajectory") expected = resolve_device(import_scaps_device(self.case, id=device.to_input().id, defaults=device.defaults), device.defaults, device.resources, sources=(self.case,)) if device.input_json != expected.input_json: @@ -389,6 +393,77 @@ def _arguments(driver: Driver, source: SourceDocument, sources: dict[str, Source return supplied, effective +def inspect_device_optical_coherence( + device: PreparedDevice, *, legacy_incoherent: bool | None = None, +) -> list[dict[str, Any]]: + """Surface per-layer declared vs effective optical coherence for a PreparedDevice.""" + if type(device) is not PreparedDevice: + raise ValueError("an actual PreparedDevice is required") + effective_default = ( + bool(dict(device.defaults.material)["incoherent"]) + if legacy_incoherent is None else bool(legacy_incoherent) + ) + raw_layers = json.loads(device.input_json)["layers"] + rows = [] + for raw, layer in zip(raw_layers, device.layers): + params = dict(layer.parameters) + raw_params = raw.get("parameters", {}) + declared_present = "incoherent" in raw_params + declared = raw_params["incoherent"] if declared_present else None + effective = effective_default if raw.get("parameterization") == "scaps" else params["incoherent"] + ignored = bool(declared_present and declared != effective) + rows.append({ + "layer": layer.id, + "name": layer.name, + "role": layer.role, + "parameterization": raw.get("parameterization", "standard"), + "declared_present": declared_present, + "declared": declared, + "normalized_configured": params["incoherent"], + "effective": effective, + "historical_loader_value": effective, + "ignored_by_legacy_loader": ignored, + "prospective_fix_owner": "P08-04" if ignored else None, + }) + return rows + + +def inspect_scaps_optical_coherence( + source: SourceDocument, *, defaults: DefaultCatalog, +) -> tuple[dict[str, Any], ...]: + """Surface declared vs effective SCAPS optical coherence without altering physics.""" + if type(source) is not SourceDocument or type(defaults) is not DefaultCatalog: + raise ValueError("explicit immutable SCAPS source and default catalog are required") + raw_doc = load_yaml_mapping(source.content) + raw_layers = raw_doc.get("layers") + if isinstance(raw_layers, list): + for i, raw_row in enumerate(raw_layers): + if isinstance(raw_row, dict) and "incoherent" in raw_row and type(raw_row["incoherent"]) is not bool: + raise ValueError(f"layers[{i}].incoherent: expected boolean") + imported = import_scaps_device(source, id="scaps_optical_coherence", defaults=defaults) + legacy_effective = bool(dict(defaults.material)["incoherent"]) + result = [] + for raw_row, layer in zip(raw_doc["layers"], imported.layers): + declared_present = "incoherent" in raw_row + declared = raw_row["incoherent"] if declared_present else None + configured = layer.parameters.incoherent if layer.parameters.incoherent is not None else legacy_effective + ignored = bool(declared_present and declared != legacy_effective) + result.append({ + "layer": layer.id, + "name": layer.name, + "role": layer.role, + "parameterization": "scaps", + "declared_present": declared_present, + "declared": declared, + "normalized_configured": bool(configured), + "effective": legacy_effective, + "historical_loader_value": legacy_effective, + "ignored_by_legacy_loader": ignored, + "prospective_fix_owner": "P08-04" if ignored else None, + }) + return tuple(result) + + @dataclass(frozen=True, slots=True) class BehaviorContext: """Independent immutable context built from actual prepared public inputs. @@ -410,7 +485,8 @@ class BehaviorContext: _document: bytes = field(init=False, repr=False) def __post_init__(self) -> None: - if self.driver not in _DRIVERS or type(self.device) is not PreparedDevice or type(self.selection) is not Selection: + all_drivers = set(_DRIVERS) | {"r1_material"} + if self.driver not in all_drivers or type(self.device) is not PreparedDevice or type(self.selection) is not Selection: raise ValueError("an inspected driver, actual PreparedDevice and Selection are required") if self.selection.topology != device_topology(self.device): raise ValueError("selection topology does not match prepared device") @@ -418,126 +494,142 @@ def __post_init__(self) -> None: if any(type(source) is not SourceDocument for source in supplied_sources): raise ValueError("behavior sources must be immutable documents") sources = {source.id: source for source in supplied_sources} - if len(sources) != len(supplied_sources) or set(sources) != set(_PINS) or any(sources[p].sha256 != h for p, h in _PINS.items()): + required_pins = dict(behavior_source_requirements(driver=self.driver)) + if len(sources) != len(supplied_sources) or set(sources) != set(required_pins) or any(sources[p].sha256 != h for p, h in required_pins.items()): raise ValueError("exact audited behavior sources are required") environment = _environment(self.environment) env = dict(environment) - supplied, arguments = _arguments(self.driver, self.arguments, sources) device = self.device.to_mapping() settings = device["settings"] - if device["grain_boundaries"] or device.get("tunnelling_channels") or settings["interface_charge_closure"] != "off": - raise ValueError("complex/charged devices require a separate historical inspection") - if any(layer.cigs_graded_optics_json is not None or layer.metastable_document_json is not None - or layer.defect_model != "effective_lifetime" for layer in self.device.layers): - raise ValueError("extended material models require a separate historical inspection") - if any(dict(layer.parameters)["carrier_statistics"] != "maxwell_boltzmann" for layer in self.device.layers): - raise ValueError("carrier statistics are outside the audited driver subset") - ceilings, flags = _material_switches(settings, env, sources) - mol = _tree(sources, "solver/mol.py") - steady = _tree(sources, "experiments/steady_state.py") - softness = (_literal(steady, "_TE_SOFTNESS") if self.driver == "scaps_steady_state" - else _literal(mol, "te_softness", "MaterialArrays")) - contact_tree = _tree(sources, "physics/contacts.py") - contact_fn = next(n for n in contact_tree.body if isinstance(n, ast.FunctionDef) and n.name == "resolved_contact_velocities") - flat_velocity = next(ast.literal_eval(n.body) for n in ast.walk(contact_fn) if isinstance(n, ast.IfExp)) - contacts = [] - for contact in device["contacts"]: - for carrier in ("n", "p"): - original = contact["S_" + carrier] - effective = flat_velocity if settings["flat_band_contacts"] and original is None else original - if not settings["flat_band_contacts"] and not ceilings["use_selective_contacts"]: - effective = None - contacts.append({"side": contact["side"], "carrier": carrier, "configured_S_m_s": original, - "effective_S_m_s": effective, "condition": "density_dirichlet" if effective is None else - "blocking_robin" if effective == 0 else "finite_exchange_robin"}) - state_requested = env.get("SOLARLAB_INTERFACE_PLANE_STATE") == "1" or arguments.get("iface_states", False) - interfaces = [] - for interface in device["interfaces"]: - if interface["electrical"]: - defect = interface.get("defect") - if defect is not None: - base, state = defect["calibration_factor"], defect["iface_state_calibration_factor"] - interfaces.append({"id": interface["id"], "base_calibration": base, "state_calibration": state, - "calibration_if_plane_exists": base * state if self.driver == "scaps_steady_state" and arguments["iface_states"] else base, - "normalized_capture_velocities_m_s": interface["microscopic_capture_velocities_m_s"]}) - ions, incoherence = [], [] - raw_layers = json.loads(self.device.input_json)["layers"] - legacy_incoherent = _literal(_tree(sources, "models/parameters.py"), "incoherent", "MaterialParams") - for raw, layer in zip(raw_layers, self.device.layers): - params = dict(layer.parameters) - incoherence.append({"layer": layer.id, "normalized_configured": params["incoherent"], - "historical_loader_value": legacy_incoherent if raw.get("parameterization") == "scaps" else params["incoherent"]}) - if layer.role == "substrate": - continue - for species, suffix in (("positive", ""), ("negative", "_neg")): - enabled = species == "positive" or ceilings["use_dual_ions"] - diffusion, population = params["D_ion" + suffix], params["P0" + suffix] - ions.append({"layer": layer.id, "species": species, "D_reference_m2_s": diffusion, - "configured_initial_population_m3": population, "enabled_by_mode": enabled, - "seed_population_and_fixed_background_m3": population if enabled else 0.0, - "diffusion_status": "disabled_by_mode" if not enabled else "frozen_zero_diffusion" if diffusion == 0 else "temperature_scaled_not_evaluated", - "inventory_status": "zero_population_and_background" if not enabled or population == 0 else "population_and_equal_opposite_background_retained"}) - optical_data = bool(device["resource_bindings"]) - tmm_eligible = ceilings["use_tmm_optics"] and optical_data - waveform = arguments.get("waveform") - generation_override = waveform["uniform_generation_rate_m3_s"] if waveform is not None else None - preconditioning = _signature(_tree(sources, "solver/illuminated_ss.py"), "solve_illuminated_ss") - preparation = {"method": "steady_carrier_newton_with_bounded_transient_fallback" if self.driver == "scaps_steady_state" else - "finite_time_waveform_from_analytic_seed" if self.driver == "ion_hysteresis" else - "finite_illuminated_preconditioning" if arguments["illuminated"] else "analytic_seed_only", - "solver_executed": False, "converged_state_observed": False, - "seed": "quasi_neutral_n_p_clipped_then_ohmic_overrides_and_StateVec_pack; no Poisson/Newton state solve", - "actual_driver_arguments": arguments} - if self.driver == "scaps_transient" and arguments["illuminated"]: - preparation["preconditioner"] = {**preconditioning, "V_app": 0.0, "rtol": arguments["rtol"], "atol": arguments["atol"]} - preparation["material_ownership"] = "outer, independent inner preconditioner, independent seed material; outer not forwarded" - inspection = { - "mode_ceiling": ceilings, "switches": flags, - "switch_scope": "resolved requests; face/DOS/parameter activation remains conditional, including interface_tunneling's nonempty capped-face gate", - "interface_state_requested": state_requested, - "interface_state_count": {"status": "unobserved", "reason": "requires actual interface partitions; a gate is not a state count"}, - "interface_state_shared_occupancy_if_enabled": self.driver == "scaps_steady_state" and arguments.get("iface_states", False), - "interfaces": interfaces, "contacts": contacts, "ions": ions, - "ion_flux_label": "diffusion_only" if flags["ion_steric_diffusion_only"] else "whole_flux", - "te": {"softness": softness, "cap": "hard_direction_preserving_magnitude_min" if softness == 0 else "legacy_logistic_magnitude_blend", - "requested_physical_normalization": flags["te_physical_norm"], - "normalization": "unobserved_face_activation_and_DOS; disabled / legacy_density_weighted / physical_dos_normalized / legacy_fallback_missing_dos remain distinct"}, - "optics": {"generation": "uniform_absorber_override" if generation_override is not None else "TMM_eligible_unobserved" if tmm_eligible else "Beer_Lambert", - "uniform_generation_m3_s": generation_override, "incoherence": incoherence, - "resources": device["resource_bindings"], - "recycling": "disabled_without_TMM_data" if not tmm_eligible else - "uniform_absorber_nonlocal_RR_eligible_unobserved" if ceilings["use_radiative_reabsorption"] else "escape_scaled_B_eligible_unobserved"}, - "electrostatics": {"configured_V_bi": settings["V_bi"], "configured_potential_mode": settings["built_in_potential_mode"], - "signed_V_bi_eff": {"status": "unobserved"}, "signed_V_bi_bc": {"status": "unobserved"}, - "rule": "compatibility None retains distinct band-derived operating value and signed manual-magnitude BC; explicit modes share the selected value; BC drop is V_bi_bc - junction_polarity*V_app"}, - "import_time_policy": _import_policy(sources, env), - "runtime_interface_requests": {"qss": env.get("SOLARLAB_IFACE_QSS") == "1", - "allow_generation": env.get("SOLARLAB_IFACE_ALLOW_GEN") == "1", - "scope": "conditional on actual interface/phi; no RHS is evaluated"}, - "preparation": preparation, - } - captured = None - if self.capture is not None: - if type(self.capture) is not CapturedPreparation: - raise ValueError("reviewed captured preparation required") - catalog = read_legacy_default_catalog(tuple(sources[path] for path in _CATALOG_SOURCES)) - if self.device.defaults.content_sha256 != catalog.content_sha256: - raise ValueError("captured default catalog does not match prepared inputs") - captured = self.capture.inspect(self.driver, self.device, arguments) - payload = captured["payload"] - if "objects" in payload: - material = payload["objects"]["inner_material"]["value"]["fields"] - else: - record = payload["record"] - material = record["boundary_calls"][0]["kwargs"].get("mat", record["preparation"][0]["material"])["fields"] - gate_fields = {"te_physical_norm": "te_physical_norm", "ion_steric_diffusion_only": "ion_steric_diffusion_only", - "interface_plane_projection": "iface_plane_projection", "interface_two_sided": "iface_two_sided", - "interface_shared_occupancy": "iface_shared_occ", "interface_plane_closure": "iface_plane_closure", - "interface_plane_generation": "iface_plane_generation"} - if any(flags[name] != material[key] for name, key in gate_fields.items()) or state_requested != (material["N_iface_state"] > 0): - raise ValueError("captured effective gates conflict with the supplied inspection snapshot") + if self.driver == "r1_material": + if self.capture is not None: + raise ValueError("SCAPS capture cannot be attached to R1 material behavior") + supplied = _mapping(self.arguments) + if supplied.keys() - {"backend"}: + raise ValueError("unknown R1 behavior argument") + if (device["grain_boundaries"] or device.get("tunnelling_channels") + or settings["interface_charge_closure"] != "equilibrium_referenced"): + raise ValueError("R1 behavior context requires an equilibrium-referenced 1D device without grain boundaries or tunnelling channels") + ordered_sources = tuple(sources[path] for path in sorted(sources)) + inspection = inspect_r1_material_behavior( + self.device, sources=ordered_sources, environment=environment, backend=supplied.get("backend"), + ) + driver_source = {"path": "experiments/one_dimensional_mechanism_r1.py", "function": "build_r1_material"} + captured = None + else: + supplied, arguments = _arguments(self.driver, self.arguments, sources) + if device["grain_boundaries"] or device.get("tunnelling_channels") or settings["interface_charge_closure"] != "off": + raise ValueError("complex/charged devices require a separate historical inspection") + if any(layer.cigs_graded_optics_json is not None or layer.metastable_document_json is not None + or layer.defect_model != "effective_lifetime" for layer in self.device.layers): + raise ValueError("extended material models require a separate historical inspection") + if any(dict(layer.parameters)["carrier_statistics"] != "maxwell_boltzmann" for layer in self.device.layers): + raise ValueError("carrier statistics are outside the audited driver subset") + ceilings, flags = _material_switches(settings, env, sources) + mol = _tree(sources, "solver/mol.py") + steady = _tree(sources, "experiments/steady_state.py") + softness = (_literal(steady, "_TE_SOFTNESS") if self.driver == "scaps_steady_state" + else _literal(mol, "te_softness", "MaterialArrays")) + contact_tree = _tree(sources, "physics/contacts.py") + contact_fn = next(n for n in contact_tree.body if isinstance(n, ast.FunctionDef) and n.name == "resolved_contact_velocities") + flat_velocity = next(ast.literal_eval(n.body) for n in ast.walk(contact_fn) if isinstance(n, ast.IfExp)) + contacts = [] + for contact in device["contacts"]: + for carrier in ("n", "p"): + original = contact["S_" + carrier] + effective = flat_velocity if settings["flat_band_contacts"] and original is None else original + if not settings["flat_band_contacts"] and not ceilings["use_selective_contacts"]: + effective = None + contacts.append({"side": contact["side"], "carrier": carrier, "configured_S_m_s": original, + "effective_S_m_s": effective, "condition": "density_dirichlet" if effective is None else + "blocking_robin" if effective == 0 else "finite_exchange_robin"}) + state_requested = env.get("SOLARLAB_INTERFACE_PLANE_STATE") == "1" or arguments.get("iface_states", False) + interfaces = [] + for interface in device["interfaces"]: + if interface["electrical"]: + defect = interface.get("defect") + if defect is not None: + base, state = defect["calibration_factor"], defect["iface_state_calibration_factor"] + interfaces.append({"id": interface["id"], "base_calibration": base, "state_calibration": state, + "calibration_if_plane_exists": base * state if self.driver == "scaps_steady_state" and arguments["iface_states"] else base, + "normalized_capture_velocities_m_s": interface["microscopic_capture_velocities_m_s"]}) + legacy_incoherent = bool(_literal(_tree(sources, "models/parameters.py"), "incoherent", "MaterialParams")) + incoherence = inspect_device_optical_coherence(self.device, legacy_incoherent=legacy_incoherent) + ions = [] + for layer in self.device.layers: + if layer.role == "substrate": + continue + params = dict(layer.parameters) + for species, suffix in (("positive", ""), ("negative", "_neg")): + enabled = species == "positive" or ceilings["use_dual_ions"] + diffusion, population = params["D_ion" + suffix], params["P0" + suffix] + ions.append({"layer": layer.id, "species": species, "D_reference_m2_s": diffusion, + "configured_initial_population_m3": population, "enabled_by_mode": enabled, + "seed_population_and_fixed_background_m3": population if enabled else 0.0, + "diffusion_status": "disabled_by_mode" if not enabled else "frozen_zero_diffusion" if diffusion == 0 else "temperature_scaled_not_evaluated", + "inventory_status": "zero_population_and_background" if not enabled or population == 0 else "population_and_equal_opposite_background_retained"}) + optical_data = bool(device["resource_bindings"]) + tmm_eligible = ceilings["use_tmm_optics"] and optical_data + waveform = arguments.get("waveform") + generation_override = waveform["uniform_generation_rate_m3_s"] if waveform is not None else None + preconditioning = _signature(_tree(sources, "solver/illuminated_ss.py"), "solve_illuminated_ss") + preparation = {"method": "steady_carrier_newton_with_bounded_transient_fallback" if self.driver == "scaps_steady_state" else + "finite_time_waveform_from_analytic_seed" if self.driver == "ion_hysteresis" else + "finite_illuminated_preconditioning" if arguments["illuminated"] else "analytic_seed_only", + "solver_executed": False, "converged_state_observed": False, + "seed": "quasi_neutral_n_p_clipped_then_ohmic_overrides_and_StateVec_pack; no Poisson/Newton state solve", + "actual_driver_arguments": arguments} + if self.driver == "scaps_transient" and arguments["illuminated"]: + preparation["preconditioner"] = {**preconditioning, "V_app": 0.0, "rtol": arguments["rtol"], "atol": arguments["atol"]} + preparation["material_ownership"] = "outer, independent inner preconditioner, independent seed material; outer not forwarded" + inspection = { + "mode_ceiling": ceilings, "switches": flags, + "switch_scope": "resolved requests; face/DOS/parameter activation remains conditional, including interface_tunneling's nonempty capped-face gate", + "interface_state_requested": state_requested, + "interface_state_count": {"status": "unobserved", "reason": "requires actual interface partitions; a gate is not a state count"}, + "interface_state_shared_occupancy_if_enabled": self.driver == "scaps_steady_state" and arguments.get("iface_states", False), + "interfaces": interfaces, "contacts": contacts, "ions": ions, + "ion_flux_label": "diffusion_only" if flags["ion_steric_diffusion_only"] else "whole_flux", + "te": {"softness": softness, "cap": "hard_direction_preserving_magnitude_min" if softness == 0 else "legacy_logistic_magnitude_blend", + "requested_physical_normalization": flags["te_physical_norm"], + "normalization": "unobserved_face_activation_and_DOS; disabled / legacy_density_weighted / physical_dos_normalized / legacy_fallback_missing_dos remain distinct"}, + "optics": {"generation": "uniform_absorber_override" if generation_override is not None else "TMM_eligible_unobserved" if tmm_eligible else "Beer_Lambert", + "uniform_generation_m3_s": generation_override, "incoherence": incoherence, + "resources": device["resource_bindings"], + "recycling": "disabled_without_TMM_data" if not tmm_eligible else + "uniform_absorber_nonlocal_RR_eligible_unobserved" if ceilings["use_radiative_reabsorption"] else "escape_scaled_B_eligible_unobserved"}, + "electrostatics": {"configured_V_bi": settings["V_bi"], "configured_potential_mode": settings["built_in_potential_mode"], + "signed_V_bi_eff": {"status": "unobserved"}, "signed_V_bi_bc": {"status": "unobserved"}, + "rule": "compatibility None retains distinct band-derived operating value and signed manual-magnitude BC; explicit modes share the selected value; BC drop is V_bi_bc - junction_polarity*V_app"}, + "import_time_policy": _import_policy(sources, env), + "runtime_interface_requests": {"qss": env.get("SOLARLAB_IFACE_QSS") == "1", + "allow_generation": env.get("SOLARLAB_IFACE_ALLOW_GEN") == "1", + "scope": "conditional on actual interface/phi; no RHS is evaluated"}, + "preparation": preparation, + } + captured = None + if self.capture is not None: + if type(self.capture) is not CapturedPreparation: + raise ValueError("reviewed captured preparation required") + catalog = read_legacy_default_catalog(tuple(sources[path] for path in _CATALOG_SOURCES)) + if self.device.defaults.content_sha256 != catalog.content_sha256: + raise ValueError("captured default catalog does not match prepared inputs") + captured = self.capture.inspect(self.driver, self.device, arguments) + payload = captured["payload"] + if "objects" in payload: + material = payload["objects"]["inner_material"]["value"]["fields"] + else: + record = payload["record"] + material = record["boundary_calls"][0]["kwargs"].get("mat", record["preparation"][0]["material"])["fields"] + gate_fields = {"te_physical_norm": "te_physical_norm", "ion_steric_diffusion_only": "ion_steric_diffusion_only", + "interface_plane_projection": "iface_plane_projection", "interface_two_sided": "iface_two_sided", + "interface_shared_occupancy": "iface_shared_occ", "interface_plane_closure": "iface_plane_closure", + "interface_plane_generation": "iface_plane_generation"} + if any(flags[name] != material[key] for name, key in gate_fields.items()) or state_requested != (material["N_iface_state"] > 0): + raise ValueError("captured effective gates conflict with the supplied inspection snapshot") + driver_source = {"path": _DRIVERS[self.driver][0], "function": _DRIVERS[self.driver][1]} document = {"schema": _SCHEMA, "version": 1, "status": "prepared_pending_dependencies", "can_execute": False, - "driver": self.driver, "driver_source": {"path": _DRIVERS[self.driver][0], "function": _DRIVERS[self.driver][1]}, + "driver": self.driver, "driver_source": driver_source, "prepared_device_sha256": self.device.content_sha256, "normalized_supplied": json.loads(self.device.input_json), "input_sources": device["input_sources"], "default_catalog": device["default_catalog"], "layer_parameter_origins": [{"id": row["id"], "provenance": row["provenance"]} for row in device["layers"]], @@ -553,6 +645,8 @@ def __post_init__(self) -> None: *device["capability_gaps"]]} if self.driver == "ion_hysteresis": document["unresolved"].append("original_ion_run_effective_flags_not_recoverable_from_saved_request_alone") + elif self.driver == "r1_material": + document["unresolved"].append("R1_common_state_history_and_reference_require_R1ExecutionContext") object.__setattr__(self, "sources", tuple(sources[path] for path in sorted(sources))) object.__setattr__(self, "environment", environment) object.__setattr__(self, "_document", _bytes(document)) @@ -565,6 +659,10 @@ def export(self) -> dict[str, Any]: """A detached JSON inspection; mutations cannot affect another context.""" return json.loads(self._document) + def optical_coherence_diagnostics(self) -> list[dict[str, Any]]: + """Detached per-layer declared vs effective optical coherence records.""" + return list(self.export()["source_inspection"]["optics"]["incoherence"]) + def inspect_historical_behavior( device: PreparedDevice, selection: Selection, *, driver: Driver, @@ -605,10 +703,36 @@ def inspect_r1_material_behavior( else: value = ast.literal_eval(keyword.value) overrides[keyword.arg] = value + qf_call = next(node for node in ast.walk(builder) if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) and node.func.id == "_build_qf_material") + quadrature_order = next(ast.literal_eval(kw.value) for kw in qf_call.keywords + if kw.arg == "defect_energy_quadrature_order") + two_sided_call = next(node for node in ast.walk(builder) if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) and node.func.id == "_prepare_two_sided_material") + physical_boundary_volumes = next(ast.literal_eval(kw.value) for kw in two_sided_call.keywords + if kw.arg == "physical_boundary_volumes") qf = _tree(by_id, "experiments/quasi_fermi_steady_state.py") charge_off = next(node for node in qf.body if isinstance(node, ast.FunctionDef) and node.name == "_research_charge_off_stack") closure = next(ast.literal_eval(keyword.value) for node in ast.walk(charge_off) if isinstance(node, ast.Call) for keyword in node.keywords if keyword.arg == "interface_charge_closure") + prep_two_sided = next(node for node in qf.body if isinstance(node, ast.FunctionDef) and node.name == "_prepare_two_sided_material") + two_sided_replace = next(node for node in ast.walk(prep_two_sided) if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) and node.func.id == "replace") + two_sided_literals = { + str(kw.arg): list(ast.literal_eval(kw.value)) if isinstance(kw.value, ast.Tuple) else ast.literal_eval(kw.value) + for kw in two_sided_replace.keywords if kw.arg in {"interface_faces", "iface_qss_two_sided_trace"} + } + qf_dc_closure = _literal(_tree(by_id, "solver/mol.py"), "EXPLICIT_DEFECT_CHARGE_QF_DC") + requires_qf_dc = any( + layer.defect_schema_version == MULTIVALENT_VERSION + or any( + item.to_mapping().get("charge_transition") in {"acceptor", "donor"} + or item.to_mapping().get("distribution", {}).get("kind") != "single_level" + or item.to_mapping().get("spatial_profile") is not None + for item in layer.defects + ) + for layer in device.layers if layer.role != "substrate" + ) backend_tree = _tree(by_id, "experiments/one_dimensional_mechanism_r1_backend.py") representations = {target.id: ast.literal_eval(node.value.args[0]) for node in backend_tree.body if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) @@ -621,18 +745,32 @@ def inspect_r1_material_behavior( else: raise ValueError("unrecognized R1 numerical backend") data = device.to_mapping() + ceilings, switches = _material_switches(data["settings"], snapshot, by_id) + legacy_incoherent = bool(_literal(_tree(by_id, "models/parameters.py"), "incoherent", "MaterialParams")) + incoherence = inspect_device_optical_coherence(device, legacy_incoherent=legacy_incoherent) return { "schema": "solarlab.r1-material-behavior-inspection.v1", "can_execute": False, "driver": "r1_material", "driver_source": "experiments/one_dimensional_mechanism_r1.py#build_r1_material", "prepared_device_sha256": device.content_sha256, "input_sources": data["input_sources"], + "mode_ceiling": ceilings, "switches": switches, + "ion_flux_label": "diffusion_only" if switches["ion_steric_diffusion_only"] else "whole_flux", "declared_interface_charge_closure": data["settings"]["interface_charge_closure"], "material_interface_charge_closure": closure, "physical_geometry": _literal(_tree(by_id, "physics/physical_control_volume.py"), "PHYSICAL_GEOMETRY_V1"), + "qf_material_preparation": { + "defect_energy_quadrature_order": quadrature_order, + "explicit_defect_charge_closure": qf_dc_closure if requires_qf_dc else "none", + }, + "two_sided_preparation": {"physical_boundary_volumes": physical_boundary_volumes, **two_sided_literals}, "material_overrides": overrides, "ions": [{"layer": layer.id, "D_reference_m2_s": dict(layer.parameters)["D_ion"], "configured_inventory_m3": dict(layer.parameters)["P0"], "zero_diffusion_retains_inventory": dict(layer.parameters)["D_ion"] == 0} for layer in device.layers if layer.role != "substrate"], + "optics": {"incoherence": incoherence, "resources": data["resource_bindings"]}, + "runtime_interface_requests": {"qss": snapshot.get("SOLARLAB_IFACE_QSS") == "1", + "allow_generation": snapshot.get("SOLARLAB_IFACE_ALLOW_GEN") == "1", + "scope": "conditional on actual interface/phi; no RHS is evaluated"}, "backend_requested": backend, "backend_representation": selected_backend, "environment_effective_snapshot": {name: snapshot.get(name) for name in sorted(_ENV_NAMES)}, "import_time_policy": _import_policy(by_id, snapshot), diff --git a/src/solarlab/config/identity.py b/src/solarlab/config/identity.py index 265a9b3a..da31cf0d 100644 --- a/src/solarlab/config/identity.py +++ b/src/solarlab/config/identity.py @@ -318,6 +318,9 @@ def __post_init__(self) -> None: else: ceilings, switches = _material_switches(data["settings"], dict(behavior.environment), {item.id: item for item in behavior.sources}) + if (document["material_behavior"]["mode_ceiling"] != ceilings + or document["material_behavior"]["switches"] != switches): + raise ValueError("R1 material behavior switches disagree with source inspection") physical = _project_r1_physics(physical, document["material_behavior"], ceilings=ceilings, switches=switches, controls=document["arguments"]["controls"], reference=json.loads(behavior.reference.content)) binding["effective_behavior"] = {"sha256": behavior.content_sha256, "context": document} @@ -488,6 +491,8 @@ def __post_init__(self) -> None: raise ValueError("execution engine must be explicitly legacy or solarlab") if self.name == "legacy" and type(self.behavior) not in {BehaviorContext, R1ExecutionContext}: raise ValueError("legacy execution identity requires an explicit BehaviorContext or complete R1ExecutionContext") + if isinstance(self.behavior, BehaviorContext) and self.behavior.driver == "r1_material": + raise ValueError("R1 execution identity requires a complete R1ExecutionContext, not material-only BehaviorContext") if self.name == "solarlab" and self.behavior is not None: raise ValueError("a legacy BehaviorContext cannot be relabelled as the solarlab engine") @@ -520,6 +525,8 @@ def physics_identity(inputs: IdentityInputs) -> Identity: def _match_behavior(behavior: BehaviorContext | R1ExecutionContext, device: PreparedDevice, selection: Selection) -> None: if type(behavior) not in {BehaviorContext, R1ExecutionContext}: raise ValueError("actual source-bound BehaviorContext or complete R1ExecutionContext required") + if isinstance(behavior, BehaviorContext) and behavior.driver == "r1_material": + raise ValueError("R1 physics and execution identity require a complete R1ExecutionContext") if behavior.device.content_sha256 != device.content_sha256 or ( isinstance(behavior, BehaviorContext) and behavior.selection.content_sha256 != selection.content_sha256 ): diff --git a/src/solarlab/config/legacy_execution.py b/src/solarlab/config/legacy_execution.py index 89437549..536022d3 100644 --- a/src/solarlab/config/legacy_execution.py +++ b/src/solarlab/config/legacy_execution.py @@ -68,6 +68,8 @@ class LegacyExecutionContext: def __post_init__(self) -> None: if type(self.behavior) is not BehaviorContext: raise ValueError("an actual historical BehaviorContext is required") + if self.behavior.driver == "r1_material": + raise ValueError("LegacyExecutionContext supports only the three high-level drivers; use R1ExecutionContext for R1") _original_input(self.behavior.device, self.input_source, scaps=self.behavior.driver.startswith("scaps_")) inspected = self.behavior.export() diff --git a/src/solarlab/config/legacy_wire.py b/src/solarlab/config/legacy_wire.py index d53db3f3..81cb5ef1 100644 --- a/src/solarlab/config/legacy_wire.py +++ b/src/solarlab/config/legacy_wire.py @@ -199,6 +199,52 @@ def _scaps_bulk(value: dict[str, Any], v_th: Any, path: str) -> dict[str, Any]: return result +def _derived_scaps_metadata_entry( + defect: dict[str, Any], index: int, previous_meta: dict[str, Any] | None, +) -> dict[str, Any]: + distribution, energy = defect["distribution"], defect["energy_level"] + kind = "single" if distribution["kind"] == "single_level" else "gaussian" + entry: dict[str, Any] = { + "defect_id": f"bulk_{index}", + "distribution": kind, + "energy_reference": energy["reference"], + "trap_depth_eV": energy["value_eV"], + } + if "width_eV" in distribution and distribution["width_eV"] is not None: + entry["E_char_eV"] = distribution["width_eV"] + elif kind == "single" and previous_meta is not None and previous_meta.get("E_char_eV") is not None: + entry["E_char_eV"] = previous_meta["E_char_eV"] + if previous_meta is not None and previous_meta.get("N_peak_m3") is not None: + entry["N_peak_m3"] = previous_meta["N_peak_m3"] + return entry + + +def _input_optical_coherence(device: DeviceInput, defaults: DefaultCatalog) -> list[dict[str, Any]]: + legacy_effective = bool(dict(defaults.material)["incoherent"]) + rows = [] + for layer in device.layers: + editing = layer.parameters.editing_data() + declared_present = "incoherent" in editing + declared = layer.parameters.incoherent if declared_present else None + configured = bool(declared) if declared_present else legacy_effective + effective = legacy_effective if layer.parameterization == "scaps" else configured + ignored = bool(declared_present and declared != effective) + rows.append({ + "layer": layer.id, + "name": layer.name, + "role": layer.role, + "parameterization": layer.parameterization, + "declared_present": declared_present, + "declared": declared, + "normalized_configured": configured, + "effective": effective, + "historical_loader_value": effective, + "ignored_by_legacy_loader": ignored, + "prospective_fix_owner": "P08-04" if ignored else None, + }) + return rows + + def _scaps_layer(raw: dict[str, Any], before: dict[str, Any], after: dict[str, Any], path: str) -> dict[str, Any]: inverse = {name: (old, unit, wire_unit) for old, (name, unit, wire_unit) in SCAPS_FIELDS.items()} profile = {"trap_N_t_interface": ("N_t_peak_cm3", "m^-3", "cm^-3"), @@ -225,21 +271,54 @@ def _scaps_layer(raw: dict[str, Any], before: dict[str, Any], after: dict[str, A else: target[old] = (_wire_quantity(b[name], unit, wire_unit) if unit is not None and wire_unit is not None else b[name]) - if not _same(before.get("bulk_defects", []), after.get("bulk_defects", [])): + bulk_before, bulk_after = before.get("bulk_defects", []), after.get("bulk_defects", []) + meta_before, meta_after = before.get("scaps_defect_metadata", []), after.get("scaps_defect_metadata", []) + bulk_changed = not _same(bulk_before, bulk_after) + meta_changed = not _same(meta_before, meta_after) + v_th_changed = bool(bulk_after) and not _same(a.get("v_th"), b.get("v_th")) + if bulk_changed or meta_changed or v_th_changed: + if meta_changed and len(meta_after) != len(bulk_after): + raise _Unsupported(f"{path}.scaps_defect_metadata", "scaps_partner_metadata_conflict", + "SCAPS partner defect metadata count disagrees with bulk_defects.") singular = "bulk_defect" in raw - old_blocks = [raw["bulk_defect"]] if singular and raw["bulk_defect"] is not None else raw.get("bulk_defects", []) + old_blocks = [raw["bulk_defect"]] if singular and raw["bulk_defect"] is not None else list(raw.get("bulk_defects", [])) blocks = [] - for i, value in enumerate(after.get("bulk_defects", [])): - target = _scaps_bulk(value, b["v_th"], f"{path}.bulk_defects[{i}]") - previous = _scaps_bulk(before["bulk_defects"][i], a["v_th"], path) if i < len(before.get("bulk_defects", [])) else {} - blocks.append(_patch(old_blocks[i] if i < len(old_blocks) else {}, previous, target)) + for i, value in enumerate(bulk_after): + if value.get("id") != f"bulk_{i}": + raise _Unsupported(f"{path}.bulk_defects[{i}].id", "scaps_bulk_defect_id", + "SCAPS positional bulk defects require sequential bulk_0..bulk_{n-1} IDs.") + target_block = _scaps_bulk(value, b["v_th"], f"{path}.bulk_defects[{i}]") + previous = _scaps_bulk(bulk_before[i], a["v_th"], path) if i < len(bulk_before) else {} + patched = _patch(old_blocks[i] if i < len(old_blocks) else {}, previous, target_block) + if meta_changed: + meta = meta_after[i] + expected_kind = "single" if value["distribution"]["kind"] == "single_level" else "gaussian" + expected_ref = value["energy_level"]["reference"] + expected_depth = value["energy_level"]["value_eV"] + expected_width = value["distribution"].get("width_eV") + if (meta["defect_id"] != f"bulk_{i}" or meta["distribution"] != expected_kind + or meta["energy_reference"] != expected_ref or not _same(meta["trap_depth_eV"], expected_depth) + or (expected_kind == "gaussian" and not _same(meta.get("E_char_eV"), expected_width))): + raise _Unsupported(f"{path}.scaps_defect_metadata[{i}]", "scaps_partner_metadata_conflict", + "SCAPS partner defect metadata disagrees with the canonical bulk_defects declaration.") + if meta.get("N_peak_m3") is not None: + patched["N_peak_cm3"] = _wire_quantity(meta["N_peak_m3"], "m^-3", "cm^-3") + else: + patched.pop("N_peak_cm3", None) + if expected_kind == "single": + if meta.get("E_char_eV") is not None: + patched["E_char_eV"] = meta["E_char_eV"] + else: + patched.pop("E_char_eV", None) + blocks.append(patched) if singular and len(blocks) == 1: raw["bulk_defect"] = blocks[0] + elif not blocks and "defect_model" not in after and "defect_schema_version" not in after: + raw.pop("bulk_defect", None) + raw.pop("bulk_defects", None) else: raw.pop("bulk_defect", None) raw["bulk_defects"] = blocks - # Partner metadata is retained independently. A divergent duplicate cannot - # disappear: the complete strict roundtrip below detects it. return raw @@ -416,6 +495,49 @@ def _semantic(value: DeviceInput | TandemInput) -> dict[str, Any]: return _without_source_metadata(value.normalized_data()) +def _sync_untouched_scaps_metadata( + checked_device: dict[str, Any], before_device: dict[str, Any], defaults: DefaultCatalog, +) -> None: + if before_device.get("source_format") != "scaps" and not any( + row.get("parameterization") == "scaps" for row in before_device.get("layers", ()) + ): + return + for before_layer, checked_layer in zip(before_device["layers"], checked_device["layers"]): + if before_layer.get("parameterization") != "scaps" and checked_layer.get("parameterization") != "scaps": + continue + bulk_before = before_layer.get("bulk_defects", []) + bulk_after = checked_layer.get("bulk_defects", []) + meta_before = before_layer.get("scaps_defect_metadata", []) + meta_after = checked_layer.get("scaps_defect_metadata", []) + if _same(bulk_before, bulk_after) or not _same(meta_before, meta_after): + continue + if bulk_after: + checked_layer["scaps_defect_metadata"] = [ + _derived_scaps_metadata_entry(item, i, meta_before[i] if i < len(meta_before) else None) + for i, item in enumerate(bulk_after) + ] + checked_layer.setdefault("defect_schema_version", "solarlab-explicit-bulk-defects-v1") + checked_layer.setdefault("defect_model", defaults.defect_model) + elif "defect_model" not in checked_layer and "defect_schema_version" not in checked_layer: + checked_layer.pop("bulk_defects", None) + checked_layer.pop("scaps_defect_metadata", None) + else: + checked_layer["scaps_defect_metadata"] = [] + + +def _expected_semantic( + checked: DeviceInput | TandemInput, before: DeviceInput | TandemInput, defaults: DefaultCatalog, +) -> dict[str, Any]: + semantic = _semantic(checked) + before_norm = before.normalized_data() + if isinstance(checked, TandemInput): + _sync_untouched_scaps_metadata(semantic["top_cell"], before_norm["top_cell"], defaults) + _sync_untouched_scaps_metadata(semantic["bottom_cell"], before_norm["bottom_cell"], defaults) + else: + _sync_untouched_scaps_metadata(semantic, before_norm, defaults) + return semantic + + def _json_default(value: Any) -> Any: if isinstance(value, Decimal): return {"decimal": str(value)} @@ -493,6 +615,13 @@ def prepare_legacy_wire( report["retained_legacy_evidence"] = (_data(before).get("legacy_fields") if isinstance(before, DeviceInput) else {side: _data(before).get(side, {}).get("legacy_fields") for side in ("top_cell", "bottom_cell")}) devices = (checked,) if isinstance(checked, DeviceInput) else (checked.top_cell, checked.bottom_cell) + report["optical_coherence"] = ( + _input_optical_coherence(checked, defaults) if isinstance(checked, DeviceInput) + else { + "top_cell": _input_optical_coherence(checked.top_cell, defaults), + "bottom_cell": _input_optical_coherence(checked.bottom_cell, defaults), + } + ) report["inheritance"] = {device.id: { "settings_from_catalog": {name: value for name, value in defaults.device if name not in device.settings.editing_data()}, "undeclared_layer_parameters": {layer.id: sorted(set(type(layer.parameters).model_fields) - set(layer.parameters.editing_data())) for layer in device.layers}, @@ -508,13 +637,37 @@ def prepare_legacy_wire( report["wire_differences"] = _differences(load_yaml_mapping(source.content), wire) report["reference_differences"] = {name: _differences(load_yaml_mapping(supplied[name].content), load_yaml_mapping(doc.content)) for name, doc in emitted_references.items()} - losses = _differences(_semantic(checked), _semantic(reopened)) + expected_semantic = _expected_semantic(checked, before, defaults) + losses = _differences(expected_semantic, _semantic(reopened)) if losses: report["roundtrip_differences"] = losses[:64] report["roundtrip_difference_count"] = len(losses) raise _Unsupported(losses[0]["path"], "roundtrip_loss", "The strict importer cannot retain this declaration/presence; no partial wire is published.") + checked_words = _without_source_metadata(_data(checked)) + if isinstance(checked, TandemInput): + for side in ("top_cell", "bottom_cell"): + if "scaps_defect_metadata" in expected_semantic[side].get("layers", [{}])[0] or any( + "scaps_defect_metadata" in row for row in expected_semantic[side]["layers"] + ): + for cw, ew in zip(checked_words[side]["layers"], expected_semantic[side]["layers"]): + for k in ("scaps_defect_metadata", "defect_schema_version", "defect_model"): + if k in ew and k not in cw: + cw[k] = ew[k] + elif k in ew and k == "scaps_defect_metadata": + cw[k] = ew[k] + elif k not in ew and k in cw and k in ("scaps_defect_metadata", "bulk_defects"): + cw.pop(k, None) + else: + for cw, ew in zip(checked_words["layers"], expected_semantic["layers"]): + for k in ("scaps_defect_metadata", "defect_schema_version", "defect_model"): + if k in ew and k not in cw: + cw[k] = ew[k] + elif k in ew and k == "scaps_defect_metadata": + cw[k] = ew[k] + elif k not in ew and k in cw and k in ("scaps_defect_metadata", "bulk_defects"): + cw.pop(k, None) report["existing_import_normalization"] = _differences( - _without_source_metadata(_data(checked)), _without_source_metadata(_data(reopened))) + checked_words, _without_source_metadata(_data(reopened))) report["normalization_policy"] = "Wire/editing evidence retains signed zero; the existing SI importer normalizes converted zero to positive zero, reported separately without changing that contract." if behavior is not None: if type(behavior) is not BehaviorContext or not isinstance(checked, DeviceInput): diff --git a/src/solarlab/config/migration.py b/src/solarlab/config/migration.py index 03bea736..0f19c805 100644 --- a/src/solarlab/config/migration.py +++ b/src/solarlab/config/migration.py @@ -13,7 +13,7 @@ from pydantic import ValidationError -from solarlab.config.behavior import _mapping +from solarlab.config.behavior import _mapping, inspect_device_optical_coherence from solarlab.config.device_import import import_standard_device from solarlab.config.legacy_wire import LegacyWire, prepare_legacy_wire from solarlab.config.resolve_device import resolve_device, resolve_tandem @@ -186,9 +186,22 @@ def migrate_configuration( report["reverse_adapter"] = wire.export() if not wire.supported or wire.document != source or dict(wire.references) != supplied: raise ValueError("the existing reverse adapter cannot retain all original bytes; keep the old path") + legacy_incoherent = bool(dict(defaults.material)["incoherent"]) + prepared_map = prepared.to_mapping() + if isinstance(prepared, PreparedDevice): + diagnostics = prepared_map.get("diagnostics", []) + optical_coherence: Any = inspect_device_optical_coherence(prepared, legacy_incoherent=legacy_incoherent) + else: + diagnostics = [{"cell": side, **item} for side in ("top_cell", "bottom_cell") + for item in prepared_map[side].get("diagnostics", [])] + optical_coherence = { + "top_cell": inspect_device_optical_coherence(prepared.top_cell, legacy_incoherent=legacy_incoherent), + "bottom_cell": inspect_device_optical_coherence(prepared.bottom_cell, legacy_incoherent=legacy_incoherent), + } report.update(supported=True, proposed=_binding(document), prepared_content_sha256=prepared.content_sha256, - input_declaration=json.loads(prepared.input_json), diagnostics=prepared.to_mapping().get("diagnostics", []), - capability_gaps=prepared.to_mapping().get("capability_gaps", []), + input_declaration=json.loads(prepared.input_json), diagnostics=diagnostics, + optical_coherence=optical_coherence, + capability_gaps=prepared_map.get("capability_gaps", []), preparation_roundtrip_exact=True, original_wire_bytes_exact=True, runtime_behavior="existing source-bound driver context still required; v2 data is not execution admission") return ConfigurationMigration(document, _encode(report)) diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json index e8251f73..a7813708 100644 --- a/src/solarlab/reproducibility/PublicAPI.json +++ b/src/solarlab/reproducibility/PublicAPI.json @@ -10,8 +10,10 @@ "BehaviorContext", "CapturedPreparation", "behavior_source_requirements", + "inspect_device_optical_coherence", "inspect_historical_behavior", - "inspect_r1_material_behavior" + "inspect_r1_material_behavior", + "inspect_scaps_optical_coherence" ], "solarlab.config.device_import": [ "import_standard_device" @@ -577,8 +579,10 @@ "BehaviorContext", "CapturedPreparation", "behavior_source_requirements", + "inspect_device_optical_coherence", "inspect_historical_behavior", - "inspect_r1_material_behavior" + "inspect_r1_material_behavior", + "inspect_scaps_optical_coherence" ], "solarlab.config.device_import": [ "import_standard_device" diff --git a/tests/refactor/test_behavior_context.py b/tests/refactor/test_behavior_context.py index 787a7498..976f23ff 100644 --- a/tests/refactor/test_behavior_context.py +++ b/tests/refactor/test_behavior_context.py @@ -20,8 +20,10 @@ from solarlab.config.behavior import ( CapturedPreparation, _verify_words, behavior_source_requirements, inspect_historical_behavior, - inspect_r1_material_behavior, + inspect_r1_material_behavior, inspect_scaps_optical_coherence, ) +from solarlab.config.identity import ExecutionEngine +from solarlab.config.legacy_execution import LegacyExecutionContext from solarlab.config.device_import import import_standard_device from solarlab.config.legacy_defaults import read_legacy_default_catalog from solarlab.config.model_parameters import device_topology, layer_parameter_source @@ -471,3 +473,110 @@ def test_r1_missing_changed_sources_backend_and_environment_refuse(r1_material_i inspect_r1_material_behavior(device, sources=sources, environment=(), backend="automatic") with pytest.raises(ValueError, match="environment"): inspect_r1_material_behavior(device, sources=sources, environment=(("UNKNOWN_FLAG", "1"),)) + + +def test_scaps_optical_coherence_surfaces_declared_vs_effective_without_changing_physics(scaps, defaults, sources): + import yaml + + path = ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml" + raw_source = SourceDocument(str(path.relative_to(ROOT)), path.read_bytes()) + rows = inspect_scaps_optical_coherence(raw_source, defaults=defaults) + assert len(rows) == 4 + glass = rows[0] + assert glass == { + "layer": "layer_0", + "name": "glass", + "role": "substrate", + "parameterization": "scaps", + "declared_present": True, + "declared": True, + "normalized_configured": True, + "effective": False, + "historical_loader_value": False, + "ignored_by_legacy_loader": True, + "prospective_fix_owner": "P08-04", + } + for item in rows[1:]: + assert item["declared_present"] is False and item["declared"] is None + assert item["normalized_configured"] is False and item["effective"] is False + assert item["ignored_by_legacy_loader"] is False and item["prospective_fix_owner"] is None + + behavior = context(scaps, sources) + diagnostics = behavior.optical_coherence_diagnostics() + assert diagnostics == list(rows) + diagnostics[0]["effective"] = True + assert behavior.optical_coherence_diagnostics()[0]["effective"] is False + + parsed = yaml.safe_load(raw_source.content) + parsed["layers"][0]["incoherent"] = False + explicit_false = SourceDocument("explicit_false.yaml", yaml.safe_dump(parsed, sort_keys=False).encode()) + false_glass = inspect_scaps_optical_coherence(explicit_false, defaults=defaults)[0] + assert false_glass["declared_present"] is True and false_glass["declared"] is False + assert false_glass["effective"] is False and false_glass["ignored_by_legacy_loader"] is False + assert false_glass["prospective_fix_owner"] is None + + for invalid in ("yes", 1): + parsed["layers"][0]["incoherent"] = invalid + bad_source = SourceDocument("bad_incoherent.yaml", yaml.safe_dump(parsed, sort_keys=False).encode()) + with pytest.raises(ValueError, match=r"layers\[0\]\.incoherent: expected boolean"): + inspect_scaps_optical_coherence(bad_source, defaults=defaults) + + +def test_r1_behavior_context_represents_all_implicit_flags_and_blocks_material_only_execution(r1_material_inputs): + device, sources = r1_material_inputs + env = (("SOLARLAB_IFACE_QSS", "1"), ("SOLARLAB_IFACE_ALLOW_GEN", "0"), ("SOLARLAB_DOS_BAND", "0")) + direct = inspect_r1_material_behavior(device, sources=sources, environment=env, backend="pair") + sel = selection(device, "transient") + r1_ctx = inspect_historical_behavior( + device, sel, driver="r1_material", sources=sources, environment=env, + arguments=document("r1_call", {"backend": "pair"}), + ) + exported = r1_ctx.export() + observed = exported["source_inspection"] + assert exported["driver"] == "r1_material" and exported["can_execute"] is False + assert exported["driver_source"] == { + "path": "experiments/one_dimensional_mechanism_r1.py", + "function": "build_r1_material", + } + assert observed["switches"] == direct["switches"] and len(observed["switches"]) == 10 + assert observed["mode_ceiling"] == direct["mode_ceiling"] + assert observed["ion_flux_label"] == direct["ion_flux_label"] == "diffusion_only" + assert observed["declared_interface_charge_closure"] == "equilibrium_referenced" + assert observed["material_interface_charge_closure"] == "off" + assert observed["qf_material_preparation"] == { + "defect_energy_quadrature_order": 32, + "explicit_defect_charge_closure": "none", + } + assert observed["two_sided_preparation"] == { + "physical_boundary_volumes": True, + "interface_faces": [], + "iface_qss_two_sided_trace": True, + } + assert observed["runtime_interface_requests"]["qss"] is True + assert observed["runtime_interface_requests"]["allow_generation"] is False + assert observed["backend_representation"] == "float64-pair-v1" + assert r1_ctx.optical_coherence_diagnostics() == direct["optics"]["incoherence"] + + dist_path = ROOT / "perovskite-sim/tests/fixtures/configs/distributed_defect_qf_dc_pn.yaml" + dist_src = SourceDocument(str(dist_path.relative_to(ROOT)), dist_path.read_bytes()) + dist_dev = resolve_device( + import_standard_device(dist_src, id="r1_qf_dc", defaults=device.defaults), + device.defaults, device.resources, sources=(dist_src,), + ) + qf_dc = inspect_r1_material_behavior(dist_dev, sources=sources, environment=()) + assert qf_dc["qf_material_preparation"]["explicit_defect_charge_closure"] == "qf_dc" + + from test_execution_identity_preparation import identity_inputs + + with pytest.raises(ValueError, match="R1ExecutionContext"): + LegacyExecutionContext(behavior=r1_ctx, input_source=device.sources[0]) + with pytest.raises(ValueError, match="R1ExecutionContext"): + ExecutionEngine("legacy", r1_ctx) + with pytest.raises(ValueError, match="R1ExecutionContext"): + identity_inputs(device, effective_behavior=r1_ctx) + with pytest.raises(ValueError, match="SCAPS capture cannot be attached"): + inspect_historical_behavior( + device, sel, driver="r1_material", sources=sources, environment=(), + arguments=document("r1_call", {}), capture=object(), # type: ignore[arg-type] + ) + diff --git a/tests/refactor/test_binding_identity.py b/tests/refactor/test_binding_identity.py index b8b36090..6e158a86 100644 --- a/tests/refactor/test_binding_identity.py +++ b/tests/refactor/test_binding_identity.py @@ -191,3 +191,44 @@ def test_real_random_order_sweep_fresh_binding_keeps_all_numerical_words(prepare assert all(value.layer("numeric_factorization").sha256 is None and not value.numerical_reuse for value in instances) assert sweep._resolved_json == before record_property("binding_payloads", json.dumps(payloads)) + + +def test_illumination_change_invalidates_physics_numeric_and_state_keys_without_changing_topology( + device, execution, layout, plan, +): + illuminated = changed(device, lambda raw: raw["settings"].update(Phi=5.0e21)) + first = bound(identity_inputs(device), execution, layout, plan) + second = bound(identity_inputs(illuminated), execution, layout, plan) + assert first.input_sha256 != second.input_sha256 + assert first.physics_sha256 != second.physics_sha256 + assert first.layer("topology_plan").sha256 == second.layer("topology_plan").sha256 + assert first.layer("numeric_parameter_binding").sha256 != second.layer("numeric_parameter_binding").sha256 + assert first.layer("working_point_initial_state").sha256 != second.layer("working_point_initial_state").sha256 + + +def test_ion_diffusivity_crossing_zero_with_layout_support_change_invalidates_all_four_layers( + device, execution, layout, plan, +): + mobile_device = changed(device, lambda raw: raw["layers"][1]["parameters"].update(D_ion=1.0e-15)) + frozen_device = changed(device, lambda raw: raw["layers"][1]["parameters"].update(D_ion=0.0)) + mobile_layout = Layout( + (Support("fixture", "global", (2,)), Support("ion_cell", "global", (2,))), + ( + VariableSpec("fixture_state", "fixture_owner", "fixture", (2,), ONE), + VariableSpec("mobile_ion", "ion_owner", "ion_cell", (2,), ONE), + ), + ( + EquationSpec("fixture_equation", "fixture_owner", "fixture", (2,), ONE, + derivative_support=("fixture_state", "mobile_ion")), + EquationSpec("ion_continuity", "ion_owner", "ion_cell", (2,), ONE, + derivative_support=("fixture_state", "mobile_ion")), + ), + ) + mobile_plan = SourceDocument("fixture:mobile_ion_plan", b'{"scope":"metadata_only","mobile_ion":true}') + mobile_matrix = SourceDocument("fixture:matrix_mobile", struct.pack("<4d", 1.0, 0.2, 0.2, 2.0)) + frozen_matrix = SourceDocument("fixture:matrix_frozen", struct.pack("<4d", 1.0, 0.0, 0.0, 2.0)) + mobile = bound(identity_inputs(mobile_device), execution, mobile_layout, mobile_plan, matrix=mobile_matrix) + frozen = bound(identity_inputs(frozen_device), execution, layout, plan, matrix=frozen_matrix) + for domain in CACHE_LAYERS: + assert mobile.layer(domain).sha256 != frozen.layer(domain).sha256 + diff --git a/tests/refactor/test_configuration_migration.py b/tests/refactor/test_configuration_migration.py index 7acdeaee..cc801a79 100644 --- a/tests/refactor/test_configuration_migration.py +++ b/tests/refactor/test_configuration_migration.py @@ -249,3 +249,188 @@ def test_exact_selected_input_reconciles_derived_metadata_without_relabelling(ma with pytest.raises(ValueError, match="differs from the original"): module.read_selected_configuration_v2(matrix, SourceDocument("selection", plan.selection_json), row["id"], documents=(document,), defaults=context[0], resources=context[1], strict_derived_metadata=True) + + +def test_scaps_and_tandem_migration_surface_declared_vs_effective_optical_coherence_without_changing_words( + matrix, context, plan, +): + import yaml + + defaults, resources = context + rows = plan.export()["rows"] + scaps_rows = [ + row for row in rows + if row["migration"]["format"] == "scaps-device-v1" and row["migration"]["diagnostics"] + ] + assert scaps_rows + for row in scaps_rows: + mig = row["migration"] + diag = next(item for item in mig["diagnostics"] if item["code"] == "legacy_scaps_ignored_incoherent") + assert diag["declared"] is True and diag["historical_effective"] is False + glass = mig["optical_coherence"][0] + assert glass["declared_present"] is True and glass["declared"] is True + assert glass["normalized_configured"] is True and glass["effective"] is False + assert glass["historical_loader_value"] is False and glass["ignored_by_legacy_loader"] is True + assert glass["prospective_fix_owner"] == "P08-04" + v2_doc = next(doc for _, doc in plan.files if doc.id == mig["proposed"]["id"]) + original = prepare_configuration(matrix, row["id"], defaults=defaults, resources=resources).prepared + migrated = read_configuration_v2(v2_doc, defaults=defaults, resources=resources, sources=matrix.sources.documents) + assert words(migrated.to_mapping()) == words(original.to_mapping()) + + tandem_rows = [row for row in rows if row["migration"]["format"] == "tandem-v1"] + assert tandem_rows + for row in tandem_rows: + assert set(row["migration"]["optical_coherence"]) == {"top_cell", "bottom_cell"} + + # Verify subcell diagnostic and optical_coherence propagation on tandem migration. + from pathlib import PurePosixPath + import posixpath + + tandem_entry = matrix.entry(tandem_rows[0]["id"]) + tandem_src = matrix.sources.at_path(matrix.spec.original_path_root + "/" + tandem_entry.original_key) + tandem_prepared = prepare_configuration(matrix, tandem_entry.id, defaults=defaults, resources=resources).prepared + assert tandem_prepared is not None + parent = PurePosixPath(matrix.sources.reference(tandem_src.id).path).parent + tandem_decl = tandem_prepared.to_input() + tandem_refs = { + name: matrix.sources.at_path(posixpath.normpath(str(parent / name))) + for name in (tandem_decl.top_cell_reference, tandem_decl.bottom_cell_reference) + } + top_key = tandem_decl.top_cell_reference + top_wire = yaml.safe_load(tandem_refs[top_key].content) + top_wire["simulation_hints"] = {"jv_sweep": {"v_rate": 1.0}} + top_wire["layers"][0]["incoherent"] = True + synthetic_refs = { + **tandem_refs, + top_key: SourceDocument(top_key, yaml.safe_dump(top_wire, sort_keys=False).encode()), + } + tandem_mig = migrate_configuration( + tandem_src, format="tandem-v1", input_id="tandem_subcell_diag", + defaults=defaults, resources=resources, references=synthetic_refs, + ) + assert tandem_mig.supported + exported = tandem_mig.export() + assert any(item.get("cell") == "top_cell" for item in exported["diagnostics"]) + top_coherence = exported["optical_coherence"]["top_cell"][0] + assert top_coherence["declared_present"] is True and top_coherence["declared"] is True + assert top_coherence["effective"] is True and top_coherence["ignored_by_legacy_loader"] is False + + +def test_scaps_bulk_defect_edits_multi_defect_promotion_and_conflict_guards_in_legacy_wire(context): + from copy import deepcopy + import yaml + + from solarlab.config.legacy_wire import prepare_legacy_wire + from solarlab.config.scaps_input import import_scaps_device + from solarlab.device.inputs import DeviceInput + + defaults, _ = context + v2_path = ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml" + scaps_src = SourceDocument(str(v2_path.relative_to(ROOT)), v2_path.read_bytes()) + base_input = import_scaps_device(scaps_src, id="scaps_edit", defaults=defaults) + + # 1. Single-field & Gaussian promotion edits on bulk_defects without manually editing scaps_defect_metadata. + edited_data = deepcopy(base_input.editing_data()) + edited_data["layers"][2]["bulk_defects"][0]["energy_level"] = { + "reference": "above_valence_band", + "value_eV": 0.55, + } + edited_data["layers"][2]["bulk_defects"][0]["kinetics"]["sigma_n_m2"] = "2e-15 cm^2" + edited_data["layers"][2]["bulk_defects"][1]["distribution"] = { + "kind": "gaussian", + "normalization": "integrated_total", + "total_density_m3": "1e12 cm^-3", + "width_eV": 0.08, + "width_convention": "scaps_characteristic_energy", + } + wire_res = prepare_legacy_wire(DeviceInput.model_validate(edited_data), source=scaps_src, defaults=defaults) + assert wire_res.supported and wire_res.document is not None + reopened = import_scaps_device(wire_res.document, id="scaps_edit", defaults=defaults) + meta = reopened.layers[2].scaps_defect_metadata + assert meta[0].energy_reference == "above_valence_band" and meta[0].trap_depth_eV == 0.55 + assert meta[1].distribution == "gaussian" and meta[1].E_char_eV == 0.08 + assert wire_res.export()["optical_coherence"][0]["ignored_by_legacy_loader"] is True + + # 2. Singular `bulk_defect` -> plural `bulk_defects` multi-defect promotion and clearing all bulk defects. + singular_yaml = yaml.safe_load(scaps_src.content) + first_defect = singular_yaml["layers"][2].pop("bulk_defects")[0] + singular_yaml["layers"][2]["bulk_defect"] = first_defect + singular_src = SourceDocument("singular_scaps.yaml", yaml.safe_dump(singular_yaml, sort_keys=False).encode()) + singular_in = import_scaps_device(singular_src, id="singular", defaults=defaults) + promoted = deepcopy(singular_in.editing_data()) + second_defect = deepcopy(promoted["layers"][2]["bulk_defects"][0]) + second_defect["id"] = "bulk_1" + second_defect["name"] = "Perovskite-VB-2" + second_defect["energy_level"] = {"reference": "above_valence_band", "value_eV": 0.25} + promoted["layers"][2]["bulk_defects"] = (*promoted["layers"][2]["bulk_defects"], second_defect) + promoted_wire = prepare_legacy_wire(DeviceInput.model_validate(promoted), source=singular_src, defaults=defaults) + assert promoted_wire.supported and promoted_wire.document is not None + promoted_parsed = yaml.safe_load(promoted_wire.document.content) + assert "bulk_defect" not in promoted_parsed["layers"][2] + assert len(promoted_parsed["layers"][2]["bulk_defects"]) == 2 + + cleared = deepcopy(singular_in.editing_data()) + cleared["layers"][2].pop("bulk_defects", None) + cleared["layers"][2].pop("scaps_defect_metadata", None) + cleared["layers"][2].pop("defect_model", None) + cleared["layers"][2].pop("defect_schema_version", None) + cleared_wire = prepare_legacy_wire(DeviceInput.model_validate(cleared), source=singular_src, defaults=defaults) + assert cleared_wire.supported and cleared_wire.document is not None + cleared_parsed = yaml.safe_load(cleared_wire.document.content) + assert "bulk_defect" not in cleared_parsed["layers"][2] and "bulk_defects" not in cleared_parsed["layers"][2] + + # 3. Independent scaps_defect_metadata N_peak_m3 edit patches N_peak_cm3 cleanly; conflicts fail closed. + meta_edit = deepcopy(base_input.editing_data()) + meta_edit["layers"][2]["scaps_defect_metadata"][0]["N_peak_m3"] = "5e14 cm^-3" + meta_wire = prepare_legacy_wire(DeviceInput.model_validate(meta_edit), source=scaps_src, defaults=defaults) + assert meta_wire.supported and meta_wire.document is not None + assert yaml.safe_load(meta_wire.document.content)["layers"][2]["bulk_defects"][0]["N_peak_cm3"] == 5e14 + + conflict = deepcopy(base_input.editing_data()) + conflict["layers"][2]["bulk_defects"][0]["energy_level"]["value_eV"] = 0.45 + conflict["layers"][2]["scaps_defect_metadata"][0]["trap_depth_eV"] = 0.30 + conflict_wire = prepare_legacy_wire(DeviceInput.model_validate(conflict), source=scaps_src, defaults=defaults) + assert not conflict_wire.supported and conflict_wire.document is None + assert conflict_wire.export()["unsupported"][0]["code"] == "scaps_partner_metadata_conflict" + + bad_id = deepcopy(base_input.editing_data()) + bad_id["layers"][2]["bulk_defects"][0]["id"] = "bulk_9" + bad_id_wire = prepare_legacy_wire(DeviceInput.model_validate(bad_id), source=scaps_src, defaults=defaults) + assert not bad_id_wire.supported and bad_id_wire.export()["unsupported"][0]["code"] == "scaps_bulk_defect_id" + + bad_vth = deepcopy(base_input.editing_data()) + bad_vth["layers"][2]["parameters"]["v_th"] = "2e7 cm/s" + bad_vth_wire = prepare_legacy_wire(DeviceInput.model_validate(bad_vth), source=scaps_src, defaults=defaults) + assert not bad_vth_wire.supported and bad_vth_wire.export()["unsupported"][0]["code"] == "scaps_bulk_representation" + + +def test_duplicate_layer_display_names_edit_via_stable_ids_without_collateral_mutation(context): + from copy import deepcopy + import yaml + + from solarlab.config.legacy_wire import prepare_legacy_wire + from solarlab.config.scaps_input import import_scaps_device + from solarlab.device.inputs import DeviceInput + + defaults, _ = context + v2_path = ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml" + parsed = yaml.safe_load(v2_path.read_bytes()) + # Give two distinct layers the exact same display name while editing only one via stable layer_id / interface_id. + parsed["layers"][1]["name"] = "shared_transport" + parsed["layers"][3]["name"] = "shared_transport" + dup_src = SourceDocument("duplicate_names_scaps.yaml", yaml.safe_dump(parsed, sort_keys=False).encode()) + imported = import_scaps_device(dup_src, id="dup_scaps", defaults=defaults) + assert [layer.id for layer in imported.layers] == ["layer_0", "layer_1", "layer_2", "layer_3"] + assert imported.layers[1].name == imported.layers[3].name == "shared_transport" + + edited = deepcopy(imported.editing_data()) + edited["layers"][3]["thickness"] = "42 nm" + edited["interfaces"][2]["defect"]["total_density_m2"] = "3e12 cm^-2" + wire_res = prepare_legacy_wire(DeviceInput.model_validate(edited), source=dup_src, defaults=defaults) + assert wire_res.supported and wire_res.document is not None + emitted = yaml.safe_load(wire_res.document.content) + assert emitted["layers"][1]["thickness_nm"] == 20.0 + assert emitted["layers"][3]["thickness_nm"] == 42.0 + assert emitted["interfaces"][0]["N_t_cm2"] == 1.0e12 + assert emitted["interfaces"][1]["N_t_cm2"] == 3.0e12 + diff --git a/tests/refactor/test_release_bundle.py b/tests/refactor/test_release_bundle.py index 11933b8c..23ae0343 100644 --- a/tests/refactor/test_release_bundle.py +++ b/tests/refactor/test_release_bundle.py @@ -276,3 +276,83 @@ def test_release_job_provenance_keeps_full_pins_and_strict_source_policy(frozen, with pytest.raises(ValueError, match="strict_same_source"): bundle.verify_job_provenance(recorded.envelope(), current, **checks) assert bundle.canonical_json == original + + +def test_target_profile_bundle_builds_roundtrips_and_verifies_without_legacy_tree(frozen, tmp_path): + source, _ = frozen + target_source = tmp_path / "target-build-source" + for rel in ("src", "uv.lock", "pyproject.toml", "reproducibility/RefactorTransitionBoundariesV1.json", + "scripts/generate_configuration_schema.py", "generated/configuration-schema.json"): + src_item = source / rel + dst_item = target_source / rel + if src_item.is_dir(): + shutil.copytree(src_item, dst_item) + else: + dst_item.parent.mkdir(parents=True, exist_ok=True) + dst_item.write_bytes(src_item.read_bytes()) + core_nk = target_source / "resources/nk/MAPbI3.csv" + core_nk.parent.mkdir(parents=True, exist_ok=True) + core_nk.write_bytes((source / "perovskite-sim/perovskite_sim/data/nk/MAPbI3.csv").read_bytes()) + target_required = tuple( + ("resources/nk/MAPbI3.csv", "resource") if role == "resource" else (rel, role) + for rel, role in REQUIRED + ) + commit = command(["git", "rev-parse", "HEAD"], ROOT).decode().strip() + target_bundle = snapshot_release_bundle( + target_source, build_source_commit=commit, profile="target", required_files=target_required, + ) + assert target_bundle.profile == "target" and not target_bundle.can_execute + assert not any(item.path.startswith("site/perovskite_sim/") for item in target_bundle.files) + installed = tmp_path / "target-installed" + write_release_bundle(target_bundle, installed) + manifest = SourceDocument("ReleaseBundle.json", (installed / "ReleaseBundle.json").read_bytes()) + assert read_release_bundle(manifest, installed, expected_sha256=target_bundle.sha256) == target_bundle + verified = verify_release_installation( + target_bundle, installed, expected_sha256=target_bundle.sha256, + module_origins=(("solarlab.config.identity", str(installed / "site/solarlab/config/identity.py")),), + required_modules=("solarlab.config.identity",), + ) + assert verified["source_installation_verified"] is True + assert verified["bundle_sha256"] == target_bundle.sha256 + assert verified["files_verified"] == len(target_bundle.files) + + +def test_historical_result_provenance_verifies_against_original_source_without_relabelling(frozen): + from solarlab.reproducibility.job_provenance import result_provenance + + bundle = frozen[1] + older_commit = command(["git", "rev-parse", "HEAD^"], ROOT).decode().strip() + historical_bundle = replace( + bundle, + build_source_commit=older_commit, + files=tuple( + replace(item, content=item.content + b"# historical\n") + if item.source_path == "src/solarlab/config/identity.py" else item + for item in bundle.files + ), + ) + inputs = {"declared_input": "historical-standalone-case"} + historical_prov = historical_bundle.job_provenance(inputs, operator="test.historical") + historical_envelope = historical_prov.envelope() + saved_identity_sha = next( + row["sha256"] for row in historical_prov.export()["source_files"] + if row["path"] == "src/solarlab/config/identity.py" + ) + saved_record = { + "job_provenance": historical_envelope, + "source_sha256": {"solarlab.config.identity": saved_identity_sha}, + "source_identity": {"git_commit": older_commit}, + } + current_prov = bundle.job_provenance(inputs, operator="test.historical") + compared = result_provenance(saved_record, current_prov, expected_inputs=inputs) + assert compared["status"] == "different" and compared["scientific_qualification"] is False + assert "git_commit" in compared["different_fields"] + assert "source_tree_sha256" in compared["different_fields"] + assert compared["producer_identity"]["record"]["git_commit"] == older_commit + assert compared["current_identity"]["record"]["git_commit"] == bundle.build_source_commit + assert saved_record["job_provenance"] == historical_envelope + with pytest.raises(ValueError, match="strict_same_source"): + result_provenance(saved_record, current_prov, strict_same_source=True, expected_inputs=inputs) + with pytest.raises(ValueError, match="different inputs"): + result_provenance(saved_record, current_prov, expected_inputs={"declared_input": "wrong"}) + From 6d105f2e801580c0f2c2abead673b738bfa10c79 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 00:10:43 +0800 Subject: [PATCH 03/46] N: add boundary-consistent affine voltage-lift predictor for G2-R BE ramp --- scripts/benchmarks/g2_reference_be.py | 179 +++++- .../test_g2_be_ramp_predictor.py | 556 ++++++++++++++++++ .../test_g2_reference_be.py | 208 +++++++ 3 files changed, 925 insertions(+), 18 deletions(-) create mode 100644 tests/numerical_contracts/test_g2_be_ramp_predictor.py diff --git a/scripts/benchmarks/g2_reference_be.py b/scripts/benchmarks/g2_reference_be.py index 4959e8c2..f04bf80a 100644 --- a/scripts/benchmarks/g2_reference_be.py +++ b/scripts/benchmarks/g2_reference_be.py @@ -28,6 +28,7 @@ import numpy as np +from perovskite_sim.physics.compensated import DD from scripts.benchmarks.conservative_device import EquationBudget, conservative_be_step from scripts.benchmarks.contract_prototype import ( ContractError, @@ -64,6 +65,10 @@ "public-double-arithmetic-divide-v1": DoubleArithmetic, "public-float-arithmetic-divide-v1": FloatArithmetic, } +INITIAL_PREDICTOR_POLICIES = ( + "zero-local-increment-v1", + "affine-input-lift-v1", +) GIB = 1024**3 TAG_FIELDS = ( "segment", @@ -458,11 +463,92 @@ class Backend: observe_point: Callable[[Point, Any], dict] observe_interval: Callable[[Point, Point, Any, Any, TimeStep], dict] metadata: dict + initial_predictor: Mapping[str, Any] | None = None + + +def _validate_initial_predictor( + spec: Any, layout_size: int, input_count: int +) -> dict: + _require( + isinstance(spec, Mapping) + and type(spec.get("policy")) is str + and spec["policy"] in INITIAL_PREDICTOR_POLICIES, + "initial_predictor_policy", + ) + policy = spec["policy"] + if policy == "zero-local-increment-v1": + _require(set(spec) == {"policy"}, "initial_predictor_fields") + return {"policy": policy} + _require( + set(spec) == {"policy", "lift_hex"} and input_count > 0, + "initial_predictor_fields", + ) + rows = spec["lift_hex"] + _require( + isinstance(rows, (list, tuple)) and len(rows) == layout_size, + "initial_predictor_shape", + ) + lift_hex = [] + for row in rows: + _require( + isinstance(row, (list, tuple)) and len(row) == input_count, + "initial_predictor_shape", + ) + lift_hex.append( + [float(_hex_time(entry, nonnegative=False)).hex() for entry in row] + ) + return {"policy": policy, "lift_hex": lift_hex} + + +def _initial_predictor_spec(backend: Backend) -> dict: + spec = ( + {"policy": "zero-local-increment-v1"} + if backend.initial_predictor is None + else backend.initial_predictor + ) + return _validate_initial_predictor( + spec, backend.problem.layout.size, backend.problem.input_count + ) + + +def _predict_initial_increment( + spec: Mapping[str, Any], + layout_size: int, + left_inputs: Any, + right_inputs: Any, +) -> PrimitiveExpansion: + """Boundary-consistent initial trial increment; never alters the BE residual.""" + left = np.asarray(left_inputs, dtype=float) + right = np.asarray(right_inputs, dtype=float) + _require( + left.ndim == 1 + and left.shape == right.shape + and np.isfinite(left).all() + and np.isfinite(right).all(), + "initial_predictor_inputs", + ) + validated = _validate_initial_predictor(spec, layout_size, left.size) + if validated["policy"] == "zero-local-increment-v1" or np.array_equal( + left, right + ): + return PrimitiveExpansion.from_value(np.zeros(layout_size)) + lift = np.array( + [[float.fromhex(entry) for entry in row] for row in validated["lift_hex"]], + dtype=float, + ) + acc = DD(np.zeros(layout_size)) + for col in range(left.size): + if right[col] != left[col] and np.any(lift[:, col] != 0.0): + da = DD(float(right[col])) - DD(float(left[col])) + acc = acc + DD(lift[:, col]) * da + high = np.where(acc.hi == 0.0, 0.0, np.asarray(acc.hi, dtype=float)) + low = np.where(acc.lo == 0.0, 0.0, np.asarray(acc.lo, dtype=float)) + return PrimitiveExpansion.from_value(DoubleArray(high, low)) def effective_controls(backend: Backend) -> dict: """Expose the exact applied BE and observation controls for pre-run pinning.""" - return { + controls = { "method": METHOD, "step_options": dict(STEP_OPTIONS), "storage_secant_arithmetic": _secant_arithmetic(backend.problem), @@ -479,6 +565,9 @@ def effective_controls(backend: Backend) -> dict: }, "observation_controls": backend.metadata["observation_controls"], } + if backend.initial_predictor is not None: + controls["initial_predictor"] = _initial_predictor_spec(backend) + return controls def _secant_arithmetic(problem: Any) -> str: @@ -1088,7 +1177,11 @@ def supervised_stage(manifest, plan, action): def _check_newton( - row: Mapping, left: Point, right: Point, ratios: tuple[Fraction, ...] + row: Mapping, + left: Point, + right: Point, + ratios: tuple[Fraction, ...], + predictor_spec: Mapping[str, Any] | None = None, ) -> None: """Validate required diagnostics, iterate chain and accounting, not E3 bounds.""" iterations, summary = row.get("newton_iterations"), row.get("newton_summary") @@ -1107,9 +1200,17 @@ def _check_newton( }, "newton_diagnostics", ) + spec = ( + {"policy": "zero-local-increment-v1"} + if predictor_spec is None + else predictor_spec + ) + initial_local = _predict_initial_increment( + spec, left.state.layout.size, left.inputs, right.inputs + ) initial = _coordinate_trial( left, - PrimitiveExpansion.from_value(np.zeros(left.state.layout.size)), + initial_local, right.time, right.inputs, ) @@ -1331,6 +1432,17 @@ def measured(name, operation, *args, **kwargs): and backend.initial.time == backend.segments[0].start, "initial_binding", ) + predictor_spec = _initial_predictor_spec(backend) + if ( + predictor_spec["policy"] == "affine-input-lift-v1" + and "voltage_lift_map" in input_payload + ): + _require( + isinstance(input_payload["voltage_lift_map"], Mapping) + and predictor_spec["lift_hex"] + == input_payload["voltage_lift_map"].get("lift_hex"), + "initial_predictor_request_binding", + ) guard() _require(backend.feasible(backend.initial), "initial_domain") directory = Path(directory) @@ -1524,6 +1636,15 @@ def feasible(point: Point) -> bool: guard() return backend.feasible(point) + phase = "step_guard" + initial_increment = measured( + "step_validation", + _predict_initial_increment, + predictor_spec, + backend.problem.layout.size, + last_point.inputs, + inputs, + ) phase = "be_step" step = measured( "be_step", @@ -1535,6 +1656,7 @@ def feasible(point: Point) -> bool: scaling=backend.scaling, budgets=backend.budgets, inputs=inputs, + initial_increment=initial_increment, feasible=feasible, **STEP_OPTIONS, ) @@ -1581,9 +1703,7 @@ def feasible(point: Point) -> bool: "step_validation", _coordinate_trial, step.left, - PrimitiveExpansion.from_value( - np.zeros(backend.problem.layout.size) - ), + initial_increment, step.right.time, step.right.inputs, ).identity, @@ -1621,6 +1741,7 @@ def feasible(point: Point) -> bool: step.left, step.right, step.residual_ratios, + predictor_spec, ) phase = "accepted_step_write" row = emit("be_accepted_step", **step_payload) @@ -1948,6 +2069,7 @@ def read_reference_history( segment = None generation = 0 expected_schedule = None + predictor_spec = {"policy": "zero-local-increment-v1"} next_interval = 1 cumulative = [{"center": [0, 1], "radius": [0, 1]} for _ in range(3)] final = None @@ -2040,22 +2162,39 @@ def check_state(value: Any, point: Point) -> None: and row["scientific_pass"] is False, "header_physical_semantics", ) - controls = { - k: row[k] - for k in ( - "method", - "step_options", - "storage_secant_arithmetic", - "equation_budgets", - "solver_scaling", - "observation_controls", - ) - } + control_keys = ( + "method", + "step_options", + "storage_secant_arithmetic", + "equation_budgets", + "solver_scaling", + "observation_controls", + ) + (("initial_predictor",) if "initial_predictor" in row else ()) + controls = {k: row[k] for k in control_keys} _require( digest(controls) == expected_identity.controls_sha256 and row["step_options"] == STEP_OPTIONS, "controls_identity", ) + predictor_spec = ( + _validate_initial_predictor( + row["initial_predictor"], + layout.size, + len(previous_point.inputs), + ) + if "initial_predictor" in row + else {"policy": "zero-local-increment-v1"} + ) + if ( + predictor_spec["policy"] == "affine-input-lift-v1" + and "voltage_lift_map" in request + ): + _require( + isinstance(request["voltage_lift_map"], Mapping) + and predictor_spec["lift_hex"] + == request["voltage_lift_map"].get("lift_hex"), + "initial_predictor_request_binding", + ) secant_arithmetic = row["storage_secant_arithmetic"] _require( secant_arithmetic in SECANT_ARITHMETICS, @@ -2235,7 +2374,7 @@ def check_state(value: Any, point: Point) -> None: _require( set(row["solver_counts"]) == set(solver_totals), "solver_counts" ) - _check_newton(row, previous_point, right, ratios) + _check_newton(row, previous_point, right, ratios, predictor_spec) for k in solver_totals: _require(_integer(row["solver_counts"][k]), "solver_counts") solver_totals[k] += row["solver_counts"][k] @@ -2893,6 +3032,10 @@ def checks(point): "model_id": definition.id, "scientific_qualification": False, }, + initial_predictor={ + "policy": "affine-input-lift-v1", + "lift_hex": [[float(v).hex() for v in row] for row in mapping.lift], + }, ) diff --git a/tests/numerical_contracts/test_g2_be_ramp_predictor.py b/tests/numerical_contracts/test_g2_be_ramp_predictor.py new file mode 100644 index 00000000..66094d86 --- /dev/null +++ b/tests/numerical_contracts/test_g2_be_ramp_predictor.py @@ -0,0 +1,556 @@ +"""Regression contracts for boundary-consistent BE voltage-ramp prediction on B. + +Constructs DynamicAcceptorIonPublicDeviceV1 (B, intervals=8) strictly from the +portable qualification_origins.json input fixture and public benchmark modules, +without external archive paths or captured floating-point output oracles. +""" + +from __future__ import annotations + +from dataclasses import asdict +from fractions import Fraction +import json +import math +from pathlib import Path + +import numpy as np +import pytest + +from perovskite_sim.constants import Q +from scripts.benchmarks import coupled_device_prototype as cdp +from scripts.benchmarks import g2_reference_be as be +from scripts.benchmarks.conservative_device import EquationBudget, conservative_be_step +from scripts.benchmarks.contract_prototype import ContractError, PhysicalScaling, SECOND +from scripts.benchmarks.precision_prototype import ( + FrameInputExpansion, + PrimitiveExpansion, + encode_point, +) + +FIXTURES = Path(__file__).with_name("fixtures") +B_ORIGIN = json.loads((FIXTURES / "qualification_origins.json").read_text())["B"] + + +def _round_down_positive(value: Fraction) -> float: + approx = float(value) + if Fraction(approx) > value: + approx = math.nextafter(approx, 0.0) + assert approx > 0.0 and Fraction(approx) <= value + return approx + + +def _build_b_probe_context(): + definition = cdp.SlabDefinition( + source_path="portable-qualification-origin", + **B_ORIGIN["definition"], + ) + model = cdp.AffineCoupledSlab(definition, 8) + mapping = cdp.AffineVoltageMap( + model, mapped_input_profile="frame-input-expansion12-v1" + ) + all_segments = tuple(cdp.ProtocolSegment(**s) for s in B_ORIGIN["segments"]) + probe_segments = all_segments[:2] + request_stub = { + "segments": B_ORIGIN["segments"], + "observation_times": B_ORIGIN["observation_times"], + } + probe_tags = be.tags_from_request(request_stub, 2) + + zero_handoff = FrameInputExpansion( + tuple(np.zeros(model.layout.size, dtype=float) for _ in range(12)) + ) + inputs0, _ = probe_segments[0].inputs(probe_segments[0].start) + initial, _ = model.coordinates.trial( + model.reference, + zero_handoff, + probe_segments[0].start, + inputs0, + predecessor=model.reference, + ) + + # Exact frozen CommanderBEConfigurationV1 formulas (tau = alpha * r_strict / 64). + tau = Fraction(1e-10) * Fraction(1e-6) / 64 + q_ref = ( + Fraction(Q) + * Fraction(definition.area) + * Fraction(definition.length) + * Fraction(definition.ion_initial) + ) + vt = float(mapping.columns[-1]) + vols = [Fraction(float(v)) for v in model.geometry.volumes] + budget_Ceiling_rows = { + "a_n": [ + _round_down_positive(tau * vols[i] * Fraction(definition.n_eq)) + for i in range(1, 8) + ], + "b_p": [ + _round_down_positive(tau * vols[i] * Fraction(definition.p_eq)) + for i in range(1, 8) + ], + "c_ion": [ + _round_down_positive(tau * vols[i] * Fraction(definition.ion_initial)) + for i in range(9) + ], + "d_trap": [ + _round_down_positive(tau * vols[i] * Fraction(definition.trap_density)) + for i in range(9) + ], + "x_poisson": [_round_down_positive(tau * q_ref / 7)] * 7, + "y_phi_contact": [_round_down_positive(tau * Fraction(vt))] * 2, + "z_n_contact": [_round_down_positive(tau * Fraction(definition.n_eq))] * 2, + "zz_p_contact": [_round_down_positive(tau * Fraction(definition.p_eq))] * 2, + } + budgets = {} + equation_budgets_cfg = {} + for eq in model.layout.equations: + unit = eq.unit * SECOND if eq.role == "storage" else eq.unit + values = budget_Ceiling_rows[eq.id] + budgets[eq.id] = EquationBudget(unit, values) + equation_budgets_cfg[eq.id] = { + "unit": json.loads(json.dumps(asdict(unit))), + "absolute_hex": [float(x).hex() for x in values], + } + + pkt = model.numeric_packet() + eq_scaling = ( + [float(vols[i] * Fraction(definition.ni)) for i in range(1, 8)] + + [float(vols[i] * Fraction(definition.ni)) for i in range(1, 8)] + + [float(vols[i] * Fraction(definition.ion_initial)) for i in range(9)] + + [float(vols[i] * Fraction(definition.trap_density)) for i in range(9)] + + [float(Fraction(1) / Fraction(r)) for r in pkt["row_scaling"][32:]] + ) + state_scaling = [float(v) for v in mapping.columns] + scaling = PhysicalScaling(eq_scaling, state_scaling) + + def feasible(point): + values = be._physical_exact(point) + for spec in model.layout.variables: + row = values[spec.id] + if spec.id in {"n_m3", "p_m3"} and min(row) <= 0: + return False + if spec.lower is not None and min(row) < Fraction(spec.lower): + return False + if spec.upper is not None and max(row) > Fraction(spec.upper): + return False + if spec.id == "c_m3" and max(row) >= Fraction(definition.ion_capacity): + return False + return True + + def checks(point): + result = cdp.affine_state_quality_evidence(model, point, B_ORIGIN["budgets"]) + return { + "safety_pass": feasible(point), + "scientific_failed": result.get("passed") is False, + "same_state_evidence": result, + } + + lift_hex = [[float(v).hex() for v in row] for row in mapping.lift] + predictor_spec = {"policy": "affine-input-lift-v1", "lift_hex": lift_hex} + return { + "model": model, + "mapping": mapping, + "all_segments": all_segments, + "probe_segments": probe_segments, + "probe_tags": probe_tags, + "initial": initial, + "budgets": budgets, + "equation_budgets_cfg": equation_budgets_cfg, + "scaling": scaling, + "eq_scaling": eq_scaling, + "state_scaling": state_scaling, + "feasible": feasible, + "checks": checks, + "predictor_spec": predictor_spec, + } + + +def _lightweight_b_backend(ctx: dict, *, initial_predictor: dict | None) -> be.Backend: + """Fast deterministic observer wrapper for multi-hundred-step BE convergence tests.""" + model = ctx["model"] + + def enclosure(val: Fraction) -> dict: + return {"center": be._pair(val), "radius": [0, 1]} + + def observe_point(point, segment): + charges = [ + sum( + Fraction(float(w[0])) + for w in model.linear_action(name, point).value.words + ) + for name in ("body_charge",) + ] + metal = model.linear_action("metal_charge", point).value + m_left = sum(Fraction(float(w[0])) for w in metal.words) + m_right = sum(Fraction(float(w[1])) for w in metal.words) + return { + "ports": { + "left": enclosure(Fraction(0)), + "right": enclosure(Fraction(0)), + "unit": "A", + }, + "charges": { + "device": enclosure(charges[0]), + "left_metal": enclosure(m_left), + "right_metal": enclosure(m_right), + "unit": "C", + }, + "observation_uncertainty": "exact affine charge action", + "derivative_origin": "same_state_affine_tangent", + "evidence_status": "represented_point_only", + } + + def observe_interval(left, right, step, segment, target): + return { + "physical_flux": [enclosure(Fraction(0)) for _ in range(3)], + "unit": "C", + "storage_secant_used_as_flux": False, + "origin": "declared_reconstruction", + "reference_error_status": "unknown_reference_error", + } + + return be.Backend( + model.public_problem(), + model.coordinates, + ctx["initial"], + ctx["scaling"], + ctx["budgets"], + ctx["probe_segments"], + ctx["feasible"], + ctx["checks"], + observe_point, + observe_interval, + { + "kind": "portable_B_probe", + "source_identity": model.source_identity, + "observation_controls": {"kind": "lightweight_b_probe"}, + }, + initial_predictor=initial_predictor, + ) + + +def test_b_small_voltage_step_solution_invariance_and_contact_lift(): + ctx = _build_b_probe_context() + model = ctx["model"] + problem = model.public_problem() + left = ctx["initial"] + h = 2.0**-13 + # Non-dyadic voltage step small enough that the unlifted trial also converges. + right_inputs = (3e-4, 0.0) + + lifted_inc = be._predict_initial_increment( + ctx["predictor_spec"], model.layout.size, left.inputs, right_inputs + ) + zero_inc = PrimitiveExpansion.from_value(np.zeros(model.layout.size)) + + # 1. Verify exact boundary lift and unchanged positive/bounded fields at trial 0. + zero_trial, zero_step_inc = model.coordinates.trial( + model.reference, + FrameInputExpansion(tuple(np.zeros(model.layout.size) for _ in range(12))).add( + zero_inc + ), + left.time + h, + right_inputs, + predecessor=left, + ) + lifted_trial, lifted_step_inc = model.coordinates.trial( + model.reference, + FrameInputExpansion(tuple(np.zeros(model.layout.size) for _ in range(12))).add( + lifted_inc + ), + left.time + h, + right_inputs, + predecessor=left, + ) + assert ctx["feasible"](lifted_trial) is True + before_exact = be._physical_exact(left) + lifted_exact = be._physical_exact(lifted_trial) + for field in ("n_m3", "p_m3", "c_m3", "f"): + assert lifted_exact[field] == before_exact[field] + assert lifted_exact["phi_V"][0] == Fraction(0) + assert lifted_exact["phi_V"][-1] + Fraction(right_inputs[0]) == Fraction(0) + + res_zero_0 = problem.conservative_residual(left, zero_trial, zero_step_inc) + res_lift_0 = problem.conservative_residual(left, lifted_trial, lifted_step_inc) + phi_contact_offset = model.graph.row_offsets["y_phi_contact"] + zero_contact_res = [ + sum(Fraction(float(w[i])) for w in res_zero_0.words) + for i in range(phi_contact_offset.start, phi_contact_offset.stop) + ] + lift_contact_res = [ + sum(Fraction(float(w[i])) for w in res_lift_0.words) + for i in range(phi_contact_offset.start, phi_contact_offset.stop) + ] + contact_budget = Fraction(ctx["budgets"]["y_phi_contact"].absolute[1]) + assert abs(zero_contact_res[1]) / contact_budget > 10**15 + assert lift_contact_res == [Fraction(0), Fraction(0)] + + # 2. Both predictors solve the identical BE equation and converge to the same state. + step_unlifted = conservative_be_step( + problem, + model.coordinates, + left, + h, + scaling=ctx["scaling"], + budgets=ctx["budgets"], + inputs=right_inputs, + initial_increment=None, + feasible=ctx["feasible"], + **be.STEP_OPTIONS, + ) + step_lifted = conservative_be_step( + problem, + model.coordinates, + left, + h, + scaling=ctx["scaling"], + budgets=ctx["budgets"], + inputs=right_inputs, + initial_increment=lifted_inc, + feasible=ctx["feasible"], + **be.STEP_OPTIONS, + ) + assert max(step_unlifted.residual_ratios) <= 1 + assert max(step_lifted.residual_ratios) <= 1 + assert len(step_lifted.iterations) <= len(step_unlifted.iterations) + + state_u = be._physical_exact(step_unlifted.right) + state_l = be._physical_exact(step_lifted.right) + for spec in model.layout.variables: + offset = model.layout.offsets[spec.id] + for j, col in enumerate(range(offset.start, offset.stop)): + scale = Fraction(ctx["state_scaling"][col]) + scaled_diff = abs(state_u[spec.id][j] - state_l[spec.id][j]) / scale + assert scaled_diff < Fraction(1, 10**18), (spec.id, j, float(scaled_diff)) + + +def test_prepare_b_backend_wires_affine_lift_predictor_and_real_slab_observer( + tmp_path, monkeypatch +): + pytest.importorskip("flint") + ctx = _build_b_probe_context() + model = ctx["model"] + mapping = ctx["mapping"] + + t1 = 2.0**-8 + t2 = 2.0**-7 + t3 = 3.0 * 2.0**-8 + v_end = 5.0 * (t2 - t1) + short_segments = ( + cdp.ProtocolSegment("dark_equilibrium_hold", 0.0, t1, (0.0, 0.0), (0.0, 0.0)), + cdp.ProtocolSegment("voltage_ramp", t1, t2, (0.0, v_end), (0.0, 0.0)), + cdp.ProtocolSegment("biased_light_soak", t2, t3, (v_end, v_end), (0.0, 0.0)), + ) + pkt = model.numeric_packet() + pkt["initial_reference"] = encode_point(model.reference) + pkt["definition_identity"] = model.definition.identity + pkt["layout_identity"] = model.layout.identity + request = { + "case_id": "DynamicAcceptorIonPublicDeviceV1", + "numeric_packet": pkt, + "voltage_lift_map": mapping.payload(), + "segments": [asdict(s) for s in short_segments], + "observation_times": { + "dark_equilibrium_hold": [0.0, t1], + "voltage_ramp": [t1, t2], + "biased_light_soak": [t2, t3], + }, + "initial_segment_frame": { + "physical_handoff_words_hex": [ + [(0.0).hex()] * model.layout.size for _ in range(12) + ] + }, + "initial_preparation": {"point_identity": ctx["initial"].identity}, + "budgets": B_ORIGIN["budgets"], + } + configuration = { + "scientific_execution_authorized": True, + "source_review_accepted": True, + "method_status": "frozen", + "commander_admission_identity": "test-admission-pin", + "segment_count": 2, + "equation_budgets": ctx["equation_budgets_cfg"], + "equation_scaling": ctx["eq_scaling"], + "state_scaling": ctx["state_scaling"], + "observation_absolute_error_C": [1, 10**18], + } + # Bypass only the external IDA parent-request lineage check while running + # the real prepare_B_backend, real SlabObserver, and real B kernel. + monkeypatch.setattr( + cdp, "validate_voltage_lift_native_request", lambda *a, **k: None + ) + + backend = be.prepare_B_backend(request, configuration) + assert backend.initial_predictor == ctx["predictor_spec"] + assert be.effective_controls(backend)["initial_predictor"] == ctx["predictor_spec"] + + tags = be.tags_from_request(request, 2) + schedule = be.compile_schedule( + backend.segments, tags, level=0, seed=Fraction(1, 512) + ) + identity = be.RunIdentity( + "B_short_real_observer", + be.digest(request), + "1" * 64, + "2" * 64, + "3" * 40, + "test-env", + schedule.identity, + backend.problem.source_identity, + backend.initial.identity, + be.digest(be.effective_controls(backend)), + ) + limits = be.Limits(120.0, output_bytes=64 * 1048576, logical_bytes=64 * 1048576) + out_dir = tmp_path / "real_observer_run" + result = be.run_reference(backend, schedule, identity, request, out_dir, limits) + readback = be.read_reference_history(out_dir, backend.problem.layout, identity) + assert result["numerical_complete"] is True + assert readback["structural_pass"] is True + assert readback["numerical_complete"] is True + assert readback["accepted_steps"] == len(schedule.steps) + + +def test_b_short_window_l0_l1_l2_ramp_convergence_and_first_order_refinement(tmp_path): + ctx = _build_b_probe_context() + model = ctx["model"] + request = { + "case_id": "DynamicAcceptorIonPublicDeviceV1", + "segments": B_ORIGIN["segments"], + "observation_times": B_ORIGIN["observation_times"], + "voltage_lift_map": {"lift_hex": ctx["predictor_spec"]["lift_hex"]}, + } + limits = be.Limits(300.0, output_bytes=128 * 1048576, logical_bytes=128 * 1048576) + + # 1. Historical unlifted behavior remains reproduced when predictor is absent: + # first voltage_ramp step (step 65 of L0) exhausts the 12-iteration budget. + unlifted_backend = _lightweight_b_backend(ctx, initial_predictor=None) + l0_schedule = be.compile_schedule(ctx["probe_segments"], ctx["probe_tags"], level=0) + unlifted_id = be.RunIdentity( + "B_Probe_Unlifted_L0", + be.digest(request), + "1" * 64, + "2" * 64, + "3" * 40, + "test-env", + l0_schedule.identity, + unlifted_backend.problem.source_identity, + unlifted_backend.initial.identity, + be.digest(be.effective_controls(unlifted_backend)), + ) + with pytest.raises(ContractError, match="conservative_iteration_budget_exhausted"): + be.run_reference( + unlifted_backend, + l0_schedule, + unlifted_id, + request, + tmp_path / "unlifted_l0", + limits, + ) + failure = json.loads((tmp_path / "unlifted_l0" / "FirstFailure.json").read_text()) + assert failure["location"]["target_step"]["index"] == 65 + assert failure["location"]["target_step"]["segment"] == "voltage_ramp" + assert be.read_reference_history( + tmp_path / "unlifted_l0", model.layout, unlifted_id + )["structural_pass"] + + # 2. With affine-input-lift-v1, L0/L1/L2 (128/256/512 steps) over 0-0.2 s + # converge cleanly within STEP_OPTIONS and pass readback + state checks. + lifted_backend = _lightweight_b_backend( + ctx, initial_predictor=ctx["predictor_spec"] + ) + terminal_points = [] + expected_steps = (128, 256, 512) + for level, step_count in enumerate(expected_steps): + schedule = be.compile_schedule( + ctx["probe_segments"], ctx["probe_tags"], level=level + ) + assert len(schedule.steps) == step_count + run_dir = tmp_path / f"lifted_l{level}" + identity = be.RunIdentity( + f"B_Probe_L{level}", + be.digest(request), + "1" * 64, + "2" * 64, + "3" * 40, + "test-env", + schedule.identity, + lifted_backend.problem.source_identity, + lifted_backend.initial.identity, + be.digest(be.effective_controls(lifted_backend)), + ) + result = be.run_reference( + lifted_backend, schedule, identity, request, run_dir, limits + ) + readback = be.read_reference_history(run_dir, model.layout, identity) + assert result["numerical_complete"] is True + assert result["scientific_status"] == "unknown_reference_error" + assert readback["structural_pass"] is True + assert readback["numerical_complete"] is True + assert readback["accepted_steps"] == step_count + assert readback["tagged_observations"] == 66 + + rows = [ + json.loads(line) + for line in (run_dir / "History/BE.jsonl").read_text().splitlines() + ] + step_rows = [r for r in rows if r["kind"] == "be_accepted_step"] + max_iters = max(len(r["newton_iterations"]) for r in step_rows) + min_damping = min( + (it["damping"] for r in step_rows for it in r["newton_iterations"]), + default=1.0, + ) + if level == 0: + assert max_iters <= 4 and min_damping >= 0.5 + else: + assert max_iters <= 3 and min_damping == 1.0 + + header_ref = rows[0]["original_reference"] + terminal_points.append( + be.unpack_point(step_rows[-1]["right"], header_ref, model.layout) + ) + + # 3. Verify asymptotic first-order temporal refinement (L0 -> L1 -> L2) at t = 0.2 s + # across all dynamic state DOFs and terminal physical port/charge observables. + states = [be._physical_exact(pt) for pt in terminal_points] + dynamic_checked = 0 + invariant_checked = 0 + for field in ("n_m3", "p_m3", "phi_V", "c_m3", "f"): + offset = model.layout.offsets[field] + for idx in range(model.count): + col = offset.start + idx + scale = Fraction(ctx["state_scaling"][col]) + v0, v1, v2 = (s[field][idx] for s in states) + d01, d12 = v0 - v1, v1 - v2 + if field in {"n_m3", "p_m3", "phi_V", "f"} and idx in ( + 0, + model.count - 1, + ): + assert abs(d01) / scale < Fraction(1, 10**24), (field, idx, d01) + assert abs(d12) / scale < Fraction(1, 10**24), (field, idx, d12) + invariant_checked += 1 + else: + verdict = be.order_check((d01, Fraction(0)), (d12, Fraction(0))) + assert verdict["status"] == "passed", (field, idx, verdict) + dynamic_checked += 1 + assert dynamic_checked == 37 + assert invariant_checked == 8 + + # Check real SlabObserver point currents & charges at t = 0.2 s when Arb is present. + try: + import flint # noqa: F401 + except ImportError: + pass + else: + observer = be.SlabObserver(model, Fraction(1, 10**18)) + ramp_segment = ctx["probe_segments"][1] + point_obs = [observer.point(pt, ramp_segment) for pt in terminal_points] + for group, keys in ( + ("ports", ("left", "right")), + ("charges", ("device", "left_metal", "right_metal")), + ): + for key in keys: + centers = [be._unpair(o[group][key]["center"]) for o in point_obs] + radii = [be._unpair(o[group][key]["radius"]) for o in point_obs] + d01 = (centers[0] - centers[1], radii[0] + radii[1]) + d12 = (centers[1] - centers[2], radii[1] + radii[2]) + verdict = be.order_check(d01, d12) + assert verdict["status"] == "passed", (group, key, verdict) diff --git a/tests/numerical_contracts/test_g2_reference_be.py b/tests/numerical_contracts/test_g2_reference_be.py index d8103f2d..46d88305 100644 --- a/tests/numerical_contracts/test_g2_reference_be.py +++ b/tests/numerical_contracts/test_g2_reference_be.py @@ -1895,6 +1895,214 @@ def test_BE4_integer_pipeline_clock_above_binary64_exact_range(tmp_path, monkeyp assert type(record["original_deadline_ns"]) is int +def test_affine_input_lift_predictor_preserves_analytic_be_solution_and_exact_lift( + tmp_path, +): + segments = ( + ProtocolSegment("a", 0.0, 0.25, (0.0, 0.0), (0.0, 0.0)), + ProtocolSegment("b", 0.25, 0.5, (0.0, 0.3), (0.0, 0.0)), + ProtocolSegment("c", 0.5, 0.75, (0.3, 0.3), (0.0, 0.0)), + ) + lift_hex = [ + [(0.0).hex(), (0.0).hex()], + [(0.0).hex(), (0.0).hex()], + [(1.0).hex(), (0.0).hex()], + ] + base_backend = manufactured("voltage", segments=segments) + lifted_backend = replace( + base_backend, + initial_predictor={"policy": "affine-input-lift-v1", "lift_hex": lift_hex}, + ) + assert "initial_predictor" not in be.effective_controls(base_backend) + assert be.effective_controls(lifted_backend)["initial_predictor"] == { + "policy": "affine-input-lift-v1", + "lift_hex": lift_hex, + } + + _, schedule, _, _, base_readback = execute( + tmp_path / "unlifted", backend=base_backend + ) + _, _, lifted_id, _, lifted_readback = execute( + tmp_path / "lifted", backend=lifted_backend + ) + assert base_readback["structural_pass"] and lifted_readback["structural_pass"] + assert ( + base_readback["accepted_steps"] + == lifted_readback["accepted_steps"] + == len(schedule.steps) + ) + + base_steps = [ + r for r in raw_rows(tmp_path / "unlifted") if r["kind"] == "be_accepted_step" + ] + lifted_steps = [ + r for r in raw_rows(tmp_path / "lifted") if r["kind"] == "be_accepted_step" + ] + # Segment a (constant V=0): identical initial trials when delta_inputs == 0. + for row_u, row_l in zip(base_steps, lifted_steps, strict=True): + if row_u["segment"] == "a": + assert ( + row_u["newton_summary"]["initial_trial_identity"] + == row_l["newton_summary"]["initial_trial_identity"] + ) + assert row_u["right"] == row_l["right"] + elif row_u["segment"] == "b": + assert ( + row_u["newton_summary"]["initial_trial_identity"] + != row_l["newton_summary"]["initial_trial_identity"] + ) + + # Terminal and intermediate tagged physical states satisfy the identical + # analytic BE solution within the 1e-24 equation budgets. + expected_n0, expected_n1 = Fraction(3), Fraction(3) + for step in schedule.steps: + h = Fraction(step.h) + t_r = Fraction(step.right) + expected_n0 += h * (2 * t_r) + expected_n1 += h * (-t_r) + terminal_v = Fraction(0.3) + expected_phi = expected_n0 + 2 * expected_n1 + terminal_v + + for readback in (base_readback, lifted_readback): + obs = readback["observations"][-1]["physical_state_words"] + n_vals = [ + sum(Fraction(float.fromhex(w[i])) for w in obs["n"]["words_hex"]) + for i in range(2) + ] + phi_val = sum(Fraction(float.fromhex(w[0])) for w in obs["phi"]["words_hex"]) + assert abs(n_vals[0] - expected_n0) <= Fraction(1e-24) + assert abs(n_vals[1] - expected_n1) <= Fraction(1e-24) + assert abs(phi_val - expected_phi) <= Fraction(3e-24) + + # On a pure boundary-lift step with zero storage change (tiny rate within budget), + # the exact DD affine lift satisfies phi - (n0 + 2*n1 + V_right) == 0 at trial 0 + # and accepts in 0 Newton iterations even for non-dyadic delta_V = 0.3 V. + pure_segments = (ProtocolSegment("ramp", 0.0, 0.125, (0.0, 0.3), (0.0, 0.0)),) + pure_base = replace( + manufactured("tiny", segments=pure_segments), + budgets={ + "balance": EquationBudget(PARTICLE, [1e-20, 1e-20]), + "constraint": EquationBudget(VOLT, [1e-30]), + }, + ) + pure_lifted = replace( + pure_base, + initial_predictor={"policy": "affine-input-lift-v1", "lift_hex": lift_hex}, + ) + pure_sched = be.compile_schedule( + pure_segments, + tags_for(pure_segments, [[0.0, 0.125]]), + level=0, + seed=Fraction(1, 8), + ) + execute(tmp_path / "pure_lifted", backend=pure_lifted, schedule=pure_sched) + pure_step = next( + r + for r in raw_rows(tmp_path / "pure_lifted") + if r["kind"] == "be_accepted_step" + ) + assert pure_step["newton_iterations"] == [] + assert pure_step["newton_summary"]["initial_trial_accepted"] is True + assert pure_step["solver_counts"] == { + "factorizations": 0, + "linear_solves": 0, + "residual_evaluations": 1, + } + assert be._unpair(pure_step["residual_ratios"][2]) == 0 + + # Independent reader rejects tampering of initial_trial_identity or header predictor. + rows = raw_rows(tmp_path / "lifted") + ramp_step = next( + r for r in rows if r["kind"] == "be_accepted_step" and r["segment"] == "b" + ) + unlifted_ramp_step = next( + r + for r in raw_rows(tmp_path / "unlifted") + if r["kind"] == "be_accepted_step" and r["segment"] == "b" + ) + ramp_step["newton_summary"]["initial_trial_identity"] = unlifted_ramp_step[ + "newton_summary" + ]["initial_trial_identity"] + reseal(tmp_path / "lifted", rows) + with pytest.raises(ContractError, match="newton_diagnostics_initial_trial"): + be.read_reference_history( + tmp_path / "lifted", lifted_backend.problem.layout, lifted_id + ) + + +def test_initial_predictor_validation_and_request_binding_rejection(tmp_path): + segments = (ProtocolSegment("ramp", 0.0, 0.125, (0.0, 0.25), (0.0, 0.0)),) + lift_hex = [ + [(0.0).hex(), (0.0).hex()], + [(0.0).hex(), (0.0).hex()], + [(-1.0).hex(), (0.0).hex()], + ] + backend = replace( + manufactured("voltage", segments=segments), + initial_predictor={"policy": "affine-input-lift-v1", "lift_hex": lift_hex}, + ) + for bad in ( + {"policy": "unknown-v1"}, + {"policy": "zero-local-increment-v1", "lift_hex": lift_hex}, + {"policy": "affine-input-lift-v1"}, + {"policy": "affine-input-lift-v1", "lift_hex": lift_hex[:2]}, + {"policy": "affine-input-lift-v1", "lift_hex": [["0x1.0p+0"], ["0x0.0p+0"], ["0x0.0p+0"]]}, + {"policy": "affine-input-lift-v1", "lift_hex": [["0x1p+0", "0x0.0p+0"]] * 3}, + ): + with pytest.raises(ContractError, match="reference_be_"): + be.effective_controls(replace(backend, initial_predictor=bad)) + + schedule = be.compile_schedule( + segments, tags_for(segments, [[0.0, 0.125]]), level=0, seed=Fraction(1, 8) + ) + bad_lift = deepcopy(lift_hex) + bad_lift[2][0] = (-0.5).hex() + mismatched_request = { + "kind": "manufactured", + "segments": [asdict(s) for s in segments], + "voltage_lift_map": {"lift_hex": bad_lift}, + } + identity = be.RunIdentity( + "manufactured", + be.digest(mismatched_request), + "1" * 64, + "2" * 64, + "3" * 40, + "manufactured-test-environment", + schedule.identity, + backend.problem.source_identity, + backend.initial.identity, + be.digest(be.effective_controls(backend)), + ) + limits = be.Limits(60.0, output_bytes=64 * 1048576, logical_bytes=64 * 1048576) + with pytest.raises(ContractError, match="initial_predictor_request_binding"): + be.run_reference( + backend, + schedule, + identity, + mismatched_request, + tmp_path / "mismatch_run", + limits, + ) + + # Also verify reader rejects header predictor tampering or request map mismatch. + good_request = dict(mismatched_request, voltage_lift_map={"lift_hex": lift_hex}) + good_id = replace(identity, input_sha256=be.digest(good_request)) + be.run_reference( + backend, schedule, good_id, good_request, tmp_path / "good_run", limits + ) + assert be.read_reference_history( + tmp_path / "good_run", backend.problem.layout, good_id + )["structural_pass"] + rows = raw_rows(tmp_path / "good_run") + rows[0]["initial_predictor"]["lift_hex"][2][0] = (-0.5).hex() + reseal(tmp_path / "good_run", rows) + with pytest.raises(ContractError, match="controls_identity"): + be.read_reference_history( + tmp_path / "good_run", backend.problem.layout, good_id + ) + + # Exact original time words are appended below from the already reviewed plan; # tests never access the archive, build the device, or open a historical gzip. From 533d2ebfc7521aa42e97ac400b7dacc8c7915745 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 10:53:55 +0800 Subject: [PATCH 04/46] feat(equations,experiments): integrate stripped CND2 time-method selection under interface-level trust (M-only) --- examples/research_1d/transient.py | 4 +- examples/research_1d/transient_voltage.py | 3 +- src/solarlab/equations/time_method.py | 910 ++++++++++++++++ src/solarlab/experiments/bdf.py | 45 +- src/solarlab/experiments/bdf_results.py | 141 ++- src/solarlab/experiments/ionic_transient.py | 38 +- .../experiments/ionic_transient_worker.py | 17 +- .../experiments/multiple_ionic_transient.py | 8 +- src/solarlab/experiments/transient.py | 38 +- src/solarlab/experiments/transient_results.py | 65 +- src/solarlab/experiments/transient_worker.py | 20 +- src/solarlab/reproducibility/PublicAPI.json | 35 + tests/ci/exclusions.json | 13 +- .../fixtures/bdf_readiness/allowlist.json | 830 +++++++++++++++ tests/integration/test_bdf_publication.py | 7 +- .../integration/test_time_method_selection.py | 989 ++++++++++++++++++ tests/integration/test_transient_1d.py | 5 +- tests/integration/test_transient_results.py | 3 +- .../integration/test_transient_voltage_1d.py | 5 +- tests/runtime/test_worker_time_method.py | 162 +++ .../assembly/test_production_provenance.py | 3 +- tests/unit/solvers/time/bdf_benchmark.py | 42 +- tests/unit/solvers/time/bdf_light_replay.py | 9 +- .../solvers/time/bdf_robustness_witness.py | 9 +- tests/unit/solvers/time/test_assembled_bdf.py | 23 +- tests/unit/solvers/time/test_bdf_1d.py | 45 +- .../solvers/time/test_time_method_axis.py | 540 ++++++++++ 27 files changed, 3866 insertions(+), 143 deletions(-) create mode 100644 src/solarlab/equations/time_method.py create mode 100644 tests/integration/fixtures/bdf_readiness/allowlist.json create mode 100644 tests/integration/test_time_method_selection.py create mode 100644 tests/runtime/test_worker_time_method.py create mode 100644 tests/unit/solvers/time/test_time_method_axis.py diff --git a/examples/research_1d/transient.py b/examples/research_1d/transient.py index cc553ed4..a41757e7 100644 --- a/examples/research_1d/transient.py +++ b/examples/research_1d/transient.py @@ -66,7 +66,9 @@ def main() -> int: # Explicit right-endpoint samples of g(t)=1+0.01*(t/400 ns)^2. # These are not inferred event times or hidden solver substeps. protocol = TransientProtocol(times, np.zeros(steps + 1), 1.0 + 0.01 * (times / times[-1]) ** 2) - result = solve_transient(device, initial, protocol, options=controls(), initial_options=initial_controls) + # A backward-Euler example: these ramps are allowlisted BDF envelopes, so the opt-out is explicit. + result = solve_transient(device, initial, protocol, options=controls(), initial_options=initial_controls, + method="backward_euler") results.append(result) if not result.completed: break diff --git a/examples/research_1d/transient_voltage.py b/examples/research_1d/transient_voltage.py index 3ac8a9ad..77f97158 100644 --- a/examples/research_1d/transient_voltage.py +++ b/examples/research_1d/transient_voltage.py @@ -40,8 +40,9 @@ def main() -> int: initial = solve_steady_state(device, voltage_V=0.1, generation_scale=1.0, options=initial_controls) results = [] for steps in ((4, 8, 16) if args.refine else (4,)): + # A backward-Euler example: these ramps are allowlisted BDF envelopes, so the opt-out is explicit. result = solve_transient(device, initial, voltage_protocol(steps), options=controls(), - initial_options=initial_controls) + initial_options=initial_controls, method="backward_euler") results.append(result) if not result.completed: break diff --git a/src/solarlab/equations/time_method.py b/src/solarlab/equations/time_method.py new file mode 100644 index 00000000..0d469a53 --- /dev/null +++ b/src/solarlab/equations/time_method.py @@ -0,0 +1,910 @@ +"""Time-method selection of the transient production entry points (CND2). + +The time integrator is an axis of its own, separate from the equation +implementation (:mod:`solarlab.equations.implementation`). One names the +integrator a history runs, the other the equation and storage classes it +evaluates. Each is resolved, recorded and refused on its own. + +The values are ``backward_euler`` and ``bdf``. A history requests one + +* per call: the entry point's ``method`` argument; +* in code: ``with time_method(BDF): ...`` (this context and what it calls); +* per process: ``NEWCORE_TIME_METHOD=``, read outside any scope; + +and otherwise takes the scope-based default. An explicit ``backward_euler`` +is the opt-out: it computes no scope and always integrates with backward +Euler. Unknown values are refused, never mapped to a default. + +``bdf`` is selectable only for an allowlisted scope, and runs the frozen +profile ``PROFILE`` (ReadinessV1 ProposedDefault ``92396791``) with the +adaptive work cap ``ADAPTIVE_MAX_STEPS`` forwarded to the adapter. The +allowlist holds exactly the ten electronic envelopes of +CommanderBdfDefaultFreezeV2 (those of V1, keyed by content). Each envelope is +one 37-node device content, one initial state, one set of source knots, +physical and initial controls and a drive without jumps. These envelopes are +all it covers, not other jobs on the same device. A scope is a +path-independent content digest (:func:`scope_digest`): compiled identities +bind the configuration path, so the device enters by the content they digest. +The exact byte grammar of the digest, with worked vectors, is the archive +record Cnd2ScopeKeyGrammarV2 (Core1D/AdaptiveBDFV1). + +Admission keys what runs, and runs what it keyed (D1, D1b, D1-R1, D2): + +* The resolver computes the scope digest itself from the call's actual + inputs. It takes the family from the compiled device's exact class. No + caller supplies a digest or a family. +* Every scoped value must be exactly its type, with no state beyond its + declared fields. +* A BDF selection records the inputs as immutable values (``_record``): + nested tuples of their declared words, as bytes and Python scalars. It + builds objects from the records and keys them again. If that key differs + from the key of the caller's objects, an input changed while it was + admitted, and the call is refused. No caller-owned object is read after + it is recorded. +* Admission returns a :class:`TimeMethodSelection` and an + :class:`AdmittedBDFCall`. The admission is a tuple of immutable values: + the family, the case, the key and the records. Records also name the + solarlab classes and enum members their inputs are built from, which + belong to solarlab's code, not to the call. Neither the selection nor + the admission holds an object that a history integrates. +* A production route admits its call once, and integrates it with + :func:`integrate_admitted`. That builds the history's inputs from the + admission's records after admission has returned, and keys them again: + they must be the admitted, allowlisted scope. It hands them to the BDF + adapter, with the protocol's own continuous drive, the frozen profile, + the work cap and the admission. +* The adapter first computes the integrator's start, interval, options, + breakpoints and events. Its last step before calling the integrator + re-keys the inputs they come from (:func:`verify_integration`). +* No function of this module returns an object that a production history + integrates. :func:`integrate_admitted` builds the inputs in place + (``_build_into``), and keys them without ``_declared_only``'s rebuild. + +Interface-level trust boundary (``interface_level_trust_standard_v1``, +archive record ``Cnd2ReviewScopeDecisionV1`` of 2026-11-02; the earlier V4 +strict-scope outcome remains preserved in history as ``not_passed`` and is +not relabelled): + +* Inputs passed to ``solve_transient``, ``solve_ionic_transient``, + ``run_production_bdf_for_publication`` and ``run_transient_for_publication`` + are copied and frozen at admission (:class:`AdmittedBDFCall`); nothing a + caller later does to its own objects, before or after admission, changes + what is integrated. +* Data handed to caller-supplied code or inspected via the public surface + cannot change a run's admitted inputs: ``_genuine`` refuses subclasses, + look-alikes and custom callbacks, ``_declared_only`` refuses state beyond + declared fields or stale derived fields, and ``_probe_drive_constructor`` + probes only a throwaway copy. +* The integrator runs only on inputs whose scope digest equals one of the + ten allowlisted keys with the frozen profile ``PROFILE`` and + ``ADAPTIVE_MAX_STEPS``; anything else raises ``ValueError`` before any + integration step, with no fallback. +* Stored records state the requested/effective method, admitted scope key, + ``trust_standard`` and ``qualification=False`` truthfully. +* Outside this interface boundary, ``solarlab``'s internal code and runtime + objects created during a run, other threads in the process, profiling, + tracing, debugging and ``sys.monitoring`` tools, low-level runtime + introspection, third-party in-process code and source changes are trusted + rather than policed by interpreter/OS hooks. + +Every other BDF request is refused before numerical work, with no fallback +to backward Euler. This covers: + +* a different device, initial state, drive or control; +* a BDF profile other than the frozen one; +* an unsupported population or entry point; +* every worker job; +* a scope whose digest cannot be computed. + +The scope-based default is backward Euler for every scope. +``ALLOWLISTED_DEFAULT`` is the separate, unapplied flip point. An allowlisted +default also requires the commander's switch date after an accepted +independent recheck; ``_SWITCH_DATE`` is unset. The earliest permitted date +is 2026-11-08 Asia/Shanghai. A missing, invalid or future switch date refuses +a selected BDF default with no fallback. Every unlisted scope keeps backward +Euler; explicit BDF requests retain their existing date-independent behavior. + +A scope is a ContextVar, as for the equation selection. Worker jobs therefore +carry the parent's request themselves. Preparation records it among the +execution manifest's child settings (:func:`time_method_setting`): +``NEWCORE_TIME_METHOD`` is unset for the default and ``backward_euler`` for +the opt-out. The child installs the setting and refuses a request that +differs (:func:`verify_time_method`). No worker scope is allowlisted, because +a worker's initial state is a cold recipe, not a frozen initial. Workers +therefore integrate with backward Euler, and refuse ``bdf`` when the job is +prepared. + +Each BDF history, captured backward-Euler publication and worker result +records its selection (:meth:`TimeMethodSelection.record`). The record holds +the request and its source and the effective method. A BDF record also holds +the scope, the profile and the work cap. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator, Mapping +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, fields, is_dataclass, replace +from datetime import date, datetime, timedelta, timezone +import enum +import hashlib +import json +import math +import os +import sys +from types import MappingProxyType +from typing import Any, Final, NamedTuple, TypeVar, cast + +import numpy as np + +__all__ = [ + "ADAPTIVE_MAX_STEPS", "ALLOWLIST", "ALLOWLIST_SHA256", "ALLOWLISTED_DEFAULT", "BACKWARD_EULER", "BDF", "ELECTRONIC", + "ENVIRONMENT", "IONIC", "MULTIPLE_IONIC", "PROFILE", "PROFILE_SHA256", "SCOPE_SCHEMA", "SELECTION_SCHEMA", + "TIME_METHODS", "TRUST_STANDARD", "AdmittedBDFCall", "TimeMethodSelection", "admit_time_method", + "electronic_components", "electronic_scope", "integrate_admitted", "ionic_scope", "requested_time_method", + "resolve_time_method", "scope_digest", "time_method", "time_method_setting", "verify_integration", + "verify_time_method", +] + +BACKWARD_EULER: Final = "backward_euler" +BDF: Final = "bdf" +TIME_METHODS = (BACKWARD_EULER, BDF) +ENVIRONMENT = "NEWCORE_TIME_METHOD" +TRUST_STANDARD: Final = "interface_level_trust_standard_v1" + +# The scope-based default of the allowlisted scopes and its authority: the 2026-11-08 flip point. +ALLOWLISTED_DEFAULT: tuple[str, str | None] = (BACKWARD_EULER, None) +# A date is set only by the commander after an accepted independent recheck. +# FreezeV2's 2026-11-08 is the earliest permitted date, not an automatic switch. +_SWITCH_DATE: str | None = None + +# Entry-point families. +ELECTRONIC = "electronic_1d" +IONIC = "ionic_1d" +MULTIPLE_IONIC = "multiple_ionic_1d" +_FAMILIES = (ELECTRONIC, IONIC, MULTIPLE_IONIC) + +SELECTION_SCHEMA = "solarlab.time-method-selection.v1" +SCOPE_SCHEMA = "solarlab.time-method-scope.v1" + +# ReadinessV1/ProposedDefault.json (file sha256), frozen by CommanderBdfDefaultFreezeV1. +PROFILE_SHA256 = "9239679194ed68a8c72780877a80a84ecca3dba24a895a17fe1ac1a94fd76bea" +PROFILE: Mapping[str, Any] = MappingProxyType({ + "initial_step_s": 0.001, "min_step_s": 1e-16, "max_step_s": 1e30, "relative_tolerance": 1e-05, + "absolute_tolerance": 1e-12, "max_order": 2, "adaptive": True, "safety": 0.8, "min_factor": 0.2, + "max_factor": 2.0, "max_steps": 10000, "max_attempts": 20000, "max_consecutive_rejections": 12, "wall_s": 30.0, +}) +# The accepted-step work cap forwarded to the BDF adapter (ReadinessReviewV2 RV2-C2). The sample +# intervals stay admitted by the physical controls' max_steps. +ADAPTIVE_MAX_STEPS = 10000 + +# CommanderBdfDefaultFreezeV2's allowlist: the ten electronic envelopes of V1 by scope digest, derived +# from the frozen ReadinessV1 Cases.json and initial artifacts (the CND2 key table, Cnd2ScopeKeyTableV1). +ALLOWLIST: Mapping[str, str] = MappingProxyType({ + "221e31f715757df14ebaaa73e4f2c2f879e6cb980a5fc483c7940a607b53cebf": "E_dark_hold", + "7dace99e619ecddd410121309ea5443a16f832720e90fb22781b8b3be591b2a5": "E_dark_voltage_ramp", + "59aca9ef958c68f5c179afe0ea59817d51d66b519af65aeaff6c847d545a03c3": "E_light_hold", + "a9364a002e141af1c09d252098eba75268136005d4755ddf6a76e954b13e5ca4": "E_light_ramp_16", + "608051152d7f5b41bdbb9d227f4cb69f6b5d37e0f9be13d9cc5b09fc1c214d33": "E_light_ramp_4", + "700083da5b3e5dcbc3eec176f91830b27290491a363a8204e5336772f38dcd27": "E_light_ramp_8", + "e79d312254e470a833c985f8304c6faf9df11c4fff139658175fdc1a983c0851": "E_saved_packet", + "8e315434aa617005a75bb7224cebabf03830f05afe06782c38626c37f49c9af8": "E_voltage_ramp_16", + "cdadc98646e0665667b9b26ef5ddc294bb89b1434faca40498f2bc3855cbff63": "E_voltage_ramp_4", + "6e315c3f151c1a0744093a63f04229ddc76fa4995bbb0272c7c9eaf3097ec1e6": "E_voltage_ramp_8", +}) + +_SCOPE: ContextVar[str | None] = ContextVar("solarlab_time_method", default=None) +_R = TypeVar("_R") + + +def _checked(name: object) -> str: + if not isinstance(name, str) or name not in TIME_METHODS: + raise ValueError(f"unknown time method {name!r}; expected one of {TIME_METHODS}") + return name + + +def _route_today() -> date: + return datetime.now(timezone(timedelta(hours=8))).date() + + +def _check_default_switch() -> None: + if type(_SWITCH_DATE) is not str: + raise ValueError("BDF is not selectable: the allowlisted default has no commander switch date") + try: + chosen = date.fromisoformat(_SWITCH_DATE) + except ValueError as exc: + raise ValueError("BDF is not selectable: the commander switch date is invalid") from exc + if chosen.isoformat() != _SWITCH_DATE or chosen < date(2026, 11, 8): + raise ValueError("BDF is not selectable: the commander switch date must be on or after 2026-11-08") + if _route_today() < chosen: + raise ValueError("BDF is not selectable: the allowlisted default starts on " + _SWITCH_DATE + " Asia/Shanghai") + + +@contextmanager +def time_method(name: str) -> Iterator[None]: + """Request ``name`` for the transient entry points called inside this block.""" + token = _SCOPE.set(_checked(name)) + try: + yield + finally: + _SCOPE.reset(token) + + +def requested_time_method(method: str | None = None) -> tuple[str | None, str]: + """The explicit request and its source; ``(None, "default")`` takes the scope-based default.""" + if method is not None: + return _checked(method), "argument" + scoped = _SCOPE.get() + if scoped is not None: + return scoped, "scope" + declared = os.environ.get(ENVIRONMENT) + if declared is not None: + return _checked(declared), "environment" + return None, "default" + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + + +def _sha256(value: Any) -> str: + return hashlib.sha256(_canonical(value)).hexdigest() + + +# Registered with the frozen allowlist; the CND2 key table lists every case it holds. +ALLOWLIST_SHA256 = _sha256(dict(ALLOWLIST)) + + +@dataclass(frozen=True) +class TimeMethodSelection: + """One resolved request: the method a history runs, and the scope that admitted BDF. + + A BDF selection without a scope is an explicit research capture of + supplied options (``source="research_capture"``), never a production + selection. A selection, and its record, describe a request. Nothing that + a history integrates is read from them. + """ + + family: str + requested: str | None + source: str + effective: str + scope: str | None = None + scope_sha256: str | None = None + + def record(self) -> dict[str, Any]: + """The provenance record of this selection; a production BDF one adds its scope, profile and work cap.""" + record: dict[str, Any] = { + "schema": SELECTION_SCHEMA, "family": self.family, "requested": self.requested, "source": self.source, + "effective": self.effective, "allowlisted_default": list(ALLOWLISTED_DEFAULT), + } + if self.effective == BDF: + production = self.scope is not None + record.update(scope=self.scope, scope_sha256=self.scope_sha256, + allowlist_sha256=ALLOWLIST_SHA256 if production else None, + profile_sha256=PROFILE_SHA256 if production else None, + profile=dict(PROFILE) if production else None, + adaptive_max_steps=ADAPTIVE_MAX_STEPS if production else None, + trust_standard=TRUST_STANDARD if production else None, + qualification=False, label="experimental_unqualified") + return record + + +def _genuine(value: object, qualname: str) -> bool: + """Whether ``value`` is exactly the module-level solarlab class ``qualname``: no subclass, no look-alike.""" + cls = type(value) + module = sys.modules.get(cls.__module__) + return (cls.__qualname__ == qualname and cls.__module__.startswith("solarlab.") and module is not None + and getattr(module, qualname, None) is cls) + + +def _family(compiled: object) -> str | None: + """The entry-point family of the actual compiled device, by its exact class.""" + for family, qualname in ((ELECTRONIC, "CompiledDevice1D"), (IONIC, "CompiledIonicDevice1D"), + (MULTIPLE_IONIC, "CompiledMultipleIonicDevice1D")): + if _genuine(compiled, qualname): + return family + return None + + +def _canonical_drive(protocol: Any) -> Any: + """The protocol's own continuous drive, built by the genuine constructor from its knots.""" + from solarlab.solvers.time.bdf_1d import BDFDrive + + values = np.column_stack((protocol.voltage_V, protocol.generation_scale)) + return BDFDrive(protocol.times_s, values, values) + + +def _probe_drive_constructor(record: tuple[Any, ...]) -> None: + """Refuse a replaced ``BDFDrive.from_protocol`` (D1); it sees a throwaway build and never builds a run's drive.""" + from solarlab.solvers.time.bdf_1d import BDFDrive + + refusal = "BDF is not selectable: the protocol's drive is not its own continuous knots" + try: + drive = BDFDrive.from_protocol(_build(record)) + except Exception as exc: + raise ValueError(refusal) from exc + if not _continuous(drive, _build(record)): + raise ValueError(refusal) + + +def _continuous(drive: object, protocol: Any) -> bool: + """A drive that is exactly a BDFDrive with the protocol's knots on both sides of every knot.""" + if not _genuine(drive, "BDFDrive"): + return False + try: + return _same(drive, _canonical_drive(protocol)) + except (TypeError, ValueError): + return False + + +_OPERATORS = {ELECTRONIC: "BDFStep:DC1DProblem", IONIC: "BDFStep:Ionic1DProblem"} +_UNSUPPORTED = {MULTIPLE_IONIC: "BDF is not selectable for multiple-domain ionic histories: this entry point has no " + "BDF adapter; request backward_euler"} + + +class AdmittedBDFCall(NamedTuple): + """One production BDF call as its admission keyed it, as immutable values only (D1b, D1-R1). + + ``inputs`` holds the records (``_record``) of the compiled device, the + initial state, the protocol, the physical controls and the initial + controls, in that order (a record of ``None`` for an ionic call's + initial controls). + A record is a tuple of the declared words of one input, as bytes and + Python scalars, with the solarlab classes and enum members it names. + ``scope_sha256`` is the admitted key, and ``case`` the allowlisted + envelope. + + No field can be rebound, and no object of a history is reachable from an + admission: :func:`integrate_admitted` builds the history's inputs from + the records when it runs. Both it and :func:`verify_integration` take + exactly this class, and read an admission through ``tuple``'s own + accessors, never its attributes. + """ + + family: str + case: str + scope_sha256: str + inputs: tuple[Any, ...] + + def __repr__(self) -> str: + values = tuple.__getitem__(self, slice(None)) + return f"AdmittedBDFCall(family={values[0]!r}, case={values[1]!r}, scope_sha256={values[2]!r}, inputs=)" + + +def _handle(admission: Any) -> tuple[str, str, str, tuple[Any, ...]]: + """An admission's values, read through ``tuple``'s own accessors: its attributes are never read.""" + refusal = "BDF is not selectable: this is not an admission of a production BDF call" + if type(admission) is not AdmittedBDFCall: + raise ValueError(refusal) + values = tuple.__getitem__(admission, slice(None)) + if len(values) != 4: + raise ValueError(refusal) + family, case, digest, inputs = values + if (type(family) is not str or family not in _OPERATORS or type(case) is not str or type(digest) is not str + or type(inputs) is not tuple or len(inputs) != 5): + raise ValueError(refusal) + return family, case, digest, inputs + + +def _scope_of(family: str, compiled: Any, initial: Any, protocol: Any, options: Any, initial_options: Any, + drive: Any, rederive: bool = True) -> str: + """The scope digest of one call's inputs, its drive included. + + ``rederive=False`` keys the inputs that a production history integrates, + which this module built from records itself. It gives the same digest. It + skips only ``_declared_only``, which refuses extra state and stale derived + fields without changing any key byte. ``_declared_only`` rebuilds a value + with ``dataclasses.replace``, whose result shares the value's fields: it + would hand those inputs on to code that observes return values. + """ + if rederive: + return (electronic_scope(compiled, initial, protocol, options=options, initial_options=initial_options, + drive=drive) if family == ELECTRONIC + else ionic_scope(compiled, initial, protocol, options=options, drive=drive)) + if family == ELECTRONIC: + return scope_digest(ELECTRONIC, _electronic_components(compiled, initial, protocol, options, initial_options, + drive, False)) + return scope_digest(IONIC, _ionic_components(compiled, initial, protocol, options, drive, False)) + + +def _built(inputs: tuple[Any, ...]) -> tuple[Any, ...]: + """The objects that records name, built anew, and the protocol's own continuous drive (never integrated).""" + compiled, initial, protocol, options, initial_options = [_build(node) for node in inputs] + return compiled, initial, protocol, options, initial_options, _canonical_drive(protocol) + + +def integrate_admitted(admission: AdmittedBDFCall, adapter: Callable[..., _R]) -> _R: + """Start one admitted production BDF history, the only way a production route starts one (D1b, D1-R1). + + The history's inputs are built here from the admission's records, after + admission has returned. They are keyed again and must be the admitted, + allowlisted scope. ``adapter`` is handed exactly these inputs, the + protocol's own continuous drive, the frozen profile, the forwarded work + cap and the admission, which it re-keys before the integrator + (:func:`verify_integration`). Any divergence is refused, with no fallback. + """ + from solarlab.solvers.time.bdf import BDFOptions + from solarlab.solvers.time.bdf_1d import BDFDrive + + family, case, digest, inputs = _handle(admission) + # The inputs are built in place, never returned by a function of this module (module docstring). + built: list[Any] = [] + try: + for node in inputs: + _build_into(node, built) + compiled, initial, protocol, options, initial_options = built + knots = np.column_stack((protocol.voltage_V, protocol.generation_scale)) + drive = BDFDrive(protocol.times_s, knots, knots) + key = _scope_of(family, compiled, initial, protocol, options, initial_options, drive, rederive=False) + except Exception as exc: + raise ValueError(f"BDF is not selectable: the admitted inputs cannot be built and keyed ({exc})") from exc + if key != digest or ALLOWLIST.get(key) != case: + raise ValueError(f"BDF is not selectable: the inputs built for integration are not the admitted, allowlisted " + f"ones (admitted {digest[:12]}, built {key[:12]})") + controls = {"initial_options": initial_options} if family == ELECTRONIC else {} + return adapter(compiled, initial, protocol, options=options, bdf_options=BDFOptions(**PROFILE), drive=drive, + adaptive_max_steps=ADAPTIVE_MAX_STEPS, admission=admission, **controls) + + +def verify_integration( + admission: AdmittedBDFCall, *, compiled: Any, initial: Any, protocol: Any, options: Any, drive: Any, start: Any, + run_options: Any, initial_options: Any = None, +) -> None: + """A BDF adapter's last step before the integrator: refuse unless it hands over the admitted inputs. + + The adapter has computed the integrator's start, interval, options, + breakpoints and events before this call, and calls the integrator right + after it. ``start`` is the first state vector and must hold the + initial's words. + ``run_options`` are the integrator's options: the frozen profile with + the forwarded work cap and the remaining wall budget. The device, + initial, protocol, controls and drive whose objects the integrator reads + are keyed again, with declared and re-derived state checked, and must + be the admitted, allowlisted scope. + """ + from solarlab.solvers.time.bdf import BDFOptions + + family, case, digest, _ = _handle(admission) + try: + wall = run_options.wall_s + profile = (type(run_options) is BDFOptions and type(run_options.max_steps) is int + and run_options.max_steps == ADAPTIVE_MAX_STEPS and type(wall) is float + and 0.0 < wall <= PROFILE["wall_s"] and _same_profile(replace(run_options, wall_s=PROFILE["wall_s"]))) + except (AttributeError, TypeError, ValueError): + profile = False + if not profile or type(start) is not np.ndarray or _words(start) != _words(initial.state.u): + raise ValueError("BDF is not selectable: the integrator's start, profile or work cap is not the admitted one") + try: + handed = _scope_of(family, compiled, initial, protocol, options, initial_options, drive) + except Exception as exc: + raise ValueError(f"BDF is not selectable: the inputs handed to the integrator cannot be keyed ({exc})") from exc + if handed != digest or ALLOWLIST.get(handed) != case: + raise ValueError(f"BDF is not selectable: the inputs handed to the integrator are not the admitted ones " + f"(admitted {digest[:12]}, handed {handed[:12]})") + + +def resolve_time_method( + method: str | None = None, *, compiled: Any, initial: Any = None, protocol: Any = None, options: Any = None, + initial_options: Any = None, bdf_options: Any = None, bdf_drive: Any = None, family: str | None = None, +) -> TimeMethodSelection: + """Resolve one production call's request from its actual inputs, before numerical work. + + This is :func:`admit_time_method`'s selection: the selection a call's + record states. + """ + return admit_time_method(method, compiled=compiled, initial=initial, protocol=protocol, options=options, + initial_options=initial_options, bdf_options=bdf_options, bdf_drive=bdf_drive, + family=family)[0] + + +def admit_time_method( + method: str | None = None, *, compiled: Any, initial: Any = None, protocol: Any = None, options: Any = None, + initial_options: Any = None, bdf_options: Any = None, bdf_drive: Any = None, family: str | None = None, +) -> tuple[TimeMethodSelection, AdmittedBDFCall | None]: + """Admit one production call before numerical work: its selection and, for BDF, the inputs BDF integrates. + + The family comes from the exact class of ``compiled``. ``family`` names + the entry point's own family, and a device of another family is refused. + + The scope digest is computed here from the actual device, initial state, + protocol and controls, never supplied. An explicit ``bdf`` request runs + exactly ``PROFILE`` with the protocol's own continuous drive. + BDFOptions or a drive must be exactly those, and are refused otherwise. + Under the scope-based default neither may be supplied, and only an + allowlisted scope can select BDF, after the flip. Every other BDF request + is refused, with no fallback. + + A BDF selection returns its :class:`AdmittedBDFCall`: + - Admission records the caller's inputs as immutable values. It builds + objects from the records, with the protocol's own drive, and keys them. + - That key must equal the key of the caller's objects. A divergence means + an input changed while it was admitted, and is refused. + - No caller-owned object is read after it is recorded. The admission + holds only the records and the key. + - The entry point integrates it with :func:`integrate_admitted`, which + builds the history's inputs from the records. + """ + requested, source = requested_time_method(method) + if family is not None and family not in _FAMILIES: + raise ValueError(f"unknown time-method family {family!r}") + if requested != BDF and (bdf_options is not None or bdf_drive is not None): + raise ValueError("BDF options or a BDF drive require an explicit bdf time-method request") + if requested == BDF and family in _UNSUPPORTED: + raise ValueError(_UNSUPPORTED[family]) + actual = _family(compiled) + label = actual or family or "unsupported" + if requested == BACKWARD_EULER: + return TimeMethodSelection(label, requested, source, BACKWARD_EULER), None + + def unselectable(reason: str) -> tuple[TimeMethodSelection, None]: + # The default keeps backward Euler wherever BDF is not selectable; a bdf request is refused. + if requested == BDF: + raise ValueError(reason) + return TimeMethodSelection(label, None, source, BACKWARD_EULER), None + + if actual is None or family not in (None, actual): + return unselectable("BDF is not selectable: the compiled device is not of " + + (f"the {family} family" if family else "a supported family")) + if requested is None and (ALLOWLISTED_DEFAULT[0] == BACKWARD_EULER or actual in _UNSUPPORTED): + return TimeMethodSelection(actual, None, source, BACKWARD_EULER), None + from solarlab.equations.implementation import selected_implementation + + if requested == BDF: + if actual in _UNSUPPORTED: + raise ValueError(_UNSUPPORTED[actual]) + selected_implementation(operator=_OPERATORS[actual]) + if bdf_options is not None and not _same_profile(bdf_options): + raise ValueError(f"production BDF runs only the frozen profile {PROFILE_SHA256[:8]}: request it without " + "BDFOptions or with exactly that profile") + if not _genuine(protocol, "TransientProtocol"): + return unselectable("BDF is not selectable: the protocol is not a TransientProtocol") + if bdf_drive is not None and not _continuous(bdf_drive, protocol): + raise ValueError("production BDF runs only the protocol's own continuous drive: request it without a drive " + "or with exactly BDFDrive.from_protocol(protocol)") + try: + digest = (electronic_scope(compiled, initial, protocol, options=options, initial_options=initial_options) + if actual == ELECTRONIC else ionic_scope(compiled, initial, protocol, options=options)) + except Exception as exc: # no scope: the default keeps backward Euler, whatever the call's inputs raise + return unselectable(f"BDF is not selectable: this call's scope cannot be computed ({exc})") + case = ALLOWLIST.get(digest) + if case is None: + return unselectable(f"BDF is not selectable for scope {digest[:12]}: only the {len(ALLOWLIST)} allowlisted " + "electronic envelopes run BDF; request backward_euler") + # The scope selects BDF. From here every failure is a refusal under either request, never run as BE. + if requested is None: + _check_default_switch() + try: + inputs = tuple(_record(value) for value in ( + compiled, initial, protocol, options, initial_options if actual == ELECTRONIC else None)) + recorded = _scope_of(actual, *_built(inputs)) + except Exception as exc: + raise ValueError(f"BDF is not selectable: this call's inputs cannot be admitted ({exc})") from exc + if recorded != digest: + raise ValueError(f"BDF is not selectable: this call's inputs changed while they were admitted (keyed " + f"{digest[:12]}, recorded {recorded[:12]})") + _probe_drive_constructor(inputs[2]) + if requested is None: + selected_implementation(operator=_OPERATORS[actual]) + return TimeMethodSelection(actual, requested, source, BDF, case, digest), AdmittedBDFCall(actual, case, digest, + inputs) + + +def _same_profile(options: Any) -> bool: + """Whether ``options`` is exactly a BDFOptions of the frozen profile, by its scope content.""" + from solarlab.solvers.time.bdf import BDFOptions + + try: + return _same(options, BDFOptions(**PROFILE)) + except TypeError: + return False + + +_WORKER_REFUSAL = ("BDF is not selectable for process or HTTP worker jobs: no worker scope is allowlisted " + "(a worker's initial state is a cold recipe); request backward_euler") + + +def _worker_selection(family: str) -> TimeMethodSelection: + """A worker job's selection: backward Euler, or a refusal of ``bdf``; no worker scope is allowlisted.""" + if family not in _FAMILIES: + raise ValueError(f"unknown time-method family {family!r}") + requested, source = requested_time_method() + if requested == BDF: + raise ValueError(_WORKER_REFUSAL) + return TimeMethodSelection(family, requested, source, BACKWARD_EULER) + + +def time_method_setting(family: str) -> tuple[str, str | None]: + """The parent's request as the child setting a worker's execution manifest records. + + The setting is unset (``None``) for the default and ``backward_euler`` + for the opt-out. A worker integrates with backward Euler, and a ``bdf`` + request is refused while the job is prepared. + """ + return ENVIRONMENT, _worker_selection(family).requested + + +def verify_time_method(settings: Iterable[tuple[str, str | None]], family: str) -> TimeMethodSelection: + """Refuse a worker whose request is not the one its job's manifest bound; return the worker's selection.""" + declared = dict(settings) + selection = _worker_selection(family) + if ENVIRONMENT not in declared or selection.requested != declared[ENVIRONMENT]: + raise ValueError("the worker's time-method selection differs from its execution manifest") + return selection + + +def _words(value: np.ndarray) -> dict[str, Any]: + """An array's dtype, shape and C-order element bytes; a 0-d array has none (V1 gave it shape [1]).""" + if type(value) is not np.ndarray: + raise TypeError("a scope array must be exactly a numpy ndarray") + if value.ndim == 0: + raise TypeError("a scope array has at least one dimension") + if value.dtype.hasobject or value.dtype.fields is not None or value.dtype.kind not in "biuf": + raise TypeError("scope arrays hold plain numerical words") + return {"dtype": value.dtype.str, "shape": list(value.shape), + "sha256": hashlib.sha256(value.tobytes(order="C")).hexdigest()} + + +# Each identity digests a prepared device, whose catalog evidence names the configuration path. +_PATH_BOUND = {"CompiledDevice1D": ("sha256",), "CompiledIonicDevice1D": ("sha256", "original_prepared_sha256")} +_MANIFEST_PATH_BOUND = {"electronic_component": ("compiled_sha256", "prepared_sha256")} + + +def _manifest(text: str) -> Any: + """An ionic binding manifest with its path-bound identities set aside; each must be present (Grammar V2, R1).""" + if type(text) is not str: + raise TypeError("an ionic binding manifest is a JSON text") + try: + manifest = json.loads(text) + manifest.pop("original_prepared_sha256") + for section, names in _MANIFEST_PATH_BOUND.items(): + identities = manifest[section] + if type(identities) is not dict or not set(names) <= set(identities): + raise KeyError(section) + manifest[section] = {key: value for key, value in identities.items() if key not in names} + except (AttributeError, KeyError, TypeError, ValueError) as exc: + raise TypeError("an ionic binding manifest must name its path-bound identities") from exc + return _content(_tuples(manifest)) + + +def _tuples(value: Any) -> Any: + """Parsed JSON with its arrays as tuples: JSON has one sequence kind, encoded as every sequence is.""" + if type(value) is list: + return tuple(_tuples(item) for item in value) + if type(value) is dict: + return {key: _tuples(item) for key, item in value.items()} + return value + + +def _declared_only(value: Any) -> None: + """Refuse a dataclass whose state is not its declared fields: no other attribute, each derived field re-derived.""" + declared = [item.name for item in fields(value)] + if set(getattr(value, "__dict__", ())) - set(declared): + raise TypeError(f"{type(value).__qualname__} carries state beyond its declared fields") + derived = [item.name for item in fields(value) if not item.init] + if derived: + try: + rebuilt = replace(value) + except Exception as exc: # whatever its own class refuses to rebuild, it did not construct + raise TypeError(f"{type(value).__qualname__} is not constructed from its declared fields") from exc + for name in derived: + if not _same(getattr(value, name), getattr(rebuilt, name)): + raise TypeError(f"{type(value).__qualname__}.{name} is not derived from its declared fields") + + +def _content(value: Any, compare: bool = False, rederive: bool = True) -> Any: + """Every declared word of ``value``, typed; a value of any other kind is refused, never skipped. + + Each value must be exactly its type. A subclass or look-alike could act + differently on equal words, so it has no scope. ``compare`` encodes a + derived field for comparison only, never for a key: it also accepts the + mapping proxies some derived fields hold. ``rederive=False`` skips + ``_declared_only`` (``_scope_of``), which never changes the content. + """ + kind = type(value) + if is_dataclass(value) and not isinstance(value, type): + name = kind.__qualname__ + if not _genuine(value, name): + raise TypeError(f"{name} is not a module-level solarlab class") + if not kind.__dataclass_params__.frozen: # type: ignore[attr-defined] + raise TypeError(f"{name} is not a frozen dataclass") + # Fields derived in __post_init__ repeat the declared ones, and must be their re-derivation. + if rederive: + _declared_only(value) + skip = _PATH_BOUND.get(name, ()) + return {"type": name, "fields": { + item.name: _manifest(getattr(value, item.name)) if item.name == "binding_manifest_json" + else _content(getattr(value, item.name), compare, rederive) for item in fields(value) + if item.init and item.name not in skip}} + if kind is np.ndarray: + return {"array": _words(value)} + if isinstance(value, enum.Enum): + if not _genuine(value, kind.__qualname__): + raise TypeError(f"{kind.__qualname__} is not a module-level solarlab enum") + return {"enum": kind.__qualname__, "value": _content(value.value, compare, rederive)} + if kind is bool or kind is int: + return value + if kind is float: + # A non-finite scalar has no single word in float.hex(); arrays keep their raw words. + if not math.isfinite(value): + raise TypeError("a scope scalar must be finite") + return {"float": value.hex()} + if value is None or kind is str: + return value + if kind is tuple: + return [_content(item, compare, rederive) for item in value] + if (kind is dict or (compare and kind is MappingProxyType)) and all(type(key) is str for key in value): + pairs = [[key, _content(value[key], compare, rederive)] for key in sorted(value)] + return {"mapping": pairs} if kind is dict else {"mapping_proxy": pairs} + raise TypeError(f"no scope content is defined for {kind.__module__}.{kind.__qualname__}") + + +def _record(value: Any) -> tuple[Any, ...]: + """One input as an immutable record of its declared words, from which a history's inputs are built (D1b, D1-R1). + + A record is a tuple of one of these kinds: + - a frozen solarlab dataclass: its class and its init fields in order; + - an array: its dtype, shape and C-order bytes; + - a tuple, or a dict with str keys: its items; + - an immutable scalar or a genuine solarlab enum member. + + It admits what the scope grammar admits, with the same exact-type rules, + and refuses everything else. + """ + kind = type(value) + if is_dataclass(value) and not isinstance(value, type): + if not (_genuine(value, kind.__qualname__) and kind.__dataclass_params__.frozen): # type: ignore[attr-defined] + raise TypeError(f"{kind.__qualname__} is not a frozen module-level solarlab class") + _declared_only(value) + return ("dataclass", kind, tuple((item.name, _record(getattr(value, item.name))) + for item in fields(value) if item.init)) + if kind is np.ndarray: + if value.dtype.hasobject or value.dtype.fields is not None or value.dtype.kind not in "biuf": + raise TypeError("scope arrays hold plain numerical words") + return ("array", value.dtype.str, tuple(value.shape), value.tobytes(order="C")) + if kind is tuple: + return ("tuple", tuple(_record(item) for item in value)) + if kind is dict and all(type(key) is str for key in value): + return ("dict", tuple((key, _record(item)) for key, item in value.items())) + if value is None or kind in (bool, int, float, str) or ( + isinstance(value, enum.Enum) and _genuine(value, kind.__qualname__)): + return ("value", value) + raise TypeError(f"no scope content is defined for {kind.__module__}.{kind.__qualname__}") + + +def _build(node: Any) -> Any: + """The object a record names, built anew (``_build_into``); for admission's own checks, never integrated.""" + built: list[Any] = [] + _build_into(node, built) + return built[0] + + +def _build_into(node: Any, built: list[Any]) -> None: + """Build the object a record names, by its own constructors over the record's immutable words, onto ``built``. + + A dataclass's derived fields are derived again. An array is a read-only + view of the record's immutable bytes. Nothing is returned, so no function + of this module returns the inputs a production history integrates + (:func:`integrate_admitted`). + """ + if type(node) is not tuple or not node or type(node[0]) is not str: + raise TypeError("a record is a tagged tuple") + if node[0] == "dataclass": + _, kind, items = node + module = sys.modules.get(getattr(kind, "__module__", "")) + if not (isinstance(kind, type) and is_dataclass(kind) and kind.__module__.startswith("solarlab.") + and module is not None and getattr(module, kind.__qualname__, None) is kind): + raise TypeError("a record names a module-level solarlab class") + arguments = {} + for name, item in items: + _build_into(item, built) + arguments[name] = built.pop() + built.append(cast(Any, kind)(**arguments)) + elif node[0] == "array": + _, dtype, shape, words = node + built.append(np.frombuffer(words, dtype=np.dtype(dtype)).reshape(shape)) + elif node[0] in ("tuple", "dict"): + values = [] + for item in node[1]: + _build_into(item if node[0] == "tuple" else item[1], built) + values.append(built.pop()) + built.append(tuple(values) if node[0] == "tuple" else dict(zip([key for key, _ in node[1]], values))) + elif node[0] == "value": + built.append(node[1]) + else: + raise TypeError(f"no record kind {node[0]!r}") + + +def _same(first: Any, second: Any) -> bool: + """Equal canonical bytes of scope content (``True`` and ``1`` differ, as do ``0.0`` and ``-0.0``).""" + return _canonical(_content(first, True)) == _canonical(_content(second, True)) + + +def scope_digest(family: str, components: Mapping[str, Any]) -> str: + """The digest of each component's canonical content, with the family.""" + return _sha256({"schema": SCOPE_SCHEMA, "family": family, + "components": {name: _sha256(value) for name, value in components.items()}}) + + +def _source(protocol: Any, drive: Any, rederive: bool = True) -> dict[str, Any]: + """The source knots, and the drive: absent, or exactly the protocol's own continuous BDFDrive. + + Any other drive has no scope: a jump drive, and a BDFDrive subclass or + look-alike with equal arrays, whose waveform its words do not bind. + """ + if not _genuine(protocol, "TransientProtocol"): + raise TypeError("a scope protocol must be a TransientProtocol") + if rederive: + _declared_only(protocol) + if drive is not None and not _continuous(drive, protocol): + raise TypeError("a scope drive must be exactly the protocol's own continuous BDFDrive") + return {"protocol": {name: _words(getattr(protocol, name)) for name in ("times_s", "voltage_V", "generation_scale")}, + "drive": "continuous_protocol_knots"} + + +def _electronic_state(state: Any) -> dict[str, Any]: + return {name: _words(getattr(state, name)) for name in ("u", "potential_V", "electron_density_m3", "hole_density_m3")} + + +def electronic_components(compiled: Any, initial: Any, protocol: Any, *, options: Any, initial_options: Any, + drive: Any = None) -> dict[str, Any]: + """The scope components of one ``solve_transient`` call, as the CND2 key table lists them. + + The initial enters by its state words, voltage and generation. + """ + return _electronic_components(compiled, initial, protocol, options, initial_options, drive, True) + + +def _electronic_components(compiled: Any, initial: Any, protocol: Any, options: Any, initial_options: Any, drive: Any, + rederive: bool) -> dict[str, Any]: + if not (_genuine(initial, "SteadyState1D") and _genuine(initial.state, "State1D")): + raise TypeError("a scope initial must be a SteadyState1D with its State1D") + if rederive: + _declared_only(initial) + _declared_only(initial.state) + return { + "device": _content(compiled, rederive=rederive), + "initial_state": {**_electronic_state(initial.state), "voltage_V": _content(initial.voltage_V), + "generation_scale": _content(initial.generation_scale)}, + **_source(protocol, drive, rederive), "physical_controls": _content(options, rederive=rederive), + "initial_controls": _content(initial_options, rederive=rederive), + } + + +def electronic_scope(compiled: Any, initial: Any, protocol: Any, *, options: Any, initial_options: Any, + drive: Any = None) -> str: + """The scope digest of one ``solve_transient`` call.""" + return scope_digest(ELECTRONIC, electronic_components(compiled, initial, protocol, options=options, + initial_options=initial_options, drive=drive)) + + +def ionic_scope(compiled: Any, initial: Any, protocol: Any, *, options: Any, drive: Any = None) -> str: + """The scope digest of one ``solve_ionic_transient`` call from its pinned steady initial. + + The initial enters by its state words, generation and steady controls. Its + evidence bytes and path name the path-bound compiled identity. + """ + return scope_digest(IONIC, _ionic_components(compiled, initial, protocol, options, drive, True)) + + +def _ionic_components(compiled: Any, initial: Any, protocol: Any, options: Any, drive: Any, + rederive: bool) -> dict[str, Any]: + if not (_genuine(initial, "IonicTransientInitial") and _genuine(initial.state, "IonicState1D") + and _genuine(initial.state.electronic_state, "State1D")): + raise TypeError("a scope initial must be an IonicTransientInitial with its IonicState1D") + if rederive: + for part in (initial, initial.state, initial.state.electronic_state): + _declared_only(part) + state = initial.state + return { + "device": _content(compiled, rederive=rederive), + "initial_state": {**{name: _words(getattr(state, name)) + for name in ("u", "positive_ion_density_m3", "negative_ion_density_m3")}, + "electronic_state": _electronic_state(state.electronic_state), + "domain_inventory_m2": _content(state.domain_inventory_m2), + "negative_domain_inventory_m2": _content(state.negative_domain_inventory_m2), + "voltage_V": _content(state.voltage_V), "generation_scale": _content(initial.generation_scale)}, + **_source(protocol, drive, rederive), "physical_controls": _content(options, rederive=rederive), + "initial_controls": _content(initial.steady_controls, rederive=rederive), + } diff --git a/src/solarlab/experiments/bdf.py b/src/solarlab/experiments/bdf.py index ddffc6c4..3ffa08a3 100644 --- a/src/solarlab/experiments/bdf.py +++ b/src/solarlab/experiments/bdf.py @@ -15,6 +15,7 @@ from solarlab.equations.assembly.ionic_1d import AssembledIonic1DProblem, AssembledMultipleIonic1DProblem from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem from solarlab.equations.implementation import use_assembled +from solarlab.equations.time_method import AdmittedBDFCall, verify_integration from solarlab.equations.ionic_1d import CompiledIonicDevice1D, Ionic1DProblem from solarlab.equations.multiple_ionic_1d import CompiledMultipleIonicDevice1D from solarlab.experiments import ionic_transient, multiple_ionic_transient @@ -172,8 +173,14 @@ def solve_electronic_bdf( compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, options: TransientOptions, initial_options: SteadyOptions, bdf_options: BDFOptions, drive: BDFDrive | None = None, adaptive_max_steps: int | None = None, - density_seed_activation: bool = False, + density_seed_activation: bool = False, admission: AdmittedBDFCall | None = None, ) -> BDFResult: + """Integrate exactly these inputs; with ``admission``, refuse at the last check inputs it does not admit. + + A production route hands it the inputs that ``integrate_admitted`` built from the admission's records. + """ + if admission is not None and type(admission) is not AdmittedBDFCall: + raise ValueError("BDF is not selectable: this is not an admission of a production BDF call") if type(density_seed_activation) is not bool: raise ValueError("density_seed_activation must be an explicit boolean") started = time.monotonic() @@ -200,13 +207,19 @@ def assessment(step: BDFStep, u: Vector) -> Assessment: remaining = min(bdf_options.wall_s, options.wall_s) - preparation_s if remaining <= 0: raise TimeoutError("BDF initial admission exhausted the whole-history wall budget") - result = solve_bdf(factory, initial.state.u, (float(protocol.times_s[0]), float(protocol.times_s[-1])), - options=replace(bdf_options, wall_s=remaining, max_steps=work_steps), settings=lambda step: base, + # The integrator's arguments are computed first, so a production history's last check comes right before it. + start, interval = initial.state.u, (float(protocol.times_s[0]), float(protocol.times_s[-1])) + run_options = replace(bdf_options, wall_s=remaining, max_steps=work_steps) + breakpoints, events = tuple(float(t) for t in source.times_s[1:-1]), _events(source, factory, options) + if admission is not None: + # A production history: what the integrator reads is re-keyed against its admission (time_method, D1-R1). + verify_integration(admission, compiled=compiled, initial=initial, protocol=protocol, options=options, + initial_options=initial_options, drive=source, start=start, run_options=run_options) + result = solve_bdf(factory, start, interval, options=run_options, settings=lambda step: base, convergence_norm=norm, assess=assessment, seed=lambda step: bdf_seed(step, options.predictor, voltage_lift=True), density_seed_context=(lambda step, failed: _generation_density_context(source, step)) if density_seed_activation else None, - breakpoints_s=tuple(float(t) for t in source.times_s[1:-1]), - events=_events(source, factory, options), output_times_s=protocol.times_s) + breakpoints_s=breakpoints, events=events, output_times_s=protocol.times_s) return replace(result, wall_s=time.monotonic() - started, controls={**result.controls, "physical_controls": asdict(options), "initial_controls": asdict(initial_options), "compiled_identity": compiled.identity, "drive": asdict(source), "initial_admission_wall_s": preparation_s, "method": "classical_physical_storage_bdf12", @@ -217,8 +230,14 @@ def assessment(step: BDFStep, u: Vector) -> Assessment: def solve_ionic_bdf( compiled: CompiledIonicDevice1D, initial: IonicTransientInitial, protocol: TransientProtocol, *, options: IonicTransientOptions, bdf_options: BDFOptions, drive: BDFDrive | None = None, - adaptive_max_steps: int | None = None, + adaptive_max_steps: int | None = None, admission: AdmittedBDFCall | None = None, ) -> BDFResult: + """Integrate exactly these inputs; with ``admission``, refuse at the last check inputs it does not admit. + + A production route hands it the inputs that ``integrate_admitted`` built from the admission's records. + """ + if admission is not None and type(admission) is not AdmittedBDFCall: + raise ValueError("BDF is not selectable: this is not an admission of a production BDF call") started = time.monotonic() work_steps = _adapter_step_budget(protocol, options.electronic.max_steps, bdf_options, adaptive_max_steps) admitted, generation, checks = _admit_evidence(compiled, initial.evidence_json, initial.source_sha256, @@ -243,12 +262,18 @@ def assessment(step: BDFStep, u: Vector) -> Assessment: remaining = min(bdf_options.wall_s, options.electronic.wall_s) - preparation_s if remaining <= 0: raise TimeoutError("BDF ionic admission exhausted the whole-history wall budget") - result = solve_bdf(factory, admitted.u, (float(protocol.times_s[0]), float(protocol.times_s[-1])), - options=replace(bdf_options, wall_s=remaining, max_steps=work_steps), + # The integrator's arguments are computed first, so a production history's last check comes right before it. + start, interval = admitted.u, (float(protocol.times_s[0]), float(protocol.times_s[-1])) + run_options = replace(bdf_options, wall_s=remaining, max_steps=work_steps) + breakpoints, events = tuple(float(t) for t in source.times_s[1:-1]), _events(source, factory, options.electronic) + if admission is not None: + # A production history: what the integrator reads is re-keyed against its admission (time_method, D1-R1). + verify_integration(admission, compiled=compiled, initial=initial, protocol=protocol, options=options, + drive=source, start=start, run_options=run_options) + result = solve_bdf(factory, start, interval, options=run_options, settings=lambda step: base, convergence_norm=norm, assess=assessment, seed=lambda step: bdf_seed(step, options.electronic.predictor, voltage_lift=True), - breakpoints_s=tuple(float(t) for t in source.times_s[1:-1]), - events=_events(source, factory, options.electronic), output_times_s=protocol.times_s) + breakpoints_s=breakpoints, events=events, output_times_s=protocol.times_s) return replace(result, wall_s=time.monotonic() - started, controls={**result.controls, "physical_controls": asdict(options), "initial_source_sha256": initial.source_sha256, "initial_checks": checks, "compiled_identity": compiled.identity, "drive": asdict(source), "initial_admission_wall_s": preparation_s, diff --git a/src/solarlab/experiments/bdf_results.py b/src/solarlab/experiments/bdf_results.py index 79193f74..6cf77719 100644 --- a/src/solarlab/experiments/bdf_results.py +++ b/src/solarlab/experiments/bdf_results.py @@ -5,7 +5,7 @@ """ from __future__ import annotations -from dataclasses import asdict, dataclass, fields, is_dataclass +from dataclasses import asdict, dataclass, fields, is_dataclass, replace from datetime import datetime, timezone from enum import Enum import gzip @@ -28,13 +28,14 @@ from solarlab.solvers.time.bdf import BDFOptions, BDFResult from solarlab.solvers.time.bdf_1d import BDFDrive -__all__ = ["CapturedBDFRun", "run_bdf_for_publication", "publish_bdf_result", - "read_bdf_result", "read_bdf_packet"] +__all__ = ["CapturedBDFRun", "run_bdf_for_publication", "run_production_bdf_for_publication", "capture_admitted_bdf", + "publish_bdf_result", "read_bdf_result", "read_bdf_packet"] _SCHEMA = "solarlab.bdf-publication.v1" _HISTORY_SCHEMA = "solarlab.physical_storage_bdf12.v1" _METHOD = "classical_physical_storage_bdf12" _LABEL = "experimental_unqualified" +_SELECTION = "solarlab.time-method-selection.v1" _TAGS = {"$array", "$scalar", "$float", "$tuple"} @@ -459,6 +460,7 @@ def _validate_body(body: dict[str, Any]) -> dict[str, Any]: == _sha(request["initial"]["evidence_json"].encode()), "BDF initial evidence hash differs") _require(_digest(request["initial_controls"]) == _digest(request["initial"]["steady_controls"]), "BDF ionic initial controls differ from admission") + _validate_time_method(request, controls) _require(body["remaining_wall_budget_s"] == controls["wall_s"] and body["initial_admission_wall_s"] == controls["initial_admission_wall_s"], "BDF wall budget accounting differs") _require(body["caps"] == {"requested_max_steps": request["bdf_options"]["max_steps"], @@ -468,6 +470,31 @@ def _validate_body(body: dict[str, Any]) -> dict[str, Any]: return summary +def _validate_time_method(request: dict[str, Any], controls: dict[str, Any]) -> None: + """The saved time-method selection agrees with its history; captures before CND2 hold none.""" + record = request.get("time_method") + _require((record is None) == ("time_method" not in controls), "BDF time-method record differs from its history") + if record is None: + return + _require(_digest(record) == _digest(controls["time_method"]) and record["schema"] == _SELECTION + and record["requested"] in ("bdf", None) and record["effective"] == "bdf" + and record["qualification"] is False and record["label"] == _LABEL, + "BDF time-method record differs from its history") + if record["source"] == "research_capture": + _require(record["requested"] == "bdf" and record.get("trust_standard") is None and all(record[name] is None for name in ( + "scope", "scope_sha256", "allowlist_sha256", "profile_sha256", "profile", "adaptive_max_steps")) + and "adapter_adaptive_max_steps" not in controls, + "a research BDF capture cannot claim an allowlisted scope, the frozen profile or a production work cap") + return + physical = request["physical_controls"].get("electronic", request["physical_controls"]) + _require(type(record["scope"]) is str and type(record["scope_sha256"]) is str + and record.get("trust_standard") in (None, "interface_level_trust_standard_v1") + and _digest(request["bdf_options"]) == _digest(record["profile"]) + and controls["adapter_adaptive_max_steps"] == record["adaptive_max_steps"] + and controls["adapter_sample_interval_limit"] == physical["max_steps"], + "a production BDF record differs from its frozen profile or forwarded work cap") + + def _capture_identity(body: dict[str, Any], provenance: dict[str, Any]) -> dict[str, str]: description, request = provenance["description"], body["request"] _require(provenance["status"] == "captured_at_computation" and description["scope"] == "bdf_computation_call" @@ -612,23 +639,97 @@ def run_bdf_for_publication( compiled: Any, initial: Any, protocol: Any, *, options: Any, bdf_options: BDFOptions, initial_options: Any = None, bdf_drive: BDFDrive | None = None, ) -> CapturedBDFRun: - """Capture an actual electronic or admitted single-ion BDF call. + """Capture an explicit research BDF call: the supplied BDFOptions and drive on any supported device. + + It admits no production scope and is recorded as ``source="research_capture"`` + with no scope, profile or work cap. Production BDF is captured by + ``run_production_bdf_for_publication``. No default is flipped and no + fallback is attempted. Admission refusals that produce no BDF history + still raise; returned failed histories are retained. Initial/DC history + is represented by its supplied bytes, not re-attributed. + """ + from solarlab.equations.ionic_1d import CompiledIonicDevice1D + from solarlab.equations.time_method import BDF, TimeMethodSelection + + family = "ionic_1d" if isinstance(compiled, CompiledIonicDevice1D) else "electronic_1d" + record = TimeMethodSelection(family, BDF, "research_capture", BDF).record() + return _capture(compiled, initial, protocol, options=options, bdf_options=bdf_options, + initial_options=initial_options, drive=bdf_drive, drive_was_explicit=bdf_drive is not None, + record=record, adaptive_max_steps=None) + + +def run_production_bdf_for_publication( + compiled: Any, initial: Any, protocol: Any, *, options: Any, initial_options: Any = None, + method: str | None = None, bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None, +) -> CapturedBDFRun: + """Capture a production BDF call: the time-method axis must select BDF for this call's own scope. + + The call is admitted here, once, from its actual inputs + (``solarlab.equations.time_method.admit_time_method``), never taken from + the caller. The capture records and integrates inputs built from the + admission's records (``capture_admitted_bdf``): the frozen profile, the + protocol's own continuous drive and the forwarded work cap. A + backward-Euler selection or any refused request raises before numerical + work. + """ + from solarlab.equations.time_method import admit_time_method + + # The family is the compiled device's own. + selection, call = admit_time_method(method, compiled=compiled, initial=initial, protocol=protocol, + options=options, initial_options=initial_options, bdf_options=bdf_options, + bdf_drive=bdf_drive) + if call is None: + raise ValueError("this call's time method is backward_euler; publish it as a transient result") + return capture_admitted_bdf(selection, call, drive_was_explicit=bdf_drive is not None) + + +def capture_admitted_bdf(selection: Any, admission: Any, *, drive_was_explicit: bool = False) -> CapturedBDFRun: + """Capture one admitted production BDF call, with no second admission (CND2 D1-R1). + + ``selection`` and ``admission`` are one ``admit_time_method`` result: + a selection that names another family, scope or key than the admission + is refused before the adapter. The capture records and integrates the + inputs that ``integrate_admitted`` builds from the admission's records. + The selection's request and source are recorded as it states them. + """ + from solarlab.equations.time_method import BDF, TimeMethodSelection, integrate_admitted + + if type(selection) is not TimeMethodSelection or selection.effective != BDF: + raise ValueError("a production BDF capture needs the BDF selection of its admission") + record = selection.record() + + def capture(compiled: Any, initial: Any, protocol: Any, *, options: Any, bdf_options: BDFOptions, + drive: BDFDrive, adaptive_max_steps: int, admission: Any, initial_options: Any = None) -> CapturedBDFRun: + # ``integrate_admitted`` has taken exactly an admission; read it as it does, through tuple's accessors. + if (selection.family, selection.scope, selection.scope_sha256) != tuple.__getitem__(admission, slice(0, 3)): + raise ValueError("the selection does not state this admission's family, scope and key") + return _capture(compiled, initial, protocol, options=options, bdf_options=bdf_options, + initial_options=initial_options, drive=drive, drive_was_explicit=drive_was_explicit, + record=record, adaptive_max_steps=adaptive_max_steps, admission=admission) + + return integrate_admitted(admission, capture) + + +def _capture( + compiled: Any, initial: Any, protocol: Any, *, options: Any, bdf_options: BDFOptions, initial_options: Any, + drive: BDFDrive | None, drive_was_explicit: bool, record: dict[str, Any], adaptive_max_steps: int | None, + admission: Any = None, +) -> CapturedBDFRun: + """Run and capture one BDF history with its time-method record, under job provenance (default: the protocol's drive). - No default is flipped and no fallback is attempted. Admission refusals that - produce no BDF history still raise; returned failed histories are retained. - Initial/DC history is represented by its supplied bytes, not re-attributed. + ``admission`` is a production call's admission; the adapter re-keys what it hands to the integrator against it. """ from solarlab.equations.dc_1d import CompiledDevice1D from solarlab.equations.implementation import ( ASSEMBLED, equation_implementation, provenance_binding, selected_implementation, ) from solarlab.equations.ionic_1d import CompiledIonicDevice1D - from solarlab.experiments.transient import solve_transient - from solarlab.experiments.ionic_transient import solve_ionic_transient + from solarlab.experiments.bdf import solve_electronic_bdf, solve_ionic_bdf from solarlab.solvers.time.bdf import BDFOptions, BDFResult from solarlab.solvers.time.bdf_1d import BDFDrive - _require(type(bdf_options) is BDFOptions, "BDF publication requires explicit BDFOptions") + if type(bdf_options) is not BDFOptions: + raise ValueError("BDF publication requires explicit BDFOptions") ionic = isinstance(compiled, CompiledIonicDevice1D) _require(ionic or isinstance(compiled, CompiledDevice1D), "BDF publication requires a supported compiled device") _require(ionic or initial_options is not None, "electronic BDF publication requires initial controls") @@ -637,8 +738,10 @@ def run_bdf_for_publication( assembled = selection == ASSEMBLED binding = provenance_binding("BDFStep:" + operator, compiled, inventory_row_node=initial.steady_controls.inventory_row_node if ionic else None, assembled=assembled) - drive = BDFDrive.from_protocol(protocol) if bdf_drive is None else bdf_drive - _require(type(drive) is BDFDrive, "BDF publication requires the actual drive") + drive = BDFDrive.from_protocol(protocol) if drive is None else drive + # The record names the drive by its knots: a drive with state of its own would run another waveform. + _require(type(drive) is BDFDrive and set(vars(drive)) == {item.name for item in fields(drive)}, + "BDF publication requires the actual drive") nodes = np.frombuffer(compiled.nodes_m.tobytes(), dtype=compiled.nodes_m.dtype).reshape(compiled.nodes_m.shape) problem_module = ("assembly.ionic_1d" if ionic else "assembly.classical_1d") if assembled else ( "ionic_1d" if ionic else "dc_1d") @@ -648,10 +751,10 @@ def run_bdf_for_publication( request = _decode(_encode({ "method": "bdf", "bdf_options": asdict(bdf_options), "physical_controls": asdict(options), "initial_controls": initial.steady_controls if ionic else asdict(initial_options), - "protocol": asdict(protocol), "drive": asdict(drive), "drive_was_explicit": bdf_drive is not None, + "protocol": asdict(protocol), "drive": asdict(drive), "drive_was_explicit": drive_was_explicit, "nodes_m": nodes, "initial": initial, "initial_sha256": _digest(initial), "initial_source_sha256": getattr(initial, "source_sha256", None), "device_sha256": compiled.identity, - "equation_implementation": implementation, + "equation_implementation": implementation, "time_method": record, "event_restart_policy": { "interpolation": "right[i] to left[i+1] between drive knots", "breakpoints_s": tuple(float(t) for t in drive.times_s[1:-1]), @@ -675,12 +778,14 @@ def run_bdf_for_publication( and admitted.export()["execution_manifest_sha256"] is None, "process-bound BDF publication requires its verified worker/manifest route") if ionic: - result = solve_ionic_transient(compiled, initial, protocol, options=options, - method="bdf", bdf_options=bdf_options, bdf_drive=drive) + result = solve_ionic_bdf(compiled, initial, protocol, options=options, bdf_options=bdf_options, + drive=drive, adaptive_max_steps=adaptive_max_steps, admission=admission) else: - result = solve_transient(compiled, initial, protocol, options=options, initial_options=initial_options, - method="bdf", bdf_options=bdf_options, bdf_drive=drive) + result = solve_electronic_bdf(compiled, initial, protocol, options=options, initial_options=initial_options, + bdf_options=bdf_options, drive=drive, adaptive_max_steps=adaptive_max_steps, + admission=admission) _require(type(result) is BDFResult, "the requested BDF call returned another method") + result = replace(result, controls={**result.controls, "time_method": record}) history = _decode(_encode(result)) summary = _validate_history(history) runtime = admitted.export()["runtime_observed"] diff --git a/src/solarlab/experiments/ionic_transient.py b/src/solarlab/experiments/ionic_transient.py index c2c9c32a..f02d6109 100644 --- a/src/solarlab/experiments/ionic_transient.py +++ b/src/solarlab/experiments/ionic_transient.py @@ -9,7 +9,7 @@ from __future__ import annotations from collections.abc import Callable -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, replace import hashlib import json import math @@ -22,6 +22,7 @@ from solarlab.contracts import frozen_array from solarlab.equations.assembly.ionic_1d import AssembledConstrainedIonic1DProblem, AssembledIonic1DProblem from solarlab.equations.implementation import equation_implementation, selected_implementation, use_assembled +from solarlab.equations.time_method import IONIC, admit_time_method, integrate_admitted from solarlab.equations.ionic_1d import CompiledIonicDevice1D, Ionic1DProblem, IonicState1D from solarlab.equations.ionic_closure import immobile_profile_binding from solarlab.experiments.transient import TransientOptions, TransientProtocol @@ -269,39 +270,50 @@ def convergence_norm(scaled: np.ndarray) -> float: @overload def solve_ionic_transient(compiled: CompiledIonicDevice1D, initial: IonicTransientInitial, - protocol: TransientProtocol, *, options: IonicTransientOptions, - method: Literal["backward_euler"] = "backward_euler", bdf_options: BDFOptions | None = None, - bdf_drive: BDFDrive | None = None) -> IonicTransientResult: ... + protocol: TransientProtocol, *, options: IonicTransientOptions, method: Literal["backward_euler"], + bdf_options: None = None, bdf_drive: None = None) -> IonicTransientResult: ... @overload def solve_ionic_transient(compiled: CompiledIonicDevice1D, initial: IonicTransientInitial, protocol: TransientProtocol, *, options: IonicTransientOptions, method: Literal["bdf"], - bdf_options: BDFOptions, bdf_drive: BDFDrive | None = None) -> BDFResult: ... + bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None) -> BDFResult: ... + + +@overload +def solve_ionic_transient(compiled: CompiledIonicDevice1D, initial: IonicTransientInitial, + protocol: TransientProtocol, *, options: IonicTransientOptions, method: None = None, + bdf_options: None = None, bdf_drive: None = None) -> IonicTransientResult | BDFResult: ... def solve_ionic_transient( compiled: CompiledIonicDevice1D, initial: IonicTransientInitial, protocol: TransientProtocol, - *, options: IonicTransientOptions, method: str = "backward_euler", + *, options: IonicTransientOptions, method: str | None = None, bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None, ) -> IonicTransientResult | BDFResult: """Run requested physical BE steps once, preserving the first partial outcome. +The time method is resolved first (:mod:`solarlab.equations.time_method`). +The frozen allowlist holds no ionic scope, so an ionic history integrates +with backward Euler and a BDF request is refused before numerical work. An +allowlisted BDF scope runs the frozen profile with the forwarded work cap, +beside the sample-interval admission of the electronic max_steps. + The one history wall budget includes initial admission and all attempted steps. Newton call budgets are explicit per step, with the total bounded by max_steps; accounting is called at most once per attempt and counted separately. Individual NumPy/SciPy calls are not preempted. Initial-only steady checks never gate the time steps, and all dynamic ion continuity rows remain in residual and J. """ - if method == "bdf": + selection, call = admit_time_method(method, compiled=compiled, initial=initial, protocol=protocol, + options=options, bdf_options=bdf_options, bdf_drive=bdf_drive, family=IONIC) + if call is not None: from solarlab.experiments.bdf import solve_ionic_bdf - if bdf_options is None: - raise ValueError("BDF selection requires explicit BDFOptions") + + # A BDF selection integrates inputs built from its admission's records, never the caller's (D1b, D1-R1). with equation_implementation(selected_implementation(operator="BDFStep:Ionic1DProblem")): - return solve_ionic_bdf(compiled, initial, protocol, options=options, - bdf_options=bdf_options, drive=bdf_drive) - if method != "backward_euler": - raise ValueError("unknown time integrator") + result = integrate_admitted(call, solve_ionic_bdf) + return replace(result, controls={**result.controls, "time_method": selection.record()}) started = time.monotonic() if not isinstance(compiled, CompiledIonicDevice1D) or not isinstance(initial, IonicTransientInitial): raise ValueError("an actual compiled ionic device and pinned steady initial are required") diff --git a/src/solarlab/experiments/ionic_transient_worker.py b/src/solarlab/experiments/ionic_transient_worker.py index 9e0746d8..d2848401 100644 --- a/src/solarlab/experiments/ionic_transient_worker.py +++ b/src/solarlab/experiments/ionic_transient_worker.py @@ -178,10 +178,12 @@ def prepare_ionic_transient_job(prepared: PreparedDevice, protocol: TransientPro inputs = _identity_inputs(prepared, implementation) body = _body(prepared, protocol, intervals, ion_domain_layer, ion_domain_endpoints, options, initial_options) from solarlab.equations.implementation import selection_setting + from solarlab.equations.time_method import IONIC, time_method_setting # The child installs these before any engine import: a queued or spawned - # job runs the equation selection of the parent that prepared it. - settings = tuple(sorted([*((name, "1") for name in _THREADS), selection_setting()])) + # job runs the equation selection and time method of the parent that + # prepared it. A worker integrates with backward Euler; BDF is refused here. + settings = tuple(sorted([*((name, "1") for name in _THREADS), selection_setting(), time_method_setting(IONIC)])) environment = RuntimeEnvironment(platform.python_implementation(), platform.python_version(), platform.system(), platform.machine(), tuple((name, importlib.metadata.version(name)) for name in _PACKAGES), tuple((name, json.dumps(value)) for name, value in settings)) description = ExecutionDescription(**_roles(prepared, body, implementation), implementation=implementation, @@ -204,8 +206,10 @@ def run_ionic_transient_worker(request: WorkerRequest, worker: WorkerContext) -> worker.check_cancel() binding = worker.consume_manifest(request, engine="solarlab") from solarlab.equations.implementation import verify_selection + from solarlab.equations.time_method import BACKWARD_EULER, IONIC, verify_time_method verify_selection(binding.environment) + time_method = verify_time_method(binding.environment, IONIC) _verify_sources(binding.execution) _limits(worker._limits) from solarlab.device.compile_ionic_1d import compile_ionic_device_1d @@ -267,7 +271,7 @@ def run_ionic_transient_worker(request: WorkerRequest, worker: WorkerContext) -> admitted = IonicTransientInitial(initial.state, float(protocol.generation_scale[0]), initial_options, INITIAL_ROLE, initial_sha256, initial_bytes.decode()) worker.progress({"stage": "ionic_time_steps", "requested_steps": protocol.times_s.size - 1}) - history = solve_ionic_transient(compiled, admitted, protocol, options=options) + history = solve_ionic_transient(compiled, admitted, protocol, options=options, method=BACKWARD_EULER) worker.check_cancel() summary, payloads = ionic_transient_payload(compiled, initial, protocol, history, initial_bytes) sources = {source.id: source.sha256 for source in binding.execution.implementation.files} @@ -279,7 +283,8 @@ def run_ionic_transient_worker(request: WorkerRequest, worker: WorkerContext) -> return WorkerResult.from_dict({"schema": _RESULT, "engine": "solarlab", "H_input": request.H_input, "H_physics": request.H_physics, "H_execution": request.execution_identity.sha256, "manifest_sha256": binding.expected_sha256, "prepared_sha256": prepared.content_sha256, "ionic_result": summary, "reason": summary["reason"], - "capture": capture, "payloads": {name: {"sha256": p.sha256, "format": p.format, "metadata": json.loads(p.metadata_json)} + "capture": capture, "time_method": time_method.record(), + "payloads": {name: {"sha256": p.sha256, "format": p.format, "metadata": json.loads(p.metadata_json)} for name, p in payloads.items()}, "scientific_qualification": False}, artifacts=tuple(payloads.items()), state="succeeded" if summary["outcome"] == "completed" else "failed") @@ -290,7 +295,7 @@ def read_ionic_transient_job(store: RunStore, run_id: str, *, attempt_id: str | from solarlab.experiments.ionic_transient_results import ( SCHEMA, result_digest, storage_components, stored_units, units, unpack_ionic_arrays, validate_ionic_history, ) - from solarlab.experiments.transient_results import _decode, _fingerprint + from solarlab.experiments.transient_results import _decode, _fingerprint, recorded_backward_euler from solarlab.io.artifacts import ArtifactPayload, _json_document, _parse_document run = store.get_run(run_id) @@ -384,6 +389,8 @@ def read_ionic_transient_job(store: RunStore, run_id: str, *, attempt_id: str | or capture["time_solve_started"] != raw["initial"]["accepted"] or capture["result_sha256"] != result_digest(summary, payloads)): raise ValueError("ionic computation capture differs from actual stored source/inputs/result") + if not recorded_backward_euler(result.get("time_method"), bound["environment"]["settings"]): + raise ValueError("ionic worker time-method record differs from its execution manifest") return {"document": {**summary, "run_id": run_id, "attempt_id": selected, "generation": attempt["generation"], "arrays": {name: by_name[name]["artifact_id"] for name in unit_map}, "logical_array_units": units(species), "array_layout": {"packed_components": storage_components(species), diff --git a/src/solarlab/experiments/multiple_ionic_transient.py b/src/solarlab/experiments/multiple_ionic_transient.py index d7a35439..42ede2e2 100644 --- a/src/solarlab/experiments/multiple_ionic_transient.py +++ b/src/solarlab/experiments/multiple_ionic_transient.py @@ -24,6 +24,7 @@ from solarlab.equations.implementation import provenance_binding, use_assembled from solarlab.equations.ionic_closure import immobile_profile_binding, ion_mobility_partition from solarlab.equations.multiple_ionic_1d import CompiledMultipleIonicDevice1D, MultipleIonic1DProblem, MultipleIonicState1D +from solarlab.equations.time_method import MULTIPLE_IONIC, resolve_time_method from solarlab.experiments.ionic_transient import IonicTransientOptions, _finite_accounting from solarlab.experiments.transient import TransientProtocol from solarlab.experiments.transient_results import _decode, _encode @@ -194,7 +195,12 @@ def solve_multiple_ionic_transient( device: CompiledMultipleIonicDevice1D, initial: MultipleIonicTransientInitial, protocol: TransientProtocol, *, options: IonicTransientOptions, ) -> MultipleIonicTransientResult: - """Exactly the requested native time steps, stopping at the first failure.""" + """Exactly the requested native time steps, stopping at the first failure. + + This entry point integrates with backward Euler only: a BDF request + (scope or process setting) is refused, never run as backward Euler. + """ + resolve_time_method(compiled=device, family=MULTIPLE_IONIC) started = time.monotonic() if not isinstance(initial, MultipleIonicTransientInitial) or not isinstance(protocol, TransientProtocol) or not isinstance(options, IonicTransientOptions): raise ValueError("explicit bound initial evidence, protocol and reviewed ionic controls are required") diff --git a/src/solarlab/experiments/transient.py b/src/solarlab/experiments/transient.py index 5e85ff2b..7987de8c 100644 --- a/src/solarlab/experiments/transient.py +++ b/src/solarlab/experiments/transient.py @@ -9,7 +9,7 @@ from __future__ import annotations from collections.abc import Callable -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, replace import math import time from typing import TYPE_CHECKING, Literal, cast, overload @@ -20,6 +20,7 @@ from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem, classical_dc_1d from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem, State1D from solarlab.equations.implementation import equation_implementation, selected_implementation, use_assembled +from solarlab.equations.time_method import ELECTRONIC, admit_time_method, integrate_admitted from solarlab.experiments.jv.operating_points import _verify_point from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton from solarlab.solvers.nonlinear.problem import CallableProblem, Matrix, SolveBudget @@ -151,14 +152,20 @@ class _WallBudgetExceeded(RuntimeError): @overload def solve_transient(compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, - options: TransientOptions, initial_options: SteadyOptions, method: Literal["backward_euler"] = "backward_euler", - bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None) -> TransientResult1D: ... + options: TransientOptions, initial_options: SteadyOptions, method: Literal["backward_euler"], + bdf_options: None = None, bdf_drive: None = None) -> TransientResult1D: ... @overload def solve_transient(compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, options: TransientOptions, initial_options: SteadyOptions, method: Literal["bdf"], - bdf_options: BDFOptions, bdf_drive: BDFDrive | None = None) -> BDFResult: ... + bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None) -> BDFResult: ... + + +@overload +def solve_transient(compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, + options: TransientOptions, initial_options: SteadyOptions, method: None = None, + bdf_options: None = None, bdf_drive: None = None) -> TransientResult1D | BDFResult: ... def solve_transient( @@ -168,12 +175,18 @@ def solve_transient( *, options: TransientOptions, initial_options: SteadyOptions, - method: str = "backward_euler", + method: str | None = None, bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None, ) -> TransientResult1D | BDFResult: """Run exactly the requested BE steps; stop and retain the first failure. +The time method is resolved first (:mod:`solarlab.equations.time_method`): +backward Euler unless BDF is requested for, or defaults on, an allowlisted +scope. BDF then runs the frozen profile with the forwarded work cap, on +inputs built from the admission's records (``integrate_admitted``). Any +other BDF request is refused before numerical work. + The wall budget is monotonic and checked around each residual/Jacobian and accounting call; individual SciPy operations are not preempted. No wall clock or evaluation budget is reset after failure. Initial DC gates are rechecked @@ -183,15 +196,16 @@ def solve_transient( The full physical secant already includes reference-voltage changes, so no additional voltage-rate storage term is added. """ - if method == "bdf": + selection, call = admit_time_method(method, compiled=compiled, initial=initial, protocol=protocol, + options=options, initial_options=initial_options, bdf_options=bdf_options, + bdf_drive=bdf_drive, family=ELECTRONIC) + if call is not None: from solarlab.experiments.bdf import solve_electronic_bdf - if bdf_options is None: - raise ValueError("BDF selection requires explicit BDFOptions") + + # A BDF selection integrates inputs built from its admission's records, never the caller's (D1b, D1-R1). with equation_implementation(selected_implementation(operator="BDFStep:DC1DProblem")): - return solve_electronic_bdf(compiled, initial, protocol, options=options, - initial_options=initial_options, bdf_options=bdf_options, drive=bdf_drive) - if method != "backward_euler": - raise ValueError("unknown time integrator") + result = integrate_admitted(call, solve_electronic_bdf) + return replace(result, controls={**result.controls, "time_method": selection.record()}) started = time.monotonic() if not isinstance(compiled, CompiledDevice1D) or not isinstance(initial, SteadyState1D): raise ValueError("an actual compiled device and accepted same-device DC initial state are required") diff --git a/src/solarlab/experiments/transient_results.py b/src/solarlab/experiments/transient_results.py index 094ad682..e7aff29a 100644 --- a/src/solarlab/experiments/transient_results.py +++ b/src/solarlab/experiments/transient_results.py @@ -9,8 +9,10 @@ from dataclasses import asdict, dataclass, fields, is_dataclass from datetime import datetime, timezone +from collections.abc import Iterable, Sequence from enum import Enum import hashlib +import json import math import re from typing import TYPE_CHECKING, Any, Literal, cast, overload @@ -35,7 +37,7 @@ from solarlab.solvers.time.bdf_1d import BDFDrive __all__ = ["CapturedTransientRun", "run_transient_for_publication", - "publish_transient_result", "read_transient_result", "transient_result_payload"] + "publish_transient_result", "read_transient_result", "recorded_backward_euler", "transient_result_payload"] _SCHEMA = "solarlab.transient-result.v1" _CURRENTS = tuple(prefix + "current_density_A_m2" for prefix in ( @@ -46,6 +48,7 @@ "electron_density_m3": "m^-3", "hole_density_m3": "m^-3", **{name: "A/m^2" for name in _CURRENTS}} _TAGS = {"$array", "$scalar", "$float", "$tuple"} +_SELECTION = "solarlab.time-method-selection.v1" _SOURCE_MODULES = (__name__, "solarlab.experiments.transient", "solarlab.solvers.time.backward_euler", "solarlab.solvers.nonlinear.newton", "solarlab.solvers.nonlinear.problem", "solarlab.solvers.nonlinear.production", "solarlab.solvers.nonlinear.steady_1d", @@ -228,6 +231,22 @@ def _payload(result: TransientResult1D, nodes_m: np.ndarray) -> tuple[dict[str, return data, payloads +def recorded_backward_euler(record: Any, settings: Iterable[Sequence[str]] | None = None) -> bool: + """Whether a saved time-method record states a backward-Euler history; records before CND2 are absent. + + Without ``settings`` the record is a capture's. With a worker manifest's child settings, it must carry + the request that manifest bound. Readers import no equation module, so the names are the saved literals. + """ + backward = (type(record) is dict and record.get("schema") == _SELECTION + and record.get("effective") == "backward_euler") + if settings is None: + return record is None or (backward and record.get("requested") in (None, "backward_euler")) + bound = {name: json.loads(value) for name, value in settings} + if record is None: + return "NEWCORE_TIME_METHOD" not in bound + return backward and "NEWCORE_TIME_METHOD" in bound and record.get("requested") == bound["NEWCORE_TIME_METHOD"] + + def _result_digest(data: dict[str, Any], payloads: dict[str, ArtifactPayload]) -> str: return _digest({"summary": data, "payloads": {name: value.sha256 for name, value in payloads.items()}}) @@ -258,8 +277,7 @@ def identity(self) -> dict[str, str]: def run_transient_for_publication( compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, options: TransientOptions, initial_options: SteadyOptions, - method: Literal["backward_euler"] = "backward_euler", bdf_options: None = None, - bdf_drive: None = None, + method: Literal["backward_euler"], bdf_options: None = None, bdf_drive: None = None, ) -> CapturedTransientRun: ... @@ -267,30 +285,44 @@ def run_transient_for_publication( def run_transient_for_publication( compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, options: TransientOptions, initial_options: SteadyOptions, method: Literal["bdf"], - bdf_options: BDFOptions, bdf_drive: BDFDrive | None = None, + bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None, ) -> CapturedBDFRun: ... +@overload +def run_transient_for_publication( + compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, + options: TransientOptions, initial_options: SteadyOptions, method: None = None, + bdf_options: None = None, bdf_drive: None = None, +) -> CapturedTransientRun | CapturedBDFRun: ... + + def run_transient_for_publication( compiled: CompiledDevice1D, initial: SteadyState1D, protocol: TransientProtocol, *, options: TransientOptions, initial_options: SteadyOptions, - method: str = "backward_euler", bdf_options: BDFOptions | None = None, + method: str | None = None, bdf_options: BDFOptions | None = None, bdf_drive: BDFDrive | None = None, ) -> CapturedTransientRun | CapturedBDFRun: """Capture this call's actual inputs/source/runtime, then run the existing solver. + The time method is resolved as by ``solve_transient``. A BDF selection is + captured with its selection record, as by + ``run_production_bdf_for_publication``. This call's single admission is + handed to ``capture_admitted_bdf``, which integrates inputs built from its + records, never the caller's objects (D1b, D1-R1). + It makes no claim about when/how the supplied compiled device or initial DC state was produced. No HEAD, build commit, release or certificate is inferred. Sources are contemporaneous file hashes, not a source archive. """ - if method == "bdf": - from solarlab.experiments.bdf_results import run_bdf_for_publication - if bdf_options is None: - raise ValueError("BDF publication requires explicit BDFOptions") - return run_bdf_for_publication(compiled, initial, protocol, options=options, - initial_options=initial_options, bdf_options=bdf_options, bdf_drive=bdf_drive) - if method != "backward_euler" or bdf_options is not None or bdf_drive is not None: - raise ValueError("mixed or unknown transient publication method/options") + from solarlab.equations.time_method import BACKWARD_EULER, ELECTRONIC, admit_time_method + + selection, call = admit_time_method(method, compiled=compiled, initial=initial, protocol=protocol, + options=options, initial_options=initial_options, bdf_options=bdf_options, + bdf_drive=bdf_drive, family=ELECTRONIC) + if call is not None: + from solarlab.experiments.bdf_results import capture_admitted_bdf + return capture_admitted_bdf(selection, call, drive_was_explicit=bdf_drive is not None) from solarlab.equations.implementation import provenance_binding from solarlab.experiments.transient import solve_transient nodes = np.frombuffer(compiled.nodes_m.tobytes(), dtype=compiled.nodes_m.dtype).reshape(compiled.nodes_m.shape) @@ -304,9 +336,10 @@ def run_transient_for_publication( "runtime": admitted.export()["runtime_observed"], "source_content": "admitted execution snapshot; historical inputs retain their own identities", "build_source_commit": admitted.export()["git_commit"], - "compiled_device_history": None, "initial_dc_history": None} + "compiled_device_history": None, "initial_dc_history": None, "time_method": selection.record()} started = datetime.now(timezone.utc).isoformat() - result = solve_transient(compiled, initial, protocol, options=options, initial_options=initial_options) + result = solve_transient(compiled, initial, protocol, options=options, initial_options=initial_options, + method=BACKWARD_EULER) data, payloads = _payload(result, nodes) identity = {"H_input": _digest(inputs), "H_physics": compiled.identity, "H_execution": _digest(description)} record = {"status": "captured_at_computation", "started_utc": started, @@ -438,7 +471,7 @@ def record(identifier: str, name: str) -> dict[str, Any]: elif read_provenance(job).export()["git_commit"] != description["build_source_commit"]: raise ValueError("transient capture source commit differs from admitted provenance") expected = {"H_input": _digest(inputs), "H_physics": document["compiled_identity"], "H_execution": _digest(description)} - if (description["scope"] != "solve_transient_call" + if (description["scope"] != "solve_transient_call" or not recorded_backward_euler(description.get("time_method")) or any(description[name] is not None for name in ("compiled_device_history", "initial_dc_history")) or description["inputs"] != inputs or provenance["identity"] != expected or manifest["identity"] != expected or provenance["result_sha256"] != _result_digest(manifest["summary"], payloads)): diff --git a/src/solarlab/experiments/transient_worker.py b/src/solarlab/experiments/transient_worker.py index e6d32c4c..fc8df2c9 100644 --- a/src/solarlab/experiments/transient_worker.py +++ b/src/solarlab/experiments/transient_worker.py @@ -147,10 +147,13 @@ def prepare_transient_job(prepared: PreparedDevice, protocol: TransientProtocol, inputs = _identity_inputs(prepared, implementation) body = _body(prepared, protocol, intervals_per_layer, options, initial_options) from solarlab.equations.implementation import selection_setting + from solarlab.equations.time_method import ELECTRONIC, time_method_setting # The child installs these before any engine import: a queued or spawned - # job runs the equation selection of the parent that prepared it. - settings = tuple(sorted([*((name, "1") for name in _THREADS), selection_setting()])) + # job runs the equation selection and time method of the parent that + # prepared it. A worker integrates with backward Euler; BDF is refused here. + settings = tuple(sorted([*((name, "1") for name in _THREADS), selection_setting(), + time_method_setting(ELECTRONIC)])) environment = RuntimeEnvironment(platform.python_implementation(), platform.python_version(), platform.system(), platform.machine(), tuple((n, importlib.metadata.version(n)) for n in _PACKAGES), tuple((name, json.dumps(value)) for name, value in settings)) @@ -177,8 +180,10 @@ def run_transient_worker(request: WorkerRequest, worker: WorkerContext) -> Worke worker.check_cancel() binding = worker.consume_manifest(request, engine="solarlab") from solarlab.equations.implementation import verify_selection + from solarlab.equations.time_method import BACKWARD_EULER, ELECTRONIC, verify_time_method verify_selection(binding.environment) + time_method = verify_time_method(binding.environment, ELECTRONIC) _verify_sources(binding.execution) body = json.loads(request.request.content) prepared = binding.inputs.prepared @@ -230,8 +235,8 @@ def run_transient_worker(request: WorkerRequest, worker: WorkerContext) -> Worke "compiled_identity": compiled.identity, "manifest_sha256": binding.expected_sha256, "runtime": runtime, "threadpools": pools} worker.progress({"stage": "transient_time_steps", "nodes": compiled.node_count}) - captured = run_transient_for_publication(compiled, initial, protocol, - options=options, initial_options=initial_options) + captured = run_transient_for_publication(compiled, initial, protocol, options=options, + initial_options=initial_options, method=BACKWARD_EULER) worker.check_cancel() summary, payloads = _payload(captured.result, captured.nodes_m) capture = json.loads(captured.capture_json) @@ -241,7 +246,7 @@ def run_transient_worker(request: WorkerRequest, worker: WorkerContext) -> Worke "prepared_sha256": prepared.content_sha256, "H_input": request.H_input, "H_physics": request.H_physics, "H_execution": request.execution_identity.sha256, "manifest_sha256": binding.expected_sha256, "transient_result": summary, "reason": summary["reason"], "cold_start": json.loads(_document("cold", cold).content), - "transient_capture": capture, + "transient_capture": capture, "time_method": time_method.record(), "payloads": {name: {"sha256": p.sha256, "format": p.format, "metadata": json.loads(p.metadata_json)} for name, p in payloads.items()}, "scientific_qualification": False}, artifacts=tuple(payloads.items()), @@ -253,7 +258,7 @@ def read_transient_job(store: RunStore, run_id: str, *, attempt_id: str | None = """Verify one committed complete/partial history without importing a solver.""" import numpy as np from solarlab.experiments.transient_results import ( - _UNITS, _decode, _digest, _inputs, _result_digest, _validate, + _UNITS, _decode, _digest, _inputs, _result_digest, _validate, recorded_backward_euler, ) from solarlab.io.artifacts import ArtifactPayload, _json_document, _parse_document @@ -320,7 +325,10 @@ def read_transient_job(store: RunStore, run_id: str, *, attempt_id: str | None = description = capture["description"] inputs = _inputs(summary["compiled_identity"], arrays, diagnostics["initial"], diagnostics["initial_controls"]) expected_identity = {"H_input": _digest(inputs), "H_physics": summary["compiled_identity"], "H_execution": _digest(description)} + if not recorded_backward_euler(result.get("time_method"), bound["environment"]["settings"]): + raise ValueError("transient worker time-method record differs from its execution manifest") if (capture["status"] != "captured_at_computation" or description["scope"] != "solve_transient_call" + or not recorded_backward_euler(description.get("time_method")) or any(description[n] is not None for n in ("compiled_device_history", "initial_dc_history")) or description["inputs"] != inputs or capture["identity"] != expected_identity or description["numerics"] != controls["transient"] diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json index a7813708..cb270340 100644 --- a/src/solarlab/reproducibility/PublicAPI.json +++ b/src/solarlab/reproducibility/PublicAPI.json @@ -130,6 +130,8 @@ "solarlab.experiments.bdf_results": [ "CapturedBDFRun", "run_bdf_for_publication", + "run_production_bdf_for_publication", + "capture_admitted_bdf", "publish_bdf_result", "read_bdf_result", "read_bdf_packet" @@ -419,6 +421,7 @@ "run_transient_for_publication", "publish_transient_result", "read_transient_result", + "recorded_backward_euler", "transient_result_payload" ], "solarlab.experiments.transient_worker": [ @@ -570,6 +573,38 @@ "diagnostics", "scope", "sources" + ], + "solarlab.equations.time_method": [ + "ADAPTIVE_MAX_STEPS", + "ALLOWLIST", + "ALLOWLIST_SHA256", + "ALLOWLISTED_DEFAULT", + "BACKWARD_EULER", + "BDF", + "ELECTRONIC", + "ENVIRONMENT", + "IONIC", + "MULTIPLE_IONIC", + "PROFILE", + "PROFILE_SHA256", + "SCOPE_SCHEMA", + "SELECTION_SCHEMA", + "TIME_METHODS", + "TRUST_STANDARD", + "AdmittedBDFCall", + "TimeMethodSelection", + "admit_time_method", + "electronic_components", + "electronic_scope", + "integrate_admitted", + "ionic_scope", + "requested_time_method", + "resolve_time_method", + "scope_digest", + "time_method", + "time_method_setting", + "verify_integration", + "verify_time_method" ] }, "public_imports": { diff --git a/tests/ci/exclusions.json b/tests/ci/exclusions.json index 3163fe69..59d8986a 100644 --- a/tests/ci/exclusions.json +++ b/tests/ci/exclusions.json @@ -28,7 +28,10 @@ "tests/integration/test_bdf_publication.py::test_saved_readiness_packets_keep_original_words_and_identity": "Reads exact captured ReadinessV1/V2 BDF words and checks stored integrity only; no locally regenerated floating output is compared, so readback runs on every platform.", "tests/integration/test_bdf_publication.py::test_historical_packet_structural_tampering_refuses": "Reads exact captured ReadinessV1/V2 BDF words and checks stored integrity only; no locally regenerated floating output is compared, so readback runs on every platform.", "tests/integration/test_bdf_publication.py::test_solver_free_process_reads_historical_packets": "Reads historical BDF fixture words with solver imports forbidden; this byte-integrity/readback test performs no local numerical recomputation and runs on every platform.", - "tests/integration/test_bdf_publication.py::test_reviewer_rejected_restart_witness_refuses_historical_packets": "Reseals one Boolean in a temporary copy of the captured V1/V2 packet; checks historical semantic integrity without recomputing floats, on every platform." + "tests/integration/test_bdf_publication.py::test_reviewer_rejected_restart_witness_refuses_historical_packets": "Reseals one Boolean in a temporary copy of the captured V1/V2 packet; checks historical semantic integrity without recomputing floats, on every platform.", + "tests/integration/test_time_method_selection.py::test_the_allowlist_holds_exactly_the_ten_frozen_envelopes": "Reads the CND2 key table; compares only declared source/control words and the embedded allowlist, so it runs on every platform.", + "tests/integration/test_time_method_selection.py::test_live_scope_keys_are_the_frozen_allowlist": "Compares live compiled-device and cold-initial digests with the frozen CND2 keys; skips off the recorded capture stack, where the other tests allowlist the platform's own keys.", + "tests/integration/test_time_method_selection.py::test_production_bdf_reproduces_the_reviewed_readiness_history": "Compares a live production BDF history with the captured ReadinessV2 E_saved_packet words; skips off the recorded capture stack." }, "markers": { "slow": "Excluded from the default fast command. scheduled-suite.yml inventories and partitions every slow node in both root and legacy suites; the older optional ci.yml smoke job retains its bounded legacy regression scope.", @@ -91,7 +94,10 @@ "tests/integration/test_bdf_publication.py::test_saved_readiness_packets_keep_original_words_and_identity", "tests/integration/test_bdf_publication.py::test_historical_packet_structural_tampering_refuses", "tests/integration/test_bdf_publication.py::test_solver_free_process_reads_historical_packets", - "tests/integration/test_bdf_publication.py::test_reviewer_rejected_restart_witness_refuses_historical_packets" + "tests/integration/test_bdf_publication.py::test_reviewer_rejected_restart_witness_refuses_historical_packets", + "tests/integration/test_time_method_selection.py::test_the_allowlist_holds_exactly_the_ten_frozen_envelopes", + "tests/integration/test_time_method_selection.py::test_live_scope_keys_are_the_frozen_allowlist", + "tests/integration/test_time_method_selection.py::test_production_bdf_reproduces_the_reviewed_readiness_history" ], "platform_bound_fixtures": { "tests/support/assembly_baselines.json": "Raw float/complex words and sparse patterns captured on the recorded Darwin arm64 Python/NumPy/SciPy and Accelerate stack.", @@ -102,7 +108,8 @@ "tests/integration/fixtures/bdf_readiness/readinessv1_e_saved_packet.json.gz": "Exact captured BDF history words; reader tests preserve bytes without running a solver or comparing locally regenerated floating outputs.", "tests/integration/fixtures/bdf_readiness/readinessv1_e_light_step.json.gz": "Exact captured BDF history words; reader tests preserve bytes without running a solver or comparing locally regenerated floating outputs.", "tests/integration/fixtures/bdf_readiness/readinessv2_e_saved_packet.json.gz": "Exact captured BDF history words; reader tests preserve bytes without running a solver or comparing locally regenerated floating outputs.", - "tests/integration/fixtures/bdf_readiness/readinessv2_e_dark_voltage_step.json.gz": "Exact captured failed ReadinessV2 BDF restart history; validate the recorded left/right words without local floating recomputation or endpoint reconstruction." + "tests/integration/fixtures/bdf_readiness/readinessv2_e_dark_voltage_step.json.gz": "Exact captured failed ReadinessV2 BDF restart history; validate the recorded left/right words without local floating recomputation or endpoint reconstruction.", + "tests/integration/fixtures/bdf_readiness/allowlist.json": "CND2 scope-key table: each frozen envelope's scope digest binds compiled-device and initial-state words of the recorded Darwin arm64 Accelerate stack; source knots, controls and profile are exact declared inputs." }, "portable_fixtures": { "tests/fixtures/native_history/accepted.jsonl": "Exact historical reader bytes from the incomplete original attempt; no local floating output is regenerated or qualified against them.", diff --git a/tests/integration/fixtures/bdf_readiness/allowlist.json b/tests/integration/fixtures/bdf_readiness/allowlist.json new file mode 100644 index 00000000..f9a70f4f --- /dev/null +++ b/tests/integration/fixtures/bdf_readiness/allowlist.json @@ -0,0 +1,830 @@ +{ + "schema": "solarlab.time-method-allowlist-fixture.v1", + "freeze": { + "name": "CommanderBdfDefaultFreezeV1", + "sha256": "4383658431b8b1e2a6106073b5fa91829456ba41049c48a4b5102397fb106066" + }, + "key_table": "CND2 path-independent scope keys of the same ten envelopes, for CommanderBdfDefaultFreezeV2", + "profile": { + "sha256": "9239679194ed68a8c72780877a80a84ecca3dba24a895a17fe1ac1a94fd76bea", + "options": { + "initial_step_s": 0.001, + "min_step_s": 1e-16, + "max_step_s": 1e+30, + "relative_tolerance": 1e-05, + "absolute_tolerance": 1e-12, + "max_order": 2, + "adaptive": true, + "safety": 0.8, + "min_factor": 0.2, + "max_factor": 2.0, + "max_steps": 10000, + "max_attempts": 20000, + "max_consecutive_rejections": 12, + "wall_s": 30.0 + }, + "adaptive_max_steps": 10000 + }, + "scope_schema": "solarlab.time-method-scope.v1", + "family": "electronic_1d", + "device": { + "config_sha256": "2003cd46e119c2c8ff324ffc11562c2e69cd32dc1e7cdeda43f22dfdd501e086", + "intervals_per_layer": 12, + "content_sha256": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac" + }, + "capture": { + "system": "Darwin", + "machine": "arm64", + "python": "3.13.15", + "numpy": "2.5.3", + "scipy": "1.18.1", + "numpy_blas": "accelerate", + "numpy_lapack": "accelerate", + "scipy_blas": "accelerate", + "scipy_lapack": "accelerate" + }, + "envelopes": [ + { + "case_id": "E_dark_hold", + "scope_sha256": "221e31f715757df14ebaaa73e4f2c2f879e6cb980a5fc483c7940a607b53cebf", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "2146bc9c8266a0e6a2b1fac978232a17e6847b26affb901255b62c27708ee791", + "protocol": "813c88451d629c420a753368dc0570e7c166130e8da26e58b7dbd171862a046a", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "dcdcb4da6cd0f970df04e92a598ce869aebf90682fa3d06953355ecb30bfd828", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07, + 3e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_light_hold", + "scope_sha256": "59aca9ef958c68f5c179afe0ea59817d51d66b519af65aeaff6c847d545a03c3", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", + "protocol": "aa2a8c23095cf5c1f020a5246ec6bff5487507f56adbbc674fdff1dedea87e85", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "fb8af7adb2d4af7b2dd8b5c459ad2aff6df4a36cf3599dc96d965b9ef693787f", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07, + 3e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_dark_voltage_ramp", + "scope_sha256": "7dace99e619ecddd410121309ea5443a16f832720e90fb22781b8b3be591b2a5", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "2146bc9c8266a0e6a2b1fac978232a17e6847b26affb901255b62c27708ee791", + "protocol": "03673360ca7baf7c4d2c0122631764dd0f6b99163c7c63d6dde9940159e2ca4f", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "dcdcb4da6cd0f970df04e92a598ce869aebf90682fa3d06953355ecb30bfd828", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07, + 3e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0005, + 0.001, + 0.0015, + 0.002 + ], + "generation_scale": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_light_ramp_4", + "scope_sha256": "608051152d7f5b41bdbb9d227f4cb69f6b5d37e0f9be13d9cc5b09fc1c214d33", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", + "protocol": "e9a2a4a2ce13370f928c749800c8db8425bc5b88b878602cb06c627257098682", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "fb8af7adb2d4af7b2dd8b5c459ad2aff6df4a36cf3599dc96d965b9ef693787f", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07, + 3e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 1.0, + 1.000625, + 1.0025, + 1.005625, + 1.01 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_voltage_ramp_4", + "scope_sha256": "cdadc98646e0665667b9b26ef5ddc294bb89b1434faca40498f2bc3855cbff63", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", + "protocol": "a89197bc7fa0b472e5968ab15ebb3f56147b39a3b49f6a6aff19d70a1d9a1652", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "36b259f39906ecd88e9df8ac12614f45610076dbfe698829d083a3a6f56d85fb", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07, + 3e-07, + 4e-07 + ], + "voltage_V": [ + 0.1, + 0.1000625, + 0.10025, + 0.1005625, + 0.101 + ], + "generation_scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_light_ramp_8", + "scope_sha256": "700083da5b3e5dcbc3eec176f91830b27290491a363a8204e5336772f38dcd27", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", + "protocol": "07ad2898d0714b8aa587fb1e833f36cf155e8568f8f73c9bacf3b030ad1a5b3f", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "fb8af7adb2d4af7b2dd8b5c459ad2aff6df4a36cf3599dc96d965b9ef693787f", + "frozen_source": { + "times_s": [ + 0.0, + 5e-08, + 1e-07, + 1.5e-07, + 2e-07, + 2.5e-07, + 3e-07, + 3.5e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 1.0, + 1.00015625, + 1.000625, + 1.00140625, + 1.0025, + 1.00390625, + 1.005625, + 1.00765625, + 1.01 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_voltage_ramp_8", + "scope_sha256": "6e315c3f151c1a0744093a63f04229ddc76fa4995bbb0272c7c9eaf3097ec1e6", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", + "protocol": "bf98884538495964633878d5e040b677466703b4c1b3f8ec1ac992eb77663aba", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "36b259f39906ecd88e9df8ac12614f45610076dbfe698829d083a3a6f56d85fb", + "frozen_source": { + "times_s": [ + 0.0, + 5e-08, + 1e-07, + 1.5e-07, + 2e-07, + 2.5e-07, + 3e-07, + 3.5e-07, + 4e-07 + ], + "voltage_V": [ + 0.1, + 0.10001562500000001, + 0.1000625, + 0.10014062500000001, + 0.10025, + 0.10039062500000001, + 0.1005625, + 0.10076562500000001, + 0.101 + ], + "generation_scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_light_ramp_16", + "scope_sha256": "a9364a002e141af1c09d252098eba75268136005d4755ddf6a76e954b13e5ca4", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", + "protocol": "d509d81b817ef0691ade9cbb24dfeda8e1ce5da31338889f722ad25eb0567371", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "fb8af7adb2d4af7b2dd8b5c459ad2aff6df4a36cf3599dc96d965b9ef693787f", + "frozen_source": { + "times_s": [ + 0.0, + 2.5e-08, + 5e-08, + 7.5e-08, + 1e-07, + 1.25e-07, + 1.5e-07, + 1.75e-07, + 2e-07, + 2.25e-07, + 2.5e-07, + 2.75e-07, + 3e-07, + 3.2499999999999996e-07, + 3.5e-07, + 3.75e-07, + 4e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 1.0, + 1.0000390625, + 1.00015625, + 1.0003515625, + 1.000625, + 1.0009765625, + 1.00140625, + 1.0019140625, + 1.0025, + 1.0031640625, + 1.00390625, + 1.0047265625, + 1.005625, + 1.0066015625, + 1.00765625, + 1.0087890625, + 1.01 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_voltage_ramp_16", + "scope_sha256": "8e315434aa617005a75bb7224cebabf03830f05afe06782c38626c37f49c9af8", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", + "protocol": "8d96602a2fd3a5f5c45667f9ca31c8ff5487165f9fa72c6ab3f5f7d2c33c8dd6", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "36b259f39906ecd88e9df8ac12614f45610076dbfe698829d083a3a6f56d85fb", + "frozen_source": { + "times_s": [ + 0.0, + 2.5e-08, + 5e-08, + 7.5e-08, + 1e-07, + 1.25e-07, + 1.5e-07, + 1.75e-07, + 2e-07, + 2.25e-07, + 2.5e-07, + 2.75e-07, + 3e-07, + 3.2499999999999996e-07, + 3.5e-07, + 3.75e-07, + 4e-07 + ], + "voltage_V": [ + 0.1, + 0.10000390625000001, + 0.10001562500000001, + 0.10003515625, + 0.1000625, + 0.10009765625, + 0.10014062500000001, + 0.10019140625, + 0.10025, + 0.10031640625, + 0.10039062500000001, + 0.10047265625, + 0.1005625, + 0.10066015625000001, + 0.10076562500000001, + 0.10087890625000001, + 0.101 + ], + "generation_scale": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + }, + { + "case_id": "E_saved_packet", + "scope_sha256": "e79d312254e470a833c985f8304c6faf9df11c4fff139658175fdc1a983c0851", + "components": { + "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", + "protocol": "9f86cabc9d07defbeeaf46ffb83e77849d9837a32f0730b044845f8089f67f0a", + "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", + "physical_controls": "f614faff432e1a62715a24b23157b3ecb0c1c9fa94c342bcd40a158dd03a79b3", + "initial_controls": "a687cb51a6a5cb76e640f8732665f2f83261f7d25876a63ab9d4ef864519426a" + }, + "initial_artifact_sha256": "fb8af7adb2d4af7b2dd8b5c459ad2aff6df4a36cf3599dc96d965b9ef693787f", + "frozen_source": { + "times_s": [ + 0.0, + 1e-07, + 2e-07 + ], + "voltage_V": [ + 0.0, + 0.0, + 0.0 + ], + "generation_scale": [ + 1.0, + 1.0025, + 1.01 + ] + }, + "physical_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "newton_budget": { + "max_iterations": 50, + "max_residual_evaluations": 1000, + "max_jacobian_evaluations": 50, + "max_backtracks": 24 + }, + "max_steps": 32, + "wall_s": 30.0, + "predictor": "previous", + "convergence_policy": "poisson_contact_balance_v1" + }, + "initial_controls": { + "poisson_tolerance": 1e-11, + "continuity_tolerance_A_m2": 1e-08, + "current_spread_tolerance_A_m2": 1e-08, + "equilibrium_current_tolerance_A_m2": 1e-10, + "contact_log_tolerance": 1e-11, + "potential_step_V": 0.1, + "quasi_fermi_step": 2.0, + "max_iterations": 100, + "max_residual_evaluations": 10000, + "max_jacobian_evaluations": 2000, + "max_backtracks": 40, + "max_bias_step_V": 0.1, + "max_continuation_steps": 100, + "convergence_policy": "historical_max_row_v1" + } + } + ], + "allowlist_sha256": "faaaf7cb92862de77d8bb48ba15d9552fdb988d1df493b2ebe7b2cddb247dbae", + "qualification": false +} diff --git a/tests/integration/test_bdf_publication.py b/tests/integration/test_bdf_publication.py index 5ac175fa..ecdd8aac 100644 --- a/tests/integration/test_bdf_publication.py +++ b/tests/integration/test_bdf_publication.py @@ -15,6 +15,7 @@ from solarlab.equations.implementation import ASSEMBLED, ENVIRONMENT, LEGACY, equation_implementation from solarlab.experiments.bdf_results import ( _canonical, _decode, _digest, _encode, _input_record, _validate_history, _work, read_bdf_packet, read_bdf_result, + run_bdf_for_publication, ) from solarlab.experiments.transient_results import ( publish_transient_result, read_transient_result, run_transient_for_publication, @@ -100,8 +101,9 @@ def reject(old, new, u): return (replace(events[0], restart=reject), *events[1:]) patch.setattr(bdf_backend, "_events", rejecting_events) - capture = run_transient_for_publication(compiled, initial, active_protocol, - options=options, initial_options=initial_options, method="bdf", bdf_options=requested, + # An explicit research capture: these scopes and BDFOptions are not allowlisted. + capture = run_bdf_for_publication(compiled, initial, active_protocol, + options=options, initial_options=initial_options, bdf_options=requested, bdf_drive=active_drive) assert (observed.original == 0 and observed.assembled > 0) if assembled else ( observed.original > 0 and observed.assembled == 0) @@ -119,7 +121,6 @@ def reject(old, new, u): from examples.research_1d.ionic_transient import controls as ionic_controls from examples.research_1d.transient import json_value from solarlab.device.compile_ionic_1d import compile_ionic_device_1d - from solarlab.experiments.bdf_results import run_bdf_for_publication from solarlab.experiments.ionic_transient import load_ionic_steady_initial from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state diff --git a/tests/integration/test_time_method_selection.py b/tests/integration/test_time_method_selection.py new file mode 100644 index 00000000..65651788 --- /dev/null +++ b/tests/integration/test_time_method_selection.py @@ -0,0 +1,989 @@ +"""The time-method axis at the transient production entry points (CND2). + +The ten allowlisted envelopes are declared as ReadinessV1 declared them, on +this checkout's research device, from cold steady initials. +CommanderBdfDefaultFreezeV1 freezes their source words and controls, and +allowlist.json holds them with each envelope's CND2 scope key. A key digests +numerical-stack words: the compiled device content and the initial state. +Only the tests that compare live keys or histories with frozen ones therefore +need the capture stack. Elsewhere the same envelopes are allowlisted under +this platform's own keys. +""" + +from contextlib import contextmanager +from dataclasses import asdict, dataclass, replace +from datetime import date +import gzip +import hashlib +import json +from pathlib import Path +import shutil + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from examples.research_1d.ionic_residual import prepare_single_ion_device +from examples.research_1d.ionic_steady import controls as ionic_steady_controls +from examples.research_1d.ionic_transient import controls as ionic_controls, json_value +from examples.research_1d.steady import load_device +from examples.research_1d.transient import controls +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.equations import time_method +from solarlab.equations.implementation import ASSEMBLED, LEGACY, equation_implementation +from solarlab.equations.time_method import ( + ADAPTIVE_MAX_STEPS, ALLOWLIST, BACKWARD_EULER, BDF, ENVIRONMENT, PROFILE, PROFILE_SHA256, AdmittedBDFCall, + electronic_components, electronic_scope, time_method as time_method_scope, +) +from solarlab.experiments import bdf as bdf_backend, bdf_results, transient +from solarlab.experiments.bdf_results import _decode, _digest, _loads, _validate_body, read_bdf_result +from solarlab.experiments.ionic_transient import load_ionic_steady_initial, solve_ionic_transient +from solarlab.experiments.transient import TransientOptions, TransientProtocol, TransientResult1D, solve_transient +from solarlab.experiments.transient_results import ( + publish_transient_result, read_transient_result, run_transient_for_publication, +) +from solarlab.io.run_store import RunStore +from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state +from solarlab.solvers.time.bdf import BDFOptions, BDFResult +from solarlab.solvers.time.bdf_1d import BDFDrive +from support.equation_provenance import counted + +ROOT = Path(__file__).resolve().parents[2] +FIXTURES = ROOT / "tests/integration/fixtures/bdf_readiness" +ALLOWLIST_FIXTURE = FIXTURES / "allowlist.json" +SAVED_PACKET = FIXTURES / "readinessv2_e_saved_packet.json.gz" + + +@pytest.fixture(scope="module", autouse=True) +def blas1(): + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(autouse=True) +def no_process_settings(monkeypatch): + for name in (ENVIRONMENT, "NEWCORE_EQUATIONS"): + monkeypatch.delenv(name, raising=False) + + +def frozen_table(): + return json.loads(ALLOWLIST_FIXTURE.read_text()) + + +def sources(): + """The ten envelopes' source knots, as ReadinessV1 declared them.""" + t = np.linspace(0, 4e-7, 5) + declared = {"E_dark_hold": (t, 0.0, 0.0), "E_light_hold": (t, 0.0, 1.0), + "E_dark_voltage_ramp": (t, .002 * t / t[-1], 0.0)} + for n in (4, 8, 16): + grid = np.linspace(0, 4e-7, n + 1) + declared[f"E_light_ramp_{n}"] = (grid, 0.0, 1 + .01 * (grid / grid[-1]) ** 2) + declared[f"E_voltage_ramp_{n}"] = (grid, .1 + .001 * (grid / grid[-1]) ** 2, 1.0) + declared["E_saved_packet"] = (np.asarray([0, 1e-7, 2e-7], float), 0.0, [1, 1.0025, 1.01]) + return {name: TransientProtocol(times, *(np.broadcast_to(value, times.shape).astype(float).copy() + for value in (voltage, light))) + for name, (times, voltage, light) in declared.items()} + + +INITIALS = {} + + +def envelope(device, protocol): + """One envelope's call: its cold steady initial, source knots and the research physical controls.""" + key = (device.identity, protocol.voltage_V[0], protocol.generation_scale[0]) + if key not in INITIALS: + INITIALS[key] = solve_steady_state(device, voltage_V=float(protocol.voltage_V[0]), + generation_scale=float(protocol.generation_scale[0]), options=SteadyOptions()) + return INITIALS[key], protocol, controls() + + +@pytest.fixture(scope="module") +def electronic37(): + """The research device, compiled from this checkout (its own path-bound identity).""" + return compile_device_1d(load_device(), intervals_per_layer=12) + + +@pytest.fixture(scope="module") +def envelopes(electronic37): + return {name: envelope(electronic37, protocol) for name, protocol in sources().items()} + + +@pytest.fixture +def unflipped(monkeypatch): + """The scope-based default before the route decision: backward Euler for every scope.""" + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BACKWARD_EULER, None)) + + +@pytest.fixture +def allowlisted(monkeypatch, electronic37, envelopes): + """This platform's own keys for the ten frozen envelopes; on the capture stack they are ALLOWLIST itself.""" + keys = {electronic_scope(electronic37, initial, protocol, options=options, initial_options=SteadyOptions()): name + for name, (initial, protocol, options) in envelopes.items()} + assert len(keys) == 10 + monkeypatch.setattr(time_method, "ALLOWLIST", keys) + # Only tests that explicitly flip the default use this prospective date. + monkeypatch.setattr(time_method, "_SWITCH_DATE", "2026-11-08") + monkeypatch.setattr(time_method, "_route_today", lambda: date(2026, 11, 8)) + return {name: key for key, name in keys.items()} + + +def capture_guard(): + import importlib.util + + spec = importlib.util.spec_from_file_location("frozen_oracle", ROOT / "tests/unit/assembly_parity/test_frozen_baselines.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.require_capture_environment(frozen_table()["capture"]) + + +def words(value): + """Every result leaf as binary64 words; wall clocks dropped.""" + if isinstance(value, dict): + return tuple((key, words(item)) for key, item in value.items() + if key not in {"wall_s", "initial_admission_wall_s", "time_method"}) + if hasattr(value, "__dataclass_fields__") and not isinstance(value, type): + return (type(value).__name__, tuple((name, words(getattr(value, name))) for name in value.__dataclass_fields__ + if name != "wall_s")) + if isinstance(value, (list, tuple)): + return tuple(words(item) for item in value) + if isinstance(value, np.ndarray): + return (value.dtype.str, value.shape, value.tobytes()) + if isinstance(value, float): + return float(value).hex() + return value + + +@contextmanager +def no_numerical_work(monkeypatch): + """Refusals come before any solve: neither integrator nor its Newton may start.""" + def forbidden(*args, **kwargs): + raise AssertionError("numerical work ran before the refusal") + + with monkeypatch.context() as patch: + for module, name in ((transient, "solve_newton"), (bdf_backend, "solve_bdf"), + (bdf_backend, "solve_electronic_bdf"), (bdf_backend, "solve_ionic_bdf")): + patch.setattr(module, name, forbidden) + yield + + +@pytest.mark.platform_bound +def test_the_allowlist_holds_exactly_the_ten_frozen_envelopes(): + table = frozen_table() + assert dict(ALLOWLIST) == {case["scope_sha256"]: case["case_id"] for case in table["envelopes"]} + assert table["allowlist_sha256"] == time_method.ALLOWLIST_SHA256 and table["qualification"] is False + assert table["profile"] == {"sha256": PROFILE_SHA256, "options": dict(PROFILE), "adaptive_max_steps": 10000} + assert (hashlib.sha256((ROOT / "examples/research_1d/device.json").read_bytes()).hexdigest() + == table["device"]["config_sha256"]) + # The declared sources and controls are the frozen ones, word for word. + declared = sources() + for case in table["envelopes"]: + protocol = declared[case["case_id"]] + for name, values in case["frozen_source"].items(): + assert np.asarray(values, dtype=float).tobytes() == getattr(protocol, name).tobytes(), case["case_id"] + physical = case["physical_controls"] + assert TransientOptions(**{**physical, "newton_budget": SolveBudget(**physical["newton_budget"])}) == controls() + assert case["initial_controls"] == asdict(SteadyOptions()) + + +def test_scope_keys_are_path_independent(tmp_path, envelopes): + """Two absolute config paths compile different identities but the same scope key for every envelope.""" + devices = [] + for name in ("first", "second/deeper"): + path = tmp_path / name / "device.json" + path.parent.mkdir(parents=True) + shutil.copyfile(ROOT / "examples/research_1d/device.json", path) + devices.append(compile_device_1d(load_device(path), intervals_per_layer=12)) + assert devices[0].identity != devices[1].identity + keys = set() + for name, declared in sources().items(): + found = set() + for device in devices: + initial, protocol, options = envelope(device, declared) + found.add(electronic_scope(device, initial, protocol, options=options, initial_options=SteadyOptions())) + assert len(found) == 1, name + keys |= found + assert len(keys) == 10 + + +def test_an_ionic_manifest_missing_any_path_bound_identity_has_no_scope(tmp_path): + """G1 (Science recheck): Grammar V2 R1 refuses a binding manifest without each identity it sets aside. + + Removing the top-level original_prepared_sha256, electronic_component.compiled_sha256, + electronic_component.prepared_sha256, or both nested ones, leaves no scope key. An explicit bdf request is then + refused as an uncomputable scope, while the complete manifest keeps its key. + """ + from solarlab.equations.time_method import ionic_scope + + device, initial, protocol = ionic_case(tmp_path) + physical = ionic_controls() + key = ionic_scope(device, initial, protocol, options=physical) + for removed in (("original_prepared_sha256",), ("electronic_component.compiled_sha256",), + ("electronic_component.prepared_sha256",), + ("electronic_component.compiled_sha256", "electronic_component.prepared_sha256")): + manifest = json.loads(device.binding_manifest_json) + for name in removed: + section, _, field = name.rpartition(".") + (manifest[section] if section else manifest).pop(field) + changed = replace(device, binding_manifest_json=json.dumps(manifest, sort_keys=True)) + with pytest.raises(TypeError, match="must name its path-bound identities"): + ionic_scope(changed, initial, protocol, options=physical) + with pytest.raises(ValueError, match="scope cannot be computed.*path-bound identities"): + time_method.resolve_time_method(BDF, compiled=changed, initial=initial, protocol=protocol, + options=physical, family=time_method.IONIC) + assert ionic_scope(replace(device), initial, protocol, options=physical) == key + + +def test_ionic_scope_keys_are_path_independent(tmp_path, monkeypatch): + """The ionic device carries three path-bound identities; its scope sets them aside too.""" + import examples.research_1d.ionic_residual as residual + from solarlab.equations.time_method import ionic_scope + + original = residual.load_device + found, identities = set(), set() + for name in ("first", "second/deeper"): + path = tmp_path / name / "device.json" + path.parent.mkdir(parents=True) + shutil.copyfile(ROOT / "examples/research_1d/device.json", path) + monkeypatch.setattr(residual, "load_device", lambda selected=None, path=path: original(path)) + device, initial, protocol = ionic_case(tmp_path / name, device=compile_ionic_device_1d( + residual.prepare_single_ion_device(diffusion_only=True), intervals_per_layer=12)) + identities.add(device.identity) + found.add(ionic_scope(device, initial, protocol, options=ionic_controls())) + assert len(identities) == 2 and len(found) == 1 + + +@pytest.mark.platform_bound +def test_live_scope_keys_are_the_frozen_allowlist(electronic37, envelopes): + """On the capture stack the live envelopes compute exactly the frozen keys and components.""" + capture_guard() + for case in frozen_table()["envelopes"]: + initial, protocol, options = envelopes[case["case_id"]] + components = electronic_components(electronic37, initial, protocol, options=options, + initial_options=SteadyOptions()) + assert {name: time_method._sha256(value) for name, value in components.items()} == case["components"] + key = electronic_scope(electronic37, initial, protocol, options=options, initial_options=SteadyOptions()) + # The cold steady initial on today's code has the frozen artifact's words. + assert ALLOWLIST[key] == case["case_id"] == ALLOWLIST[case["scope_sha256"]] + + +def test_the_default_is_bitwise_the_backward_euler_history_on_every_envelope(monkeypatch, electronic37, envelopes, + allowlisted, unflipped): + for name, (initial, protocol, options) in envelopes.items(): + call = dict(options=options, initial_options=SteadyOptions()) + default = solve_transient(electronic37, initial, protocol, **call) + explicit = solve_transient(electronic37, initial, protocol, method=BACKWARD_EULER, **call) + with time_method_scope(BACKWARD_EULER): + scoped = solve_transient(electronic37, initial, protocol, **call) + monkeypatch.setenv(ENVIRONMENT, BACKWARD_EULER) + process = solve_transient(electronic37, initial, protocol, **call) + monkeypatch.delenv(ENVIRONMENT) + assert type(default) is TransientResult1D and default.completed, name + assert words(default) == words(explicit) == words(scoped) == words(process), name + + +def assert_frozen_bdf(result, name, source): + assert type(result) is BDFResult and result.completed, (name, result.termination, result.error) + controls_ = result.controls + assert {key: controls_[key] for key in PROFILE if key not in {"max_steps", "wall_s"}} == { + key: value for key, value in PROFILE.items() if key not in {"max_steps", "wall_s"}} + # The forwarded adaptive work cap and the separate sample-interval admission (RV2-C2). + assert controls_["max_steps"] == controls_["adapter_adaptive_max_steps"] == ADAPTIVE_MAX_STEPS == 10000 + assert controls_["adapter_sample_interval_limit"] == 32 and controls_["max_attempts"] == 20000 + assert controls_["max_consecutive_rejections"] == 12 and 0 < controls_["wall_s"] <= 30.0 + record = controls_["time_method"] + assert (record["requested"], record["source"], record["effective"], record["scope"]) == ( + None if source == "default" else BDF, source, BDF, name) + assert record["profile"] == dict(PROFILE) and record["profile_sha256"] == PROFILE_SHA256 + assert record["adaptive_max_steps"] == 10000 and record["qualification"] is False + + +def test_explicit_bdf_runs_the_frozen_profile_with_the_forwarded_cap(monkeypatch, electronic37, envelopes, + allowlisted): + for name, (initial, protocol, options) in envelopes.items(): + call = dict(options=options, initial_options=SteadyOptions()) + argument = solve_transient(electronic37, initial, protocol, method=BDF, **call) + assert_frozen_bdf(argument, name, "argument") + if name in {"E_saved_packet", "E_dark_voltage_ramp"}: + with time_method_scope(BDF): + scoped = solve_transient(electronic37, initial, protocol, **call) + monkeypatch.setenv(ENVIRONMENT, BDF) + process = solve_transient(electronic37, initial, protocol, **call) + monkeypatch.delenv(ENVIRONMENT) + assert_frozen_bdf(scoped, name, "scope") + assert_frozen_bdf(process, name, "environment") + exact = solve_transient(electronic37, initial, protocol, method=BDF, bdf_options=BDFOptions(**PROFILE), + bdf_drive=BDFDrive.from_protocol(protocol), **call) + # BDF runs the assembled equations by default (A3) and the original ones on the LEGACY opt-out. + with equation_implementation(LEGACY), counted() as original: + legacy = solve_transient(electronic37, initial, protocol, method=BDF, **call) + with equation_implementation(ASSEMBLED), counted() as assembled: + forced = solve_transient(electronic37, initial, protocol, method=BDF, **call) + assert original.original > 0 and original.assembled == 0, name + assert assembled.original == 0 and assembled.assembled > 0, name + assert words(argument) == words(scoped) == words(process) == words(exact) == words(legacy) == words( + forced), name + + +@pytest.mark.platform_bound +def test_production_bdf_reproduces_the_reviewed_readiness_history(electronic37, envelopes): + """E_saved_packet through solve_transient is the ReadinessV2 history (cap 10000), word for word.""" + capture_guard() + packet = _decode(_loads(gzip.decompress(SAVED_PACKET.read_bytes()))) + initial, protocol, options = envelopes["E_saved_packet"] + result = solve_transient(electronic37, initial, protocol, options=options, initial_options=SteadyOptions(), + method=BDF) + history = _decode(_loads(json.dumps(bdf_results._encode(result)).encode())) + saved = packet["result"] + assert packet["BDF_options"] == dict(PROFILE) + for name in ("accepted_times_s", "accepted_coordinates", "attempts", "samples", "restarts", "nonlinear_calls", + "evaluation_counts", "completed", "termination", "requested_output_times_s"): + assert words(history[name]) == words(saved[name]), name + path_bound = {"compiled_identity", "time_method", "initial_admission_wall_s", "wall_s"} + assert ({key: value for key, value in history["controls"].items() if key not in path_bound | {"initial_controls"}} + .keys() == {key for key in saved["controls"] if key not in path_bound | {"initial_controls"}}) + for key in saved["controls"]: + if key not in path_bound: + assert words(history["controls"][key]) == words(saved["controls"][key]), key + + +def ionic_case(tmp_path, device=None): + if device is None: + device = compile_ionic_device_1d(prepare_single_ion_device(diffusion_only=True), intervals_per_layer=12) + admission = ionic_steady_controls(device.ion_node_count) + point = solve_ionic_steady_state(device, voltage_V=.002, generation_scale=0.0, options=admission) + raw = (json.dumps(json_value({"summary": {"accepted": True, "compiled_identity": device.identity, + "voltage_V": .002, "generation_scale": 0.0}, "result": point}), allow_nan=False) + "\n").encode() + path = tmp_path / "Steady.json" + path.write_bytes(raw) + initial = load_ionic_steady_initial(device, path, hashlib.sha256(raw).hexdigest(), controls=admission) + times = np.linspace(0.0, 1.0, 5) + return device, initial, TransientProtocol(times, .002 + .002 * times, np.zeros(5)) + + +def test_unlisted_scopes_custom_profiles_and_assembled_bdf_are_refused(monkeypatch, tmp_path, electronic37, + envelopes, allowlisted): + initial, protocol, options = envelopes["E_light_ramp_4"] + call = dict(options=options, initial_options=SteadyOptions()) + nudged = protocol.generation_scale.copy() + nudged[-1] = np.nextafter(nudged[-1], 2.0) + jump = BDFDrive(protocol.times_s, np.column_stack((protocol.voltage_V, protocol.generation_scale)), + np.column_stack((protocol.voltage_V, nudged))) + other_device = compile_device_1d(load_device(), intervals_per_layer=8) + other_initial = solve_steady_state(other_device, voltage_V=0.0, generation_scale=1.0, options=SteadyOptions()) + moved = initial.state.u.copy() + moved[electronic37.node_count] = np.nextafter(moved[electronic37.node_count], np.inf) + other_state = replace(initial, state=electronic37.state(moved, voltage_V=initial.voltage_V)) + unlisted = { + "one-ulp source word": lambda: solve_transient(electronic37, initial, replace(protocol, generation_scale=nudged), + method=BDF, **call), + "physical control": lambda: solve_transient(electronic37, initial, protocol, method=BDF, + options=replace(options, max_steps=31), initial_options=SteadyOptions()), + "initial control": lambda: solve_transient(electronic37, initial, protocol, method=BDF, options=options, + initial_options=replace(SteadyOptions(), max_iterations=99)), + "other device": lambda: solve_transient(other_device, other_initial, protocol, method=BDF, **call), + "one-ulp initial word": lambda: solve_transient(electronic37, other_state, protocol, method=BDF, **call), + } + with no_numerical_work(monkeypatch): + for reason, run in unlisted.items(): + with pytest.raises(ValueError, match="only the 10 allowlisted electronic envelopes"): + run() + with time_method_scope(BDF), pytest.raises(ValueError, match="only the 10 allowlisted"): + run() + for custom in (BDFOptions(1e-7), replace(BDFOptions(**PROFILE), relative_tolerance=1e-4)): + with pytest.raises(ValueError, match="only the frozen profile 92396791"): + solve_transient(electronic37, initial, protocol, method=BDF, bdf_options=custom, **call) + # An unknown equation selection is refused before the time-method scope is computed. + for request in (lambda: solve_transient(electronic37, initial, protocol, method=BDF, **call), + lambda: run_transient_for_publication(electronic37, initial, protocol, method=BDF, **call)): + monkeypatch.setenv("NEWCORE_EQUATIONS", "unknown") + with pytest.raises(ValueError, match="unknown equation implementation"): + request() + monkeypatch.delenv("NEWCORE_EQUATIONS") + with pytest.raises(ValueError, match="protocol's own continuous drive"): + solve_transient(electronic37, initial, protocol, method=BDF, bdf_drive=jump, **call) + with pytest.raises(ValueError, match="explicit bdf time-method request"): + solve_transient(electronic37, initial, protocol, bdf_options=BDFOptions(**PROFILE), **call) + with pytest.raises(ValueError, match="explicit bdf time-method request"): + solve_transient(electronic37, initial, protocol, method=BACKWARD_EULER, bdf_drive=jump, **call) + device, ionic_initial, ionic_protocol = ionic_case(tmp_path) + with no_numerical_work(monkeypatch): + with pytest.raises(ValueError, match="only the 10 allowlisted"): + solve_ionic_transient(device, ionic_initial, ionic_protocol, options=ionic_controls(), method=BDF) + for implementation in (ASSEMBLED, LEGACY): + with time_method_scope(BDF), equation_implementation(implementation), pytest.raises( + ValueError, match="only the 10 allowlisted"): + solve_ionic_transient(device, ionic_initial, ionic_protocol, options=ionic_controls()) + from solarlab.experiments.multiple_ionic_transient import solve_multiple_ionic_transient + + with time_method_scope(BDF), pytest.raises(ValueError, match="no BDF adapter"): + solve_multiple_ionic_transient(None, None, None, options=None) + + +class InteriorDrive(BDFDrive): + """Science's D1 reproducer: the protocol's own arrays, another waveform between the knots.""" + + def values(self, t, side="right"): + voltage, light = super().values(t, side) + return voltage, light + 0.1 + + +@dataclass(frozen=True) +class LookAlikeDrive: + times_s: np.ndarray + left_values: np.ndarray + right_values: np.ndarray + + +def test_admission_trusts_no_caller_drive_family_or_digest(monkeypatch, tmp_path, electronic37, envelopes, allowlisted): + """D1 and D2 at every production entry point: each is refused explicitly before numerical work, never run as BE. + + The drive is the protocol's own: a subclass with equal arrays and its own values(), an equal drive carrying + a method of its own, an equal look-alike of another type and a replaced from_protocol are refused. The + family is the compiled device's exact class, and no entry point takes a scope digest. + """ + from solarlab.equations.dc_1d import CompiledDevice1D + + initial, protocol, options = envelopes["E_saved_packet"] + call = dict(options=options, initial_options=SteadyOptions()) + values = np.column_stack((protocol.voltage_V, protocol.generation_scale)) + carried = BDFDrive.from_protocol(protocol) + object.__setattr__(carried, "values", lambda t, side="right": (0.0, 1.1)) + drives = {"subclass with its own values()": InteriorDrive(protocol.times_s, values, values), + "equal drive carrying a method": carried, + "equal arrays, another type": LookAlikeDrive(protocol.times_s, values, values)} + entries = { + "solve_transient": lambda **kw: solve_transient(electronic37, initial, protocol, **call, **kw), + "run_transient_for_publication": lambda **kw: run_transient_for_publication(electronic37, initial, protocol, + **call, **kw), + "run_production_bdf_for_publication": lambda **kw: bdf_results.run_production_bdf_for_publication( + electronic37, initial, protocol, **call, **kw), + } + with no_numerical_work(monkeypatch): + for entry, run in entries.items(): + for reason, drive in drives.items(): + with pytest.raises(ValueError, match="protocol's own continuous drive"): + run(method=BDF, bdf_drive=drive) + with time_method_scope(BDF), pytest.raises(ValueError, match="protocol's own continuous drive"): + run(bdf_drive=drive) + with pytest.raises(ValueError, match="explicit bdf time-method request"): + run(bdf_drive=drive) + for mode in ("explicit", "flipped default"): + with monkeypatch.context() as patch: + patch.setattr(BDFDrive, "from_protocol", + classmethod(lambda cls, p: InteriorDrive(p.times_s, values, values))) + if mode == "explicit": + with pytest.raises(ValueError, match="not its own continuous knots"): + run(method=BDF) + else: + patch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + with pytest.raises(ValueError, match="not its own continuous knots"): + run() + # D2: the family is the device's exact class; a device of another family or a subclass is refused. + device, ionic_initial, ionic_protocol = ionic_case(tmp_path) + with pytest.raises(ValueError, match="not of the ionic_1d family"): + solve_ionic_transient(electronic37, initial, protocol, options=ionic_controls(), method=BDF) + with pytest.raises(ValueError, match="not of the electronic_1d family"): + solve_transient(device, ionic_initial, ionic_protocol, options=options, initial_options=SteadyOptions(), + method=BDF) + + class WidenedDevice(CompiledDevice1D): + pass + + widened = object.__new__(WidenedDevice) + widened.__dict__.update(vars(electronic37)) + for run in (lambda: solve_transient(widened, initial, protocol, method=BDF, **call), + lambda: bdf_results.run_production_bdf_for_publication(widened, initial, protocol, method=BDF, + **call)): + with pytest.raises(ValueError, match="not of a supported family|not of the electronic_1d family"): + run() + # The scope words come from the actual call: a device whose derived geometry is not its own has none. + stale = replace(electronic37.geometry) + object.__setattr__(stale, "extent_m", stale.extent_m * 2) + bent = replace(electronic37) + object.__setattr__(bent, "geometry", stale) + with pytest.raises(ValueError, match="scope cannot be computed.*not derived"): + solve_transient(bent, initial, protocol, method=BDF, **call) + with pytest.raises(TypeError): + time_method.resolve_time_method(time_method.IONIC, method=BDF, scope=lambda: allowlisted["E_saved_packet"]) + + +class IntegratorReached(BaseException): + """Raised by the integrator spy: the gate admitted the call; no step was taken.""" + + +def production_routes(electronic37, initial, protocol, call): + """The three production BDF routes, each with an explicit bdf request.""" + from support.provenance import checked_provenance_owner + + def owned(run): + def route(): + with checked_provenance_owner(): + return run() + return route + + return { + "solve_transient": lambda: solve_transient(electronic37, initial, protocol, method=BDF, **call), + "run_production_bdf_for_publication": owned(lambda: bdf_results.run_production_bdf_for_publication( + electronic37, initial, protocol, method=BDF, **call)), + "run_transient_for_publication": owned(lambda: run_transient_for_publication( + electronic37, initial, protocol, method=BDF, **call)), + } + + +def test_admission_keys_what_runs_and_runs_what_it_keyed(monkeypatch, electronic37, allowlisted): + """D1b: the integrator receives exactly the inputs admission keyed, or the call is refused before it. + + Science's reproducer (probe_constructor_mutation.py): a replaced BDFDrive.from_protocol changes the generation + of the protocol it is handed after keying, and returns the exact drive of the changed protocol. Here it is + refused at every production route. A variant changes the caller's protocol, initial state and options while + admission runs, which cannot reach the integrator. A change to the inputs that the adapter prepares, which lasts + until its last check, is refused there. The integrator is a spy: no step runs. + """ + from solarlab.experiments import bdf as bdf_backend + from solarlab.solvers.time.bdf_1d import BDFDrive + + initial, protocol, options = owned_envelope(electronic37) + call = dict(options=options, initial_options=SteadyOptions()) + keyed = {"u": initial.state.u.tobytes(), "generation": protocol.generation_scale.tobytes(), + "max_steps": options.max_steps, "budget": options.newton_budget} + midpoint = float(protocol.times_s[1] / 2) + seen = [] + + def spy(factory, start, span, **kwargs): + problem = factory(midpoint, "right").problem + seen.append({"generation": problem.generation_scale, "start": start.tobytes(), + "budget": kwargs["settings"](None).budget}) + raise IntegratorReached() + + mutate_caller, restore_caller = caller_changes(electronic37, initial, protocol, options) + monkeypatch.setattr(bdf_backend, "solve_bdf", spy) + for route, run in production_routes(electronic37, initial, protocol, call).items(): + # Science's attack: the replaced constructor changes the protocol it is handed, after keying. + def changes_its_argument(cls, p): + changed = p.generation_scale.copy() + changed[1] += 0.1 + object.__setattr__(p, "generation_scale", TransientProtocol(p.times_s, p.voltage_V, changed).generation_scale) + values = np.column_stack((p.voltage_V, p.generation_scale)) + return cls(p.times_s, values, values) + + with monkeypatch.context() as patch: + patch.setattr(BDFDrive, "from_protocol", classmethod(changes_its_argument)) + with pytest.raises(ValueError, match="not its own continuous knots"): + run() + assert protocol.generation_scale.tobytes() == keyed["generation"] and not seen, route + + # The caller's own objects change while admission runs: the integrator still receives the keyed words. + def mutates_the_caller(cls, p): + mutate_caller() + values = np.column_stack((p.voltage_V, p.generation_scale)) + return cls(p.times_s, values, values) + + with monkeypatch.context() as patch: + patch.setattr(BDFDrive, "from_protocol", classmethod(mutates_the_caller)) + with pytest.raises(IntegratorReached): + run() + restore_caller() + observed = seen.pop() + assert observed["generation"] == 0.0 and observed["start"] == keyed["u"], route + assert observed["budget"] == keyed["budget"] and observed["budget"].max_iterations > 1, route + + # A change to the inputs the adapter prepares that lasts until its last check: refused there. + verify_point = bdf_backend._verify_point + + def swaps_the_built_initial(compiled, point, generation, controls): + verify_point(compiled, point, generation, controls) + moved = point.state.u.copy() + moved[compiled.node_count] = np.nextafter(moved[compiled.node_count], np.inf) + object.__setattr__(point, "state", compiled.state(moved, voltage_V=point.voltage_V)) + + with monkeypatch.context() as patch: + patch.setattr(bdf_backend, "_verify_point", swaps_the_built_initial) + with pytest.raises(ValueError, match="inputs handed to the integrator are not the admitted ones"): + run() + assert not seen, route + + # Science's attack under the flipped default (a default request on the allowlisted envelope): refused too. + def changes_its_argument(cls, p): + changed = p.generation_scale.copy() + changed[1] += 0.1 + object.__setattr__(p, "generation_scale", TransientProtocol(p.times_s, p.voltage_V, changed).generation_scale) + values = np.column_stack((p.voltage_V, p.generation_scale)) + return cls(p.times_s, values, values) + + with monkeypatch.context() as patch: + patch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + patch.setattr(BDFDrive, "from_protocol", classmethod(changes_its_argument)) + for run in (lambda: solve_transient(electronic37, initial, protocol, **call), + lambda: bdf_results.run_production_bdf_for_publication(electronic37, initial, protocol, **call)): + with pytest.raises(ValueError, match="not its own continuous knots"): + run() + assert protocol.generation_scale.tobytes() == keyed["generation"] and not seen + # A caller object that changes between keying and its record is a divergence, refused under either request. + record = time_method._record + + def changes_before_its_record(value): + if value is protocol: + mutate_caller() + return record(value) + + for request in (BDF, None): + with monkeypatch.context() as patch: + patch.setattr(time_method, "_record", changes_before_its_record) + if request is None: + patch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + with pytest.raises(ValueError, match="changed while they were admitted"): + solve_transient(electronic37, initial, protocol, method=request, **call) + restore_caller() + assert not seen + # An admission holds records with the admitted key, never an object of the caller's. + selection, admitted = time_method.admit_time_method(BDF, compiled=electronic37, initial=initial, protocol=protocol, + family=time_method.ELECTRONIC, **call) + assert admitted is not None and admitted.scope_sha256 == selection.scope_sha256 == allowlisted["E_dark_hold"] + built = [time_method._build(node) for node in admitted.inputs] + for copy, value in zip(built, (electronic37, initial, protocol, options, SteadyOptions())): + assert copy is not value and type(copy) is type(value) and time_method._same(copy, value) + assert time_method._scope_of(time_method.ELECTRONIC, *built, time_method._canonical_drive(built[2])) == ( + admitted.scope_sha256) + + +def test_a_production_capture_takes_one_admission_and_its_own_selection(monkeypatch, electronic37, allowlisted): + """D1-R1: capture_admitted_bdf, the single-admission capture, refuses a selection that is not its admission's.""" + from dataclasses import replace as rebuilt + + initial, protocol, options = owned_envelope(electronic37) + call = dict(options=options, initial_options=SteadyOptions()) + selection, admitted = time_method.admit_time_method(BDF, compiled=electronic37, initial=initial, protocol=protocol, + family=time_method.ELECTRONIC, **call) + light_initial, light_protocol, light_options = envelope(electronic37, sources()["E_light_hold"]) + other, _ = time_method.admit_time_method(BDF, compiled=electronic37, initial=light_initial, protocol=light_protocol, + options=light_options, initial_options=SteadyOptions(), + family=time_method.ELECTRONIC) + assert other.scope == "E_light_hold" and other.scope_sha256 != selection.scope_sha256 + backward = time_method.resolve_time_method(BACKWARD_EULER, compiled=electronic37, family=time_method.ELECTRONIC) + with no_numerical_work(monkeypatch): + for wrong in (other, rebuilt(selection, scope_sha256=other.scope_sha256), rebuilt(selection, scope="E_light_hold"), + rebuilt(selection, family=time_method.IONIC), backward, selection.record()): + with pytest.raises(ValueError, match="selection"): + bdf_results.capture_admitted_bdf(wrong, admitted) + with pytest.raises(ValueError, match="not an admission of a production BDF call"): + bdf_results.capture_admitted_bdf(selection, tuple(admitted)) + + +def owned_envelope(electronic37): + """E_dark_hold with protocol, initial state and controls of the caller's own, which the tests change.""" + initial, protocol, options = envelope(electronic37, sources()["E_dark_hold"]) + return replace(initial), replace(protocol), replace(options, newton_budget=replace(options.newton_budget)) + + +def caller_changes(electronic37, initial, protocol, options, drive=None): + """Change, and restore, every field of the caller's objects that the recheck changed (Cnd2D1D2RecheckV2).""" + saved = [(protocol, "generation_scale", protocol.generation_scale), (initial, "state", initial.state), + (options, "max_steps", options.max_steps), + (options.newton_budget, "max_iterations", options.newton_budget.max_iterations)] + if drive is not None: + saved += [(drive, "left_values", drive.left_values), (drive, "right_values", drive.right_values)] + + def mutate(): + changed = protocol.generation_scale.copy() + changed[1] += 0.1 + object.__setattr__(protocol, "generation_scale", TransientProtocol( + protocol.times_s, protocol.voltage_V, changed).generation_scale) + moved = initial.state.u.copy() + moved[electronic37.node_count] = np.nextafter(moved[electronic37.node_count], np.inf) + object.__setattr__(initial, "state", electronic37.state(moved, voltage_V=initial.voltage_V)) + object.__setattr__(options, "max_steps", 31) + object.__setattr__(options.newton_budget, "max_iterations", options.newton_budget.max_iterations + 1) + if drive is not None: + values = np.column_stack((protocol.voltage_V, protocol.generation_scale)) + object.__setattr__(drive, "left_values", BDFDrive(protocol.times_s, values, values).left_values) + object.__setattr__(drive, "right_values", BDFDrive(protocol.times_s, values, values).right_values) + + def restore(): + for target, name, value in saved: + object.__setattr__(target, name, value) + + return mutate, restore + + +class Recast(tuple): + """A layout-compatible tuple class: what rebinding an admission's class would give it.""" + + __slots__ = () + + +@pytest.mark.parametrize("request_source", ["argument", "scope", "environment", "default"]) +@pytest.mark.parametrize("route", ["solve_transient", "run_production_bdf_for_publication", + "run_transient_for_publication"]) +@pytest.mark.parametrize("condition", ["profile", "trace", "monitoring", "gc", "numpy", "signal", "thread"]) +def test_interface_trust_admits_monitoring_profilers_callbacks_and_worker_threads( + monkeypatch, electronic37, allowlisted, route, request_source, condition): + """2026-11-02 interface_level_trust_standard_v1: monitoring, profilers, callbacks and worker threads are trusted.""" + import gc + import signal + import sys + import threading + + from support.provenance import checked_provenance_owner + + initial, protocol, options = owned_envelope(electronic37) + call = dict(options=options, initial_options=SteadyOptions()) + expected_u = initial.state.u.tobytes() + entry = {"solve_transient": solve_transient, "run_transient_for_publication": run_transient_for_publication, + "run_production_bdf_for_publication": bdf_results.run_production_bdf_for_publication}[route] + if request_source == "environment": + monkeypatch.setenv(ENVIRONMENT, BDF) + elif request_source == "default": + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + observed = [] + collecting = gc.isenabled() + + def spy(factory, start, interval, **kwargs): + observed.append((start.tobytes(), kwargs["settings"](None).budget.max_iterations, + kwargs["output_times_s"].tobytes(), kwargs["options"].max_steps)) + assert gc.isenabled() is collecting + raise IntegratorReached() + + monkeypatch.setattr(bdf_backend, "solve_bdf", spy) + + def run(): + def invoke(): + if request_source == "scope": + with time_method_scope(BDF): + return entry(electronic37, initial, protocol, **call) + return entry(electronic37, initial, protocol, method=BDF if request_source == "argument" else None, **call) + + if route == "solve_transient": + return invoke() + with checked_provenance_owner(): + return invoke() + + def observer(frame, event, value): + return observer + + def callback(*args): + return None + + ready, finish = threading.Event(), threading.Event() + worker = None + previous_profile, previous_trace = sys.getprofile(), sys.gettrace() + previous_signal, previous_error = signal.getsignal(signal.SIGUSR1), np.geterrcall() + tool = 5 + if condition == "monitoring" and not hasattr(sys, "monitoring"): + pytest.skip("sys.monitoring is unavailable on Python 3.11; profile and trace routes are covered") + try: + if condition == "profile": + sys.setprofile(observer) + elif condition == "trace": + sys.settrace(observer) + elif condition == "monitoring": + sys.monitoring.use_tool_id(tool, "cnd2_input_observer") + elif condition == "gc": + gc.callbacks.append(callback) + elif condition == "numpy": + np.seterrcall(callback) + elif condition == "signal": + signal.signal(signal.SIGUSR1, callback) + elif condition == "thread": + def caller(): + ready.set() + finish.wait(10) + worker = threading.Thread(target=caller) + worker.start() + assert ready.wait(5) + with pytest.raises(IntegratorReached): + run() + assert observed == [(expected_u, options.newton_budget.max_iterations, protocol.times_s.tobytes(), 10000)] + finally: + sys.setprofile(previous_profile) + sys.settrace(previous_trace) + signal.signal(signal.SIGUSR1, previous_signal) + np.seterrcall(previous_error) + if callback in gc.callbacks: + gc.callbacks.remove(callback) + if condition == "monitoring" and hasattr(sys, "monitoring"): + sys.monitoring.free_tool_id(tool) + finish.set() + if worker is not None: + worker.join(5) + assert not worker.is_alive() + + +def test_admitted_records_are_immutable_and_a_recast_admission_refuses(monkeypatch, electronic37, allowlisted): + initial, protocol, options = owned_envelope(electronic37) + selection, admitted = time_method.admit_time_method( + BDF, compiled=electronic37, initial=initial, protocol=protocol, options=options, + initial_options=SteadyOptions()) + assert admitted is not None and admitted.scope_sha256 == selection.scope_sha256 + for name in AdmittedBDFCall._fields + ("cache",): + with pytest.raises(AttributeError): + object.__setattr__(admitted, name, None) + admitted.__class__ = Recast + with no_numerical_work(monkeypatch), pytest.raises(ValueError, match="not an admission"): + time_method.integrate_admitted(admitted, bdf_backend.solve_electronic_bdf) + + +@pytest.mark.parametrize("name", list(sources())) +def test_canonical_bdf_admission_with_real_supervisor_helper( + name, monkeypatch, tmp_path, electronic37, envelopes, allowlisted): + """Ordinary product helper threads and SQLite trace callbacks remain admitted without pausing GC.""" + import gc + import sys + + from solarlab.experiments.execution import ProcessSupervisor + from solarlab.experiments.transient_worker import transient_worker_binding + + initial, protocol, options = envelopes[name] + expected = initial.state.u.tobytes() + observed = [] + collecting = gc.isenabled() + + def recording(factory, start, interval, **kwargs): + observed.append((start.tobytes(), kwargs["settings"](None).budget.max_iterations, + kwargs["output_times_s"].tobytes(), kwargs["options"].max_steps)) + assert gc.isenabled() is collecting + raise IntegratorReached() + + monkeypatch.setattr(bdf_backend, "solve_bdf", recording) + with RunStore(tmp_path / "store") as store, ProcessSupervisor( + store, tmp_path / "work", (transient_worker_binding(),), max_active=1, max_pending=1, + shared_rss_bytes=3 * 1024**3, shared_output_bytes=384 * 1024**2) as supervisor: + assert supervisor._thread is not None and supervisor._thread.is_alive() + frames = sys._current_frames() + assert supervisor._thread.ident in frames + store._db.set_trace_callback(lambda statement: None) + try: + with pytest.raises(IntegratorReached): + solve_transient(electronic37, initial, protocol, options=options, + initial_options=SteadyOptions(), method=BDF) + finally: + store._db.set_trace_callback(None) + assert gc.isenabled() is collecting + assert observed == [(expected, options.newton_budget.max_iterations, protocol.times_s.tobytes(), 10000)] + + +def test_the_flip_point_defaults_only_allowlisted_envelopes_to_bdf(monkeypatch, tmp_path, electronic37, envelopes, + allowlisted): + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + initial, protocol, options = envelopes["E_saved_packet"] + call = dict(options=options, initial_options=SteadyOptions()) + default = solve_transient(electronic37, initial, protocol, **call) + assert_frozen_bdf(default, "E_saved_packet", "default") + assert words(default) == words(solve_transient(electronic37, initial, protocol, method=BDF, **call)) + for opt_out in (lambda: solve_transient(electronic37, initial, protocol, method=BACKWARD_EULER, **call), + lambda: run_transient_for_publication(electronic37, initial, protocol, method=BACKWARD_EULER, + **call).result): + assert type(opt_out()) is TransientResult1D + light = protocol.generation_scale.copy() + light[-1] *= 1.0001 + unlisted = replace(protocol, generation_scale=light) + kept = solve_transient(electronic37, initial, unlisted, **call) + assert type(kept) is TransientResult1D and kept.completed + assert words(kept) == words(solve_transient(electronic37, initial, unlisted, method=BACKWARD_EULER, **call)) + device, ionic_initial, ionic_protocol = ionic_case(tmp_path) + assert solve_ionic_transient(device, ionic_initial, ionic_protocol, options=ionic_controls()).completed + # The flipped default on either equation implementation: the same BDF history. + for implementation in (ASSEMBLED, LEGACY): + with equation_implementation(implementation): + assert words(solve_transient(electronic37, initial, protocol, **call)) == words(default), implementation + + +def test_the_ionic_production_branch_forwards_the_work_cap_past_the_old_clip(monkeypatch, tmp_path): + """RV2-C2 on ReadinessV2's ionic_single13 envelope, admitted by an injected test allowlist entry. + + No ionic scope is allowlisted: without the entry the request is refused. With it, the production caller + runs the frozen profile with the forwarded cap of 10000 beside the sample-interval admission of 16. The + adapter with the cap omitted keeps its old clipping and exhausts it at 16 accepted steps, as ReadinessV1 + recorded (G3). + """ + from solarlab.equations.time_method import ionic_scope + from solarlab.experiments.bdf import solve_ionic_bdf + + device, initial, protocol = ionic_case(tmp_path) + physical = ionic_controls() + with pytest.raises(ValueError, match="only the 10 allowlisted"): + solve_ionic_transient(device, initial, protocol, options=physical, method=BDF) + monkeypatch.setattr(time_method, "ALLOWLIST", + {ionic_scope(device, initial, protocol, options=physical): "test:ionic_single13"}) + result = solve_ionic_transient(device, initial, protocol, options=physical, method=BDF) + assert type(result) is BDFResult and result.completed, (result.termination, result.error) + assert len(result.accepted_steps) > physical.electronic.max_steps == 16 + assert result.controls["max_steps"] == result.controls["adapter_adaptive_max_steps"] == ADAPTIVE_MAX_STEPS + assert result.controls["adapter_sample_interval_limit"] == 16 + assert {key: result.controls[key] for key in PROFILE if key not in {"max_steps", "wall_s"}} == { + key: value for key, value in PROFILE.items() if key not in {"max_steps", "wall_s"}} + record = result.controls["time_method"] + assert (record["family"], record["scope"], record["adaptive_max_steps"]) == ("ionic_1d", "test:ionic_single13", 10000) + with equation_implementation(LEGACY): + clipped = solve_ionic_bdf(device, initial, protocol, options=physical, bdf_options=BDFOptions(**PROFILE)) + assert (clipped.termination, len(clipped.accepted_steps), clipped.controls["max_steps"]) == ( + "step_budget_exhausted", 16, 16) + assert words(result.accepted_coordinates[:17]) == words(clipped.accepted_coordinates) + + +def published(store, name, capture, nodes_m): + row = store.enqueue(name, opaque_identity=capture.identity, input_metadata={"fixture": name}) + token = store.claim(name, expected_attempt_id=row["current_attempt_id"], expected_generation=row["generation"], + owner_id="test") + document = publish_transient_result(store, token, capture.result, nodes_m=nodes_m, capture=capture) + store.complete(token, state="succeeded" if capture.result.completed else "failed", result=document, + artifacts=document["artifact_ids"]) + + +def test_both_methods_publish_their_selection_and_read_back_without_a_solver(tmp_path, electronic37, envelopes, + allowlisted, unflipped): + from support.provenance import checked_provenance_owner + + initial, protocol, options = envelopes["E_saved_packet"] + call = dict(options=options, initial_options=SteadyOptions()) + with checked_provenance_owner(): + production = run_transient_for_publication(electronic37, initial, protocol, method=BDF, **call) + with checked_provenance_owner(): + research = bdf_results.run_bdf_for_publication(electronic37, initial, protocol, + bdf_options=BDFOptions(1e-7, adaptive=False, max_order=1), **call) + with checked_provenance_owner(): + default = run_transient_for_publication(electronic37, initial, protocol, **call) + assert type(default.result) is TransientResult1D + with RunStore(tmp_path / "store") as store: + for name, capture in (("production", production), ("research", research), ("default", default)): + published(store, name, capture, electronic37.nodes_m) + loaded = read_bdf_result(store, "production") + record = loaded["record"]["request"]["time_method"] + assert record == production.result.controls["time_method"] == loaded["history"]["controls"]["time_method"] + assert (record["requested"], record["source"], record["effective"], record["scope"]) == ( + BDF, "argument", BDF, "E_saved_packet") + assert record["scope_sha256"] == allowlisted["E_saved_packet"] + assert loaded["record"]["caps"] == {"requested_max_steps": 10000, "physical_max_steps": 32, + "effective_max_steps": 10000, "effective_max_attempts": 20000} + assert loaded["summary"]["completed"] and loaded["requested_end_state"] is not None + assert read_transient_result(store, "production")["summary"] == loaded["summary"] + explicit = read_bdf_result(store, "research")["record"]["request"]["time_method"] + assert (explicit["source"], explicit["scope"], explicit["profile"], explicit["adaptive_max_steps"]) == ( + "research_capture", None, None, None) + saved = read_transient_result(store, "default") + assert saved["provenance"]["description"]["time_method"] == { + "schema": "solarlab.time-method-selection.v1", "family": "electronic_1d", "requested": None, + "source": "default", "effective": BACKWARD_EULER, "allowlisted_default": [BACKWARD_EULER, None]} + body = _decode(_loads(production.history_bytes)) + assert _validate_body(body) == loaded["summary"] + for change in ("history_record", "scope", "profile", "cap", "research_claims_scope"): + changed = _decode(_loads(production.history_bytes)) + request, history = changed["request"], changed["history"] + if change == "history_record": + del history["controls"]["time_method"] + elif change == "scope": + request["time_method"] = history["controls"]["time_method"] = {**request["time_method"], "scope": None} + elif change == "profile": + request["time_method"] = history["controls"]["time_method"] = { + **request["time_method"], "profile": {**PROFILE, "relative_tolerance": 1e-4}} + elif change == "cap": + history["controls"]["adapter_adaptive_max_steps"] = 32 + else: + request["time_method"] = history["controls"]["time_method"] = { + **request["time_method"], "source": "research_capture"} + with pytest.raises(ValueError, match="time-method|frozen profile|research BDF capture"): + _validate_body(changed) + assert _digest(body) == _digest(_decode(_loads(production.history_bytes))) diff --git a/tests/integration/test_transient_1d.py b/tests/integration/test_transient_1d.py index ea9a4b03..95f5be4f 100644 --- a/tests/integration/test_transient_1d.py +++ b/tests/integration/test_transient_1d.py @@ -206,8 +206,9 @@ def test_generation_predictor_is_explicit_and_does_not_modify_old_state(case): @pytest.fixture(scope="module") def refinements(case): device, point, initial_controls = case - return tuple(solve_transient(device, point, protocol(n), options=controls(), initial_options=initial_controls) - for n in (4, 8, 16)) + # These are backward-Euler histories; the light ramps are allowlisted BDF envelopes, so opt out explicitly. + return tuple(solve_transient(device, point, protocol(n), options=controls(), initial_options=initial_controls, + method="backward_euler") for n in (4, 8, 16)) def test_real_37_node_time_refinement_and_maxwell_accounting(case, refinements): diff --git a/tests/integration/test_transient_results.py b/tests/integration/test_transient_results.py index a3526132..96b77c1a 100644 --- a/tests/integration/test_transient_results.py +++ b/tests/integration/test_transient_results.py @@ -90,8 +90,9 @@ def saved(tmp_path_factory): with RunStore(root / "store") as store: for name, protocol, options in cases: with checked_provenance_owner(): + # Backward-Euler publications; "completed" is the allowlisted saved-packet envelope. capture = run_transient_for_publication(compiled, initial, protocol, - options=options, initial_options=initial_controls) + options=options, initial_options=initial_controls, method="backward_euler") result = capture.result assert result.completed == (name == "completed") source_words = expected(result, compiled.nodes_m) diff --git a/tests/integration/test_transient_voltage_1d.py b/tests/integration/test_transient_voltage_1d.py index 727dd14a..e0f8a421 100644 --- a/tests/integration/test_transient_voltage_1d.py +++ b/tests/integration/test_transient_voltage_1d.py @@ -122,8 +122,9 @@ def test_variable_bias_jacobian_is_the_new_endpoint_analytic_jacobian(case): @pytest.fixture(scope="module") def runs(case): device, point, initial_options = case - return tuple(solve_transient(device, point, voltage_protocol(n), options=controls(), initial_options=initial_options) - for n in (4, 8, 16)) + # These are backward-Euler histories; the voltage ramps are allowlisted BDF envelopes, so opt out explicitly. + return tuple(solve_transient(device, point, voltage_protocol(n), options=controls(), initial_options=initial_options, + method="backward_euler") for n in (4, 8, 16)) def test_real_variable_bias_histories_and_maxwell_refinement(case, runs): diff --git a/tests/runtime/test_worker_time_method.py b/tests/runtime/test_worker_time_method.py new file mode 100644 index 00000000..eb3d00c1 --- /dev/null +++ b/tests/runtime/test_worker_time_method.py @@ -0,0 +1,162 @@ +"""Process and HTTP transient workers carry their parent's time-method request (CND2). + +Preparation records the parent's request among the execution manifest's +child settings: ``NEWCORE_TIME_METHOD`` is unset for the default and +``backward_euler`` for the explicit opt-out. It is part of the execution +identity; the input and physics identities are unchanged. The spawned child +installs the setting before any engine import, refuses a request that +differs, and records its selection in the saved worker result. No worker +scope is allowlisted, because a worker's initial state is a cold recipe. A +``bdf`` request is therefore refused while the job is prepared, through the +process and HTTP routes alike. A worker never integrates with BDF, and BDF is +never run as backward Euler. The saved arrays are the same words under the +default and the explicit opt-out. +""" + +from __future__ import annotations + +import json +from pathlib import Path +import subprocess +from typing import Any + +import pytest + +from solarlab.equations import time_method +from solarlab.equations.time_method import BACKWARD_EULER, BDF, ENVIRONMENT +from solarlab.experiments.execution import ProcessSupervisor +from solarlab.experiments.worker import ResourceLimits +from solarlab.io.run_store import RunStore + +pytestmark = pytest.mark.requires_clean_core + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.fixture(scope="module") +def commit() -> str: + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True, timeout=5).strip() + + +@pytest.fixture(autouse=True) +def no_process_setting(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(ENVIRONMENT, raising=False) + + +def transient_job(commit: str) -> Any: + from examples.research_1d.process_transient import example_job + from examples.research_1d.service import committed_implementation + + return example_job(committed_implementation(commit), current_repository_head=commit) + + +def ionic_transient_job(commit: str) -> Any: + from examples.research_1d.process_ionic_transient import example_job, source_build + + return example_job(source_build(commit), current_repository_head=commit) + + +JOBS = {"transient": transient_job, "ionic_transient": ionic_transient_job} + + +def declared(job: Any) -> str | None: + """The request a prepared job's manifest binds for its child.""" + settings = dict(job.execution.environment) + assert dict(job.execution.execution.environment.settings)[ENVIRONMENT] == json.dumps(settings[ENVIRONMENT]) + return settings[ENVIRONMENT] + + +@pytest.mark.parametrize("family", JOBS) +def test_preparation_records_the_parents_request_and_refuses_bdf(family: str, commit: str, + monkeypatch: pytest.MonkeyPatch) -> None: + prepare = JOBS[family] + default = prepare(commit) + with time_method.time_method(BACKWARD_EULER): + scoped = prepare(commit) + monkeypatch.setenv(ENVIRONMENT, BACKWARD_EULER) + process = prepare(commit) + monkeypatch.delenv(ENVIRONMENT) + assert (declared(default), declared(scoped), declared(process)) == (None, BACKWARD_EULER, BACKWARD_EULER) + assert default.request.H_input == scoped.request.H_input and default.request.H_physics == scoped.request.H_physics + assert default.execution.manifest.execution_sha256 != scoped.execution.manifest.execution_sha256 + assert scoped.execution.manifest.execution_sha256 == process.execution.manifest.execution_sha256 + with time_method.time_method(BDF), pytest.raises(ValueError, match="not selectable for process or HTTP worker"): + prepare(commit) + monkeypatch.setenv(ENVIRONMENT, BDF) + with pytest.raises(ValueError, match="not selectable for process or HTTP worker"): + prepare(commit) + monkeypatch.setenv(ENVIRONMENT, "Bdf") + with pytest.raises(ValueError, match="unknown time method"): + prepare(commit) + # Flipped, the default still forwards no request and the worker still integrates with backward Euler. + monkeypatch.delenv(ENVIRONMENT) + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + assert declared(prepare(commit)) is None + + +def test_the_http_transient_route_refuses_a_bdf_request_before_enqueueing(tmp_path: Path, commit: str, + monkeypatch: pytest.MonkeyPatch) -> None: + from fastapi.testclient import TestClient + + from examples.research_1d.service import committed_implementation + from examples.research_1d.transient_service import example_submission, installed_catalog + from solarlab_server.app import create_app + from solarlab_server.job_service import JobService + + catalog = installed_catalog(committed_implementation(commit), commit) + with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work", catalog=catalog) as supervisor: + with TestClient(create_app(store.root, job_service=JobService(catalog, supervisor))) as client: + advertised = client.get("/experiments") + headers = {name: advertised.headers[name] for name in ("x-solarlab-registry", "x-solarlab-job-schema")} + monkeypatch.setenv(ENVIRONMENT, BDF) + refused = client.post("/jobs", json=example_submission("http-bdf"), headers=headers) + assert refused.status_code == 422, refused.text + assert "not selectable for process or HTTP worker" in refused.text + assert store.events() == [] + + +def pool(store: RunStore, work: Path, *, catalog: Any = None) -> ProcessSupervisor: + from solarlab.experiments.ionic_transient_worker import ionic_transient_worker_binding + from solarlab.experiments.transient_worker import transient_worker_binding + + bindings = (transient_worker_binding(), ionic_transient_worker_binding()) if catalog is None else catalog.worker_bindings() + return ProcessSupervisor(store, work, bindings, max_active=1, max_pending=4, + shared_rss_bytes=3 * 1024**3, shared_output_bytes=384 * 1024**2, + poll_seconds=0.02, soft_grace_seconds=0.2, terminate_grace_seconds=0.2) + + +def test_spawned_workers_run_and_record_their_prepared_request(commit: str, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + from solarlab.experiments.ionic_transient_worker import read_ionic_transient_job + from solarlab.experiments.transient_worker import read_transient_job + + jobs = {} + for family, prepare in JOBS.items(): + jobs[family + "-default"] = prepare(commit) + with time_method.time_method(BACKWARD_EULER): + jobs[family + "-opt-out"] = prepare(commit) + limits = ResourceLimits(30.0, 1536 * 1024**2, 96 * 1024**2, None, None) + readers = {"transient": read_transient_job, "ionic_transient": read_ionic_transient_job} + saved: dict[str, dict[str, bytes]] = {} + # The submitting context requests BDF: the manifest, not the submitter, decides. + with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: + with time_method.time_method(BDF): + handles = {name: job.submit(supervisor, name, limits) for name, job in jobs.items()} + for name, handle in handles.items(): + receipt = supervisor.wait(handle, 90).data + assert receipt["store_state"] == "succeeded", receipt + attempt, = store.attempts(name) + result = attempt["result"]["worker_result"] + family, _, mode = name.partition("-") + requested = None if mode == "default" else BACKWARD_EULER + assert result["time_method"] == { + "schema": "solarlab.time-method-selection.v1", "family": "electronic_1d" if family == "transient" + else "ionic_1d", "requested": requested, "source": "default" if requested is None else "environment", + "effective": BACKWARD_EULER, "allowlisted_default": list(time_method.ALLOWLISTED_DEFAULT)}, name + loaded = readers[family](store, name) + assert loaded["worker_result"]["time_method"] == result["time_method"] + records = [store.artifact(ref["artifact_id"]) for ref in attempt["terminal"]["artifacts"]] + saved[name] = {record["name"]: store.read_artifact(record["artifact_id"]) + for record in records if record["format"] == "npy"} + for family in JOBS: + assert saved[family + "-default"] and saved[family + "-default"] == saved[family + "-opt-out"] diff --git a/tests/unit/assembly/test_production_provenance.py b/tests/unit/assembly/test_production_provenance.py index 5ead96f1..170e363a 100644 --- a/tests/unit/assembly/test_production_provenance.py +++ b/tests/unit/assembly/test_production_provenance.py @@ -138,8 +138,9 @@ def test_dc_transient_publication_admits_the_implementation_that_ran(dc_device: with equation_implementation(LEGACY): initial = solve_steady_state(dc_device, voltage_V=0.0, generation_scale=1.0, options=SteadyOptions()) protocol = TransientProtocol([0, 1e-7, 2e-7], [0, 0, 0], [1, 1.0025, 1.01]) + # The backward-Euler producer; this protocol is the allowlisted saved-packet envelope, so opt out explicitly. pair(lambda: run_transient_for_publication(dc_device, initial, protocol, options=transient_controls(), - initial_options=SteadyOptions()), + initial_options=SteadyOptions(), method="backward_euler"), lambda capture: json.loads(capture.capture_json)["description"]["job_provenance"], "BackwardEuler1DStep", dc_device) diff --git a/tests/unit/solvers/time/bdf_benchmark.py b/tests/unit/solvers/time/bdf_benchmark.py index dc9d5400..514d684b 100644 --- a/tests/unit/solvers/time/bdf_benchmark.py +++ b/tests/unit/solvers/time/bdf_benchmark.py @@ -25,9 +25,11 @@ from solarlab.device.compile_1d import compile_device_1d from solarlab.device.compile_ionic_1d import compile_ionic_device_1d from solarlab.equations.dc_1d import DC1DProblem +from solarlab.equations.implementation import LEGACY, equation_implementation from solarlab.equations.ionic_1d import Ionic1DProblem +from solarlab.experiments.bdf import solve_electronic_bdf, solve_ionic_bdf from solarlab.experiments.transient import TransientProtocol, solve_transient -from solarlab.experiments.ionic_transient import load_ionic_steady_initial, solve_ionic_transient +from solarlab.experiments.ionic_transient import load_ionic_steady_initial from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state from solarlab.solvers.time.bdf import BDFOptions, solve_bdf @@ -37,6 +39,15 @@ from solarlab.solvers.nonlinear.problem import ResidualScaling, StepControl, SolveBudget, GateOutcome +def research_bdf(adapter, *args, **kwargs): + """An explicit research BDF call on the original equations, as the transient entry points ran it before CND2. + + The production entry points run only the frozen profile on allowlisted scopes (solarlab.equations.time_method). + """ + with equation_implementation(LEGACY): + return adapter(*args, **kwargs) + + def generic_controls(step): count = len(step.history[0].u) return NewtonSettings(ResidualScaling(np.ones(count)), 1e-12, @@ -146,9 +157,8 @@ def diagnostic(output): finals = [] ns = [2, 4, 8, 16, 32, 64, 128] for n in ns: - result = solve_transient(device, initial, request, options=controls, initial_options=admission, - method="bdf", bdf_options=BDFOptions(4e-7 / n, adaptive=False, max_order=2, - wall_s=90, min_step_s=1e-23), bdf_drive=drive) + result = research_bdf(solve_electronic_bdf, device, initial, request, options=controls, initial_options=admission, + bdf_options=BDFOptions(4e-7 / n, adaptive=False, max_order=2, wall_s=90, min_step_s=1e-23), drive=drive) value = ElectronicStorage1D(DC1DProblem(device, 0, 1.1)).physical_storage(result.accepted_coordinates[-1]) finals.append(value) record["runs"].append({"n": n, "final_inventory": value, "result": result}) @@ -196,9 +206,9 @@ def electronic(output): for order in (1, 2): for n in ns: requested = TransientProtocol([0.0, 4e-7], [0, 0], [1, 1.01]) - result = solve_transient(device, initial, requested, options=control, initial_options=admission, - method="bdf", bdf_options=BDFOptions(4e-7 / n, max_order=order, adaptive=False, - min_step_s=1e-23, wall_s=90), bdf_drive=drive) + result = research_bdf(solve_electronic_bdf, device, initial, requested, options=control, + initial_options=admission, bdf_options=BDFOptions(4e-7 / n, max_order=order, adaptive=False, + min_step_s=1e-23, wall_s=90), drive=drive) adapter = ElectronicStorage1D(DC1DProblem(device, 0.0, 1.01)) final = adapter.physical_storage(result.accepted_coordinates[-1]) finals[order].append(final) @@ -210,9 +220,11 @@ def electronic(output): record["fits"][str(order)] = fit(ns[:-1], differences) times = np.linspace(0, 4e-7, 5) requested = TransientProtocol(times, np.zeros(5), 1 + .01 * (times / times[-1])**2) - baseline = solve_transient(device, initial, requested, options=control, initial_options=admission) - candidate = solve_transient(device, initial, requested, options=control, initial_options=admission, - method="bdf", bdf_options=BDFOptions(1e-7, max_order=1, adaptive=False)) + # The BE baseline opts out explicitly: this light ramp is an allowlisted BDF envelope. + baseline = solve_transient(device, initial, requested, options=control, initial_options=admission, + method="backward_euler") + candidate = research_bdf(solve_electronic_bdf, device, initial, requested, options=control, + initial_options=admission, bdf_options=BDFOptions(1e-7, max_order=1, adaptive=False)) differences = [float(np.max(abs(a.u - b))) for a, b in zip(baseline.states, candidate.accepted_coordinates)] record["BE_parity"] = {"maximum_coordinate_difference": max(differences), "bitwise_coordinates": all(a.u.tobytes() == b.tobytes() for a, b in zip(baseline.states, candidate.accepted_coordinates)), @@ -246,8 +258,8 @@ def ionic(output): "steppers_verified_byte_unchanged": True} references = [] for n in (64, 128): - result = solve_ionic_transient(device, initial, sample, options=control, method="bdf", - bdf_options=BDFOptions(1 / n, adaptive=False, max_order=2, wall_s=90, min_step_s=1e-23), bdf_drive=drive) + result = research_bdf(solve_ionic_bdf, device, initial, sample, options=control, + bdf_options=BDFOptions(1 / n, adaptive=False, max_order=2, wall_s=90, min_step_s=1e-23), drive=drive) final = adapter.physical_storage(result.accepted_coordinates[-1]) references.append(final) record["references"].append({"method": "fixed BDF2", "n": n, "final_inventory": final, "result": result}) @@ -271,14 +283,14 @@ def ionic(output): if not result.completed: raise RuntimeError("first fixed BE comparison failure retained") if n == 4: - parity = solve_ionic_transient(device, initial, protocol, options=control, method="bdf", + parity = research_bdf(solve_ionic_bdf, device, initial, protocol, options=control, bdf_options=BDFOptions(.25, adaptive=False, max_order=1)) record["BE_parity"] = {"maximum_coordinate_difference": max(float(np.max(abs(a.u - b))) for a, b in zip(result.states, parity.accepted_coordinates)), "bitwise_coordinates": all(a.u.tobytes() == b.tobytes() for a, b in zip(result.states, parity.accepted_coordinates)), "candidate": parity} for tolerance in (1e-4, 1e-5, 1e-6): - result = solve_ionic_transient(device, initial, sample, options=control, method="bdf", - bdf_options=BDFOptions(.1, relative_tolerance=tolerance, max_step_s=.5, wall_s=90), bdf_drive=drive) + result = research_bdf(solve_ionic_bdf, device, initial, sample, options=control, + bdf_options=BDFOptions(.1, relative_tolerance=tolerance, max_step_s=.5, wall_s=90), drive=drive) final = adapter.physical_storage(result.accepted_coordinates[-1]) error = float(np.max(abs(final - reference) / scales)) record["work_precision"].append({"method": "adaptive BDF1/2", "error_rtol": tolerance, diff --git a/tests/unit/solvers/time/bdf_light_replay.py b/tests/unit/solvers/time/bdf_light_replay.py index ff5f6b93..7e8b37e5 100644 --- a/tests/unit/solvers/time/bdf_light_replay.py +++ b/tests/unit/solvers/time/bdf_light_replay.py @@ -22,7 +22,8 @@ from examples.research_1d.steady import load_device from examples.research_1d.transient import controls, json_value from solarlab.device.compile_1d import compile_device_1d -from solarlab.experiments.transient import solve_transient +from solarlab.equations.implementation import LEGACY, equation_implementation +from solarlab.experiments.bdf import solve_electronic_bdf from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state from solarlab.solvers.time.bdf import BDFOptions @@ -111,8 +112,10 @@ def main() -> int: json.dump(json_value(receipt), stream, indent=2, allow_nan=False) stream.write("\n") # Exactly one invocation. A failed result is saved without a retry. - result = solve_transient(device, initial, requested, options=physical, initial_options=admission, - method="bdf", bdf_options=options, bdf_drive=drive) + # An explicit research BDF call on the original equations, as solve_transient ran it before CND2. + with equation_implementation(LEGACY): + result = solve_electronic_bdf(device, initial, requested, options=physical, initial_options=admission, + bdf_options=options, drive=drive) receipt.update(result=result, new_adaptive_light_calls=1, source_pins_unchanged=source_pins() == pins, process_wall_s=time.monotonic() - started) with (args.output / "LightAttempt.json").open("x") as stream: diff --git a/tests/unit/solvers/time/bdf_robustness_witness.py b/tests/unit/solvers/time/bdf_robustness_witness.py index c7a0e587..e6c439bf 100644 --- a/tests/unit/solvers/time/bdf_robustness_witness.py +++ b/tests/unit/solvers/time/bdf_robustness_witness.py @@ -37,7 +37,8 @@ def main(): from examples.research_1d.steady import load_device from solarlab.device.compile_1d import compile_device_1d from solarlab.solvers.time.bdf import BDFOptions - from solarlab.experiments.transient import solve_transient + from solarlab.equations.implementation import LEGACY, equation_implementation + from solarlab.experiments.bdf import solve_electronic_bdf from examples.research_1d.transient import controls from solarlab.solvers.nonlinear.steady_1d import SteadyOptions raw_bytes = (args.root / "NativeParity01.json").read_bytes() @@ -56,8 +57,10 @@ def main(): "original_failure_preserved": True}) requested, drive = module["protocol"](0.0, np.array([0.0, .13, .31, 1.0]) * 4e-7) settings = BDFOptions(1e-7, max_step_s=2e-7, relative_tolerance=1e-5) - original = solve_transient(device, initial, requested, options=controls(), initial_options=SteadyOptions(), - method="bdf", bdf_options=settings, bdf_drive=drive) + # An explicit research BDF call on the original equations, as solve_transient ran it before CND2. + with equation_implementation(LEGACY): + original = solve_electronic_bdf(device, initial, requested, options=controls(), initial_options=SteadyOptions(), + bdf_options=settings, drive=drive) module["record"]("N_legacy_dark", original) assembled = module["run_assembled"](device, initial, requested, drive, settings) module["record"]("N_assembled_dark", assembled) diff --git a/tests/unit/solvers/time/test_assembled_bdf.py b/tests/unit/solvers/time/test_assembled_bdf.py index 0c986268..3a3fd77e 100644 --- a/tests/unit/solvers/time/test_assembled_bdf.py +++ b/tests/unit/solvers/time/test_assembled_bdf.py @@ -37,7 +37,7 @@ from solarlab.solvers.time.backward_euler import BackwardEuler1DStep, step_accounting from solarlab.solvers.time.bdf import Assessment, BDFEvent, BDFOptions, BDFStep, HistoryPoint, solve_bdf from solarlab.solvers.time.bdf_1d import BDFDrive, ElectronicStorage1D, bdf_accounting -from solarlab.experiments.bdf import _events +from solarlab.experiments.bdf import _events, solve_electronic_bdf from support.equation_provenance import counted, one_ulp_residual @@ -266,17 +266,17 @@ def test_fixed_step_assembled_BE_and_BDF1_are_bitwise(device, generation): requested, drive = protocol(generation) settings = BDFOptions(1e-7, max_step_s=1e-7, max_order=1, adaptive=False) original_BE = legacy_reference(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions())) + initial_options=SteadyOptions(), method="backward_euler")) record("BE_" + str(generation), original_BE) - original_BDF = legacy_reference(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions(), method="bdf", bdf_options=settings)) + original_BDF = legacy_reference(lambda: solve_electronic_bdf(device, point, requested, options=controls(), + initial_options=SteadyOptions(), bdf_options=settings)) record("BDF1_legacy_" + str(generation), original_BDF) assembled_BDF = assembled_candidate(lambda: run_assembled(device, point, requested, drive, settings)) record("BDF1_assembled_" + str(generation), assembled_BDF) assert_bdf(original_BDF, assembled_BDF, device, drive) # The production BE driver on its assembled storage system (one binding per history). assembled_BE = assembled_candidate(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions())) + initial_options=SteadyOptions(), method="backward_euler")) record("BE_assembled_" + str(generation), assembled_BE) assert_be(original_BE, assembled_BE, assembled_BDF) @@ -288,13 +288,14 @@ def test_a_one_ulp_assembled_residual_change_fails_both_comparisons(device): requested, drive = protocol(1.0) settings = BDFOptions(1e-7, max_step_s=1e-7, max_order=1, adaptive=False) original_BE = legacy_reference(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions())) - original_BDF = legacy_reference(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions(), method="bdf", bdf_options=settings)) + initial_options=SteadyOptions(), method="backward_euler")) + original_BDF = legacy_reference(lambda: solve_electronic_bdf(device, point, requested, options=controls(), + initial_options=SteadyOptions(), bdf_options=settings)) with one_ulp_residual() as perturbed: assembled_BDF = assembled_candidate(lambda: run_assembled(device, point, requested, drive, settings)) assembled_BE = assembled_candidate(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions())) + initial_options=SteadyOptions(), + method="backward_euler")) assert perturbed with pytest.raises(AssertionError): assert_bdf(original_BDF, assembled_BDF, device, drive) @@ -311,8 +312,8 @@ def test_adaptive_assembled_history_orders_rejections_and_dense_samples_are_bitw point = initial(device, generation) requested, drive = protocol(generation, np.array([0.0, .13, .31, 1.0]) * 4e-7) settings = BDFOptions(1e-7, max_step_s=2e-7, relative_tolerance=1e-5) - original = legacy_reference(lambda: solve_transient(device, point, requested, options=controls(), - initial_options=SteadyOptions(), method="bdf", bdf_options=settings, bdf_drive=drive)) + original = legacy_reference(lambda: solve_electronic_bdf(device, point, requested, options=controls(), + initial_options=SteadyOptions(), bdf_options=settings, drive=drive)) record("adaptive_legacy_" + str(generation), original) assembled = assembled_candidate(lambda: run_assembled(device, point, requested, drive, settings)) record("adaptive_assembled_" + str(generation), assembled) diff --git a/tests/unit/solvers/time/test_bdf_1d.py b/tests/unit/solvers/time/test_bdf_1d.py index 23cdc1d4..f95509b8 100644 --- a/tests/unit/solvers/time/test_bdf_1d.py +++ b/tests/unit/solvers/time/test_bdf_1d.py @@ -39,6 +39,16 @@ def blas1(): yield +def research_bdf(adapter, *args, **kwargs): + """An explicit research BDF call of an adapter, on the original equations (the LEGACY opt-out). + + The production entry points run only the frozen profile on allowlisted + scopes (solarlab.equations.time_method); these tests exercise the adapters. + """ + with equation_implementation(LEGACY): + return adapter(*args, **kwargs) + + @pytest.fixture(scope="module") def electronic(): device = compile_device_1d(load_device(), intervals_per_layer=12) @@ -80,9 +90,10 @@ def test_electronic_fixed_step_BDF1_matches_real_BE_trajectory(electronic): device, initial, admission = electronic times = np.linspace(0, 4e-7, 5) protocol = TransientProtocol(times, np.zeros(5), 1 + .01 * (times / times[-1])**2) - old = solve_transient(device, initial, protocol, options=controls(), initial_options=admission) - new = solve_transient(device, initial, protocol, options=controls(), initial_options=admission, - method="bdf", bdf_options=BDFOptions(1e-7, adaptive=False, max_order=1)) + old = solve_transient(device, initial, protocol, options=controls(), initial_options=admission, + method="backward_euler") + new = research_bdf(solve_electronic_bdf, device, initial, protocol, options=controls(), initial_options=admission, + bdf_options=BDFOptions(1e-7, adaptive=False, max_order=1)) assert old.completed and new.completed, (new.termination, new.error) for state, point in zip(old.states, new.accepted_coordinates): np.testing.assert_array_equal(state.u, point) @@ -97,9 +108,9 @@ def test_single_ion_fixed_step_BDF1_matches_real_BE_trajectory(ionic): device, initial = ionic times = np.linspace(0, 1, 5) protocol = TransientProtocol(times, .002 + .002 * times, np.zeros(5)) - old = solve_ionic_transient(device, initial, protocol, options=ionic_controls()) - new = solve_ionic_transient(device, initial, protocol, options=ionic_controls(), method="bdf", - bdf_options=BDFOptions(.25, adaptive=False, max_order=1)) + old = solve_ionic_transient(device, initial, protocol, options=ionic_controls(), method="backward_euler") + new = research_bdf(solve_ionic_bdf, device, initial, protocol, options=ionic_controls(), + bdf_options=BDFOptions(.25, adaptive=False, max_order=1)) assert old.completed and new.completed, (new.termination, new.error) for state, point in zip(old.states, new.accepted_coordinates): np.testing.assert_array_equal(state.u, point) @@ -154,8 +165,8 @@ def test_real_electronic_voltage_jump_preserves_inventory_and_restarts(electroni drive = BDFDrive(np.array([0, 2e-7, 4e-7]), np.array([[0, 1], [0, 1], [.002, 1]]), np.array([[0, 1], [.002, 1], [.002, 1]])) protocol = TransientProtocol([0, 2e-7, 4e-7], [0, .002, .002], [1, 1, 1]) - result = solve_transient(device, initial, protocol, options=controls(), initial_options=admission, - method="bdf", bdf_options=BDFOptions(1e-7, adaptive=False), bdf_drive=drive) + result = research_bdf(solve_electronic_bdf, device, initial, protocol, options=controls(), + initial_options=admission, bdf_options=BDFOptions(1e-7, adaptive=False), drive=drive) assert result.completed, (result.termination, result.error) assert result.restarts and result.restarts[0].accepted assert result.restarts[0].assessment.accounting["relative_inventory_change"] < 1e-11 @@ -165,9 +176,10 @@ def test_real_electronic_voltage_jump_preserves_inventory_and_restarts(electroni def test_selection_and_unsupported_population_refusals_are_explicit(electronic): device, initial, admission = electronic protocol = TransientProtocol([0, 1e-7], [0, 0], [1, 1]) - with pytest.raises(ValueError, match="explicit BDFOptions"): + # An unlisted scope is refused at the production entry point, never run as backward Euler. + with pytest.raises(ValueError, match="BDF is not selectable for scope"): solve_transient(device, initial, protocol, options=controls(), initial_options=admission, method="bdf") - with pytest.raises(ValueError, match="unknown"): + with pytest.raises(ValueError, match="unknown time method"): solve_transient(device, initial, protocol, options=controls(), initial_options=admission, method="bogus") @@ -183,20 +195,21 @@ def _numerical_bdf_bytes(result): @pytest.mark.parametrize("family", ["electronic", "single-ion"]) def test_public_assembled_BDF2_history_is_bitwise_and_uses_only_its_selected_equations(electronic, ionic, family): + # These custom BDFOptions are a research call of the adapters: the production entry points run only the + # frozen profile on allowlisted scopes, and test_time_method_selection checks that route in both modes. if family == "electronic": device, initial, admission = electronic request = TransientProtocol([0., 1e-7, 2e-7, 4e-7], [0.] * 4, [1.] * 4) def run(): - return solve_transient(device, initial, request, options=controls(), initial_options=admission, - method="bdf", bdf_options=BDFOptions(1e-7)) + return solve_electronic_bdf(device, initial, request, options=controls(), initial_options=admission, + bdf_options=BDFOptions(1e-7)) else: device, initial = ionic request = TransientProtocol([0., .25, .5, 1.], [.002] * 4, [0.] * 4) def run(): - return solve_ionic_transient(device, initial, request, options=ionic_controls(), method="bdf", - bdf_options=BDFOptions(.25)) + return solve_ionic_bdf(device, initial, request, options=ionic_controls(), bdf_options=BDFOptions(.25)) results = [] for implementation in (LEGACY, ASSEMBLED): with equation_implementation(implementation), counted() as observed: @@ -213,8 +226,8 @@ def test_public_BDF_does_not_fall_back_after_an_assembled_only_word_change(elect request = TransientProtocol([0., 1e-7, 2e-7], [0.] * 3, [1., 1.001, 1.004]) def run(): - return solve_transient(device, initial, request, options=controls(), initial_options=admission, - method="bdf", bdf_options=BDFOptions(1e-7, adaptive=False, max_order=1)) + return solve_electronic_bdf(device, initial, request, options=controls(), initial_options=admission, + bdf_options=BDFOptions(1e-7, adaptive=False, max_order=1)) with equation_implementation(LEGACY): reference = run() with equation_implementation(ASSEMBLED), counted() as observed, one_ulp_residual() as mutations: diff --git a/tests/unit/solvers/time/test_time_method_axis.py b/tests/unit/solvers/time/test_time_method_axis.py new file mode 100644 index 00000000..fb337f54 --- /dev/null +++ b/tests/unit/solvers/time/test_time_method_axis.py @@ -0,0 +1,540 @@ +"""The time-method axis (CND2): requests, scope-based defaults, refusals and records. + +Every scope here is a stand-in digest; the production entry points compute +real ones (tests/integration/test_time_method_selection.py). +""" + +from datetime import date, datetime, timedelta, timezone + +import numpy as np +import pytest + +from solarlab.equations import time_method +from solarlab.equations.time_method import ( + ADAPTIVE_MAX_STEPS, ALLOWLIST, BACKWARD_EULER, BDF, ELECTRONIC, ENVIRONMENT, IONIC, MULTIPLE_IONIC, PROFILE, + PROFILE_SHA256, TRUST_STANDARD, TimeMethodSelection, requested_time_method, resolve_time_method, scope_digest, + time_method_setting, verify_time_method, +) + +LISTED = next(iter(ALLOWLIST)) +UNLISTED = "0" * 64 + + +@pytest.fixture(autouse=True) +def no_process_setting(monkeypatch): + monkeypatch.delenv(ENVIRONMENT, raising=False) + + +def never(): + raise AssertionError("the scope was computed") + + +def flipped(monkeypatch): + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BDF, "CommanderBdfDefaultFreezeV2")) + monkeypatch.setattr(time_method, "_SWITCH_DATE", "2026-11-08") + monkeypatch.setattr(time_method, "_route_today", lambda: date(2026, 11, 8)) + + +def test_no_default_is_flipped_before_the_route_decision(): + """No flip until the commander sets a post-recheck date, never before 2026-11-08 Asia/Shanghai.""" + method, authority = time_method.ALLOWLISTED_DEFAULT + chosen = time_method._SWITCH_DATE + today = datetime.now(timezone(timedelta(hours=8))).date() + if chosen is None or today < date.fromisoformat(chosen): + assert (method, authority) == (BACKWARD_EULER, None) + if chosen is not None: + assert date.fromisoformat(chosen) >= date(2026, 11, 8) + assert method in time_method.TIME_METHODS and (method == BDF) == (authority is not None) + assert authority is None or authority.startswith("CommanderBdfDefaultFreeze") + + +@pytest.mark.parametrize("chosen,today,allowed", [ + (None, date(2026, 11, 2), False), (None, date(2026, 11, 8), False), + (None, date(2026, 11, 9), False), ("2026-11-07", date(2026, 11, 8), False), + ("2026-11-08", date(2026, 11, 7), False), ("2026-11-08", date(2026, 11, 8), True), + ("2026-11-09", date(2026, 11, 8), False), ("2026-11-09", date(2026, 11, 9), True), +]) +def test_the_default_switch_requires_a_commander_date(monkeypatch, chosen, today, allowed): + monkeypatch.setattr(time_method, "_SWITCH_DATE", chosen) + monkeypatch.setattr(time_method, "_route_today", lambda: today) + if allowed: + time_method._check_default_switch() + else: + with pytest.raises(ValueError, match="BDF is not selectable"): + time_method._check_default_switch() + + +def test_requests_resolve_by_argument_then_scope_then_process_setting(monkeypatch): + assert requested_time_method() == (None, "default") + monkeypatch.setenv(ENVIRONMENT, BACKWARD_EULER) + assert requested_time_method() == (BACKWARD_EULER, "environment") + with time_method.time_method(BDF): + assert requested_time_method() == (BDF, "scope") + assert requested_time_method(BACKWARD_EULER) == (BACKWARD_EULER, "argument") + with time_method.time_method(BACKWARD_EULER): + assert requested_time_method() == (BACKWARD_EULER, "scope") + assert requested_time_method() == (BDF, "scope") + for refused in ("Bdf", "radau", ""): + monkeypatch.setenv(ENVIRONMENT, refused) + with pytest.raises(ValueError, match="unknown time method"): + requested_time_method() + monkeypatch.delenv(ENVIRONMENT) + with pytest.raises(ValueError, match="unknown time method"): + requested_time_method("ida") + with pytest.raises(ValueError, match="unknown time method"), time_method.time_method("backward-euler"): + pass + + +@pytest.fixture(scope="module") +def device(): + """A genuine compiled electronic device; the scope digest itself is stood in for below.""" + from examples.research_1d.steady import load_device + from solarlab.device.compile_1d import compile_device_1d + + return compile_device_1d(load_device(), intervals_per_layer=12) + + +@pytest.fixture +def protocol(): + from solarlab.experiments.transient import TransientProtocol + + return TransientProtocol(np.linspace(0, 4e-7, 5), np.zeros(5), np.zeros(5)) + + +@pytest.fixture +def stand_in(monkeypatch): + """The resolver's own scope computation, replaced by a stand-in digest the test sets.""" + digest = {"value": LISTED, "calls": 0} + + def scope(*args, **kwargs): + digest["calls"] += 1 + if isinstance(digest["value"], Exception): + raise digest["value"] + return digest["value"] + + monkeypatch.setattr(time_method, "electronic_scope", scope) + return digest + + +def call(device, protocol, **kwargs): + return resolve_time_method(kwargs.pop("method", None), compiled=device, protocol=protocol, family=ELECTRONIC, **kwargs) + + +@pytest.mark.parametrize("flip", [False, True], ids=["before_flip", "after_flip"]) +def test_backward_euler_is_the_explicit_opt_out_and_computes_no_scope(monkeypatch, device, protocol, stand_in, flip): + if flip: + flipped(monkeypatch) + selection = call(device, protocol, method=BACKWARD_EULER) + assert selection == TimeMethodSelection(ELECTRONIC, BACKWARD_EULER, "argument", BACKWARD_EULER) + with time_method.time_method(BACKWARD_EULER): + assert call(device, protocol).effective == BACKWARD_EULER + monkeypatch.setenv(ENVIRONMENT, BACKWARD_EULER) + assert call(device, protocol).source == "environment" + assert stand_in["calls"] == 0 + + +def test_the_default_is_backward_euler_for_every_scope_before_the_flip(monkeypatch, device, protocol, stand_in): + monkeypatch.setattr(time_method, "ALLOWLISTED_DEFAULT", (BACKWARD_EULER, None)) + assert call(device, protocol) == TimeMethodSelection(ELECTRONIC, None, "default", BACKWARD_EULER) + assert resolve_time_method(compiled=None, family=MULTIPLE_IONIC).effective == BACKWARD_EULER + assert stand_in["calls"] == 0 + + +def test_the_flip_point_defaults_to_bdf_on_allowlisted_scopes_only(monkeypatch, device, protocol, stand_in): + flipped(monkeypatch) + listed = call(device, protocol) + assert (listed.requested, listed.source, listed.effective) == (None, "default", BDF) + assert (listed.scope, listed.scope_sha256) == (ALLOWLIST[LISTED], LISTED) + stand_in["value"] = UNLISTED + assert call(device, protocol).effective == BACKWARD_EULER + # A scope that cannot be computed is not allowlisted: the default keeps backward Euler. + stand_in["value"] = TypeError("no scope content is defined for object") + assert call(device, protocol).effective == BACKWARD_EULER + assert resolve_time_method(compiled=object(), family=ELECTRONIC).effective == BACKWARD_EULER + stand_in["value"] = LISTED + from solarlab.equations.implementation import ASSEMBLED, LEGACY, equation_implementation + + # The equation selection is its own axis: either implementation keeps the time-method selection. + for implementation in (ASSEMBLED, LEGACY): + with equation_implementation(implementation): + assert call(device, protocol).effective == BDF + monkeypatch.setenv("NEWCORE_EQUATIONS", "unknown") + with pytest.raises(ValueError, match="unknown equation implementation"): + call(device, protocol) + + +@pytest.mark.parametrize("flip", [False, True], ids=["before_flip", "after_flip"]) +def test_explicit_bdf_needs_an_allowlisted_scope_and_the_frozen_profile(monkeypatch, device, protocol, stand_in, flip): + from dataclasses import replace + + from solarlab.solvers.time.bdf import BDFOptions + + if flip: + flipped(monkeypatch) + assert call(device, protocol, method=BDF) == TimeMethodSelection(ELECTRONIC, BDF, "argument", BDF, + ALLOWLIST[LISTED], LISTED) + assert call(device, protocol, method=BDF, bdf_options=BDFOptions(**PROFILE)).effective == BDF + for options in (replace(BDFOptions(**PROFILE), relative_tolerance=1e-4), replace(BDFOptions(**PROFILE), max_steps=32), + BDFOptions(**{**PROFILE, "wall_s": 30.5}), dict(PROFILE), BDFOptions(**{**PROFILE, "adaptive": 1}), + BDFOptions(**{**PROFILE, "max_order": 2.0})): + with pytest.raises(ValueError, match="only the frozen profile 92396791"): + call(device, protocol, method=BDF, bdf_options=options) + stand_in["value"] = UNLISTED + with pytest.raises(ValueError, match="only the 10 allowlisted electronic envelopes"): + call(device, protocol, method=BDF) + stand_in["value"] = TypeError("no scope content is defined for object") + with pytest.raises(ValueError, match="scope cannot be computed"): + call(device, protocol, method=BDF) + with time_method.time_method(BDF), pytest.raises(ValueError, match="no BDF adapter"): + resolve_time_method(compiled=_multiple_device(), family=MULTIPLE_IONIC) + stand_in["value"] = LISTED + with time_method.time_method(BDF): + assert call(device, protocol).source == "scope" + monkeypatch.setenv(ENVIRONMENT, BDF) + assert call(device, protocol).source == "environment" + + +def _multiple_device(): + from support.assembly_references import REFERENCE_FACTORIES + + return REFERENCE_FACTORIES["multiple_constrained:positive"]().device + + +def test_the_family_comes_from_the_device_and_is_never_taken_from_the_caller(device, protocol, stand_in): + """D2: a stated family or a supplied hash that disagrees with the actual device is refused, never admitted.""" + with pytest.raises(ValueError, match=f"not of the {IONIC} family"): + resolve_time_method(BDF, compiled=device, protocol=protocol, family=IONIC) + # The multiple-domain entry point has no BDF adapter for any device. + with pytest.raises(ValueError, match="no BDF adapter"): + resolve_time_method(BDF, compiled=device, protocol=protocol, family=MULTIPLE_IONIC) + with pytest.raises(ValueError, match="not of a supported family"): + resolve_time_method(BDF, compiled=object(), protocol=protocol) + # A subclass of the compiled device has no family, whatever it states. + from solarlab.equations.dc_1d import CompiledDevice1D + + class Device(CompiledDevice1D): + pass + + widened = object.__new__(Device) + widened.__dict__.update(vars(device)) + with pytest.raises(ValueError, match="not of the electronic_1d family"): + resolve_time_method(BDF, compiled=widened, protocol=protocol, family=ELECTRONIC) + assert stand_in["calls"] == 0 + # The resolver takes no family or scope digest of its own: the old form is refused outright. + with pytest.raises(TypeError): + resolve_time_method("ionic_1d", method=BDF, scope=lambda: LISTED) # type: ignore[call-arg] + with pytest.raises(ValueError, match="unknown time method"): + resolve_time_method("ionic_1d", compiled=device, protocol=protocol) + with pytest.raises(ValueError, match="unknown time-method family"): + resolve_time_method(BDF, compiled=device, protocol=protocol, family="electronic_2d") + + +def test_only_the_protocols_own_bdf_drive_is_admitted(monkeypatch, device, protocol, stand_in): + """D1: the drive is not a free input; a subclass, look-alike or replaced construction is refused.""" + from dataclasses import dataclass + + from solarlab.solvers.time.bdf_1d import BDFDrive + + values = np.column_stack((protocol.voltage_V, protocol.generation_scale)) + assert call(device, protocol, method=BDF, bdf_drive=BDFDrive.from_protocol(protocol)).effective == BDF + + class Interior(BDFDrive): + def values(self, t, side="right"): + voltage, light = super().values(t, side) + return voltage, light + 0.1 + + @dataclass(frozen=True) + class LookAlike: + times_s: np.ndarray + left_values: np.ndarray + right_values: np.ndarray + + jump = values.copy() + jump[1, 1] = np.nextafter(jump[1, 1], np.inf) + for drive in (Interior(protocol.times_s, values, values), LookAlike(protocol.times_s, values, values), + BDFDrive(protocol.times_s, values, jump)): + with pytest.raises(ValueError, match="protocol's own continuous drive"): + call(device, protocol, method=BDF, bdf_drive=drive) + for replacement in (lambda cls, p: Interior(p.times_s, values, values), lambda cls, p: BDFDrive(p.times_s, values, jump)): + with monkeypatch.context() as patch: + patch.setattr(BDFDrive, "from_protocol", classmethod(replacement)) + with pytest.raises(ValueError, match="not its own continuous knots"): + call(device, protocol, method=BDF) + flipped(patch) + with pytest.raises(ValueError, match="not its own continuous knots"): + call(device, protocol) + genuine = BDFDrive.from_protocol(protocol) + carried = BDFDrive.from_protocol(protocol) + object.__setattr__(carried, "values", lambda t, side="right": (0.0, 1.0)) + for drive in (Interior(protocol.times_s, values, values), LookAlike(protocol.times_s, values, values), + BDFDrive(protocol.times_s, values, jump), carried): + with pytest.raises(TypeError, match="exactly the protocol's own continuous BDFDrive"): + time_method._source(protocol, drive) + assert time_method._source(protocol, genuine) == time_method._source(protocol, None) + assert time_method._source(protocol, None)["drive"] == "continuous_protocol_knots" + # The same drive carrying a method of its own is refused at admission, and from a replaced constructor too. + with pytest.raises(ValueError, match="protocol's own continuous drive"): + call(device, protocol, method=BDF, bdf_drive=carried) + with monkeypatch.context() as patch: + patch.setattr(BDFDrive, "from_protocol", classmethod(lambda cls, p: carried)) + with pytest.raises(ValueError, match="not its own continuous knots"): + call(device, protocol, method=BDF) + + +def test_bdf_options_or_drive_need_an_explicit_bdf_request(device, protocol, stand_in): + from solarlab.solvers.time.bdf import BDFOptions + from solarlab.solvers.time.bdf_1d import BDFDrive + + for method in (None, BACKWARD_EULER): + with pytest.raises(ValueError, match="explicit bdf time-method request"): + call(device, protocol, method=method, bdf_options=BDFOptions(**PROFILE)) + with pytest.raises(ValueError, match="explicit bdf time-method request"): + call(device, protocol, method=method, bdf_drive=BDFDrive.from_protocol(protocol)) + + +def test_workers_forward_the_request_and_refuse_bdf_while_prepared(monkeypatch): + assert time_method_setting(ELECTRONIC) == (ENVIRONMENT, None) + with time_method.time_method(BACKWARD_EULER): + assert time_method_setting(IONIC) == (ENVIRONMENT, BACKWARD_EULER) + flipped(monkeypatch) + assert time_method_setting(ELECTRONIC) == (ENVIRONMENT, None) + with time_method.time_method(BDF), pytest.raises(ValueError, match="worker jobs"): + time_method_setting(ELECTRONIC) + monkeypatch.setenv(ENVIRONMENT, BDF) + with pytest.raises(ValueError, match="worker jobs"): + time_method_setting(IONIC) + monkeypatch.delenv(ENVIRONMENT) + threads = (("OMP_NUM_THREADS", "1"),) + default = verify_time_method((*threads, (ENVIRONMENT, None)), ELECTRONIC) + assert (default.requested, default.effective) == (None, BACKWARD_EULER) + monkeypatch.setenv(ENVIRONMENT, BACKWARD_EULER) + explicit = verify_time_method((*threads, (ENVIRONMENT, BACKWARD_EULER)), ELECTRONIC) + assert (explicit.requested, explicit.source, explicit.effective) == (BACKWARD_EULER, "environment", BACKWARD_EULER) + for settings in (threads, (*threads, (ENVIRONMENT, None))): + with pytest.raises(ValueError, match="differs from its execution manifest"): + verify_time_method(settings, ELECTRONIC) + monkeypatch.setenv(ENVIRONMENT, BDF) + with pytest.raises(ValueError, match="worker jobs"): + verify_time_method((*threads, (ENVIRONMENT, BDF)), IONIC) + + +def test_records_state_the_request_effective_method_and_production_scope(): + default = TimeMethodSelection(ELECTRONIC, None, "default", BACKWARD_EULER).record() + assert default == {"schema": "solarlab.time-method-selection.v1", "family": ELECTRONIC, "requested": None, + "source": "default", "effective": BACKWARD_EULER, + "allowlisted_default": list(time_method.ALLOWLISTED_DEFAULT)} + production = TimeMethodSelection(ELECTRONIC, BDF, "argument", BDF, ALLOWLIST[LISTED], LISTED).record() + assert production["profile"] == dict(PROFILE) and production["profile_sha256"] == PROFILE_SHA256 + assert production["adaptive_max_steps"] == ADAPTIVE_MAX_STEPS == 10000 + assert (production["scope"], production["scope_sha256"]) == (ALLOWLIST[LISTED], LISTED) + assert production["allowlist_sha256"] == time_method.ALLOWLIST_SHA256 + assert production["trust_standard"] == TRUST_STANDARD == "interface_level_trust_standard_v1" + assert production["qualification"] is False and production["label"] == "experimental_unqualified" + research = TimeMethodSelection(IONIC, BDF, "research_capture", BDF).record() + assert all(research[name] is None for name in ("scope", "scope_sha256", "allowlist_sha256", "profile_sha256", + "profile", "adaptive_max_steps", "trust_standard")) + + +def test_the_frozen_profile_and_allowlist_are_the_reviewed_ones(): + assert dict(PROFILE) == { + "initial_step_s": 0.001, "min_step_s": 1e-16, "max_step_s": 1e+30, "relative_tolerance": 1e-05, + "absolute_tolerance": 1e-12, "max_order": 2, "adaptive": True, "safety": 0.8, "min_factor": 0.2, + "max_factor": 2.0, "max_steps": 10000, "max_attempts": 20000, "max_consecutive_rejections": 12, "wall_s": 30.0} + assert PROFILE_SHA256 == "9239679194ed68a8c72780877a80a84ecca3dba24a895a17fe1ac1a94fd76bea" + assert sorted(ALLOWLIST.values()) == sorted([ + "E_dark_hold", "E_light_hold", "E_dark_voltage_ramp", "E_light_ramp_4", "E_light_ramp_8", "E_light_ramp_16", + "E_voltage_ramp_4", "E_voltage_ramp_8", "E_voltage_ramp_16", "E_saved_packet"]) + assert time_method.ALLOWLIST_SHA256 == "faaaf7cb92862de77d8bb48ba15d9552fdb988d1df493b2ebe7b2cddb247dbae" + + +def test_scope_content_refuses_a_value_it_cannot_encode(): + """The grammar of Cnd2ScopeKeyGrammarV1: tagged hex floats, typed envelopes, raw array words.""" + assert scope_digest(ELECTRONIC, {"a": time_method._content(np.zeros(2))}) != scope_digest( + ELECTRONIC, {"a": time_method._content(np.array([0.0, -0.0]))}) + assert time_method._content(-0.0) == {"float": "-0x0.0p+0"} != time_method._content(0.0) + assert time_method._content(1.0) != time_method._content(1) and time_method._content(True) is True + nan = np.array([np.nan]) + assert time_method._content(nan) == {"array": {"dtype": " Date: Thu, 12 Nov 2026 11:13:51 +0800 Subject: [PATCH 05/46] test(solvers): align test_cnd2_interface_audit with CND2 admission contract (M-only) --- .../solvers/time/test_cnd2_interface_audit.py | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/tests/unit/solvers/time/test_cnd2_interface_audit.py b/tests/unit/solvers/time/test_cnd2_interface_audit.py index 1abae2e6..1e3f371c 100644 --- a/tests/unit/solvers/time/test_cnd2_interface_audit.py +++ b/tests/unit/solvers/time/test_cnd2_interface_audit.py @@ -14,6 +14,7 @@ from pathlib import Path import numpy as np +import pytest from examples.research_1d.ionic_residual import prepare_single_ion_device from examples.research_1d.ionic_steady import controls as steady_ionic_controls @@ -31,6 +32,8 @@ from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem from solarlab.equations.assembly.ionic_1d import AssembledMultipleIonic1DProblem +from solarlab.equations.time_method import ALLOWLISTED_DEFAULT, resolve_time_method +from solarlab.experiments.bdf import solve_electronic_bdf from solarlab.experiments.ionic_transient import ( IonicTransientResult, load_ionic_steady_initial, @@ -61,10 +64,11 @@ def test_public_transient_entry_points_keep_backward_euler_default( """Backward Euler remains the public default; BDF requires explicit opt-in.""" electronic_sig = inspect.signature(solve_transient) ionic_sig = inspect.signature(solve_ionic_transient) - assert electronic_sig.parameters["method"].default == "backward_euler" + assert electronic_sig.parameters["method"].default is None assert electronic_sig.parameters["bdf_options"].default is None - assert ionic_sig.parameters["method"].default == "backward_euler" + assert ionic_sig.parameters["method"].default is None assert ionic_sig.parameters["bdf_options"].default is None + assert ALLOWLISTED_DEFAULT == ("backward_euler", None) device = compile_device_1d(load_device(), intervals_per_layer=8) steady_opts = SteadyOptions() @@ -78,20 +82,51 @@ def test_public_transient_entry_points_keep_backward_euler_default( np.array([1.0, 1.002, 1.005]), ) + assert ( + resolve_time_method( + None, + compiled=device, + initial=initial, + protocol=protocol, + options=controls(), + initial_options=steady_opts, + ).effective + == "backward_euler" + ) be_res = solve_transient( device, initial, protocol, options=controls(), initial_options=steady_opts ) assert isinstance(be_res, TransientResult1D) assert len(be_res.accepted_times_s) == 3 - bdf_res = solve_transient( + custom_bdf = BDFOptions(1e-7, adaptive=False, max_order=2) + with pytest.raises(ValueError, match="production BDF runs only the frozen profile"): + solve_transient( + device, + initial, + protocol, + options=controls(), + initial_options=steady_opts, + method="bdf", + bdf_options=custom_bdf, + ) + with pytest.raises(ValueError, match="BDF is not selectable"): + solve_transient( + device, + initial, + protocol, + options=controls(), + initial_options=steady_opts, + method="bdf", + ) + + bdf_res = solve_electronic_bdf( device, initial, protocol, options=controls(), initial_options=steady_opts, - method="bdf", - bdf_options=BDFOptions(1e-7, adaptive=False, max_order=2), + bdf_options=custom_bdf, ) assert isinstance(bdf_res, BDFResult) assert bdf_res.completed From 8384f7505535e67aadadd0f54040deb78f6e38d6 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 11:25:41 +0800 Subject: [PATCH 06/46] M: close P06-04..06 runtime sweep resume/equivalence and YAML-to-SSE chains --- src/solarlab/sweeps/steady_worker.py | 86 ++- src/solarlab_server/steady_preparation.py | 11 +- .../test_p06_route_and_sse_closeout.py | 606 ++++++++++++++++++ .../test_p06_sweep_resume_and_equivalence.py | 438 +++++++++++++ 4 files changed, 1133 insertions(+), 8 deletions(-) create mode 100644 tests/runtime/test_p06_route_and_sse_closeout.py create mode 100644 tests/runtime/test_p06_sweep_resume_and_equivalence.py diff --git a/src/solarlab/sweeps/steady_worker.py b/src/solarlab/sweeps/steady_worker.py index 7258e112..2219bafa 100644 --- a/src/solarlab/sweeps/steady_worker.py +++ b/src/solarlab/sweeps/steady_worker.py @@ -6,15 +6,17 @@ """ from __future__ import annotations +from collections.abc import Sequence from dataclasses import asdict, dataclass import json -from typing import TYPE_CHECKING, Any +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal from solarlab.config.identity import BuildSource, ExecutionEngine from solarlab.device.resolved import PreparedDevice from solarlab.experiments.execution import ProcessSupervisor, ScanPoint, ScanRunner, ScanSpec from solarlab.experiments.jv.worker import ( - SteadyJVProtocol, prepare_steady_jv_job, read_steady_jv_job, + SteadyJVProtocol, prepare_steady_jv_job, read_steady_jv_job, steady_jv_worker_binding, ) from solarlab.experiments.worker import ManifestBinding, ResourceLimits, RunSpec from solarlab.sweeps.preparation import PreparedSweep, digest, encode, prepare_point @@ -54,11 +56,65 @@ def submit(self, supervisor: ProcessSupervisor, *, max_in_flight: int = 1) -> Sc """Use this exact shared supervisor; serial admission is the default.""" return supervisor.scan(self.spec, executions=self.executions, max_in_flight=max_in_flight) + @classmethod + def from_declaration( + cls, declaration: bytes | Path, *, executions: Sequence[ManifestBinding], + ) -> SteadySweepJobs: + """Restore a persisted ScanSpec for sweep resumption with verified bindings.""" + raw = declaration.read_bytes() if isinstance(declaration, Path) else declaration + spec = ScanSpec.from_bytes(raw) + by_manifest: dict[str, list[ManifestBinding]] = {} + for binding in executions: + if type(binding) is not ManifestBinding: + raise ValueError("explicit ManifestBinding instances are required") + by_manifest.setdefault(binding.expected_sha256, []).append(binding) + ordered: list[ManifestBinding] = [] + if len(executions) == len(spec.points) and all( + b.expected_sha256 == p.spec.manifest_sha256 for p, b in zip(spec.points, executions) + ): + ordered = list(executions) + else: + for point in spec.points: + candidates = by_manifest.get(point.spec.manifest_sha256, []) + if not candidates: + raise ValueError(f"missing ManifestBinding for point {point.point_id}") + ordered.append(candidates[0]) + return cls(spec, tuple(ordered)) + + def reordered( + self, point_ids: Sequence[str], *, scan_id: str | None = None, + ) -> SteadySweepJobs: + """Permute point dispatch order while preserving declared coordinate indices.""" + if isinstance(point_ids, (str, bytes)): + raise ValueError("point_ids must be an explicit sequence of point IDs") + ordered_ids = tuple(point_ids) + by_id = {point.point_id: (point, binding) + for point, binding in zip(self.spec.points, self.executions)} + if len(ordered_ids) != len(self.spec.points) or set(ordered_ids) != set(by_id): + raise ValueError("point_ids must be an exact permutation of declared sweep points") + target_scan_id = self.spec.scan_id if scan_id is None else scan_id + points: list[ScanPoint] = [] + executions: list[ManifestBinding] = [] + for point_id in ordered_ids: + point, binding = by_id[point_id] + if (scan_id is not None + and point.run_id == "scan:" + digest([self.spec.scan_id, point.point_id])): + point = ScanPoint( + point.point_id, + "scan:" + digest([target_scan_id, point.point_id]), + point.coordinates_json, + point.spec, + ) + points.append(point) + executions.append(binding) + return SteadySweepJobs(ScanSpec(target_scan_id, tuple(points)), tuple(executions)) + def prepare_steady_sweep_jobs( sweep: PreparedSweep, protocol: SteadyJVProtocol, *, limits: ResourceLimits, implementation: BuildSource, current_repository_head: str, engine: ExecutionEngine, scan_id: str | None = None, + reuse_scope: Literal["scan", "execution_identity"] = "scan", ) -> SteadySweepJobs: """Resolve every point afresh and bind its actual cold steady invocation. @@ -66,17 +122,24 @@ def prepare_steady_sweep_jobs( before submission. Failures during execution remain individual RunStore attempts and do not prevent later points from running. Continuation is confined to the voltages of one point, never across parameter changes. + When ``reuse_scope="execution_identity"``, ``run_id`` is bound to the + complete ``RunSpec`` and ``steady_jv`` worker source digest so completed + points can be reused across resumed or overlapping sweeps only when full + input/physics/execution/manifest/schema/budget identity matches. """ if type(sweep) is not PreparedSweep: raise TypeError("an actual PreparedSweep is required") if sweep.to_input().base.schema_version != "solarlab.device-preparation.v1": raise ValueError("steady process sweeps require a device base and an explicit steady protocol") + if reuse_scope not in ("scan", "execution_identity"): + raise ValueError("reuse_scope must be 'scan' or 'execution_identity'") _limits(limits) declaration = sweep.to_mapping() scan_id = declaration["id"] if scan_id is None else scan_id for point in declaration["points"]: if point["status"] != "prepared_pending_dependencies" or point["applied_input"] is None: raise ValueError(f"unresolved sweep point {point['id']}: {point.get('field_errors', [])}") + worker_source_sha256 = steady_jv_worker_binding().source_sha256 points, executions = [], [] for index, point in enumerate(declaration["points"]): prepared = prepare_point(point["applied_input"], sweep.defaults, sweep.resources, sweep.sources) @@ -99,8 +162,12 @@ def prepare_steady_sweep_jobs( "targets": {axis["id"]: axis["target"] for axis in declaration["axes"]}, "units": {axis["id"]: axis["input_field_schema"].get("unit") for axis in declaration["axes"]}, } - run_id = "scan:" + digest([scan_id, point["id"]]) spec = RunSpec.from_binding("steady_jv", job.request, limits, binding) + run_id = ( + "scan:" + digest([scan_id, point["id"]]) + if reuse_scope == "scan" + else "exec:" + digest([spec.to_document(), worker_source_sha256]) + ) points.append(ScanPoint(point["id"], run_id, encode(coordinates).decode(), spec)) executions.append(binding) return SteadySweepJobs(ScanSpec(scan_id, tuple(points)), tuple(executions)) @@ -119,9 +186,12 @@ def read_steady_sweep_jobs(store: RunStore, spec: ScanSpec) -> tuple[dict[str, A associations = {row["point_id"]: row for row in store.sweep_points(spec.scan_id)} if set(associations) - {point.point_id for point in spec.points}: raise ValueError("stored sweep contains points outside this declaration") - output = [] + indexed: list[tuple[int, dict[str, Any]]] = [] for point in spec.points: coordinates = json.loads(point.coordinates_json) + declared_index = coordinates.get("index") + if type(declared_index) is not int or declared_index < 0: + raise ValueError("point declaration lacks a valid declared index") request = point.spec.request body = json.loads(request.request.content) if (point.spec.worker_id != "steady_jv" or body.get("engine") != "solarlab" @@ -135,7 +205,7 @@ def read_steady_sweep_jobs(store: RunStore, spec: ScanSpec) -> tuple[dict[str, A } association = associations.get(point.point_id) if association is None: - output.append(value) + indexed.append((declared_index, value)) continue if (association["run_id"] != point.run_id or association["coordinates"] != coordinates or association["opaque_execution_identity"] != request.execution_identity.sha256): @@ -162,5 +232,7 @@ def read_steady_sweep_jobs(store: RunStore, spec: ScanSpec) -> tuple[dict[str, A latest = next(a for a in attempts if a["attempt_id"] == run["current_attempt_id"]) value.update(state=latest["state"], reason=latest["reason"], attempt_id=latest["attempt_id"], attempts=attempts, result=latest["steady_result"]) - output.append(value) - return tuple(output) + indexed.append((declared_index, value)) + if sorted(idx for idx, _ in indexed) != list(range(len(indexed))): + raise ValueError("declared point indices must form a complete 0..N-1 sequence") + return tuple(value for _, value in sorted(indexed, key=lambda item: item[0])) diff --git a/src/solarlab_server/steady_preparation.py b/src/solarlab_server/steady_preparation.py index 1539c1b6..8c4829b2 100644 --- a/src/solarlab_server/steady_preparation.py +++ b/src/solarlab_server/steady_preparation.py @@ -39,6 +39,8 @@ class SteadyJobInput(BaseModel): intervals_per_layer: int = Field(ge=2, le=256) generation_scale: float = Field(ge=0) incident_power_W_m2: float | None = Field(gt=0) + expected_prepared_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$") + expected_source_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$") @model_validator(mode="after") def check_protocol(self) -> SteadyJobInput: @@ -103,7 +105,14 @@ def export(self) -> dict[str, Any]: def prepare_steady_input(input: SteadyJobInput, context: SteadyPreparationContext) -> SteadyJVJob: """Prepare the existing cold worker; all trusted records stay server-owned.""" - return prepare_steady_jv_job(context.device(input.device_id), input.protocol(), + prepared = context.device(input.device_id) + if (input.expected_prepared_sha256 is not None + and prepared.content_sha256 != input.expected_prepared_sha256): + raise ValueError("registered device prepared_sha256 differs from expected_prepared_sha256") + if input.expected_source_sha256 is not None: + if not prepared.sources or prepared.sources[0].sha256 != input.expected_source_sha256: + raise ValueError("registered device source sha256 differs from expected_source_sha256") + return prepare_steady_jv_job(prepared, input.protocol(), implementation=context.implementation, current_repository_head=context.current_repository_head, engine=ExecutionEngine("solarlab")) diff --git a/tests/runtime/test_p06_route_and_sse_closeout.py b/tests/runtime/test_p06_route_and_sse_closeout.py new file mode 100644 index 00000000..fa7749b6 --- /dev/null +++ b/tests/runtime/test_p06_route_and_sse_closeout.py @@ -0,0 +1,606 @@ +"""P06-06 + P03-07 + P06-04 closeout: accepted YAML -> GET -> no-op editor save -> POST -> SSE -> readback.""" +from __future__ import annotations + +import hashlib +import io +import json +import subprocess +from typing import Literal +import time + +import numpy as np +from pydantic import BaseModel, ConfigDict, Field +import pytest + +from examples.research_1d.service import committed_implementation +from examples.research_1d.steady import load_device +from job_route_fixtures import Parameters +from legacy_fixtures import LEGACY, ROOT, make_job +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.legacy_wire import prepare_legacy_wire +from solarlab.config.resolve_device import resolve_device +from solarlab.config.scaps_input import import_scaps_device +from solarlab.config.schema import configuration_schema_representation +from solarlab.device.inputs import DeviceInput +from solarlab.experiments.execution import JobHandle, ProcessSupervisor +from solarlab.experiments.jv.worker import read_steady_jv_job, validate_steady_jv_scope +from solarlab.experiments.registry import ExperimentDefinition, ExperimentRegistry +from solarlab.experiments.worker import ResourceLimits, WorkerBinding +from solarlab.io.artifacts import bytes_artifact +from solarlab.io.run_bundle import RunBundle +from solarlab.io.run_store import RunStore +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.physics.registry import CapabilityRule, EvidenceRef +from solarlab_server.configuration import ConfigurationPreviewContext +from solarlab_server.job_service import ExecutionCatalog, JobService, JobSubmission, LegacyRegistration +from solarlab_server.legacy_engine import legacy_worker_binding +from solarlab_server.steady_preparation import SteadyPreparationContext, steady_execution_catalog +from test_event_service import _HTTPServer as _BaseHTTPServer, _all_events, _blocks, _next_event + +pytestmark = pytest.mark.requires_clean_core + +DEFAULT_PATHS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +class _HTTPServer(_BaseHTTPServer): + def client(self): + client = super().client() + client.timeout = 30.0 + return client + + +class ScapsBoundInput(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + device: None + config_path: Literal["fixture:scaps"] + expected_source_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + expected_prepared_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + params: Parameters + + +def prepare_scaps_jv(input: ScapsBoundInput): + job, _ = make_job(arguments=input.params.model_dump()) + prepared = job.execution.inputs.prepared + if not prepared.sources or prepared.sources[0].sha256 != input.expected_source_sha256: + raise ValueError("SCAPS source sha256 differs from expected_source_sha256") + if prepared.content_sha256 != input.expected_prepared_sha256: + raise ValueError("SCAPS prepared_sha256 differs from expected_prepared_sha256") + return job + + +def _slot_gate(request, context): + """Non-numerical worker holding the single active slot for deterministic SSE cursor staging.""" + context.consume_manifest(request, engine="solarlab") + context.progress({"stage": "slot_gate_ready"}) + while True: + context.check_cancel() + time.sleep(0.005) + + +@pytest.fixture(scope="module") +def legacy_defaults_and_resources(): + defaults = read_legacy_default_catalog( + tuple(SourceDocument(name, (LEGACY / name).read_bytes()) for name in DEFAULT_PATHS) + ) + resources = ResourceLibrary( + tuple( + ResourceTable(path.stem, "nk", SourceDocument(path.name, path.read_bytes())) + for path in sorted((LEGACY / "data/nk").glob("*.csv")) + ) + ) + return defaults, resources + + +@pytest.fixture(scope="module") +def standard_steady_bundle(legacy_defaults_and_resources): + defaults, resources = legacy_defaults_and_resources + fixture_path = ROOT / "perovskite-sim/tests/fixtures/configs/nip_MAPbI3.yaml" + seed = SourceDocument("nip_steady.yaml", fixture_path.read_bytes()) + imported = import_standard_device(seed, id="nip_steady", defaults=defaults) + editing = imported.editing_data() + editing["settings"].pop("V_bi", None) + editing["settings"]["built_in_potential_mode"] = "semiconductor_work_function" + editing["settings"]["ion_steric_diffusion_only"] = False + editing["settings"]["ion_steric_shared_site"] = False + for dst_layer, src_layer in zip(editing["layers"], load_device().layers, strict=True): + dst_layer["parameters"] = { + k: v for k, v in dict(src_layer.parameters).items() if v is not None + } + exported = prepare_legacy_wire(DeviceInput.model_validate(editing), source=seed, defaults=defaults) + assert exported.document is not None and exported.export()["strict_roundtrip_passed"] is True + yaml_source = exported.document + reimported = import_standard_device(yaml_source, id="nip_steady", defaults=defaults) + prepared = resolve_device(reimported, defaults, resources, sources=(yaml_source,)) + validate_steady_jv_scope(prepared) + head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() + steady_ctx = SteadyPreparationContext((("nip_steady", prepared),), committed_implementation(head), head) + ceiling = ResourceLimits(60.0, 1536 * 1024**2, 96 * 1024**2, None, None) + catalog = steady_execution_catalog(steady_ctx, ceiling=ceiling) + preview_ctx = ConfigurationPreviewContext(defaults, resources, (yaml_source,)) + return yaml_source, prepared, preview_ctx, catalog, ceiling + + +def _job_headers(catalog: ExecutionCatalog) -> dict[str, str]: + return { + "X-Solarlab-Registry": catalog.document.sha256, + "X-Solarlab-Job-Schema": catalog.schema.sha256, + } + + +def _wire_headers() -> dict[str, str]: + return { + "Content-Type": "application/json", + "X-Solarlab-Configuration-Schema": configuration_schema_representation()[1], + } + + +def _scaps_bound_catalog(ceiling: ResourceLimits) -> tuple[ExecutionCatalog, object]: + job, _ = make_job() + documents: dict[str, bytes] = {} + + def reference(path: str, symbol: str = "") -> EvidenceRef: + documents[path] = (ROOT / path).read_bytes() + return EvidenceRef( + path + ("#" + symbol if symbol else ""), + hashlib.sha256(documents[path]).hexdigest(), + "source", + ) + + factory = reference("tests/runtime/test_p06_route_and_sse_closeout.py", "prepare_scaps_jv") + schema = json.dumps( + ScapsBoundInput.model_json_schema(), sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + documents["schema:scaps-bound-http-fixture"] = schema + schema_ref = EvidenceRef("schema:scaps-bound-http-fixture", hashlib.sha256(schema).hexdigest(), "source") + definition = ExperimentDefinition( + "jv", + 1, + "Source-bound SCAPS YAML J-V route", + schema_ref, + reference("src/solarlab/experiments/worker.py", "WorkerResult"), + factory, + reference("src/solarlab_server/legacy_engine/__init__.py", "_run_legacy"), + "jv", + reference("web/src/workstation/panes/main-plot-pane.ts", "renderJV"), + CapabilityRule("scaps-bound-http-fixture", (1,), ("transient",), (factory,), backends=("metadata_only",)), + ) + documents["physics/temperature.py"] = (LEGACY / "physics/temperature.py").read_bytes() + registry = ExperimentRegistry((definition,)) + models = job.execution.inputs.registry + registration = LegacyRegistration( + "jv", 1, "scaps_transient", ScapsBoundInput, prepare_scaps_jv, legacy_kinds=("jv",) + ) + catalog = ExecutionCatalog( + registry, + models, + tuple(SourceDocument(k, v) for k, v in documents.items()), + (registration,), + expected_registry_sha256=registry.content_sha256, + expected_model_sha256=models.content_sha256, + ceiling=ceiling, + ) + return catalog, job + + +def test_standard_yaml_get_noop_editor_save_post_steady_job_two_sse_cursors_and_restart_readback( + tmp_path, standard_steady_bundle +): + yaml_source, prepared, preview_ctx, catalog, ceiling = standard_steady_bundle + database = (tmp_path / "steady-chain-store").resolve() + work = (tmp_path / "steady-chain-work").resolve() + gate_binding = WorkerBinding.from_function( + "slot_gate_fixture", + _slot_gate, + registry_sha256=catalog.document.sha256, + schema_sha256=catalog.schema.sha256, + ) + + def payload( + run_id: str = "yaml-steady-e2e", + *, + source_sha256: str | None = None, + prepared_sha256: str | None = None, + ) -> dict: + return { + "schema_version": "solarlab.job-submission.v1", + "run_id": run_id, + "experiment_id": "steady_jv", + "version": 1, + "engine": "solarlab", + "input": { + "device_id": "nip_steady", + "voltage_V": [0.0, 0.05, 0.1], + "intervals_per_layer": 8, + "generation_scale": 1.0, + "incident_power_W_m2": None, + "expected_source_sha256": yaml_source.sha256 if source_sha256 is None else source_sha256, + "expected_prepared_sha256": prepared.content_sha256 if prepared_sha256 is None else prepared_sha256, + }, + "limits": { + "wall_seconds": 60.0, + "rss_bytes": 1536 * 1024**2, + "output_bytes": 96 * 1024**2, + "accepted_steps": None, + "calls": None, + }, + } + + with RunStore(database) as store, ProcessSupervisor( + store, + work, + (catalog.worker_binding("solarlab"), gate_binding), + max_active=1, + max_pending=2, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + soft_grace_seconds=0.1, + terminate_grace_seconds=0.1, + poll_seconds=0.01, + ) as supervisor: + service = JobService(catalog, supervisor) + with _HTTPServer(database, configuration_preview=preview_ctx, job_service=service) as server: + with server.client() as http, server.client() as sub_a_client, server.client() as sub_b_client: + # 1. GET /configs & GET /configs/{id} + listing = http.get("/configs") + assert listing.status_code == 200 + assert listing.json()["sources"] == [ + {"id": yaml_source.id, "sha256": yaml_source.sha256, "bytes": len(yaml_source.content)} + ] + fetched = http.get(f"/configs/{yaml_source.id}") + assert fetched.status_code == 200 + assert fetched.headers["etag"] == f'"{yaml_source.sha256}"' + assert fetched.content == yaml_source.content + + # 2. Import YAML -> POST /configuration-preview/device + imported = import_standard_device( + SourceDocument(yaml_source.id, fetched.content), id="nip_steady", defaults=preview_ctx.defaults + ) + dto_wire = DeviceInput.model_validate(imported).model_dump(mode="json", exclude_unset=True) + dev_preview = http.post("/configuration-preview/device", json=dto_wire) + assert dev_preview.status_code == 200, dev_preview.text + dev_json = dev_preview.json() + assert dev_json["can_execute"] is False and dev_json["status"] == "prepared_pending_dependencies" + preview_prepared_sha = dev_json["identity"]["content_sha256"] + assert preview_prepared_sha == prepared.content_sha256 + + # 3. No-op editor save via POST /configuration-preview/legacy-wire + wire_req = { + "schema_version": "solarlab.legacy-wire-preview-request.v1", + "input": dev_json["input"], + "source": {"id": yaml_source.id, "sha256": yaml_source.sha256}, + "references": {}, + } + assert http.post("/configuration-preview/legacy-wire", json=wire_req).status_code == 428 + assert ( + http.post( + "/configuration-preview/legacy-wire", + json=wire_req, + headers={**_wire_headers(), "X-Solarlab-Configuration-Schema": "0" * 64}, + ).status_code + == 409 + ) + wire_resp = http.post("/configuration-preview/legacy-wire", json=wire_req, headers=_wire_headers()) + assert wire_resp.status_code == 200, wire_resp.text + wire_json = wire_resp.json() + assert wire_json["can_execute"] is False and wire_json["status"] == "prepared_data_only" + assert wire_json["report"]["strict_roundtrip_passed"] is True + assert wire_json["report"]["differences"] == [] + assert len(wire_json["documents"]) == 1 + saved_doc = wire_json["documents"][0] + assert saved_doc["sha256"] == yaml_source.sha256 + assert saved_doc["utf8"].encode("utf-8") == yaml_source.content + + reimported = import_standard_device( + SourceDocument(saved_doc["source_id"], saved_doc["utf8"].encode("utf-8")), + id="nip_steady", + defaults=preview_ctx.defaults, + ) + repreview = http.post( + "/configuration-preview/device", + json=DeviceInput.model_validate(reimported).model_dump(mode="json", exclude_unset=True), + ) + assert repreview.status_code == 200 + assert repreview.json()["identity"]["content_sha256"] == preview_prepared_sha + assert store.events() == [] + + # 4. Pre-enqueue schema / registry / source / prepared SHA-256 mismatch refusals + assert http.post("/jobs", json=payload()).status_code == 428 + for hdr in _job_headers(catalog): + bad_hdr = {**_job_headers(catalog), hdr: "0" * 64} + assert http.post("/jobs", json=payload(), headers=bad_hdr).status_code == 409 + bad_src = http.post("/jobs", json=payload(source_sha256="0" * 64), headers=_job_headers(catalog)) + assert bad_src.status_code == 422 and bad_src.json()["detail"]["code"] == "capability_or_binding_refused" + bad_prep = http.post("/jobs", json=payload(prepared_sha256="f" * 64), headers=_job_headers(catalog)) + assert bad_prep.status_code == 422 and bad_prep.json()["detail"]["code"] == "capability_or_binding_refused" + assert store.events() == [] + + # 5. Stage slot gate so two live SSE subscribers attach before compute finishes + spec, execution = catalog.prepare(JobSubmission.model_validate(payload())) + gate_handle = supervisor.submit("slot-gate", gate_binding.id, spec.request, ceiling, execution=execution) + until = time.monotonic() + 10 + while time.monotonic() < until: + if any( + e["payload"].get("ui_progress", {}).get("stage") == "slot_gate_ready" + for e in store.events(run_id="slot-gate", limit=100) + ): + break + time.sleep(0.005) + else: + pytest.fail("slot_gate did not reach ready barrier") + + accepted_resp = http.post("/jobs", json=payload(), headers=_job_headers(catalog)) + assert accepted_resp.status_code == 202, accepted_resp.text + accepted = accepted_resp.json() + assert accepted["scientific_qualification"] is False + dup_resp = http.post("/jobs", json=payload(), headers=_job_headers(catalog)) + assert dup_resp.status_code == 202 and dup_resp.json()["attempt_id"] == accepted["attempt_id"] + + obs_a = server.observe("sub-a") + obs_b = server.observe("sub-b") + with sub_a_client.stream( + "GET", accepted["events_url"], headers={"X-Test-Subscriber": "sub-a"} + ) as stream_a: + with sub_b_client.stream( + "GET", accepted["events_url"], headers={"X-Test-Subscriber": "sub-b"} + ) as stream_b: + assert obs_a.started.wait(3) and obs_b.started.wait(3) + blocks_a, blocks_b = _blocks(stream_a), _blocks(stream_b) + queued_a = _next_event(blocks_a) + queued_b = _next_event(blocks_b) + assert queued_a == queued_b and queued_a["kind"] == "queued" + + # Disconnect subscriber A while job is queued/about to run; compute MUST NOT cancel. + stream_a.close() + assert obs_a.finished.wait(3) + assert store.get_run(accepted["run_id"])["state"] == "queued" + + # Release slot gate so real cold steady_jv job runs to completion while subscriber B streams. + assert supervisor.cancel(gate_handle, reason="release_slot_for_e2e") + assert supervisor.wait(gate_handle, 10).data["store_state"] == "cancelled" + + remaining_b = [] + for block in blocks_b: + if "data" in block: + rec = json.loads(block["data"]) + assert int(block["id"]) == rec["sequence"] + remaining_b.append(rec) + all_b = [queued_b, *remaining_b] + assert all_b[-1]["kind"] == "terminal" and all_b[-1]["payload"]["state"] == "succeeded" + assert sum(e["kind"] == "terminal" for e in all_b) == 1 + + # Reconnect subscriber A with Last-Event-ID and verify gapless, duplicate-free replay. + with server.client() as reconnect_client: + with reconnect_client.stream( + "GET", + accepted["events_url"], + headers={"Last-Event-ID": str(queued_a["sequence"])}, + ) as reconnected: + replayed_a = _all_events(reconnected) + assert [queued_a, *replayed_a] == all_b + terminal_seq = all_b[-1]["sequence"] + ack = reconnect_client.get( + accepted["events_url"], headers={"Last-Event-ID": str(terminal_seq)} + ) + assert ack.status_code == 204 and ack.content == b"" + + # 6. Verify HTTP result + 8 NPY array artifacts + manifest against read_steady_jv_job + job_handle = JobHandle(store.store_id, accepted["run_id"], accepted["attempt_id"]) + receipt = supervisor.wait(job_handle, 10).data + assert receipt["store_state"] == "succeeded" and receipt["process_joined"] + result_json = http.get(accepted["result_url"]).json() + assert result_json["state"] == "succeeded" and len(result_json["artifacts"]) == 9 + assert result_json["result"]["worker_result"]["scientific_qualification"] is False + loaded = read_steady_jv_job(store, accepted["run_id"], attempt_id=accepted["attempt_id"]) + for item in result_json["artifacts"]: + blob = http.get(item["content_url"]) + assert blob.status_code == 200 + assert hashlib.sha256(blob.content).hexdigest() == item["sha256"] + if item["name"] == "execution_manifest": + assert item["sha256"] == result_json["result"]["worker_result"]["manifest_sha256"] + else: + decoded = np.load(io.BytesIO(blob.content), allow_pickle=False) + assert decoded.tobytes() == loaded["arrays"][item["name"]].tobytes() + + # 7. Read-only server restart readback (no JobService / no ProcessSupervisor) + with _HTTPServer(database) as readonly_server, readonly_server.client() as reader: + assert reader.get(accepted["result_url"]).json() == result_json + with reader.stream("GET", accepted["events_url"]) as full_stream: + assert _all_events(full_stream) == all_b + with reader.stream( + "GET", accepted["events_url"], headers={"Last-Event-ID": str(queued_a["sequence"])} + ) as tail_stream: + assert [queued_a, *_all_events(tail_stream)] == all_b + assert reader.post("/jobs", json=payload(), headers=_job_headers(catalog)).status_code == 503 + + +def test_scaps_yaml_get_noop_editor_save_post_legacy_job_and_orphan_recovery_readback( + tmp_path, legacy_defaults_and_resources +): + defaults, resources = legacy_defaults_and_resources + ceiling = ResourceLimits(30.0, 1024**3, 64 * 1024**2, None, None) + catalog, job = _scaps_bound_catalog(ceiling) + prepared = job.execution.inputs.prepared + scaps_source = prepared.sources[0] + preview_ctx = ConfigurationPreviewContext(defaults, resources, (scaps_source,)) + + database = (tmp_path / "scaps-chain-store").resolve() + work = (tmp_path / "scaps-chain-work").resolve() + + def scaps_submission( + run_id: str = "scaps-yaml-e2e", + *, + source_sha256: str | None = None, + prepared_sha256: str | None = None, + ) -> dict: + return { + "schema_version": "solarlab.job-submission.v1", + "run_id": run_id, + "experiment_id": "jv", + "version": 1, + "engine": "legacy", + "input": { + "device": None, + "config_path": "fixture:scaps", + "expected_source_sha256": scaps_source.sha256 if source_sha256 is None else source_sha256, + "expected_prepared_sha256": prepared.content_sha256 if prepared_sha256 is None else prepared_sha256, + "params": {}, + }, + "limits": { + "wall_seconds": 30.0, + "rss_bytes": 1024**3, + "output_bytes": 64 * 1024**2, + "accepted_steps": None, + "calls": None, + }, + } + + with RunStore(database) as store, ProcessSupervisor( + store, + work, + (catalog.worker_binding("legacy"), legacy_worker_binding()), + max_active=1, + max_pending=2, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + soft_grace_seconds=0.1, + terminate_grace_seconds=0.1, + poll_seconds=0.01, + ) as supervisor: + service = JobService(catalog, supervisor) + with _HTTPServer(database, configuration_preview=preview_ctx, job_service=service) as server: + with server.client() as http: + # 1. GET /configs/{id} -> import_scaps_device -> preview -> no-op legacy-wire save + fetched = http.get(f"/configs/{scaps_source.id}") + assert fetched.status_code == 200 and fetched.content == scaps_source.content + assert fetched.headers["etag"] == f'"{scaps_source.sha256}"' + + editable = import_scaps_device( + SourceDocument(scaps_source.id, fetched.content), id="legacy_job", defaults=defaults + ) + dev_resp = http.post( + "/configuration-preview/device", + json=DeviceInput.model_validate(editable).model_dump(mode="json", exclude_unset=True), + ) + assert dev_resp.status_code == 200 + dev_json = dev_resp.json() + assert dev_json["identity"]["content_sha256"] == prepared.content_sha256 + + wire_resp = http.post( + "/configuration-preview/legacy-wire", + json={ + "schema_version": "solarlab.legacy-wire-preview-request.v1", + "input": dev_json["input"], + "source": {"id": scaps_source.id, "sha256": scaps_source.sha256}, + "references": {}, + }, + headers=_wire_headers(), + ) + assert wire_resp.status_code == 200, wire_resp.text + wire_json = wire_resp.json() + assert wire_json["report"]["strict_roundtrip_passed"] is True + assert wire_json["report"]["differences"] == [] + assert wire_json["documents"][0]["sha256"] == scaps_source.sha256 + assert wire_json["documents"][0]["utf8"].encode("utf-8") == scaps_source.content + assert store.events() == [] + + # 2. Refusal on source / prepared SHA-256 mismatch before enqueue, then valid POST /jobs + assert ( + http.post("/jobs", json=scaps_submission(source_sha256="0" * 64), headers=_job_headers(catalog)).status_code + == 422 + ) + assert ( + http.post("/jobs", json=scaps_submission(prepared_sha256="0" * 64), headers=_job_headers(catalog)).status_code + == 422 + ) + assert store.events() == [] + + sub_resp = http.post("/jobs", json=scaps_submission(), headers=_job_headers(catalog)) + assert sub_resp.status_code == 202, sub_resp.text + accepted = sub_resp.json() + with http.stream("GET", accepted["events_url"]) as stream: + events = _all_events(stream) + assert events[-1]["kind"] == "terminal" and events[-1]["payload"]["state"] == "succeeded" + assert sum(e["kind"] == "terminal" for e in events) == 1 + assert ( + http.get(accepted["events_url"], headers={"Last-Event-ID": str(events[-1]["sequence"])}).status_code + == 204 + ) + receipt = supervisor.wait(JobHandle(store.store_id, accepted["run_id"], accepted["attempt_id"]), 10).data + assert receipt["process_joined"] and receipt["process_exit_observed"] + result_json = http.get(accepted["result_url"]).json() + assert result_json["state"] == "succeeded" + assert result_json["result"]["worker_result"]["scientific_qualification"] is False + + # 3. P06-04 crash-injection + orphan-only recovery + RunBundle + missing-committed-file HTTP 409 check + bundle_path = (tmp_path / "scaps-completed.slrun").resolve() + bundle_pub = store.archive_run(accepted["run_id"], bundle_path) + assert not bundle_pub["contains_active_database"] + + # Inject a crashed attempt that published an uncommitted object AND left a half-written .part file. + store.enqueue( + "crashed-writer", + opaque_identity={"H_input": "crash:i", "H_physics": "crash:p", "H_execution": "crash:e"}, + input_metadata={"kind": "crash_injection"}, + ) + queued = store.get_run("crashed-writer") + crash_token = store.claim( + "crashed-writer", + expected_attempt_id=queued["current_attempt_id"], + expected_generation=queued["generation"], + owner_id="crashed-owner", + ) + orphan_pub = store.publish( + crash_token, "uncommitted_blob", bytes_artifact(b"orphan-published-before-db-commit", metadata={}) + ) + half_part = database / "partial" / (orphan_pub["artifact_id"] + ".part") + half_part.write_bytes(b"half-written") + orphan_obj = database / orphan_pub["relative_path"] + assert orphan_obj.is_file() and half_part.is_file() + + interrupted = store.recover_interrupted() + assert interrupted["interrupted_attempts"] == [crash_token.attempt_id] + collected = store.recover_artifacts(cleanup=True) + assert collected["issues"] == [] + assert orphan_pub["relative_path"] in collected["removed_paths"] + assert f"partial/{orphan_pub['artifact_id']}.part" in collected["removed_paths"] + assert not orphan_obj.exists() and not half_part.exists() + + # Committed HTTP run survives orphan cleanup intact in both read-only HTTP server and RunBundle! + with RunBundle(bundle_path, expected_sha256=bundle_pub["sha256"]) as bundle: + assert bundle.get_run()["state"] == "succeeded" + assert len(bundle.events()) == len(events) + + with _HTTPServer(database) as readonly_server, readonly_server.client() as reader: + assert reader.get(accepted["result_url"]).json() == result_json + for item in result_json["artifacts"]: + resp = reader.get(item["content_url"]) + assert resp.status_code == 200 and hashlib.sha256(resp.content).hexdigest() == item["sha256"] + + # Simulate missing indexed committed artifact on disk -> explicit HTTP 409 artifact_integrity (never silent!). + target_artifact = result_json["artifacts"][0] + committed_path = database / target_artifact["relative_path"] + saved_bytes = committed_path.read_bytes() + committed_path.unlink() + try: + with RunStore(database, read_only=True) as audit_store: + audit = audit_store.recover_artifacts(cleanup=False) + assert any(issue["artifact_id"] == target_artifact["artifact_id"] for issue in audit["issues"]) + with _HTTPServer(database) as broken_server, broken_server.client() as reader: + res_err = reader.get(accepted["result_url"]) + assert res_err.status_code == 409 and res_err.json()["detail"]["code"] == "artifact_integrity" + art_err = reader.get(target_artifact["content_url"]) + assert art_err.status_code == 409 and art_err.json()["detail"]["code"] == "artifact_integrity" + finally: + committed_path.write_bytes(saved_bytes) diff --git a/tests/runtime/test_p06_sweep_resume_and_equivalence.py b/tests/runtime/test_p06_sweep_resume_and_equivalence.py new file mode 100644 index 00000000..ffbc073e --- /dev/null +++ b/tests/runtime/test_p06_sweep_resume_and_equivalence.py @@ -0,0 +1,438 @@ +"""P06-05 closeout: real RunSpec sweep equivalence, interrupted resume, retry and full-identity reuse.""" +from __future__ import annotations + +from dataclasses import replace +import json +import multiprocessing +import os +from pathlib import Path +import signal +import subprocess +import time + +import pytest + +from solarlab.config.identity import ExecutionEngine +from solarlab.experiments.execution import JobHandle, ProcessSupervisor, ScanSpec +from solarlab.experiments.jv.worker import SteadyJVProtocol, steady_jv_worker_binding +from solarlab.experiments.worker import ResourceLimits +from solarlab.io.run_store import RunStore, StateConflict +from solarlab.materials.source import SourceDocument +from solarlab.sweeps.inputs import SweepInput +from solarlab.sweeps.preparation import prepare_sweep +from solarlab.sweeps.steady_worker import ( + SteadySweepJobs, prepare_steady_sweep_jobs, read_steady_sweep_jobs, +) + +pytestmark = pytest.mark.requires_clean_core + +ROOT = Path(__file__).resolve().parents[2] +LIMITS = ResourceLimits(60.0, 1536 * 1024**2, 96 * 1024**2, None, None) +PROTOCOL = SteadyJVProtocol((0.0, 0.05, 0.1), 8, 1.0, None) +ARRAY_NAMES = ( + "nodes_m", + "voltage_V", + "current_density_A_m2", + "contact_current_density_A_m2", + "output_current_A_m2", + "potential_V", + "electron_density_m3", + "hole_density_m3", +) + + +@pytest.fixture(scope="module") +def implementation(): + from examples.research_1d.service import committed_implementation + + commit = os.environ.get("SOLARLAB_PROCESS_SWEEP_SOURCE_PIN") or subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True, timeout=5 + ).strip() + return committed_implementation(commit) + + +@pytest.fixture(scope="module") +def three_point_sweep(): + from examples.research_1d.jv_scan import make_sweep + + return make_sweep( + ROOT / "examples/research_1d/device.json", + study_id="p06-05-three-point", + parameter="tau_n", + values=["1 us", "2 us", "4 us"], + ) + + +@pytest.fixture(scope="module") +def three_point_jobs(three_point_sweep, implementation): + return prepare_steady_sweep_jobs( + three_point_sweep, + PROTOCOL, + limits=LIMITS, + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + ) + + +def _pool(store: RunStore, work: Path, *, max_active: int = 1, max_pending: int = 2) -> ProcessSupervisor: + return ProcessSupervisor( + store, + work, + (steady_jv_worker_binding(),), + max_active=max_active, + max_pending=max_pending, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + soft_grace_seconds=0.1, + terminate_grace_seconds=0.1, + poll_seconds=0.01, + ) + + +def _terminals(store: RunStore, run_id: str) -> list[dict]: + return [event for event in store.events(run_id=run_id, limit=1000) if event["kind"] == "terminal"] + + +def _daemon_nested_supervisor_probe(store_root: str, work_root: str, result_queue: multiprocessing.Queue) -> None: + try: + with RunStore(Path(store_root)) as child_store: + ProcessSupervisor( + child_store, + Path(work_root), + (steady_jv_worker_binding(),), + max_active=1, + max_pending=1, + shared_rss_bytes=512 * 1024**2, + shared_output_bytes=64 * 1024**2, + ) + except ValueError as error: + result_queue.put(("rejected", str(error))) + else: + result_queue.put(("allowed", "")) + + +@pytest.fixture(scope="module") +def serial_reference(tmp_path_factory, three_point_jobs): + root = tmp_path_factory.mktemp("p06-05-serial-ref") + with RunStore(root / "store") as store, _pool(store, root / "work", max_active=1, max_pending=2) as supervisor: + scan = three_point_jobs.submit(supervisor, max_in_flight=1) + status = scan.wait(180) + assert status["complete"] and status["state"] == "succeeded", status + assert status["max_in_flight"] == 1 and status["coordinator_uses_process_slot"] is False + assert status["scientific_qualification_inferred"] is False + declaration_bytes = scan.declaration_path.read_bytes() + with RunStore(root / "store", read_only=True) as reader: + points = read_steady_sweep_jobs(reader, ScanSpec.from_bytes(declaration_bytes)) + return points + + +def _assert_points_bitwise_equivalent(actual: tuple[dict, ...], reference: tuple[dict, ...]) -> None: + assert [p["point_id"] for p in actual] == [p["point_id"] for p in reference] + assert [p["coordinates"]["index"] for p in actual] == [0, 1, 2] + assert [p["coordinates"]["normalized_coordinates"]["tau_n"]["value"] for p in actual] == [1e-6, 2e-6, 4e-6] + for got, ref in zip(actual, reference, strict=True): + assert got["state"] == ref["state"] == "succeeded" + got_res, ref_res = got["result"], ref["result"] + assert got_res is not None and ref_res is not None + assert got_res["worker_result"]["scientific_qualification"] is False + assert ref_res["worker_result"]["scientific_qualification"] is False + assert got_res["document"]["compiled_identity"] == ref_res["document"]["compiled_identity"] + assert got_res["document"]["metrics"] == ref_res["document"]["metrics"] + assert got_res["document"]["solver_evidence"] == ref_res["document"]["solver_evidence"] + assert set(got_res["arrays"]) == set(ARRAY_NAMES) + for name in ARRAY_NAMES: + assert got_res["arrays"][name].dtype == ref_res["arrays"][name].dtype + assert got_res["arrays"][name].shape == ref_res["arrays"][name].shape + assert got_res["arrays"][name].tobytes() == ref_res["arrays"][name].tobytes() + + +def test_real_sweep_serial_parallel_and_random_order_bitwise_equivalence_and_non_starvation( + tmp_path, three_point_sweep, three_point_jobs, serial_reference +): + assert not three_point_sweep.can_execute + + # 1. Bounded-parallel execution (max_active=2, max_in_flight=2). + par_store = (tmp_path / "parallel-store").resolve() + par_work = (tmp_path / "parallel-work").resolve() + par_jobs = prepare_steady_sweep_jobs( + three_point_sweep, + PROTOCOL, + limits=LIMITS, + implementation=three_point_jobs.executions[0].execution.implementation, + current_repository_head=three_point_jobs.executions[0].execution.current_repository_head, + engine=ExecutionEngine("solarlab"), + scan_id="p06-05-parallel", + ) + with RunStore(par_store) as store, _pool(store, par_work, max_active=2, max_pending=2) as supervisor: + par_scan = par_jobs.submit(supervisor, max_in_flight=2) + par_status = par_scan.wait(180) + assert par_status["complete"] and par_status["state"] == "succeeded", par_status + assert par_status["max_in_flight"] == 2 + assert par_status["coordinator_uses_process_slot"] is False + assert par_status["scientific_qualification_inferred"] is False + par_decl = par_scan.declaration_path.read_bytes() + with RunStore(par_store, read_only=True) as reader: + par_points = read_steady_sweep_jobs(reader, ScanSpec.from_bytes(par_decl)) + _assert_points_bitwise_equivalent(par_points, serial_reference) + + # 2. Permuted / random point dispatch order [p2, p0, p1] with max_in_flight=2 > max_active=1: + # proves coordinator never occupies or starves the single worker slot AND readback restores declared order. + declared_ids = [p.point_id for p in three_point_jobs.spec.points] + permuted_ids = [declared_ids[2], declared_ids[0], declared_ids[1]] + reordered_jobs = three_point_jobs.reordered(permuted_ids, scan_id="p06-05-random-order") + assert [p.point_id for p in reordered_jobs.spec.points] == permuted_ids + assert [json.loads(p.coordinates_json)["index"] for p in reordered_jobs.spec.points] == [2, 0, 1] + + with pytest.raises(ValueError, match="exact permutation"): + three_point_jobs.reordered([declared_ids[0], declared_ids[0], declared_ids[1]]) + + rand_store = (tmp_path / "random-store").resolve() + rand_work = (tmp_path / "random-work").resolve() + with RunStore(rand_store) as store, _pool(store, rand_work, max_active=1, max_pending=1) as supervisor: + rand_scan = reordered_jobs.submit(supervisor, max_in_flight=2) + rand_status = rand_scan.wait(180) + assert rand_status["complete"] and rand_status["state"] == "succeeded", rand_status + assert rand_status["max_in_flight"] == 2 + assert rand_status["coordinator_uses_process_slot"] is False + rand_decl = rand_scan.declaration_path + restored = SteadySweepJobs.from_declaration(rand_decl, executions=three_point_jobs.executions) + assert [p.point_id for p in restored.spec.points] == permuted_ids + with RunStore(rand_store, read_only=True) as reader: + rand_points = read_steady_sweep_jobs(reader, restored.spec) + _assert_points_bitwise_equivalent(rand_points, serial_reference) + + # 3. Daemon worker processes cannot construct nested ProcessSupervisors (no nested worker-pool deadlock). + ctx = multiprocessing.get_context("spawn") + nested_store = (tmp_path / "nested-store").resolve() + nested_work = (tmp_path / "nested-work").resolve() + with RunStore(nested_store): + pass + queue: multiprocessing.Queue = ctx.Queue() + proc = ctx.Process( + target=_daemon_nested_supervisor_probe, + args=(str(nested_store), str(nested_work), queue), + daemon=True, + ) + proc.start() + outcome, detail = queue.get(timeout=15) + proc.join(timeout=10) + assert proc.exitcode == 0 + assert outcome == "rejected" and "nested supervisors or scans" in detail + + +def test_real_sweep_interrupted_resumption_and_explicit_point_retry_preserve_failed_attempt( + tmp_path, three_point_jobs, serial_reference +): + store_root = (tmp_path / "resume-store").resolve() + work_root = (tmp_path / "resume-work").resolve() + p0, p1, p2 = three_point_jobs.spec.points + + # Session 1: p0 completes, p1 is killed mid-flight, p2 remains unstarted ('declared'). + with RunStore(store_root) as store, _pool(store, work_root, max_active=1, max_pending=1) as supervisor: + scan = three_point_jobs.submit(supervisor, max_in_flight=1) + declaration_path = scan.declaration_path + + deadline = time.monotonic() + 90 + p1_attempt_id = None + p1_pid = None + while time.monotonic() < deadline: + snap = scan.advance() + s0, s1, s2 = snap["points"] + if s0["state"] == "succeeded" and s1["attempt_id"] is not None: + p1_attempt_id = s1["attempt_id"] + spawned_file = work_root / f"{store.store_id}-{p1_attempt_id}" / "spawned.json" + if spawned_file.exists(): + p1_pid = json.loads(spawned_file.read_text())["pid"] + assert s2["state"] == "declared" and s2["attempt_id"] is None + break + time.sleep(0.002) + else: + pytest.fail("timed out waiting for p0 completion and p1 spawn") + + assert isinstance(p1_pid, int) and p1_pid > 0 + os.kill(p1_pid, signal.SIGKILL) + failed_receipt = supervisor.wait(JobHandle(store.store_id, p1.run_id, p1_attempt_id), 15).data + assert failed_receipt["store_state"] == "failed" + assert failed_receipt["process_exit_observed"] is True and failed_receipt["process_joined"] is True + assert store.get_run(p0.run_id)["state"] == "succeeded" + assert store.get_run(p1.run_id)["state"] == "failed" + with pytest.raises(KeyError): + store.get_run(p2.run_id) # p2 was never enqueued before session interruption. + + # Session 2: reopen RunStore + ProcessSupervisor, restore persisted ScanSpec, reuse p0, run p2, retry p1. + with RunStore(store_root) as store2, _pool(store2, work_root, max_active=1, max_pending=1) as supervisor2: + resumed_jobs = SteadySweepJobs.from_declaration(declaration_path, executions=three_point_jobs.executions) + resumed = resumed_jobs.submit(supervisor2, max_in_flight=1) + mid = resumed.advance() + assert mid["points"][0]["state"] == "succeeded" and mid["points"][0]["reused"] is True + assert len(store2.attempts(p0.run_id)) == 1 + assert mid["points"][1]["state"] == "failed" and mid["points"][1]["attempt_id"] == p1_attempt_id + assert mid["points"][2]["state"] in {"queued", "running"} + + with pytest.raises(StateConflict, match="exact current failed/cancelled attempt"): + resumed.retry(p1.point_id, expected_attempt_id="stale-attempt-id") + retry_handle = resumed.retry(p1.point_id, expected_attempt_id=p1_attempt_id) + assert retry_handle.attempt_id != p1_attempt_id + + final = resumed.wait(120) + assert final["complete"] and final["state"] == "succeeded", final + assert final["points"][0]["reused"] is True + assert len(store2.attempts(p0.run_id)) == 1 + assert len(store2.attempts(p2.run_id)) == 1 + p1_attempts = store2.attempts(p1.run_id) + assert [a["state"] for a in p1_attempts] == ["failed", "succeeded"] + assert p1_attempts[0]["attempt_id"] == p1_attempt_id + assert p1_attempts[0]["terminal"]["artifacts"] == [] + assert len(p1_attempts[1]["terminal"]["artifacts"]) == 9 + assert len(_terminals(store2, p0.run_id)) == 1 + assert len(_terminals(store2, p1.run_id)) == 2 + assert len(_terminals(store2, p2.run_id)) == 1 + + with RunStore(store_root, read_only=True) as reader: + points = read_steady_sweep_jobs(reader, resumed_jobs.spec) + assert len(points[1]["attempts"]) == 2 + assert points[1]["attempts"][0]["state"] == "failed" and points[1]["attempts"][0]["steady_result"] is None + assert points[1]["attempts"][1]["state"] == "succeeded" and points[1]["attempts"][1]["steady_result"] is not None + _assert_points_bitwise_equivalent(points, serial_reference) + + +def test_real_sweep_completed_point_reuse_bound_to_full_execution_identity_and_mismatch_refusal( + tmp_path, implementation +): + from examples.research_1d.jv_scan import make_sweep + + sweep_a = make_sweep( + ROOT / "examples/research_1d/device.json", + study_id="p06-05-exec-a", + parameter="tau_n", + values=["1 us", "2 us"], + ) + sweep_b = make_sweep( + ROOT / "examples/research_1d/device.json", + study_id="p06-05-exec-b", + parameter="tau_n", + values=["2 us", "4 us"], + ) + jobs_a = prepare_steady_sweep_jobs( + sweep_a, + PROTOCOL, + limits=LIMITS, + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + reuse_scope="execution_identity", + ) + jobs_b = prepare_steady_sweep_jobs( + sweep_b, + PROTOCOL, + limits=LIMITS, + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + reuse_scope="execution_identity", + ) + shared_run_id = jobs_a.spec.points[1].run_id + assert shared_run_id.startswith("exec:") + assert jobs_b.spec.points[0].run_id == shared_run_id + assert jobs_a.spec.points[0].run_id != shared_run_id + assert jobs_b.spec.points[1].run_id != shared_run_id + + store_root = (tmp_path / "exec-reuse-store").resolve() + work_root = (tmp_path / "exec-reuse-work").resolve() + with RunStore(store_root) as store, _pool(store, work_root, max_active=1, max_pending=2) as supervisor: + status_a = jobs_a.submit(supervisor, max_in_flight=1).wait(120) + assert status_a["complete"] and status_a["state"] == "succeeded" + assert [p["reused"] for p in status_a["points"]] == [False, False] + shared_events_before = store.events(run_id=shared_run_id, limit=1000) + + status_b = jobs_b.submit(supervisor, max_in_flight=1).wait(120) + assert status_b["complete"] and status_b["state"] == "succeeded" + assert status_b["points"][0]["reused"] is True + assert status_b["points"][1]["reused"] is False + # Zero new attempts or events were created on the reused '2 us' point. + assert len(store.attempts(shared_run_id)) == 1 + assert store.events(run_id=shared_run_id, limit=1000) == shared_events_before + + # Negative checks: mutating H_input, H_execution/protocol, BuildSource, ResourceLimits, or schema + # never maps to the same execution-identity run_id, and forcing the old run_id raises StateConflict. + raw_input_changed = sweep_b.to_input().model_dump(mode="json", exclude_unset=True) + raw_input_changed["base"]["layers"][1]["thickness"] = "420 nm" + sweep_input_changed = prepare_sweep( + SweepInput.model_validate(raw_input_changed), + sweep_b.defaults, + sweep_b.resources, + sources=sweep_b.sources, + ) + jobs_input_changed = prepare_steady_sweep_jobs( + sweep_input_changed, + PROTOCOL, + limits=LIMITS, + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + scan_id="p06-05-input-diff", + reuse_scope="execution_identity", + ) + jobs_protocol_changed = prepare_steady_sweep_jobs( + sweep_b, + SteadyJVProtocol((0.0, 0.04, 0.1), 8, 1.0, None), + limits=LIMITS, + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + scan_id="p06-05-proto-diff", + reuse_scope="execution_identity", + ) + jobs_limits_changed = prepare_steady_sweep_jobs( + sweep_b, + PROTOCOL, + limits=replace(LIMITS, wall_seconds=45.0), + implementation=implementation, + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + scan_id="p06-05-limits-diff", + reuse_scope="execution_identity", + ) + jobs_source_changed = prepare_steady_sweep_jobs( + sweep_b, + PROTOCOL, + limits=LIMITS, + implementation=replace(implementation, build_source_commit="1" * 40), + current_repository_head=implementation.build_source_commit, + engine=ExecutionEngine("solarlab"), + scan_id="p06-05-source-diff", + reuse_scope="execution_identity", + ) + + for index, variant in enumerate( + (jobs_input_changed, jobs_protocol_changed, jobs_limits_changed, jobs_source_changed) + ): + assert variant.spec.points[0].run_id != shared_run_id + forced_point = replace(variant.spec.points[0], run_id=shared_run_id) + forced_jobs = SteadySweepJobs( + ScanSpec(f"forced-mismatch-{index}", (forced_point,)), + (variant.executions[0],), + ) + with pytest.raises(StateConflict, match="differs from the complete stored execution request"): + forced_jobs.submit(supervisor) + + # Also verify schema-digest mismatch refusal on WorkerRequest. + altered_schema = SourceDocument("solarlab.steady-jv.worker-request.v2", b'{"schema":"v2"}') + bad_req = replace(jobs_b.spec.points[0].spec.request, schema=altered_schema) + bad_spec = replace(jobs_b.spec.points[0].spec, request=bad_req) + with pytest.raises(ValueError, match="schema"): + SteadySweepJobs( + ScanSpec("forced-schema-mismatch", (replace(jobs_b.spec.points[0], spec=bad_spec),)), + (jobs_b.executions[0],), + ).submit(supervisor) + + assert len(store.attempts(shared_run_id)) == 1 + + with RunStore(store_root, read_only=True) as reader: + read_a = read_steady_sweep_jobs(reader, jobs_a.spec) + read_b = read_steady_sweep_jobs(reader, jobs_b.spec) + assert read_a[1]["coordinates"]["index"] == 1 + assert read_b[0]["coordinates"]["index"] == 0 + for name in ARRAY_NAMES: + assert read_a[1]["result"]["arrays"][name].tobytes() == read_b[0]["result"]["arrays"][name].tobytes() From 60c40ffe95f5d3bd156c3081623534e91f99b1f0 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 16:08:00 +0800 Subject: [PATCH 07/46] N(experiments): add P05-02b and P05-03a characterization recipes - P05-02b: genuine DC Suns-V_oc (suns_voc.py), cold temperature-rebound V_oc(T) (voc_t.py), DC dark J-V with curvature-window diode extraction (dark_jv.py), and Backward Euler piecewise/triangular waveform J-V with displacement-inclusive PV/conjugate current reporting (waveform_jv.py). - P05-03a: small-signal AC C-f / C-V / Mott-Schottky with apparent_built_in_voltage_V, active vs frozen ionic modes, and inductive/0-Hz refusal (mott_schottky.py); monochromatic EQE with closed PhotonBudget and J_sc_eqe_A_m2 (eqe.py); and Rau reciprocity EL spectrum with radiative vs total recombination decomposition (el_spectrum.py). - Add T1/T2/T4 analytic, coupled-ionic, and perovskite_sim parity test suites across 5 test modules. --- src/solarlab/experiments/dark_jv.py | 566 ++++++++ src/solarlab/experiments/el_spectrum.py | 436 ++++++ src/solarlab/experiments/eqe.py | 862 +++++++++++ src/solarlab/experiments/mott_schottky.py | 1260 +++++++++++++++++ src/solarlab/experiments/suns_voc.py | 1050 ++++++++++++++ src/solarlab/experiments/voc_t.py | 328 +++++ src/solarlab/experiments/waveform_jv.py | 954 +++++++++++++ tests/integration/test_eqe_el_spectrum.py | 438 ++++++ tests/integration/test_mott_schottky_cv_cf.py | 341 +++++ tests/integration/test_suns_voc_voc_t.py | 284 ++++ tests/integration/test_waveform_dark_jv.py | 331 +++++ .../experiments/test_characterization_p05.py | 396 ++++++ 12 files changed, 7246 insertions(+) create mode 100644 src/solarlab/experiments/dark_jv.py create mode 100644 src/solarlab/experiments/el_spectrum.py create mode 100644 src/solarlab/experiments/eqe.py create mode 100644 src/solarlab/experiments/mott_schottky.py create mode 100644 src/solarlab/experiments/suns_voc.py create mode 100644 src/solarlab/experiments/voc_t.py create mode 100644 src/solarlab/experiments/waveform_jv.py create mode 100644 tests/integration/test_eqe_el_spectrum.py create mode 100644 tests/integration/test_mott_schottky_cv_cf.py create mode 100644 tests/integration/test_suns_voc_voc_t.py create mode 100644 tests/integration/test_waveform_dark_jv.py create mode 100644 tests/unit/experiments/test_characterization_p05.py diff --git a/src/solarlab/experiments/dark_jv.py b/src/solarlab/experiments/dark_jv.py new file mode 100644 index 00000000..d8a3f462 --- /dev/null +++ b/src/solarlab/experiments/dark_jv.py @@ -0,0 +1,566 @@ +"""Dark DC J-V sweep, exponential diode window selection, and ideality extraction. + +Solves genuine dark steady-state operating points (``generation_scale = 0.0``) on +the unified assembled 1D drift-diffusion (or coupled ionic-electronic) residual. +Both terminal sign conventions are reported explicitly: + +- ``pv_output_current_A_m2``: photovoltaic output convention (negative under + forward dark injection ``V > 0``, matching ``SteadyJVResult.output_current_A_m2`` + and legacy ``DarkJVResult.J``). +- ``voltage_conjugate_current_A_m2``: passive port input convention (positive + under forward dark injection ``V > 0``). + +Failed points record ``np.nan`` and an explicit ``point_reasons`` entry; ``0.0`` +is never substituted. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass, field +import math +from typing import Any + +import numpy as np + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.equations.dc_1d import CompiledDevice1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, IonicState1D +from solarlab.experiments.suns_voc import ( + default_ionic_steady_options, + solve_ionic_dc_operating_point, +) +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyStateError, + solve_steady_state, +) + +__all__ = [ + "DarkJVOptions", + "DarkJVResult", + "extract_dark_diode_parameters", + "run_dark_jv", + "select_dark_diode_window", +] + +BOLTZMANN_J_K = 1.380649e-23 +ProgressCallback = Callable[[str, int, int, str], None] + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class DarkJVOptions: + """Explicit numerical and diode-fitting controls for dark DC J-V.""" + + steady: SteadyOptions = field(default_factory=SteadyOptions) + ionic_steady: IonicSteadyOptions | None = None + min_diode_window_points: int = 8 + current_floor_A_m2: float = 1e-6 + min_forward_voltage_V: float = 0.01 + require_all_converged: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + if ( + type(self.min_diode_window_points) is not int + or self.min_diode_window_points < 3 + ): + raise ValueError("min_diode_window_points must be an integer >= 3") + if not math.isfinite(self.current_floor_A_m2) or self.current_floor_A_m2 <= 0.0: + raise ValueError("current_floor_A_m2 must be finite and positive") + if ( + not math.isfinite(self.min_forward_voltage_V) + or self.min_forward_voltage_V < 0.0 + ): + raise ValueError("min_forward_voltage_V must be finite and nonnegative") + + +@dataclass(frozen=True) +class DarkJVResult: + """Genuine dark DC J-V curve and extracted Shockley diode metrics.""" + + voltage_V: np.ndarray + pv_output_current_A_m2: np.ndarray + voltage_conjugate_current_A_m2: np.ndarray + converged_mask: np.ndarray + point_reasons: tuple[str | None, ...] + local_ideality_factor: np.ndarray + fit_mask: np.ndarray + n_ideality: float + saturation_current_J0_A_m2: float + V_fit_lo_V: float + V_fit_hi_V: float + r_squared: float + series_resistance_est_ohm_m2: float + fit_failure_reason: str | None + max_current_spread_A_m2: float + temperature_K: float + voltage_polarity: float + compiled_identity: str + solver_controls: dict[str, Any] + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "voltage_V", + "pv_output_current_A_m2", + "voltage_conjugate_current_A_m2", + "local_ideality_factor", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ("converged_mask", "fit_mask"): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + @property + def V(self) -> np.ndarray: + return self.voltage_V + + @property + def J(self) -> np.ndarray: + return self.pv_output_current_A_m2 + + @property + def J_0(self) -> float: + return self.saturation_current_J0_A_m2 + + @property + def V_fit_lo(self) -> float: + return self.V_fit_lo_V + + @property + def V_fit_hi(self) -> float: + return self.V_fit_hi_V + + @property + def completed(self) -> bool: + return bool(np.all(self.converged_mask)) + + +def select_dark_diode_window( + voltage_V: Sequence[float] | np.ndarray, + pv_output_current_A_m2: Sequence[float] | np.ndarray, + *, + converged_mask: Sequence[bool] | np.ndarray | None = None, + min_points: int = 8, + J_floor_A_m2: float = 1e-6, + min_forward_voltage_V: float = 0.01, +) -> tuple[np.ndarray, str | None]: + """Identify the contiguous exponential forward-injection diode window. + + Selects ``min_points`` valid forward-injecting samples (``V > min_forward_voltage_V``, + ``J_pv < 0``, ``|J_pv| > J_floor_A_m2``) with minimal mean ``|d^2(ln|J|)/dV^2|`` + and grows outward while ``|d^2(ln|J|)/dV^2| <= max(10 * best_mean, 1e-10)``. + """ + v_arr: np.ndarray = np.asarray(voltage_V, dtype=float) + j_pv: np.ndarray = np.asarray(pv_output_current_A_m2, dtype=float) + if v_arr.ndim != 1 or j_pv.shape != v_arr.shape: + raise ValueError("voltage_V and pv_output_current_A_m2 must be matching 1D arrays") + conv = ( + np.isfinite(v_arr) & np.isfinite(j_pv) + if converged_mask is None + else np.asarray(converged_mask, dtype=bool) + & np.isfinite(v_arr) + & np.isfinite(j_pv) + ) + abs_j = np.abs(j_pv) + valid = ( + conv + & (v_arr > min_forward_voltage_V) + & (j_pv < 0.0) + & (abs_j > J_floor_A_m2) + ) + idx = np.flatnonzero(valid) + fit_mask: np.ndarray = np.zeros(v_arr.shape, dtype=bool) + if idx.size < min_points: + return ( + fit_mask, + f"insufficient_forward_injection_points:{idx.size}_need_{min_points}", + ) + + v_valid = v_arr[idx] + if np.any(np.diff(v_valid) <= 0.0): + raise ValueError("valid forward voltage samples must be strictly ascending") + log_j = np.log(abs_j[idx]) + dlog = np.gradient(log_j, v_valid) + d2log = np.gradient(dlog, v_valid) + + w_len = min_points + best_i = 0 + best_score = float("inf") + for i in range(0, int(idx.size) - w_len + 1): + # Also require positive local log-slope across candidate window. + if np.any(dlog[i : i + w_len] <= 0.0): + continue + score = float(np.mean(np.abs(d2log[i : i + w_len]))) + if score < best_score: + best_score = score + best_i = i + + if not math.isfinite(best_score): + return fit_mask, "no_positive_slope_exponential_window" + + threshold = max(10.0 * best_score, 1e-10) + lo = best_i + hi = best_i + w_len - 1 + while lo > 0 and abs(d2log[lo - 1]) <= threshold and dlog[lo - 1] > 0.0: + lo -= 1 + while ( + hi < int(idx.size) - 1 + and abs(d2log[hi + 1]) <= threshold + and dlog[hi + 1] > 0.0 + ): + hi += 1 + + # Keep only a contiguous slice in the original voltage array if non-converged + # gaps existed inside idx[lo:hi+1]. + fit_indices = idx[lo : hi + 1] + fit_mask[fit_indices] = True + return fit_mask, None + + +def extract_dark_diode_parameters( + voltage_V: Sequence[float] | np.ndarray, + pv_output_current_A_m2: Sequence[float] | np.ndarray, + *, + temperature_K: float, + converged_mask: Sequence[bool] | np.ndarray | None = None, + min_points: int = 8, + J_floor_A_m2: float = 1e-6, + min_forward_voltage_V: float = 0.01, +) -> tuple[ + np.ndarray, + np.ndarray, + float, + float, + float, + float, + float, + float, + str | None, +]: + """Compute local ideality, exponential diode fit, and high-bias R_s estimate.""" + v_arr: np.ndarray = np.asarray(voltage_V, dtype=float) + j_pv: np.ndarray = np.asarray(pv_output_current_A_m2, dtype=float) + if not math.isfinite(temperature_K) or temperature_K <= 0.0: + raise ValueError("temperature_K must be finite and positive") + v_thermal = BOLTZMANN_J_K * float(temperature_K) / ELEMENTARY_CHARGE_C + + conv = ( + np.isfinite(v_arr) & np.isfinite(j_pv) + if converged_mask is None + else np.asarray(converged_mask, dtype=bool) + & np.isfinite(v_arr) + & np.isfinite(j_pv) + ) + j_conj = -j_pv + fwd_valid = conv & (v_arr > min_forward_voltage_V) & (j_conj > J_floor_A_m2) + local_n: np.ndarray = np.full(v_arr.shape, np.nan, dtype=float) + if int(np.count_nonzero(fwd_valid)) >= 2: + v_fwd = v_arr[fwd_valid] + if np.all(np.diff(v_fwd) > 0.0): + dln_j_dv = np.gradient(np.log(j_conj[fwd_valid]), v_fwd) + with np.errstate(divide="ignore", invalid="ignore"): + n_vals = np.where(dln_j_dv > 0.0, 1.0 / (v_thermal * dln_j_dv), np.nan) + local_n[fwd_valid] = n_vals + + fit_mask, reason = select_dark_diode_window( + v_arr, + j_pv, + converged_mask=conv, + min_points=min_points, + J_floor_A_m2=J_floor_A_m2, + min_forward_voltage_V=min_forward_voltage_V, + ) + if reason is not None or not np.any(fit_mask): + return ( + local_n, + fit_mask, + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float("nan"), + reason or "empty_diode_window", + ) + + v_fit = v_arr[fit_mask] + log_j_fit = np.log(j_conj[fit_mask]) + slope, intercept = np.polyfit(v_fit, log_j_fit, 1) + if not math.isfinite(slope) or slope <= 0.0: + return ( + local_n, + fit_mask, + float("nan"), + float("nan"), + float(v_fit[0]), + float(v_fit[-1]), + float("nan"), + float("nan"), + "nonpositive_diode_slope", + ) + + n_id = float(1.0 / (v_thermal * slope)) + j0 = float(math.exp(intercept)) + pred = slope * v_fit + intercept + ss_res = float(np.sum((log_j_fit - pred) ** 2)) + ss_tot = float(np.sum((log_j_fit - np.mean(log_j_fit)) ** 2)) + r_sq = float(1.0 - ss_res / ss_tot) if ss_tot > 0.0 else 1.0 + + # Estimate R_s [Ohm * m^2] from post-window series roll-off where V > V_fit_hi. + hi_v = float(v_fit[-1]) + post_mask = conv & (v_arr > hi_v) & (j_conj > J_floor_A_m2) + rs_est = float("nan") + if np.any(post_mask): + v_post = v_arr[post_mask] + j_post = j_conj[post_mask] + v_ideal = (np.log(j_post) - intercept) / slope + dv = v_post - v_ideal + pos_dv = dv > 0.0 + if np.any(pos_dv): + rs_est = float(np.median(dv[pos_dv] / j_post[pos_dv])) + + return ( + local_n, + fit_mask, + n_id, + j0, + float(v_fit[0]), + hi_v, + r_sq, + rs_est, + None, + ) + + +def _normalize_voltages( + voltage_V: Sequence[float] | np.ndarray | None, + *, + V_min: float, + V_max: float, + n_points: int, +) -> np.ndarray: + if voltage_V is not None: + arr: np.ndarray = np.asarray([float(v) for v in voltage_V], dtype=float) + if arr.ndim != 1 or arr.size < 3 or not np.all(np.isfinite(arr)): + raise ValueError("voltage_V must be a 1D finite sequence with >= 3 points") + if np.any(np.diff(arr) <= 0.0): + raise ValueError("voltage_V must be strictly ascending") + return arr + if type(n_points) is not int or n_points < 3: + raise ValueError("n_points must be an integer >= 3") + if not math.isfinite(V_min) or not math.isfinite(V_max) or V_max <= V_min: + raise ValueError("V_min and V_max must be finite with V_max > V_min") + return np.linspace(float(V_min), float(V_max), n_points, dtype=float) + + +def _rebase_ionic_state( + compiled: CompiledIonicDevice1D, state: IonicState1D, voltage_V: float +) -> IonicState1D: + if state.voltage_V == voltage_V: + return state + coords = state.u.copy() + n_elec = 3 * compiled.node_count + coords[:n_elec] = compiled.electronic_component.rebase_coordinates( + coords[:n_elec], state.voltage_V, voltage_V + ) + return compiled.state(coords, voltage_V=voltage_V) + + +def run_dark_jv( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + *, + voltage_V: Sequence[float] | np.ndarray | None = None, + V_min: float = 0.0, + V_max: float = 1.2, + n_points: int = 60, + options: DarkJVOptions | None = None, + progress: ProgressCallback | None = None, +) -> DarkJVResult: + """Run a genuine dark DC J-V sweep and extract Shockley diode metrics.""" + opts = DarkJVOptions() if options is None else options + voltages = _normalize_voltages( + voltage_V, V_min=V_min, V_max=V_max, n_points=n_points + ) + count = int(voltages.size) + + j_pv: np.ndarray = np.full(count, np.nan, dtype=float) + j_conj: np.ndarray = np.full(count, np.nan, dtype=float) + conv_mask: np.ndarray = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + spread_max = 0.0 + + if isinstance(compiled, CompiledDevice1D): + polarity = float(compiled.voltage_polarity) + temperature_K = float( + compiled.thermal_voltage_V * ELEMENTARY_CHARGE_C / BOLTZMANN_J_K + ) + controls_record: dict[str, Any] = { + "mode": "electronic_dc", + "steady": asdict(opts.steady), + } + prev_state = None + for idx, v_val in enumerate(voltages): + try: + sol = solve_steady_state( + compiled, + voltage_V=float(v_val), + generation_scale=0.0, + initial_state=prev_state, + options=opts.steady, + ) + if not sol.converged: + reasons[idx] = "dc_not_converged:unconverged_steady_result" + continue + except SteadyStateError as exc: + reasons[idx] = f"dc_not_converged:{exc}" + continue + + prev_state = sol.state + faces = np.asarray(sol.current_density_A_m2, dtype=float) + contacts = np.asarray(sol.contact_current_density_A_m2, dtype=float) + spread_max = max(spread_max, float(np.ptp(faces))) + j_pv[idx] = float(-polarity * faces[0]) + j_conj[idx] = float( + polarity * contacts[0 if polarity > 0.0 else -1] + ) + conv_mask[idx] = True + if progress is not None: + progress( + "dark_jv", + idx + 1, + count, + f"V={v_val:.4f} V, J_pv={j_pv[idx]:.3e} A/m^2", + ) + + elif isinstance(compiled, CompiledIonicDevice1D): + polarity = float(compiled.electronic_component.voltage_polarity) + temperature_K = float( + compiled.electronic_component.thermal_voltage_V + * ELEMENTARY_CHARGE_C + / BOLTZMANN_J_K + ) + ionic_controls = ( + default_ionic_steady_options( + compiled.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + controls_record = { + "mode": "ionic_dc", + "ionic_steady": asdict(ionic_controls), + } + prev_ionic: IonicState1D | None = None + for idx, v_val in enumerate(voltages): + sol_ion = solve_ionic_dc_operating_point( + compiled, + voltage_V=float(v_val), + generation_scale=0.0, + options=ionic_controls, + base_state=prev_ionic, + base_generation_scale=0.0, + ) + if ( + not sol_ion.accepted + or sol_ion.state is None + or sol_ion.diagnostics is None + ): + reason = sol_ion.error or sol_ion.termination + reasons[idx] = f"dc_not_converged:{reason}" + continue + + prev_ionic = sol_ion.state + all_faces = np.asarray( + sol_ion.diagnostics["total_current_density_A_m2"], dtype=float + ) + spread_max = max(spread_max, float(np.ptp(all_faces))) + j_pv[idx] = float(-polarity * all_faces[0]) + j_conj[idx] = float( + polarity * all_faces[0 if polarity > 0.0 else -1] + ) + conv_mask[idx] = True + if progress is not None: + progress( + "dark_jv", + idx + 1, + count, + f"V={v_val:.4f} V, J_pv={j_pv[idx]:.3e} A/m^2", + ) + else: + raise TypeError( + "compiled must be a CompiledDevice1D or CompiledIonicDevice1D" + ) + + if opts.require_all_converged and not bool(np.all(conv_mask)): + bad = [ + f"V={voltages[i]:.4g}V ({reasons[i]})" + for i in range(count) + if not conv_mask[i] + ] + raise RuntimeError( + "Dark J-V failed to converge at all points: " + ", ".join(bad) + ) + + ( + local_n, + fit_mask, + n_id, + j0, + v_lo, + v_hi, + r_sq, + rs_est, + fit_reason, + ) = extract_dark_diode_parameters( + voltages, + j_pv, + temperature_K=temperature_K, + converged_mask=conv_mask, + min_points=opts.min_diode_window_points, + J_floor_A_m2=opts.current_floor_A_m2, + min_forward_voltage_V=opts.min_forward_voltage_V, + ) + + return DarkJVResult( + voltage_V=voltages, + pv_output_current_A_m2=j_pv, + voltage_conjugate_current_A_m2=j_conj, + converged_mask=conv_mask, + point_reasons=tuple(reasons), + local_ideality_factor=local_n, + fit_mask=fit_mask, + n_ideality=n_id, + saturation_current_J0_A_m2=j0, + V_fit_lo_V=v_lo, + V_fit_hi_V=v_hi, + r_squared=r_sq, + series_resistance_est_ohm_m2=rs_est, + fit_failure_reason=fit_reason, + max_current_spread_A_m2=float(spread_max), + temperature_K=temperature_K, + voltage_polarity=polarity, + compiled_identity=compiled.identity, + solver_controls=controls_record, + ) diff --git a/src/solarlab/experiments/el_spectrum.py b/src/solarlab/experiments/el_spectrum.py new file mode 100644 index 00000000..1dce64e2 --- /dev/null +++ b/src/solarlab/experiments/el_spectrum.py @@ -0,0 +1,436 @@ +"""Forward-injection reciprocity electroluminescence (EL) spectrum on 1D DC. + +Evaluates Rau's optoelectronic reciprocity relation around a genuine dark +forward-injection DC operating point at ``V_inj_V > 0``: + + Phi_EL(lambda, V_inj) = A_abs(lambda) * phi_bb(lambda, T) * exp(q * V_inj / (k_B * T)) + +together with radiative emission current ``J_em_rad_A_m2 = q * int Phi_EL dlambda``, +total injected dark current ``J_inj_conjugate_A_m2`` (and PV-convention +``J_inj_pv_A_m2``), luminescent external quantum efficiency +``EQE_EL = J_em_rad / J_inj_conjugate``, and non-radiative open-circuit voltage +loss ``delta_V_nr_V = -(k_B * T / q) * ln(min(EQE_EL, 1))``. + +Key N-class contracts (P05-03a): + +1. **Refusal of invalid or unsupported inputs**: Missing tabulated ``nk`` + optical resources (Beer-Lambert-only configurations), graded/incoherent + optics, ``V_inj_V <= 0``, fewer than 2 distinct probe wavelengths, out-of-range + wavelengths, or non-injecting / non-converged dark DC states raise explicit + ``ValueError``, ``CapabilityError``, or ``RuntimeError`` rather than + fabricating zeros. +2. **Exact TMM layer absorptance by default**: ``absorptance_mode="exact_layer"`` + uses analytical Poynting-flux layer absorptance from ``PhotonBudget`` (with + ``"node_trapezoid"`` available for spatial-grid quadrature comparisons). +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass, field +import math +from typing import Any, Literal + +import numpy as np +from scipy.integrate import trapezoid + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.ionic_1d import IonicState1D +from solarlab.experiments.eqe import ( + build_wavelength_optical_binding, + ensure_compilable_spectral_device, +) +from solarlab.experiments.suns_voc import ( + default_ionic_steady_options, + solve_ionic_dc_operating_point, +) +from solarlab.physics.generation.optical_binding import PhotonBudget +from solarlab.physics.generation.spectrum import wavelength_grid_m +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyStateError, + solve_steady_state, +) + +__all__ = [ + "ELOptions", + "ELSpectrumResult", + "blackbody_photon_flux_m2_s_m", + "run_el_spectrum", +] + +BOLTZMANN_J_K = 1.380649e-23 +PLANCK_J_S = 6.62607015e-34 +SPEED_OF_LIGHT_M_S = 299_792_458.0 +ProgressCallback = Callable[[str, int, int, str], None] + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class ELOptions: + """Explicit numerical and optical controls for reciprocity EL spectra.""" + + intervals_per_layer: int = 24 + continuation_steps: int = 12 + absorptance_mode: Literal["exact_layer", "node_trapezoid"] = "exact_layer" + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + steady: SteadyOptions = field(default_factory=SteadyOptions) + ionic_steady: IonicSteadyOptions | None = None + + def __post_init__(self) -> None: + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if type(self.continuation_steps) is not int or self.continuation_steps < 1: + raise ValueError("continuation_steps must be an integer >= 1") + if self.absorptance_mode not in ("exact_layer", "node_trapezoid"): + raise ValueError( + "absorptance_mode must be 'exact_layer' or 'node_trapezoid'" + ) + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + + +@dataclass(frozen=True) +class ELSpectrumResult: + """Forward-injection reciprocity EL spectrum and non-radiative V_oc loss.""" + + wavelengths_nm: np.ndarray + Phi_EL_m2_s_m: np.ndarray + EL_spectrum_m2_s_nm: np.ndarray + blackbody_flux_m2_s_m: np.ndarray + absorber_absorptance: np.ndarray + V_inj_V: float + J_inj_pv_A_m2: float + J_inj_conjugate_A_m2: float + J_em_rad_A_m2: float + EQE_EL: float + delta_V_nr_V: float + delta_V_nr_mV: float + temperature_K: float + photon_budget: PhotonBudget + absorptance_mode: str + optical_binding_sha256: str + compiled_identity: str + solver_controls: dict[str, Any] + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "wavelengths_nm", + "Phi_EL_m2_s_m", + "EL_spectrum_m2_s_nm", + "blackbody_flux_m2_s_m", + "absorber_absorptance", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + @property + def EL_spectrum(self) -> np.ndarray: + return self.EL_spectrum_m2_s_nm + + @property + def V_inj(self) -> float: + return self.V_inj_V + + @property + def J_inj(self) -> float: + return self.J_inj_pv_A_m2 + + @property + def J_em_rad(self) -> float: + return self.J_em_rad_A_m2 + + @property + def T(self) -> float: + return self.temperature_K + + +def blackbody_photon_flux_m2_s_m( + wavelengths_m: Sequence[float] | np.ndarray, temperature_K: float +) -> np.ndarray: + """Hemispherical Lambertian blackbody photon flux [photons m^-2 s^-1 m^-1].""" + wl_m: np.ndarray = np.asarray(wavelengths_m, dtype=float) + if wl_m.ndim != 1 or wl_m.size == 0 or np.any(~np.isfinite(wl_m)) or np.any(wl_m <= 0.0): + raise ValueError("wavelengths_m must be a non-empty 1D positive finite array") + if not math.isfinite(temperature_K) or temperature_K <= 0.0: + raise ValueError("temperature_K must be finite and positive") + + x = PLANCK_J_S * SPEED_OF_LIGHT_M_S / (wl_m * BOLTZMANN_J_K * float(temperature_K)) + x_safe = np.clip(x, 0.0, 700.0) + e_neg = np.exp(-x_safe) + denom = 1.0 - e_neg + denom = np.where(denom > 1e-300, denom, 1.0) + return np.asarray( + (2.0 * math.pi * SPEED_OF_LIGHT_M_S / (wl_m**4)) * (e_neg / denom), + dtype=float, + ) + + +def _normalize_el_wavelengths( + wavelengths_nm: Sequence[float] | np.ndarray | None, +) -> np.ndarray: + if wavelengths_nm is None: + return np.linspace(400.0, 1000.0, 25, dtype=float) + raw = [float(w) for w in wavelengths_nm] + if len(raw) < 2: + raise ValueError("wavelengths_nm must have >= 2 distinct wavelengths for EL integration") + if any(not math.isfinite(w) or w <= 0.0 for w in raw): + raise ValueError(f"wavelengths_nm must be finite and positive, got {raw}") + wl = np.array(sorted(set(raw)), dtype=float) + if wl.size < 2: + raise ValueError("wavelengths_nm must have >= 2 distinct wavelengths for EL integration") + return wl + + +def _absorber_layer_indices(prepared: PreparedDevice) -> tuple[int, ...]: + abs_idx = tuple( + idx for idx, layer in enumerate(prepared.layers) if layer.role == "absorber" + ) + if abs_idx: + return abs_idx + return tuple( + idx for idx, layer in enumerate(prepared.layers) if layer.role != "substrate" + ) + + +def _absorber_node_mask(nodes_m: np.ndarray, prepared: PreparedDevice) -> np.ndarray: + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + if not any(layer.role == "absorber" for layer in elec_layers): + return np.ones_like(nodes_m, dtype=bool) + mask = np.zeros_like(nodes_m, dtype=bool) + cursor = 0.0 + eps = 1e-15 + for layer in elec_layers: + hi = cursor + layer.thickness + if layer.role == "absorber": + mask |= (nodes_m >= cursor - eps) & (nodes_m <= hi + eps) + cursor = hi + return mask + + +def _rebase_ionic_state( + compiled: Any, state: IonicState1D, voltage_V: float +) -> IonicState1D: + if state.voltage_V == voltage_V: + return state + coords = state.u.copy() + n_elec = 3 * compiled.node_count + coords[:n_elec] = compiled.electronic_component.rebase_coordinates( + coords[:n_elec], state.voltage_V, voltage_V + ) + return compiled.state(coords, voltage_V=voltage_V) + + +def run_el_spectrum( + prepared: PreparedDevice, + *, + V_inj_V: float = 1.0, + wavelengths_nm: Sequence[float] | np.ndarray | None = None, + options: ELOptions | None = None, + progress: ProgressCallback | None = None, +) -> ELSpectrumResult: + """Compute forward-injection EL spectrum, EQE_EL, and non-radiative V_oc loss.""" + opts = ELOptions() if options is None else options + v_inj = float(V_inj_V) + if not math.isfinite(v_inj) or v_inj <= 0.0: + raise ValueError(f"V_inj_V must be finite and positive, got {V_inj_V}") + + wl_nm = _normalize_el_wavelengths(wavelengths_nm) + wl_m = wavelength_grid_m(wl_nm) + binding, budget = build_wavelength_optical_binding( + prepared, wl_nm, caller_name="run_el_spectrum" + ) + if progress is not None: + progress("el", 1, 3, "evaluated TMM optical stack") + + compilable = ensure_compilable_spectral_device(prepared, wl_nm) + if opts.ion_domain_layer is not None: + compiled_ion = compile_ionic_device_1d( + compilable, + intervals_per_layer=opts.intervals_per_layer, + ion_domain_layer=opts.ion_domain_layer, + ion_domain_endpoints=opts.ion_domain_endpoints, + ) + elec = compiled_ion.electronic_component + compiled_identity = compiled_ion.identity + else: + compiled_ion = None + elec = compile_device_1d( + compilable, intervals_per_layer=opts.intervals_per_layer + ) + compiled_identity = elec.identity + + if opts.absorptance_mode == "exact_layer": + abs_indices = _absorber_layer_indices(prepared) + a_abs = np.clip( + np.sum(budget.layer_absorptance[list(abs_indices), :], axis=0), + 0.0, + 1.0, + ) + else: + a_xl = binding.absorption_profile(elec.nodes_m) + node_mask = _absorber_node_mask(elec.nodes_m, prepared) + x_abs = elec.nodes_m[node_mask] + if x_abs.size < 2: + raise ValueError( + "absorber node mask contains fewer than 2 nodes; increase intervals_per_layer" + ) + a_abs = np.clip( + np.asarray(trapezoid(a_xl[node_mask, :], x_abs, axis=0), dtype=float), + 0.0, + 1.0, + ) + + temperature_K = float( + elec.thermal_voltage_V * ELEMENTARY_CHARGE_C / BOLTZMANN_J_K + ) + v_thermal = float(elec.thermal_voltage_V) + phi_bb = blackbody_photon_flux_m2_s_m(wl_m, temperature_K) + boltzmann_factor = math.exp(min(v_inj / v_thermal, 700.0)) + phi_el = a_abs * phi_bb * boltzmann_factor + el_per_nm = phi_el * 1e-9 + j_em_rad = float(ELEMENTARY_CHARGE_C * trapezoid(phi_el, wl_m)) + + if progress is not None: + progress("el", 2, 3, f"solving dark forward injection to V_inj={v_inj:.3f} V") + + polarity = float(elec.voltage_polarity) + v_steps: np.ndarray = np.linspace( + 0.0, v_inj, opts.continuation_steps + 1, dtype=float + ) + + if compiled_ion is None: + controls_record: dict[str, Any] = { + "mode": "electronic_dc", + "steady": asdict(opts.steady), + "continuation_steps": opts.continuation_steps, + } + prev_state = None + last_sol = None + for v_step in v_steps: + try: + sol = solve_steady_state( + elec, + voltage_V=float(v_step), + generation_scale=0.0, + initial_state=prev_state, + options=opts.steady, + ) + except SteadyStateError as exc: + raise RuntimeError( + f"EL dark forward continuation failed at V={v_step:.4f} V: {exc}" + ) from exc + if not sol.converged: + raise RuntimeError( + f"EL dark forward continuation failed to converge at V={v_step:.4f} V" + ) + prev_state = sol.state + last_sol = sol + assert last_sol is not None + faces = np.asarray(last_sol.current_density_A_m2, dtype=float) + contacts = np.asarray(last_sol.contact_current_density_A_m2, dtype=float) + j_inj_pv = float(-polarity * faces[0]) + j_inj_conj = float(polarity * contacts[0 if polarity > 0.0 else -1]) + else: + ion_controls = ( + default_ionic_steady_options( + compiled_ion.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + controls_record = { + "mode": "ionic_dc", + "ionic_steady": asdict(ion_controls), + "continuation_steps": opts.continuation_steps, + } + prev_ion: IonicState1D | None = None + last_ion = None + for v_step in v_steps: + sol_ion = solve_ionic_dc_operating_point( + compiled_ion, + voltage_V=float(v_step), + generation_scale=0.0, + options=ion_controls, + base_state=prev_ion, + base_generation_scale=0.0, + ) + if ( + not sol_ion.accepted + or sol_ion.state is None + or sol_ion.diagnostics is None + ): + reason = sol_ion.error or sol_ion.termination + raise RuntimeError( + f"EL ionic dark forward continuation failed at V={v_step:.4f} V ({reason})" + ) + prev_ion = sol_ion.state + last_ion = sol_ion + assert last_ion is not None and last_ion.diagnostics is not None + all_faces = np.asarray( + last_ion.diagnostics["total_current_density_A_m2"], dtype=float + ) + j_inj_pv = float(-polarity * all_faces[0]) + j_inj_conj = float(polarity * all_faces[0 if polarity > 0.0 else -1]) + + if not math.isfinite(j_inj_conj) or j_inj_conj <= 1e-30: + raise RuntimeError( + f"run_el_spectrum requires positive forward dark injection current at " + f"V_inj={v_inj} V, got J_inj_conjugate={j_inj_conj:.3e} A/m^2 " + f"(J_inj_pv={j_inj_pv:.3e} A/m^2); refusing to fabricate zero EQE_EL." + ) + + eqe_el = float(j_em_rad / j_inj_conj) + if eqe_el <= 0.0: + raise RuntimeError( + "run_el_spectrum computed zero radiative emission over the probe wavelength " + "window (absorber_absorptance is identically zero); check wavelengths_nm." + ) + eqe_el_clamped = min(max(eqe_el, 1e-300), 1.0) + delta_v_nr_v = float(-v_thermal * math.log(eqe_el_clamped)) + + if progress is not None: + progress( + "el", + 3, + 3, + f"EQE_EL={eqe_el:.2e}, dV_nr={delta_v_nr_v * 1e3:.1f} mV", + ) + + return ELSpectrumResult( + wavelengths_nm=wl_nm, + Phi_EL_m2_s_m=phi_el, + EL_spectrum_m2_s_nm=el_per_nm, + blackbody_flux_m2_s_m=phi_bb, + absorber_absorptance=a_abs, + V_inj_V=v_inj, + J_inj_pv_A_m2=j_inj_pv, + J_inj_conjugate_A_m2=j_inj_conj, + J_em_rad_A_m2=j_em_rad, + EQE_EL=eqe_el, + delta_V_nr_V=delta_v_nr_v, + delta_V_nr_mV=float(delta_v_nr_v * 1e3), + temperature_K=temperature_K, + photon_budget=budget, + absorptance_mode=opts.absorptance_mode, + optical_binding_sha256=binding.sha256, + compiled_identity=compiled_identity, + solver_controls=controls_record, + ) diff --git a/src/solarlab/experiments/eqe.py b/src/solarlab/experiments/eqe.py new file mode 100644 index 00000000..b11eeca4 --- /dev/null +++ b/src/solarlab/experiments/eqe.py @@ -0,0 +1,862 @@ +"""Monochromatic perturbation EQE(lambda) on the unified 1D DC core. + +Computes external quantum efficiency + + EQE(lambda) = (J_pv(lambda, V_bias) - J_pv_dark(V_bias)) / (q * Phi_inc(lambda)) + +around an accepted dark/bias DC operating point using the coherent transfer-matrix +optical stack (``OpticalStackBinding``) and photon-conserving control-volume +generation profiles (or exact linearized DC Jacobian tangent in +``perturbation_mode="linear_response"``). + +Key N-class contracts (P05-03a): + +1. **Explicit optical capability enforcement**: Devices lacking wavelength-resolved + tabulated ``nk`` optical resources (e.g. scalar Beer-Lambert ``alpha``-only + configurations), graded optics, incoherent layers, non-positive ``Phi_incident``, + or probe wavelengths outside tabulated ``nk`` bounds raise ``CapabilityError`` + or ``ValueError`` before solver work rather than returning zeros or clamping. +2. **Sign-faithful EQE**: Never wraps ``J_k`` in ``abs()``; negative incremental + photocurrent emits a ``RuntimeWarning`` and remains negative in ``EQE``. +3. **Closed photon budget & spectrum-bound J_sc_eqe**: Records per-wavelength + ``PhotonBudget`` (verifying ``|R + T + sum(A) - 1| <= 1e-12``) and integrates + ``J_sc_eqe_A_m2`` against an explicit or declared ``SpectralPhotonFlux`` + without silent edge extrapolation. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass, field, replace +import hashlib +import json +import math +from typing import Any, Literal, cast +import warnings + +import numpy as np +from scipy.sparse.linalg import spsolve + +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.optical_generation import PHOTON_BUDGET_RTOL +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.dc_1d import CapabilityError, CompiledDevice1D, DC1DProblem +from solarlab.equations.implementation import DCProblem, use_assembled +from solarlab.equations.ionic_1d import CompiledIonicDevice1D +from solarlab.experiments.suns_voc import ( + default_ionic_steady_options, + solve_ionic_dc_operating_point, +) +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument as MaterialSourceDocument +from solarlab.physics.generation.optical_binding import ( + OpticalLayerSpec, + OpticalStackBinding, + PhotonBudget, + constant_index_optical_constants, +) +from solarlab.physics.generation.profile import ( + GenerationProfile, + control_volume_digest, +) +from solarlab.physics.generation.spectrum import ( + SpectralPhotonFlux, + sample_nk_table, + sample_tabulated, + wavelength_grid_m, +) +from solarlab.physics.generation.transfer_matrix import tmm_cumulative_absorptance +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.reproducibility.sources import SourceDocument +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyStateError, + solve_steady_state, +) + +__all__ = [ + "EQEOptions", + "EQEResult", + "build_wavelength_optical_binding", + "compute_eqe", + "ensure_compilable_spectral_device", +] + +ProgressCallback = Callable[[str, int, int, str], None] + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +def _dc_problem( + device: CompiledDevice1D, voltage_V: float, generation_scale: float +) -> DCProblem: + if use_assembled(): + return AssembledDC1DProblem(device, voltage_V, generation_scale) + return DC1DProblem(device, voltage_V, generation_scale) + + +@dataclass(frozen=True) +class EQEOptions: + """Explicit optical, bias, and solver controls for monochromatic EQE.""" + + intervals_per_layer: int = 24 + bias_voltage_V: float = 0.0 + perturbation_mode: Literal["finite_flux", "linear_response"] = "finite_flux" + generation_discretization: Literal["cell_flux", "node_profile"] = "cell_flux" + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + steady: SteadyOptions = field(default_factory=SteadyOptions) + ionic_steady: IonicSteadyOptions | None = None + require_all_converged: bool = True + require_reference_spectrum: bool = False + + def __post_init__(self) -> None: + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if not math.isfinite(self.bias_voltage_V): + raise ValueError("bias_voltage_V must be finite") + if self.perturbation_mode not in ("finite_flux", "linear_response"): + raise ValueError( + "perturbation_mode must be 'finite_flux' or 'linear_response'" + ) + if self.generation_discretization not in ("cell_flux", "node_profile"): + raise ValueError( + "generation_discretization must be 'cell_flux' or 'node_profile'" + ) + if ( + self.ion_domain_layer is not None + and self.perturbation_mode == "linear_response" + ): + raise ValueError( + "linear_response EQE currently supports ion-free devices; use finite_flux for ionic" + ) + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + + +@dataclass(frozen=True) +class EQEResult: + """Monochromatic EQE(lambda), IQE(lambda), photon budget, and integrated J_sc.""" + + wavelengths_nm: np.ndarray + EQE: np.ndarray + IQE: np.ndarray + electrical_absorptance: np.ndarray + J_photo_per_lambda_A_m2: np.ndarray + dark_bias_current_A_m2: float + Phi_incident_m2_s: float + bias_voltage_V: float + converged_mask: np.ndarray + point_reasons: tuple[str | None, ...] + photon_budget: PhotonBudget + J_sc_eqe_A_m2: float + quadrature_weights_m: np.ndarray | None + reference_spectrum_id: str | None + integration_failure_reason: str | None + max_current_spread_A_m2: float + perturbation_mode: str + generation_discretization: str + optical_binding_sha256: str + compiled_identity: str + solver_controls: dict[str, Any] + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "wavelengths_nm", + "EQE", + "IQE", + "electrical_absorptance", + "J_photo_per_lambda_A_m2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + object.__setattr__(self, "converged_mask", _ro_bool(self.converged_mask)) + if self.quadrature_weights_m is not None: + object.__setattr__( + self, "quadrature_weights_m", _ro_float(self.quadrature_weights_m) + ) + + @property + def J_sc_per_lambda(self) -> np.ndarray: + return self.J_photo_per_lambda_A_m2 + + @property + def J_sc_integrated(self) -> float: + return self.J_sc_eqe_A_m2 + + @property + def Phi_incident(self) -> float: + return self.Phi_incident_m2_s + + @property + def J_spread_max(self) -> float: + return self.max_current_spread_A_m2 + + +def _normalize_probe_wavelengths( + wavelengths_nm: Sequence[float] | np.ndarray | None, + *, + default_lo_nm: float = 300.0, + default_hi_nm: float = 1000.0, + default_count: int = 29, +) -> np.ndarray: + if wavelengths_nm is None: + return np.linspace(default_lo_nm, default_hi_nm, default_count, dtype=float) + raw = [float(w) for w in wavelengths_nm] + if not raw: + raise ValueError("wavelengths_nm must be non-empty") + if any(not math.isfinite(w) or w <= 0.0 for w in raw): + raise ValueError(f"wavelengths_nm must be finite and positive, got {raw}") + unique_sorted = np.array(sorted(set(raw)), dtype=float) + return unique_sorted + + +def build_wavelength_optical_binding( + prepared: PreparedDevice, + wavelengths_nm: np.ndarray, + *, + caller_name: str = "compute_eqe", +) -> tuple[OpticalStackBinding, PhotonBudget]: + """Validate wavelength-resolved optics on ``prepared`` and build TMM binding.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice instance") + data = prepared.to_mapping() + if data["settings"]["graded_optics"]: + raise CapabilityError( + f"{caller_name}: graded_optics is not bound in this 1D coherent TMM slice" + ) + has_tabulated_nk = any(layer.optical is not None for layer in prepared.layers) + if not has_tabulated_nk: + raise ValueError( + f"{caller_name} requires at least one layer with tabulated wavelength-resolved " + f"optical_material (n, k) data; scalar Beer-Lambert alpha-only stacks are refused." + ) + + probe_flux = np.ones_like(wavelengths_nm, dtype=float) + if wavelengths_nm.size >= 2: + spec_wl = wavelengths_nm + spec_flux = probe_flux + else: + # SpectralPhotonFlux requires >= 2 grid points; pad a tiny epsilon twin for + # 1-wavelength queries and slice [0:1] when reading per-wavelength quantities. + w0 = float(wavelengths_nm[0]) + spec_wl = np.array([w0, w0 * (1.0 + 1e-12)], dtype=float) + spec_flux = np.ones(2, dtype=float) + + spectrum = SpectralPhotonFlux(spec_wl, spec_flux, f"{caller_name}_unit_probe") + deps: dict[str, str] = { + "binding_convention": f"{caller_name}_coherent_tmm_1d_v1", + "prepared_device_sha256": prepared.content_sha256, + "temperature_K": str(data["settings"]["T"]), + } + + specs: list[OpticalLayerSpec] = [] + for layer in prepared.layers: + params = dict(layer.parameters) + if params["incoherent"]: + raise CapabilityError( + f"{caller_name}: layer {layer.id!r} sets incoherent=True; " + f"only coherent TMM stacks are bound in this slice" + ) + if layer.cigs_graded_optics_json is not None: + raise CapabilityError( + f"{caller_name}: layer {layer.id!r} uses unsupported graded optics" + ) + if layer.optical is not None: + if params["n_optical"] is not None: + raise CapabilityError( + f"{caller_name}: layer {layer.id!r} cannot declare both optical_material and n_optical" + ) + native = layer.optical.array + n_arr, k_arr = sample_nk_table( + native[:, 0] * 1e9, + native[:, 1], + native[:, 2], + spec_wl, + material=layer.optical.name, + ) + deps[f"nk_resource:{layer.id}"] = layer.optical.content_sha256 + else: + n_opt = params["n_optical"] + eps_r = cast(float, params["eps_r"]) + n_arr, k_arr = constant_index_optical_constants( + spec_wl, + absorption_coefficient_m1=cast(float, params["alpha"]), + refractive_index=None if n_opt is None else float(n_opt), + relative_permittivity=eps_r, + ) + specs.append( + OpticalLayerSpec( + name=layer.id, + thickness_m=layer.thickness, + n=n_arr, + k=k_arr, + incoherent=False, + electrical=layer.role != "substrate", + ) + ) + + binding = OpticalStackBinding( + tuple(specs), + spectrum, + ambient_index=1.0, + exit_index=1.0, + incidence="front", + dependencies=tuple(deps.items()), + ) + budget = binding.photon_budget() + if np.max(np.abs(budget.spectral_closure_residual())) > PHOTON_BUDGET_RTOL: + raise CapabilityError( + f"{caller_name}: TMM spectral photon budget failed closure check" + ) + return binding, budget + + +def ensure_compilable_spectral_device( + prepared: PreparedDevice, wavelengths_nm: np.ndarray +) -> PreparedDevice: + """Bind a zero-flux placeholder spectrum over ``wavelengths_nm`` for dark/mono compilation. + + Full-spectrum reference tables such as ASTM AM1.5G (280-1500 nm) can extend + beyond a layer's tabulated ``nk`` window (e.g. MAPbI3 300-1100 nm) even when + the requested monochromatic probe ``wavelengths_nm`` lie strictly inside all + ``nk`` bounds. Binding a zero-flux spectrum over ``[min(wl), max(wl)]`` keeps + ``compile_device_1d`` within validated ``nk`` bounds without touching + ``prepared``'s declared reference spectrum. + """ + lo_nm = float(np.min(wavelengths_nm)) + hi_nm = float(np.max(wavelengths_nm)) + if hi_nm <= lo_nm: + hi_nm = lo_nm + 1.0 + csv_bytes = ( + "wavelength_nm,spectral_flux_m-2_s-1_m-1\n" + f"{lo_nm:.6f},0.0\n" + f"{hi_nm:.6f},0.0\n" + ).encode("utf-8") + spec_name = "__solarlab_eqe_zero_flux_placeholder__" + spec_table = ResourceTable( + spec_name, + "spectrum", + MaterialSourceDocument("eqe.zero_flux_placeholder.csv", csv_bytes), + ) + merged_tables = [ + table for table in prepared.resources.tables if table.name != spec_name + ] + merged_tables.append(spec_table) + lib = ResourceLibrary(tuple(merged_tables)) + + editing = prepared.to_input().editing_data() + editing["spectrum"] = spec_name + editing["fixed_generation"] = None + settings = dict(editing.get("settings") or {}) + settings["Phi"] = 0.0 + editing["settings"] = settings + src = SourceDocument( + "eqe.bind_zero_flux_spectrum", + json.dumps( + editing, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8"), + ) + return resolve_device( + DeviceInput.model_validate(editing), + prepared.defaults, + lib, + sources=(*prepared.sources, src), + ) + + +def _resolve_reference_spectrum( + prepared: PreparedDevice, + reference_spectrum: SpectralPhotonFlux | None, +) -> SpectralPhotonFlux | None: + if reference_spectrum is not None: + if not isinstance(reference_spectrum, SpectralPhotonFlux): + raise TypeError( + "reference_spectrum must be None or a SpectralPhotonFlux instance" + ) + return reference_spectrum + spec_name = prepared.to_mapping()["declaration"].get("spectrum") + if spec_name is None: + return None + table = prepared.resources.get(spec_name, "spectrum") + if table.units != ("m", "m^-3/s"): + return None + return SpectralPhotonFlux( + table.array[:, 0] * 1e9, table.array[:, 1], table.source.id + ) + + +def _trapezoid_weights(x: np.ndarray) -> np.ndarray: + w = np.zeros_like(x, dtype=float) + if x.size < 2: + return w + dx = np.diff(x) + w[0] = 0.5 * dx[0] + w[-1] = 0.5 * dx[-1] + if x.size > 2: + w[1:-1] = 0.5 * (dx[:-1] + dx[1:]) + return w + + +def _monochromatic_device( + base_compiled: CompiledDevice1D, + source_m3_s: np.ndarray, + absorbed_m2_s: np.ndarray, + optical_binding_sha256: str, + lam_nm: float, + phi_inc: float, +) -> CompiledDevice1D: + cv_digest = control_volume_digest(base_compiled.geometry) + mono_bind_sha = hashlib.sha256( + f"{optical_binding_sha256}|lam_nm={lam_nm!r}|phi={phi_inc!r}".encode("ascii") + ).hexdigest() + profile = GenerationProfile( + method="transfer_matrix_monochromatic", + geometry_name=base_compiled.geometry.name, + source_m3_s=source_m3_s, + absorbed_m2_s=absorbed_m2_s, + binding_sha256=mono_bind_sha, + control_volume_sha256=cv_digest, + ) + dev_sha = hashlib.sha256( + f"{base_compiled.sha256}|mono={mono_bind_sha}".encode("ascii") + ).hexdigest() + return replace(base_compiled, generation=profile, sha256=dev_sha) + + +def _monochromatic_ionic_device( + base_ionic: CompiledIonicDevice1D, + source_m3_s: np.ndarray, + absorbed_m2_s: np.ndarray, + optical_binding_sha256: str, + lam_nm: float, + phi_inc: float, +) -> CompiledIonicDevice1D: + mono_elec = _monochromatic_device( + base_ionic.electronic_component, + source_m3_s, + absorbed_m2_s, + optical_binding_sha256, + lam_nm, + phi_inc, + ) + manifest = dict(base_ionic.binding_manifest) + comp_bind = dict(cast(dict[str, Any], manifest["electronic_component"])) + comp_bind["compiled_sha256"] = mono_elec.identity + manifest["electronic_component"] = comp_bind + manifest_json = json.dumps( + manifest, sort_keys=True, separators=(",", ":"), allow_nan=False + ) + ion_sha = hashlib.sha256(manifest_json.encode("utf-8")).hexdigest() + return replace( + base_ionic, + electronic_component=mono_elec, + binding_manifest_json=manifest_json, + sha256=ion_sha, + ) + + +def _slice_single_point_budget(budget: PhotonBudget, count: int) -> PhotonBudget: + if budget.wavelengths_nm.size == count: + return budget + return PhotonBudget( + wavelengths_nm=budget.wavelengths_nm[:count], + incident_spectral_m2_s_m=budget.incident_spectral_m2_s_m[:count], + reflectance=budget.reflectance[:count], + transmittance=budget.transmittance[:count], + layer_absorptance=budget.layer_absorptance[:, :count], + dropped_multipass=budget.dropped_multipass[:count], + layer_names=budget.layer_names, + layer_electrical=budget.layer_electrical, + ) + + +def compute_eqe( + prepared: PreparedDevice, + wavelengths_nm: Sequence[float] | np.ndarray | None = None, + *, + Phi_incident: float = 4e21, + reference_spectrum: SpectralPhotonFlux | None = None, + options: EQEOptions | None = None, + progress: ProgressCallback | None = None, +) -> EQEResult: + """Compute monochromatic EQE(lambda), photon budget, and integrated J_sc_eqe.""" + opts = EQEOptions() if options is None else options + phi_inc = float(Phi_incident) + if not math.isfinite(phi_inc) or phi_inc <= 0.0: + raise ValueError(f"Phi_incident must be finite and positive, got {Phi_incident}") + + wl_nm = _normalize_probe_wavelengths(wavelengths_nm) + n_wl = int(wl_nm.size) + + binding, raw_budget = build_wavelength_optical_binding( + prepared, wl_nm, caller_name="compute_eqe" + ) + budget = _slice_single_point_budget(raw_budget, n_wl) + elec_mask: np.ndarray = np.asarray(budget.layer_electrical, dtype=bool) + elec_abs: np.ndarray = np.asarray( + np.sum(budget.layer_absorptance[elec_mask, :n_wl], axis=0), dtype=float + ) + + compilable = ensure_compilable_spectral_device(prepared, wl_nm) + if opts.ion_domain_layer is not None: + base_ionic = compile_ionic_device_1d( + compilable, + intervals_per_layer=opts.intervals_per_layer, + ion_domain_layer=opts.ion_domain_layer, + ion_domain_endpoints=opts.ion_domain_endpoints, + ) + base_elec = base_ionic.electronic_component + compiled_identity = base_ionic.identity + else: + base_ionic = None + base_elec = compile_device_1d( + compilable, intervals_per_layer=opts.intervals_per_layer + ) + compiled_identity = base_elec.identity + + measures = np.asarray(base_elec.geometry.cell_measures_m, dtype=float) + faces_opt = ( + np.asarray(base_elec.geometry.cell_faces_m, dtype=float) + + binding.electrical_offset_m + ) + if opts.generation_discretization == "cell_flux": + cum_abs = tmm_cumulative_absorptance( + list(binding.tmm_layers), + binding.wavelengths_m, + faces_opt, + binding.boundaries_m, + binding.ambient_index, + binding.exit_index, + )[:, :n_wl] + cell_abs = np.maximum(0.0, np.diff(cum_abs, axis=0)) + absorbed_all = cell_abs * phi_inc + source_all = absorbed_all / measures[:, None] + else: + a_xl = np.maximum( + 0.0, binding.absorption_profile(base_elec.nodes_m)[:, :n_wl] + ) + source_all = a_xl * phi_inc + absorbed_all = source_all * measures[:, None] + + polarity = float(base_elec.voltage_polarity) + eqe_arr: np.ndarray = np.full(n_wl, np.nan, dtype=float) + iqe_arr: np.ndarray = np.full(n_wl, np.nan, dtype=float) + j_photo_arr: np.ndarray = np.full(n_wl, np.nan, dtype=float) + conv_mask: np.ndarray = np.zeros(n_wl, dtype=bool) + reasons: list[str | None] = [None] * n_wl + spread_max = 0.0 + + if base_ionic is None: + controls_record: dict[str, Any] = { + "mode": "electronic_dc", + "perturbation_mode": opts.perturbation_mode, + "steady": asdict(opts.steady), + } + dark_sol = solve_steady_state( + base_elec, + voltage_V=opts.bias_voltage_V, + generation_scale=0.0, + options=opts.steady, + ) + if not dark_sol.converged: + raise RuntimeError( + f"EQE dark baseline DC solve failed at V={opts.bias_voltage_V} V" + ) + dark_faces = np.asarray(dark_sol.current_density_A_m2, dtype=float) + j_dark = float(-polarity * dark_faces[0]) + spread_max = max(spread_max, float(np.ptp(dark_faces))) + + if opts.perturbation_mode == "linear_response": + prob_dark = _dc_problem(base_elec, opts.bias_voltage_V, 0.0) + u_dark = dark_sol.state.u + jac_dark = prob_dark.jacobian(u_dark) + f_dark = prob_dark.residual(u_dark) + for k in range(n_wl): + mono_dev = _monochromatic_device( + base_elec, + source_all[:, k], + absorbed_all[:, k], + binding.sha256, + float(wl_nm[k]), + phi_inc, + ) + prob_mono = _dc_problem(mono_dev, opts.bias_voltage_V, 1.0) + b_gen = prob_mono.residual(u_dark) - f_dark + delta_u = np.asarray(spsolve(jac_dark, -b_gen), dtype=float) + if not np.all(np.isfinite(delta_u)): + reasons[k] = "linear_response_nonfinite_tangent" + continue + u_norm = max(float(np.linalg.norm(delta_u, ord=np.inf)), 1e-30) + eps = 1e-7 / u_norm + j_plus = prob_dark.current_density(u_dark + eps * delta_u) + j_minus = prob_dark.current_density(u_dark - eps * delta_u) + dj_faces = (j_plus - j_minus) / (2.0 * eps) + spread_max = max(spread_max, float(np.ptp(dj_faces))) + dj_pv = float(-polarity * dj_faces[0]) + j_photo_arr[k] = dj_pv + eqe_arr[k] = dj_pv / (ELEMENTARY_CHARGE_C * phi_inc) + iqe_arr[k] = ( + eqe_arr[k] / elec_abs[k] if elec_abs[k] > 1e-12 else float("nan") + ) + conv_mask[k] = True + if progress is not None: + progress( + "eqe", + k + 1, + n_wl, + f"lambda={wl_nm[k]:.0f} nm, EQE={eqe_arr[k]:.3f}", + ) + else: + for k in range(n_wl): + mono_dev = _monochromatic_device( + base_elec, + source_all[:, k], + absorbed_all[:, k], + binding.sha256, + float(wl_nm[k]), + phi_inc, + ) + rebased_seed = mono_dev.state( + dark_sol.state.u, voltage_V=opts.bias_voltage_V + ) + has_gen = bool(np.max(source_all[:, k]) > 0.0) + try: + if has_gen: + try: + sol_k = solve_steady_state( + mono_dev, + voltage_V=opts.bias_voltage_V, + generation_scale=1.0, + options=opts.steady, + ) + except ValueError: + sol_k = solve_steady_state( + mono_dev, + voltage_V=opts.bias_voltage_V, + generation_scale=1.0, + initial_state=rebased_seed, + options=opts.steady, + ) + else: + sol_k = solve_steady_state( + mono_dev, + voltage_V=opts.bias_voltage_V, + generation_scale=1.0, + initial_state=rebased_seed, + options=opts.steady, + ) + if not sol_k.converged: + reasons[k] = "monochromatic_dc_not_converged" + continue + except SteadyStateError as exc: + reasons[k] = f"monochromatic_dc_not_converged:{exc}" + continue + + faces_k = np.asarray(sol_k.current_density_A_m2, dtype=float) + spread_max = max(spread_max, float(np.ptp(faces_k))) + j_pv_k = float(-polarity * faces_k[0]) + dj_pv = j_pv_k - j_dark + j_photo_arr[k] = dj_pv + eqe_arr[k] = dj_pv / (ELEMENTARY_CHARGE_C * phi_inc) + iqe_arr[k] = ( + eqe_arr[k] / elec_abs[k] if elec_abs[k] > 1e-12 else float("nan") + ) + conv_mask[k] = True + if progress is not None: + progress( + "eqe", + k + 1, + n_wl, + f"lambda={wl_nm[k]:.0f} nm, EQE={eqe_arr[k]:.3f}", + ) + else: + ion_controls = ( + default_ionic_steady_options( + base_ionic.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + controls_record = { + "mode": "ionic_dc", + "perturbation_mode": opts.perturbation_mode, + "ionic_steady": asdict(ion_controls), + } + dark_ion = solve_ionic_dc_operating_point( + base_ionic, + voltage_V=opts.bias_voltage_V, + generation_scale=0.0, + options=ion_controls, + ) + if ( + not dark_ion.accepted + or dark_ion.state is None + or dark_ion.diagnostics is None + ): + reason = dark_ion.error or dark_ion.termination + raise RuntimeError( + f"EQE ionic dark baseline DC solve failed at V={opts.bias_voltage_V} V ({reason})" + ) + dark_all_faces = np.asarray( + dark_ion.diagnostics["total_current_density_A_m2"], dtype=float + ) + j_dark = float(-polarity * dark_all_faces[0]) + spread_max = max(spread_max, float(np.ptp(dark_all_faces))) + + for k in range(n_wl): + mono_ion = _monochromatic_ionic_device( + base_ionic, + source_all[:, k], + absorbed_all[:, k], + binding.sha256, + float(wl_nm[k]), + phi_inc, + ) + seed_ion = mono_ion.state( + dark_ion.state.u, voltage_V=opts.bias_voltage_V + ) + sol_ion_k = solve_ionic_dc_operating_point( + mono_ion, + voltage_V=opts.bias_voltage_V, + generation_scale=1.0, + options=ion_controls, + base_state=seed_ion, + base_generation_scale=0.0, + ) + if ( + not sol_ion_k.accepted + or sol_ion_k.state is None + or sol_ion_k.diagnostics is None + ): + reason = sol_ion_k.error or sol_ion_k.termination + reasons[k] = f"monochromatic_dc_not_converged:{reason}" + continue + faces_ion_k = np.asarray( + sol_ion_k.diagnostics["total_current_density_A_m2"], dtype=float + ) + spread_max = max(spread_max, float(np.ptp(faces_ion_k))) + dj_pv = float(-polarity * faces_ion_k[0]) - j_dark + j_photo_arr[k] = dj_pv + eqe_arr[k] = dj_pv / (ELEMENTARY_CHARGE_C * phi_inc) + iqe_arr[k] = ( + eqe_arr[k] / elec_abs[k] if elec_abs[k] > 1e-12 else float("nan") + ) + conv_mask[k] = True + if progress is not None: + progress( + "eqe", + k + 1, + n_wl, + f"lambda={wl_nm[k]:.0f} nm, EQE={eqe_arr[k]:.3f}", + ) + + if opts.require_all_converged and not bool(np.all(conv_mask)): + bad = [ + f"{wl_nm[i]:.1f}nm ({reasons[i]})" + for i in range(n_wl) + if not conv_mask[i] + ] + raise RuntimeError( + "compute_eqe failed to converge at probe wavelengths: " + ", ".join(bad) + ) + + neg_wl = wl_nm[conv_mask & (eqe_arr < -1e-9)] + if neg_wl.size > 0: + preview = ", ".join(f"{w:.0f}" for w in neg_wl[:5]) + suffix = " ..." if neg_wl.size > 5 else "" + warnings.warn( + f"Negative EQE at {neg_wl.size} wavelength(s) ({preview}{suffix} nm): " + f"incremental photocurrent flows opposite to the PV output convention.", + RuntimeWarning, + stacklevel=2, + ) + + ref_spec = _resolve_reference_spectrum(prepared, reference_spectrum) + jsc_int = float("nan") + quad_weights: np.ndarray | None = None + ref_id: str | None = None + int_reason: str | None = None + + if ref_spec is None: + int_reason = "no_reference_spectrum_declared" + if opts.require_reference_spectrum: + raise ValueError( + "compute_eqe: require_reference_spectrum=True, but no reference_spectrum " + "or declared PreparedDevice spectrum resource was provided" + ) + elif n_wl < 2: + ref_id = ref_spec.source_id + int_reason = "fewer_than_two_wavelengths_for_quadrature" + if opts.require_reference_spectrum: + raise ValueError( + "compute_eqe requires >= 2 probe wavelengths to integrate J_sc_eqe" + ) + elif not bool(np.all(conv_mask)): + ref_id = ref_spec.source_id + int_reason = "incomplete_eqe_wavelength_convergence" + else: + ref_id = ref_spec.source_id + try: + phi_ref = sample_tabulated( + ref_spec.wavelengths_nm, + ref_spec.flux_m2_s_m, + wl_nm, + name=ref_spec.source_id, + ) + except ValueError as exc: + int_reason = f"wavelengths_outside_reference_spectrum:{exc}" + if opts.require_reference_spectrum: + raise + else: + wl_m = wavelength_grid_m(wl_nm) + quad_weights = _trapezoid_weights(wl_m) + jsc_int = float( + ELEMENTARY_CHARGE_C * np.sum(eqe_arr * phi_ref * quad_weights) + ) + + return EQEResult( + wavelengths_nm=wl_nm, + EQE=eqe_arr, + IQE=iqe_arr, + electrical_absorptance=elec_abs, + J_photo_per_lambda_A_m2=j_photo_arr, + dark_bias_current_A_m2=j_dark, + Phi_incident_m2_s=phi_inc, + bias_voltage_V=opts.bias_voltage_V, + converged_mask=conv_mask, + point_reasons=tuple(reasons), + photon_budget=budget, + J_sc_eqe_A_m2=jsc_int, + quadrature_weights_m=quad_weights, + reference_spectrum_id=ref_id, + integration_failure_reason=int_reason, + max_current_spread_A_m2=float(spread_max), + perturbation_mode=opts.perturbation_mode, + generation_discretization=opts.generation_discretization, + optical_binding_sha256=binding.sha256, + compiled_identity=compiled_identity, + solver_controls=controls_record, + ) diff --git a/src/solarlab/experiments/mott_schottky.py b/src/solarlab/experiments/mott_schottky.py new file mode 100644 index 00000000..d8cdcc2d --- /dev/null +++ b/src/solarlab/experiments/mott_schottky.py @@ -0,0 +1,1260 @@ +"""AC capacitance-frequency C(omega), capacitance-voltage C(V), and Mott-Schottky. + +Built directly on the exact linearized small-signal operators around accepted DC +operating points: + +- ``solve_impedance`` for ion-free ``CompiledDevice1D`` +- ``solve_ionic_impedance`` for single-domain ``CompiledIonicDevice1D`` + (``ion_mode="mobile"`` or ``"frozen"``) +- ``solve_multiple_ionic_impedance`` for multi-domain + ``CompiledMultipleIonicDevice1D`` + +Key scientific and numerical contracts (P05-03a): + +1. **Active vs frozen species**: ``active_species`` and ``frozen_species`` are + recorded explicitly on every CF, CV, and Mott-Schottky result. +2. **Sign-faithful capacitive susceptance**: ``C = Im(Y) / (2 * pi * f)`` is + reported only where ``f > 0`` and ``Im(Y) > 0``. Inductive or zero-susceptance + points are never hidden with ``abs(Im(Y))`` or ``0.0``; they record ``np.nan``, + ``valid_capacitive_mask[i] = False``, and an explicit entry in ``point_reasons`` + (or raise ``RuntimeError`` when ``strict_capacitive=True``). +3. **Apparent built-in voltage**: The Mott-Schottky intercept is explicitly + named ``apparent_built_in_voltage_V`` (not an unqualified ``V_bi``), alongside + ``apparent_doping_m3``, ``V_fit_lo_V``, ``V_fit_hi_V``, ``fit_mask``, and + ``r_squared``. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field, fields, is_dataclass +from enum import Enum +import hashlib +import json +import math +from typing import Any, Literal, TypeAlias, cast + +import numpy as np + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.resolved import PreparedDevice +from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M +from solarlab.equations.dc_1d import CompiledDevice1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, IonicState1D +from solarlab.equations.ionic_closure import ion_mobility_partition +from solarlab.equations.multiple_ionic_1d import ( + CompiledMultipleIonicDevice1D, + MultipleIonicState1D, +) +from solarlab.experiments.impedance import solve_impedance +from solarlab.experiments.ionic_impedance import ( + IonicImpedanceAttempt, + IonicImpedanceOptions, + solve_ionic_impedance, +) +from solarlab.experiments.ionic_transient import IonicTransientInitial +from solarlab.experiments.multiple_ionic_impedance import ( + solve_multiple_ionic_impedance, +) +from solarlab.experiments.multiple_ionic_transient import ( + MultipleIonicTransientInitial, +) +from solarlab.experiments.results import encode_array +from solarlab.experiments.suns_voc import ( + default_ionic_steady_options, + solve_ionic_dc_operating_point, +) +from solarlab.experiments.waveform_jv import package_ionic_steady_initial +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.solvers.linear import FrequencyOptions +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions +from solarlab.solvers.nonlinear.multiple_ionic_1d import ( + MultipleIonicSteadyResult, + solve_multiple_ionic_steady_state, +) +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + SteadyStateError, + solve_steady_state, +) + +__all__ = [ + "CFOptions", + "CFResult", + "CVResult", + "MottSchottkyOptions", + "MottSchottkyResult", + "fit_mott_schottky_curve", + "package_multiple_ionic_steady_initial", + "resolve_depletion_permittivity", + "run_capacitance_frequency", + "run_capacitance_voltage", + "run_mott_schottky", + "select_mott_schottky_window", +] + +BOLTZMANN_J_K = 1.380649e-23 +ProgressCallback = Callable[[str, int, int, str], None] +AnyCompiledACDevice: TypeAlias = ( + CompiledDevice1D | CompiledIonicDevice1D | CompiledMultipleIonicDevice1D +) + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_complex(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.complex128, copy=True) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class CFOptions: + """Explicit DC, linear AC, and species-mode controls for CF/CV sweeps.""" + + steady: SteadyOptions = field(default_factory=SteadyOptions) + ionic_steady: IonicSteadyOptions | None = None + linear: FrequencyOptions = field(default_factory=FrequencyOptions) + ionic_impedance: IonicImpedanceOptions = field( + default_factory=IonicImpedanceOptions + ) + ion_mode: Literal["mobile", "frozen"] = "mobile" + voltage_phasor_V: complex = 1.0 + 0.0j + strict_capacitive: bool = False + require_all_dc_converged: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + if not isinstance(self.linear, FrequencyOptions): + raise ValueError("linear must be an explicit FrequencyOptions instance") + if not isinstance(self.ionic_impedance, IonicImpedanceOptions): + raise ValueError( + "ionic_impedance must be an explicit IonicImpedanceOptions" + ) + if self.ion_mode not in ("mobile", "frozen"): + raise ValueError("ion_mode must be 'mobile' or 'frozen'") + phasor = complex(self.voltage_phasor_V) + if not np.isfinite(phasor) or phasor == 0.0j: + raise ValueError("voltage_phasor_V must be finite and nonzero") + object.__setattr__(self, "voltage_phasor_V", phasor) + + +@dataclass(frozen=True) +class MottSchottkyOptions: + """Controls for CV probing and Mott-Schottky linear window extraction.""" + + ac: CFOptions = field(default_factory=CFOptions) + min_window_points: int = 4 + max_residual_ratio: float = 0.01 + min_relative_variation: float = 0.05 + + def __post_init__(self) -> None: + if not isinstance(self.ac, CFOptions): + raise ValueError("ac must be an explicit CFOptions instance") + if type(self.min_window_points) is not int or self.min_window_points < 3: + raise ValueError("min_window_points must be an integer >= 3") + if ( + not math.isfinite(self.max_residual_ratio) + or self.max_residual_ratio <= 0.0 + ): + raise ValueError("max_residual_ratio must be finite and positive") + if ( + not math.isfinite(self.min_relative_variation) + or self.min_relative_variation < 0.0 + ): + raise ValueError("min_relative_variation must be finite and >= 0") + + +@dataclass(frozen=True) +class CFResult: + """Small-signal capacitance-frequency C(omega) sweep at fixed DC bias.""" + + frequencies_Hz: np.ndarray + bias_voltage_V: float + generation_scale: float + admittance_density_S_m2: np.ndarray + capacitance_F_m2: np.ndarray + conductance_S_m2: np.ndarray + loss_tangent: np.ndarray + ac_accepted_mask: np.ndarray + valid_capacitive_mask: np.ndarray + point_reasons: tuple[str | None, ...] + active_species: tuple[str, ...] + frozen_species: tuple[str, ...] + compiled_identity: str + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + object.__setattr__( + self, + "admittance_density_S_m2", + _ro_complex(self.admittance_density_S_m2), + ) + for name in ( + "frequencies_Hz", + "capacitance_F_m2", + "conductance_S_m2", + "loss_tangent", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ("ac_accepted_mask", "valid_capacitive_mask"): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + +@dataclass(frozen=True) +class CVResult: + """Small-signal capacitance-voltage C(V) sweep at fixed AC frequency.""" + + voltage_V: np.ndarray + frequency_Hz: float + generation_scale: float + admittance_density_S_m2: np.ndarray + capacitance_F_m2: np.ndarray + conductance_S_m2: np.ndarray + dc_converged_mask: np.ndarray + ac_accepted_mask: np.ndarray + valid_capacitive_mask: np.ndarray + point_reasons: tuple[str | None, ...] + active_species: tuple[str, ...] + frozen_species: tuple[str, ...] + compiled_identity: str + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + object.__setattr__( + self, + "admittance_density_S_m2", + _ro_complex(self.admittance_density_S_m2), + ) + for name in ( + "voltage_V", + "capacitance_F_m2", + "conductance_S_m2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ( + "dc_converged_mask", + "ac_accepted_mask", + "valid_capacitive_mask", + ): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + +@dataclass(frozen=True) +class MottSchottkyResult: + """C-V sweep and Mott-Schottky 1/C^2 linear depletion extraction.""" + + voltage_V: np.ndarray + capacitance_F_m2: np.ndarray + one_over_C2_m4_F2: np.ndarray + dc_converged_mask: np.ndarray + ac_accepted_mask: np.ndarray + valid_capacitive_mask: np.ndarray + point_reasons: tuple[str | None, ...] + fit_mask: np.ndarray + apparent_built_in_voltage_V: float + apparent_doping_m3: float + slope_m4_F2_V: float + intercept_m4_F2: float + V_fit_lo_V: float + V_fit_hi_V: float + r_squared: float + fit_failure_reason: str | None + frequency_Hz: float + eps_r_used: float + temperature_K: float + active_species: tuple[str, ...] + frozen_species: tuple[str, ...] + compiled_identity: str + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "voltage_V", + "capacitance_F_m2", + "one_over_C2_m4_F2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ( + "dc_converged_mask", + "ac_accepted_mask", + "valid_capacitive_mask", + "fit_mask", + ): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + @property + def V(self) -> np.ndarray: + return self.voltage_V + + @property + def C(self) -> np.ndarray: + return self.capacitance_F_m2 + + @property + def one_over_C2(self) -> np.ndarray: + return self.one_over_C2_m4_F2 + + @property + def V_bi_fit(self) -> float: + return self.apparent_built_in_voltage_V + + @property + def N_eff_fit(self) -> float: + return self.apparent_doping_m3 + + @property + def V_fit_lo(self) -> float: + return self.V_fit_lo_V + + @property + def V_fit_hi(self) -> float: + return self.V_fit_hi_V + + @property + def frequency(self) -> float: + return self.frequency_Hz + + @property + def fit_window_V(self) -> tuple[float, float]: + return (self.V_fit_lo_V, self.V_fit_hi_V) + + +def _species_partition( + compiled: AnyCompiledACDevice, ion_mode: Literal["mobile", "frozen"] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + if isinstance(compiled, CompiledDevice1D): + return ("electrons", "holes"), () + if isinstance(compiled, CompiledIonicDevice1D): + mobile, immobile = ion_mobility_partition(compiled) + if ion_mode == "frozen": + return ( + ("electrons", "holes"), + tuple(f"ion:{s}" for s in compiled.ion_species_names), + ) + return ( + ("electrons", "holes", *(f"ion:{s}" for s in mobile)), + tuple(f"ion:{s}" for s in immobile), + ) + if isinstance(compiled, CompiledMultipleIonicDevice1D): + if ion_mode == "frozen": + return ( + ("electrons", "holes"), + tuple( + f"{d.domain_layer_id}:{s}" + for d in compiled.domains + for s in d.ion_species_names + ), + ) + active_ions: list[str] = [] + frozen_ions: list[str] = [] + for dom in compiled.domains: + mob, imm = ion_mobility_partition(dom) + active_ions.extend(f"{dom.domain_layer_id}:{s}" for s in mob) + frozen_ions.extend(f"{dom.domain_layer_id}:{s}" for s in imm) + return ("electrons", "holes", *active_ions), tuple(frozen_ions) + raise TypeError(f"unsupported AC device type: {type(compiled).__name__}") + + +def _encode_diagnostic_tree(value: Any) -> Any: + """Lossless public codec matching ``solarlab.multiple_ionic_steady.v1``.""" + if is_dataclass(value) and not isinstance(value, type): + return { + f.name: _encode_diagnostic_tree(getattr(value, f.name)) + for f in fields(value) + } + if type(value) is np.ndarray: + return { + "$array": encode_array( + value, unit="raw diagnostic; units follow the named producer field" + ) + } + if isinstance(value, np.generic): + return {"$scalar": encode_array(np.asarray(value), unit="raw diagnostic")} + if isinstance(value, Enum): + return _encode_diagnostic_tree(value.value) + if type(value) is tuple: + return {"$tuple": [_encode_diagnostic_tree(item) for item in value]} + if type(value) is list: + return [_encode_diagnostic_tree(item) for item in value] + if type(value) is dict: + return {str(k): _encode_diagnostic_tree(v) for k, v in value.items()} + if type(value) is float and not math.isfinite(value): + return {"$float": encode_array(np.asarray(value), unit="raw diagnostic")} + return value + + +def package_multiple_ionic_steady_initial( + device: CompiledMultipleIonicDevice1D, + point: MultipleIonicSteadyResult, + *, + controls: IonicSteadyOptions, + source_label: str = "in_memory://multiple_ionic_steady.json", +) -> MultipleIonicTransientInitial: + """Package an accepted ``MultipleIonicSteadyResult`` for multi-domain AC.""" + if not point.accepted or point.state is None: + reason = point.error or point.termination + raise RuntimeError( + f"cannot initialize multi-domain AC from unaccepted DC result ({reason})" + ) + doc = { + "schema": "solarlab.multiple_ionic_steady.v1", + "result": _encode_diagnostic_tree(point), + "qualification": False, + } + evidence_json = json.dumps(doc, sort_keys=True, allow_nan=False) + "\n" + digest = hashlib.sha256(evidence_json.encode("utf-8")).hexdigest() + return MultipleIonicTransientInitial( + state=point.state, + generation_scale=0.0, + source_path=source_label, + source_sha256=digest, + evidence_json=evidence_json, + steady_controls=controls, + ) + + +def resolve_depletion_permittivity( + compiled: AnyCompiledACDevice, + *, + prepared: PreparedDevice | None = None, + eps_r: float | None = None, +) -> float: + """Resolve the relative permittivity ``eps_r`` of the depletion region.""" + if eps_r is not None: + val = float(eps_r) + if not math.isfinite(val) or val <= 0.0: + raise ValueError("eps_r must be finite and positive") + return val + + if prepared is not None: + for layer in prepared.layers: + if layer.role == "absorber": + return float(cast(float, dict(layer.parameters)["eps_r"])) + best_eps: float | None = None + best_doping = float("inf") + for layer in prepared.layers: + if layer.role == "substrate": + continue + params = dict(layer.parameters) + doping = max( + float(cast(float, params.get("N_A", 0.0))), + float(cast(float, params.get("N_D", 0.0))), + float(cast(float, params.get("ni", 0.0))), + ) + if doping < best_doping: + best_doping = doping + best_eps = float(cast(float, params["eps_r"])) + if best_eps is not None: + return best_eps + raise ValueError("prepared device contains no electrical layer with eps_r") + + elec = ( + compiled + if isinstance(compiled, CompiledDevice1D) + else compiled.electronic_component + ) + dx = np.diff(elec.nodes_m) + face_eps = elec.poisson.face_capacitance_F_m2 * dx / VACUUM_PERMITTIVITY_F_M + n_ref = elec.reference_electron_density_m3 + p_ref = elec.reference_hole_density_m3 + face_carrier_scale = 0.5 * ( + np.maximum(n_ref[:-1], p_ref[:-1]) + np.maximum(n_ref[1:], p_ref[1:]) + ) + idx = int(np.argmin(face_carrier_scale)) + return float(face_eps[idx]) + + +def _capacitance_from_admittance( + freq_hz: float, + y_val: complex, + *, + strict_capacitive: bool, +) -> tuple[float, float, float, bool, str | None]: + g_val = float(y_val.real) + b_val = float(y_val.imag) + if freq_hz <= 0.0: + if strict_capacitive: + raise RuntimeError( + "capacitance extraction requires strictly positive AC frequency (f > 0)" + ) + return float("nan"), g_val, float("nan"), False, "zero_frequency" + if b_val < 0.0: + if strict_capacitive: + raise RuntimeError( + f"inductive susceptance Im(Y)={b_val:.3e} S/m^2 at f={freq_hz:.4g} Hz" + ) + return float("nan"), g_val, float("nan"), False, "inductive_susceptance" + if b_val == 0.0: + if strict_capacitive: + raise RuntimeError(f"zero susceptance Im(Y)=0 at f={freq_hz:.4g} Hz") + return float("nan"), g_val, float("nan"), False, "zero_susceptance" + cap = float(b_val / (2.0 * math.pi * freq_hz)) + tan_d = float(g_val / b_val) + return cap, g_val, tan_d, True, None + + +def _unpack_ionic_attempts( + requested_Hz: np.ndarray, + attempts: Sequence[IonicImpedanceAttempt], + *, + strict_capacitive: bool, +) -> tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + list[str | None], +]: + count = int(requested_Hz.size) + y_arr: np.ndarray = np.full(count, np.nan + 1j * np.nan, dtype=complex) + c_arr: np.ndarray = np.full(count, np.nan, dtype=float) + g_arr: np.ndarray = np.full(count, np.nan, dtype=float) + loss_arr: np.ndarray = np.full(count, np.nan, dtype=float) + ac_ok: np.ndarray = np.zeros(count, dtype=bool) + cap_ok: np.ndarray = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + + for idx in range(count): + if idx >= len(attempts): + reasons[idx] = "ac_not_evaluated:preceding_frequency_failed" + continue + att = attempts[idx] + if not att.accepted or att.observation is None: + reason = att.error or att.termination + reasons[idx] = f"ac_not_accepted:{reason}" + continue + y_val = complex(att.observation["admittance_density_S_m2"]) + y_arr[idx] = y_val + ac_ok[idx] = True + cap, g_val, tan_d, ok_c, r_c = _capacitance_from_admittance( + float(requested_Hz[idx]), y_val, strict_capacitive=strict_capacitive + ) + c_arr[idx] = cap + g_arr[idx] = g_val + loss_arr[idx] = tan_d + cap_ok[idx] = ok_c + reasons[idx] = r_c + return y_arr, c_arr, g_arr, loss_arr, ac_ok, cap_ok, reasons + + +def run_capacitance_frequency( + compiled: AnyCompiledACDevice, + frequencies_Hz: Sequence[float] | np.ndarray, + *, + bias_voltage_V: float = 0.0, + generation_scale: float = 0.0, + initial: SteadyState1D + | IonicTransientInitial + | MultipleIonicTransientInitial + | None = None, + options: CFOptions | None = None, +) -> CFResult: + """Evaluate C(omega) around an accepted DC operating point.""" + opts = CFOptions() if options is None else options + freqs: np.ndarray = np.asarray([float(f) for f in frequencies_Hz], dtype=float) + if ( + freqs.ndim != 1 + or freqs.size == 0 + or not np.all(np.isfinite(freqs)) + or np.any(freqs < 0.0) + or np.unique(freqs).size != freqs.size + ): + raise ValueError( + "frequencies_Hz must be a non-empty 1D sequence of distinct finite >= 0 Hz" + ) + v_bias = float(bias_voltage_V) + gen = float(generation_scale) + if not math.isfinite(v_bias) or not math.isfinite(gen) or gen < 0.0: + raise ValueError("bias_voltage_V must be finite and generation_scale >= 0") + + active_sp, frozen_sp = _species_partition(compiled, opts.ion_mode) + count = int(freqs.size) + + if isinstance(compiled, CompiledDevice1D): + if initial is None: + dc_sol = solve_steady_state( + compiled, voltage_V=v_bias, generation_scale=gen, options=opts.steady + ) + if not dc_sol.converged: + raise RuntimeError(f"CF DC solve failed to converge at {v_bias} V") + elif isinstance(initial, SteadyState1D): + dc_sol = initial + else: + raise TypeError( + "CompiledDevice1D requires initial=None or SteadyState1D" + ) + + ss = solve_impedance( + compiled, + dc_sol, + freqs, + voltage_phasor_V=opts.voltage_phasor_V, + steady_options=opts.steady, + linear_options=opts.linear, + ) + y_arr: np.ndarray = np.array( + ss.admittance_density_S_m2, dtype=complex, copy=True + ) + c_arr: np.ndarray = np.full(count, np.nan, dtype=float) + g_arr: np.ndarray = np.empty(count, dtype=float) + loss_arr: np.ndarray = np.full(count, np.nan, dtype=float) + ac_ok: np.ndarray = np.ones(count, dtype=bool) + cap_ok: np.ndarray = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + for idx in range(count): + cap, g_val, tan_d, ok_c, r_c = _capacitance_from_admittance( + float(freqs[idx]), + complex(y_arr[idx]), + strict_capacitive=opts.strict_capacitive, + ) + c_arr[idx] = cap + g_arr[idx] = g_val + loss_arr[idx] = tan_d + cap_ok[idx] = ok_c + reasons[idx] = r_c + + elif isinstance(compiled, CompiledIonicDevice1D): + ion_controls = ( + default_ionic_steady_options( + compiled.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + if initial is None: + dc_ion = solve_ionic_dc_operating_point( + compiled, + voltage_V=v_bias, + generation_scale=gen, + options=ion_controls, + ) + ion_init = package_ionic_steady_initial( + compiled, + dc_ion, + voltage_V=v_bias, + generation_scale=gen, + controls=ion_controls, + source_label="in_memory://cf_ionic_steady.json", + ) + elif isinstance(initial, IonicTransientInitial): + ion_init = initial + v_bias = float(ion_init.state.voltage_V) + gen = float(ion_init.generation_scale) + else: + raise TypeError( + "CompiledIonicDevice1D requires initial=None or IonicTransientInitial" + ) + + ion_ac = solve_ionic_impedance( + compiled, + ion_init, + freqs, + ion_mode=opts.ion_mode, + voltage_phasor_V=opts.voltage_phasor_V, + options=opts.ionic_impedance, + ) + y_arr, c_arr, g_arr, loss_arr, ac_ok, cap_ok, reasons = _unpack_ionic_attempts( + freqs, ion_ac.attempts, strict_capacitive=opts.strict_capacitive + ) + + elif isinstance(compiled, CompiledMultipleIonicDevice1D): + if gen != 0.0: + raise ValueError( + "multiple-domain ionic AC currently admits only dark DC (generation_scale=0.0)" + ) + ion_controls = ( + default_ionic_steady_options( + min(d.ion_node_count for d in compiled.domains), + electronic=opts.steady, + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + if initial is None: + dc_mult = solve_multiple_ionic_steady_state( + compiled, + voltage_V=v_bias, + generation_scale=0.0, + options=ion_controls, + ) + mult_init = package_multiple_ionic_steady_initial( + compiled, dc_mult, controls=ion_controls + ) + elif isinstance(initial, MultipleIonicTransientInitial): + mult_init = initial + v_bias = float(mult_init.state.voltage_V) + else: + raise TypeError( + "CompiledMultipleIonicDevice1D requires initial=None or MultipleIonicTransientInitial" + ) + + mult_ac = solve_multiple_ionic_impedance( + compiled, + mult_init, + freqs, + voltage_phasor_V=opts.voltage_phasor_V, + ion_mode=opts.ion_mode, + options=opts.ionic_impedance, + ) + y_arr, c_arr, g_arr, loss_arr, ac_ok, cap_ok, reasons = _unpack_ionic_attempts( + freqs, mult_ac.attempts, strict_capacitive=opts.strict_capacitive + ) + else: + raise TypeError(f"unsupported AC device type: {type(compiled).__name__}") + + return CFResult( + frequencies_Hz=freqs, + bias_voltage_V=v_bias, + generation_scale=gen, + admittance_density_S_m2=y_arr, + capacitance_F_m2=c_arr, + conductance_S_m2=g_arr, + loss_tangent=loss_arr, + ac_accepted_mask=ac_ok, + valid_capacitive_mask=cap_ok, + point_reasons=tuple(reasons), + active_species=active_sp, + frozen_species=frozen_sp, + compiled_identity=compiled.identity, + ) + + +def _rebase_ionic_state( + compiled: CompiledIonicDevice1D, state: IonicState1D, voltage_V: float +) -> IonicState1D: + if state.voltage_V == voltage_V: + return state + coords = state.u.copy() + n_elec = 3 * compiled.node_count + coords[:n_elec] = compiled.electronic_component.rebase_coordinates( + coords[:n_elec], state.voltage_V, voltage_V + ) + return compiled.state(coords, voltage_V=voltage_V) + + +def _rebase_multiple_ionic_state( + device: CompiledMultipleIonicDevice1D, + state: MultipleIonicState1D, + voltage_V: float, +) -> MultipleIonicState1D: + if state.voltage_V == voltage_V: + return state + coords = state.u.copy() + n_elec = 3 * device.node_count + coords[:n_elec] = device.electronic_component.rebase_coordinates( + coords[:n_elec], state.voltage_V, voltage_V + ) + return device.state(coords, voltage_V=voltage_V) + + +def run_capacitance_voltage( + compiled: AnyCompiledACDevice, + voltage_V: Sequence[float] | np.ndarray, + *, + frequency_Hz: float = 1e5, + generation_scale: float = 0.0, + options: CFOptions | None = None, + progress: ProgressCallback | None = None, +) -> CVResult: + """Sweep DC bias ``voltage_V`` and probe small-signal C(V) at ``frequency_Hz``.""" + opts = CFOptions() if options is None else options + freq = float(frequency_Hz) + if not math.isfinite(freq) or freq <= 0.0: + raise ValueError(f"frequency_Hz must be finite and positive, got {frequency_Hz}") + gen = float(generation_scale) + if not math.isfinite(gen) or gen < 0.0: + raise ValueError("generation_scale must be finite and >= 0") + + raw_v = [float(v) for v in voltage_V] + if len(raw_v) < 2 or any(not math.isfinite(v) for v in raw_v): + raise ValueError("voltage_V must contain at least 2 finite bias values") + voltages = np.array(sorted(set(raw_v)), dtype=float) + if voltages.size < 2: + raise ValueError("voltage_V must contain at least 2 distinct bias values") + + active_sp, frozen_sp = _species_partition(compiled, opts.ion_mode) + count = int(voltages.size) + y_arr: np.ndarray = np.full(count, np.nan + 1j * np.nan, dtype=complex) + c_arr: np.ndarray = np.full(count, np.nan, dtype=float) + g_arr: np.ndarray = np.full(count, dtype=float, fill_value=np.nan) + dc_ok: np.ndarray = np.zeros(count, dtype=bool) + ac_ok: np.ndarray = np.zeros(count, dtype=bool) + cap_ok: np.ndarray = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + freq_vec = np.array([freq], dtype=float) + + if isinstance(compiled, CompiledDevice1D): + prev_state = None + for idx, v_val in enumerate(voltages): + try: + dc_sol = solve_steady_state( + compiled, + voltage_V=float(v_val), + generation_scale=gen, + initial_state=prev_state, + options=opts.steady, + ) + if not dc_sol.converged: + reasons[idx] = "dc_not_converged:unconverged_steady_result" + continue + except SteadyStateError as exc: + reasons[idx] = f"dc_not_converged:{exc}" + continue + + prev_state = dc_sol.state + dc_ok[idx] = True + cf_pt = run_capacitance_frequency( + compiled, + freq_vec, + bias_voltage_V=float(v_val), + generation_scale=gen, + initial=dc_sol, + options=opts, + ) + y_arr[idx] = cf_pt.admittance_density_S_m2[0] + c_arr[idx] = cf_pt.capacitance_F_m2[0] + g_arr[idx] = cf_pt.conductance_S_m2[0] + ac_ok[idx] = bool(cf_pt.ac_accepted_mask[0]) + cap_ok[idx] = bool(cf_pt.valid_capacitive_mask[0]) + reasons[idx] = cf_pt.point_reasons[0] + if progress is not None: + progress( + "cv", + idx + 1, + count, + f"V={v_val:.3f} V, C={c_arr[idx]:.3e} F/m^2", + ) + + elif isinstance(compiled, CompiledIonicDevice1D): + ion_controls = ( + default_ionic_steady_options( + compiled.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + prev_ion: IonicState1D | None = None + for idx, v_val in enumerate(voltages): + dc_ion = solve_ionic_dc_operating_point( + compiled, + voltage_V=float(v_val), + generation_scale=gen, + options=ion_controls, + base_state=prev_ion, + base_generation_scale=gen, + ) + if not dc_ion.accepted or dc_ion.state is None: + reason = dc_ion.error or dc_ion.termination + reasons[idx] = f"dc_not_converged:{reason}" + continue + + prev_ion = dc_ion.state + dc_ok[idx] = True + ion_init = package_ionic_steady_initial( + compiled, + dc_ion, + voltage_V=float(v_val), + generation_scale=gen, + controls=ion_controls, + source_label=f"in_memory://cv_ionic_steady_{idx}.json", + ) + cf_pt = run_capacitance_frequency( + compiled, + freq_vec, + bias_voltage_V=float(v_val), + generation_scale=gen, + initial=ion_init, + options=opts, + ) + y_arr[idx] = cf_pt.admittance_density_S_m2[0] + c_arr[idx] = cf_pt.capacitance_F_m2[0] + g_arr[idx] = cf_pt.conductance_S_m2[0] + ac_ok[idx] = bool(cf_pt.ac_accepted_mask[0]) + cap_ok[idx] = bool(cf_pt.valid_capacitive_mask[0]) + reasons[idx] = cf_pt.point_reasons[0] + if progress is not None: + progress( + "cv", + idx + 1, + count, + f"V={v_val:.3f} V, C={c_arr[idx]:.3e} F/m^2", + ) + + elif isinstance(compiled, CompiledMultipleIonicDevice1D): + if gen != 0.0: + raise ValueError( + "multiple-domain ionic CV currently admits only dark DC (generation_scale=0.0)" + ) + ion_controls = ( + default_ionic_steady_options( + min(d.ion_node_count for d in compiled.domains), + electronic=opts.steady, + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + prev_mult: MultipleIonicState1D | None = None + for idx, v_val in enumerate(voltages): + seed_m = ( + None + if prev_mult is None + else _rebase_multiple_ionic_state(compiled, prev_mult, float(v_val)) + ) + dc_mult = solve_multiple_ionic_steady_state( + compiled, + voltage_V=float(v_val), + generation_scale=0.0, + options=ion_controls, + initial_state=seed_m, + ) + if not dc_mult.accepted or dc_mult.state is None: + reason = dc_mult.error or dc_mult.termination + reasons[idx] = f"dc_not_converged:{reason}" + continue + + prev_mult = dc_mult.state + dc_ok[idx] = True + mult_init = package_multiple_ionic_steady_initial( + compiled, + dc_mult, + controls=ion_controls, + source_label=f"in_memory://cv_mult_ionic_steady_{idx}.json", + ) + cf_pt = run_capacitance_frequency( + compiled, + freq_vec, + bias_voltage_V=float(v_val), + generation_scale=0.0, + initial=mult_init, + options=opts, + ) + y_arr[idx] = cf_pt.admittance_density_S_m2[0] + c_arr[idx] = cf_pt.capacitance_F_m2[0] + g_arr[idx] = cf_pt.conductance_S_m2[0] + ac_ok[idx] = bool(cf_pt.ac_accepted_mask[0]) + cap_ok[idx] = bool(cf_pt.valid_capacitive_mask[0]) + reasons[idx] = cf_pt.point_reasons[0] + if progress is not None: + progress( + "cv", + idx + 1, + count, + f"V={v_val:.3f} V, C={c_arr[idx]:.3e} F/m^2", + ) + else: + raise TypeError(f"unsupported AC device type: {type(compiled).__name__}") + + if opts.require_all_dc_converged and not bool(np.all(dc_ok)): + bad = [ + f"V={voltages[i]:.4g}V ({reasons[i]})" + for i in range(count) + if not dc_ok[i] + ] + raise RuntimeError("CV DC operating points failed: " + ", ".join(bad)) + + return CVResult( + voltage_V=voltages, + frequency_Hz=freq, + generation_scale=gen, + admittance_density_S_m2=y_arr, + capacitance_F_m2=c_arr, + conductance_S_m2=g_arr, + dc_converged_mask=dc_ok, + ac_accepted_mask=ac_ok, + valid_capacitive_mask=cap_ok, + point_reasons=tuple(reasons), + active_species=active_sp, + frozen_species=frozen_sp, + compiled_identity=compiled.identity, + ) + + +def select_mott_schottky_window( + voltage_V: Sequence[float] | np.ndarray, + one_over_C2_m4_F2: Sequence[float] | np.ndarray, + *, + valid_mask: Sequence[bool] | np.ndarray | None = None, + min_points: int = 4, + max_residual_ratio: float = 0.01, +) -> tuple[int, int] | None: + """Select the widest contiguous valid sub-slice that is linear in ``(V, 1/C^2)``.""" + v_arr: np.ndarray = np.asarray(voltage_V, dtype=float) + y_arr: np.ndarray = np.asarray(one_over_C2_m4_F2, dtype=float) + if v_arr.ndim != 1 or y_arr.shape != v_arr.shape: + raise ValueError("voltage_V and one_over_C2_m4_F2 must have matching 1D shapes") + mask = ( + np.isfinite(v_arr) & np.isfinite(y_arr) & (y_arr > 0.0) + if valid_mask is None + else np.asarray(valid_mask, dtype=bool) + & np.isfinite(v_arr) + & np.isfinite(y_arr) + & (y_arr > 0.0) + ) + n_tot = int(v_arr.size) + if n_tot < min_points: + return None + + best: tuple[int, int] | None = None + best_len = 0 + for lo in range(0, n_tot - min_points + 1): + for hi in range(lo + min_points - 1, n_tot): + if not np.all(mask[lo : hi + 1]): + break + v_sub = v_arr[lo : hi + 1] + y_sub = y_arr[lo : hi + 1] + slope, intercept = np.polyfit(v_sub, y_sub, 1) + resid = y_sub - (slope * v_sub + intercept) + y_span = float(y_sub.max() - y_sub.min()) + if y_span <= 0.0: + continue + rms = float(np.sqrt(np.mean(resid * resid))) + win_len = hi - lo + 1 + if rms <= max_residual_ratio * y_span and win_len > best_len: + best_len = win_len + best = (lo, hi) + return best + + +def fit_mott_schottky_curve( + voltage_V: Sequence[float] | np.ndarray, + capacitance_F_m2: Sequence[float] | np.ndarray, + *, + eps_r: float, + temperature_K: float, + valid_capacitive_mask: Sequence[bool] | np.ndarray | None = None, + min_window_points: int = 4, + max_residual_ratio: float = 0.01, + min_relative_variation: float = 0.05, +) -> tuple[ + np.ndarray, + np.ndarray, + float, + float, + float, + float, + float, + float, + float, + str | None, +]: + """Fit ``1/C^2 = slope * V + intercept`` and extract apparent V_bi and N_eff.""" + v_arr: np.ndarray = np.asarray(voltage_V, dtype=float) + c_arr: np.ndarray = np.asarray(capacitance_F_m2, dtype=float) + if not math.isfinite(eps_r) or eps_r <= 0.0: + raise ValueError("eps_r must be finite and positive") + if not math.isfinite(temperature_K) or temperature_K <= 0.0: + raise ValueError("temperature_K must be finite and positive") + + val_mask = ( + np.isfinite(v_arr) & np.isfinite(c_arr) & (c_arr > 0.0) + if valid_capacitive_mask is None + else np.asarray(valid_capacitive_mask, dtype=bool) + & np.isfinite(v_arr) + & np.isfinite(c_arr) + & (c_arr > 0.0) + ) + one_over_c2: np.ndarray = np.full(v_arr.shape, np.nan, dtype=float) + one_over_c2[val_mask] = 1.0 / (c_arr[val_mask] * c_arr[val_mask]) + fit_mask: np.ndarray = np.zeros(v_arr.shape, dtype=bool) + + window = select_mott_schottky_window( + v_arr, + one_over_c2, + valid_mask=val_mask, + min_points=min_window_points, + max_residual_ratio=max_residual_ratio, + ) + if window is None: + return ( + one_over_c2, + fit_mask, + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float("nan"), + "no_contiguous_linear_depletion_window", + ) + + lo, hi = window + v_fit = v_arr[lo : hi + 1] + y_fit = one_over_c2[lo : hi + 1] + fit_mask[lo : hi + 1] = True + + y_span = float(y_fit.max() - y_fit.min()) + y_mid = float(np.median(np.abs(y_fit))) + if y_mid <= 0.0 or (y_span / y_mid) < min_relative_variation: + return ( + one_over_c2, + fit_mask, + float("nan"), + float("nan"), + float("nan"), + float("nan"), + float(v_fit[0]), + float(v_fit[-1]), + float("nan"), + "flat_geometric_capacitance_insufficient_variation", + ) + + slope, intercept = np.polyfit(v_fit, y_fit, 1) + if not math.isfinite(slope) or slope >= -1e-30: + return ( + one_over_c2, + fit_mask, + float("nan"), + float("nan"), + float(slope), + float(intercept), + float(v_fit[0]), + float(v_fit[-1]), + float("nan"), + "nonnegative_mott_schottky_slope", + ) + + v_thermal = BOLTZMANN_J_K * float(temperature_K) / ELEMENTARY_CHARGE_C + apparent_vbi = float(-intercept / slope + 2.0 * v_thermal) + apparent_n = float( + -2.0 / (ELEMENTARY_CHARGE_C * float(eps_r) * VACUUM_PERMITTIVITY_F_M * slope) + ) + pred = slope * v_fit + intercept + ss_res = float(np.sum((y_fit - pred) ** 2)) + ss_tot = float(np.sum((y_fit - np.mean(y_fit)) ** 2)) + r_sq = float(1.0 - ss_res / ss_tot) if ss_tot > 0.0 else 1.0 + + return ( + one_over_c2, + fit_mask, + apparent_vbi, + apparent_n, + float(slope), + float(intercept), + float(v_fit[0]), + float(v_fit[-1]), + r_sq, + None, + ) + + +def run_mott_schottky( + compiled: AnyCompiledACDevice, + *, + voltage_V: Sequence[float] | np.ndarray | None = None, + V_lo: float = -0.3, + V_hi: float = 0.5, + n_points: int = 20, + frequency_Hz: float = 1e5, + generation_scale: float = 0.0, + prepared: PreparedDevice | None = None, + eps_r: float | None = None, + options: MottSchottkyOptions | None = None, + progress: ProgressCallback | None = None, +) -> MottSchottkyResult: + """Run a dark/illuminated C-V sweep and fit apparent V_bi and N_eff.""" + opts = MottSchottkyOptions() if options is None else options + if voltage_V is None: + if type(n_points) is not int or n_points < opts.min_window_points: + raise ValueError( + f"n_points must be an integer >= {opts.min_window_points}, got {n_points}" + ) + if not math.isfinite(V_lo) or not math.isfinite(V_hi) or V_hi <= V_lo: + raise ValueError(f"V_hi ({V_hi}) must exceed V_lo ({V_lo})") + bias_grid: np.ndarray = np.linspace( + float(V_lo), float(V_hi), n_points, dtype=float + ) + else: + bias_grid = np.asarray([float(v) for v in voltage_V], dtype=float) + if bias_grid.ndim != 1 or bias_grid.size < opts.min_window_points: + raise ValueError( + f"voltage_V must have at least {opts.min_window_points} points" + ) + + eps_used = resolve_depletion_permittivity( + compiled, prepared=prepared, eps_r=eps_r + ) + elec = ( + compiled + if isinstance(compiled, CompiledDevice1D) + else compiled.electronic_component + ) + temperature_K = float( + elec.thermal_voltage_V * ELEMENTARY_CHARGE_C / BOLTZMANN_J_K + ) + + cv = run_capacitance_voltage( + compiled, + bias_grid, + frequency_Hz=frequency_Hz, + generation_scale=generation_scale, + options=opts.ac, + progress=progress, + ) + ( + one_over_c2, + fit_mask, + app_vbi, + app_n, + slope, + intercept, + v_fit_lo, + v_fit_hi, + r_sq, + fit_reason, + ) = fit_mott_schottky_curve( + cv.voltage_V, + cv.capacitance_F_m2, + eps_r=eps_used, + temperature_K=temperature_K, + valid_capacitive_mask=cv.valid_capacitive_mask, + min_window_points=opts.min_window_points, + max_residual_ratio=opts.max_residual_ratio, + min_relative_variation=opts.min_relative_variation, + ) + + return MottSchottkyResult( + voltage_V=cv.voltage_V, + capacitance_F_m2=cv.capacitance_F_m2, + one_over_C2_m4_F2=one_over_c2, + dc_converged_mask=cv.dc_converged_mask, + ac_accepted_mask=cv.ac_accepted_mask, + valid_capacitive_mask=cv.valid_capacitive_mask, + point_reasons=cv.point_reasons, + fit_mask=fit_mask, + apparent_built_in_voltage_V=app_vbi, + apparent_doping_m3=app_n, + slope_m4_F2_V=slope, + intercept_m4_F2=intercept, + V_fit_lo_V=v_fit_lo, + V_fit_hi_V=v_fit_hi, + r_squared=r_sq, + fit_failure_reason=fit_reason, + frequency_Hz=cv.frequency_Hz, + eps_r_used=eps_used, + temperature_K=temperature_K, + active_species=cv.active_species, + frozen_species=cv.frozen_species, + compiled_identity=cv.compiled_identity, + ) diff --git a/src/solarlab/experiments/suns_voc.py b/src/solarlab/experiments/suns_voc.py new file mode 100644 index 00000000..3c9a9b74 --- /dev/null +++ b/src/solarlab/experiments/suns_voc.py @@ -0,0 +1,1050 @@ +"""Suns-V_oc characterization on the unified 1D DC residual. + +Each illumination level ``X > 0`` solves genuine DC operating points on the +assembled drift-diffusion (or coupled ionic-electronic) equations rather than +finite-time transient relaxation: + +1. Short-circuit operating point at ``V = 0`` with ``generation_scale = X`` + (optionally subtracting the matched dark ``V = 0`` baseline offset). +2. Open-circuit root ``V_oc(X)`` refined by ``solve_direct_voc`` (or bounded + coupled ionic DC bisection) inside an accepted sign-change voltage bracket. + +Non-converged or unbracketed points record ``np.nan`` and an explicit entry in +``point_reasons``; ``0.0`` is never substituted for a missing operating point. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass, field +import math +from typing import Any + +import numpy as np + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem +from solarlab.equations.implementation import DCProblem, use_assembled +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, IonicState1D +from solarlab.experiments.jv.operating_points import ( + DirectVocError, + VocBracketError, + solve_direct_voc, +) +from solarlab.experiments.jv.steady import SteadyJVResult, steady_jv_metrics +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.solvers.nonlinear.ionic_1d import ( + IonicSteadyOptions, + IonicSteadyResult, + solve_ionic_steady_state, +) +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + SteadyStateError, + density_basin_seed, + solve_steady_state, +) + +__all__ = [ + "DEFAULT_SUNS", + "SunsVocOptions", + "SunsVocResult", + "compute_pseudo_ff", + "compute_suns_voc_ideality", + "default_ionic_steady_options", + "run_suns_voc", + "solve_ionic_dc_operating_point", +] + +BOLTZMANN_J_K = 1.380649e-23 +DEFAULT_SUNS: tuple[float, ...] = (0.01, 0.1, 1.0, 5.0, 10.0) +ProgressCallback = Callable[[str, int, int, str], None] + + +def default_ionic_steady_options( + ion_node_count: int, + *, + electronic: SteadyOptions | None = None, +) -> IonicSteadyOptions: + """Explicit production coupled ionic DC controls when none are supplied.""" + elec = ( + SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + if electronic is None + else electronic + ) + return IonicSteadyOptions( + electronic=elec, + inventory_relative_tolerance=1e-12, + ion_balance_tolerance_m2_s=1e6, + ion_flux_tolerance_m2_s=1e6, + ion_logit_step=1.0, + inventory_row_node=max(int(ion_node_count) - 1, 0), + budget=SolveBudget(60, 600, 60, 24), + wall_s=30.0, + ) + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class SunsVocOptions: + """Explicit numerical controls for DC Suns-V_oc sweeps.""" + + steady: SteadyOptions = field( + default_factory=lambda: SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + ) + ionic_steady: IonicSteadyOptions | None = None + voc_voltage_tol_V: float = 1e-6 + voc_current_tol_A_m2: float = 1e-6 + voc_bracket_step_V: float = 0.05 + voc_bracket_max_V: float = 3.0 + max_voc_solve_calls: int = 64 + max_continuation_subdivisions: int = 16 + subtract_dark_offset_at_jsc: bool = True + require_all_bracketed: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + for name, value in ( + ("voc_voltage_tol_V", self.voc_voltage_tol_V), + ("voc_current_tol_A_m2", self.voc_current_tol_A_m2), + ("voc_bracket_step_V", self.voc_bracket_step_V), + ("voc_bracket_max_V", self.voc_bracket_max_V), + ): + if not math.isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be finite and positive") + if self.voc_bracket_step_V > self.voc_bracket_max_V: + raise ValueError("voc_bracket_step_V cannot exceed voc_bracket_max_V") + if type(self.max_voc_solve_calls) is not int or self.max_voc_solve_calls < 4: + raise ValueError("max_voc_solve_calls must be an integer >= 4") + if ( + type(self.max_continuation_subdivisions) is not int + or self.max_continuation_subdivisions < 2 + ): + raise ValueError("max_continuation_subdivisions must be an integer >= 2") + + +@dataclass(frozen=True) +class SunsVocResult: + """Genuine DC Suns-V_oc sweep, ideality diagnostics, and Sinton pseudo-JV.""" + + suns_levels: np.ndarray + V_oc_V: np.ndarray + J_sc_A_m2: np.ndarray + dark_short_circuit_A_m2: float + converged_mask: np.ndarray + voc_bracketed_mask: np.ndarray + point_reasons: tuple[str | None, ...] + local_ideality_factor: np.ndarray + ideality_factor_fit: float + ideality_r_squared: float + J_pseudo_V: np.ndarray + J_pseudo_A_m2: np.ndarray + pseudo_FF: float + pseudo_ff_reason: str | None + reference_index: int + max_current_spread_A_m2: float + temperature_K: float + voltage_polarity: float + compiled_identity: str + solver_controls: dict[str, Any] + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "suns_levels", + "V_oc_V", + "J_sc_A_m2", + "local_ideality_factor", + "J_pseudo_V", + "J_pseudo_A_m2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ("converged_mask", "voc_bracketed_mask"): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + @property + def suns(self) -> np.ndarray: + return self.suns_levels + + @property + def V_oc(self) -> np.ndarray: + return self.V_oc_V + + @property + def J_sc(self) -> np.ndarray: + return self.J_sc_A_m2 + + @property + def J_pseudo_J(self) -> np.ndarray: + return self.J_pseudo_A_m2 + + @property + def J_spread_max(self) -> float: + return self.max_current_spread_A_m2 + + @property + def completed(self) -> bool: + return bool(np.all(self.converged_mask & self.voc_bracketed_mask)) + + +def compute_suns_voc_ideality( + suns_levels: Sequence[float] | np.ndarray, + V_oc_V: Sequence[float] | np.ndarray, + *, + temperature_K: float, + valid_mask: Sequence[bool] | np.ndarray | None = None, +) -> tuple[np.ndarray, float, float]: + """Compute local ``n_id(X)`` and global log-linear fit over valid points.""" + suns: np.ndarray = np.asarray(suns_levels, dtype=float) + voc: np.ndarray = np.asarray(V_oc_V, dtype=float) + if suns.ndim != 1 or voc.shape != suns.shape or suns.size == 0: + raise ValueError("suns_levels and V_oc_V must be matching 1D non-empty arrays") + if not math.isfinite(temperature_K) or temperature_K <= 0.0: + raise ValueError("temperature_K must be finite and positive") + v_thermal = BOLTZMANN_J_K * float(temperature_K) / ELEMENTARY_CHARGE_C + + mask = ( + np.isfinite(suns) & (suns > 0.0) & np.isfinite(voc) + if valid_mask is None + else np.asarray(valid_mask, dtype=bool) + & np.isfinite(suns) + & (suns > 0.0) + & np.isfinite(voc) + ) + local: np.ndarray = np.full(suns.shape, np.nan, dtype=float) + if int(np.count_nonzero(mask)) < 2: + return local, float("nan"), float("nan") + + ln_x = np.log(suns[mask]) + y = voc[mask] + if np.any(np.diff(ln_x) <= 0.0): + raise ValueError("valid suns_levels must be strictly ascending") + + local_valid = np.gradient(y, ln_x) / v_thermal + local[mask] = local_valid + + slope, intercept = np.polyfit(ln_x, y, 1) + n_fit = float(slope / v_thermal) + ss_tot = float(np.sum((y - np.mean(y)) ** 2)) + ss_res = float(np.sum((y - (slope * ln_x + intercept)) ** 2)) + r_sq = float(1.0 - ss_res / ss_tot) if ss_tot > 0.0 else 1.0 + return local, n_fit, r_sq + + +def compute_pseudo_ff( + J_pseudo_V: Sequence[float] | np.ndarray, + J_pseudo_A_m2: Sequence[float] | np.ndarray, + *, + V_oc_ref_V: float, + J_sc_ref_A_m2: float, +) -> tuple[float, str | None]: + """Compute Sinton pseudo-FF on the valid power-quadrant points.""" + if ( + not math.isfinite(V_oc_ref_V) + or not math.isfinite(J_sc_ref_A_m2) + or V_oc_ref_V <= 0.0 + or J_sc_ref_A_m2 <= 0.0 + ): + return float("nan"), "missing_or_nonpositive_reference" + + v_arr: np.ndarray = np.asarray(J_pseudo_V, dtype=float) + j_arr: np.ndarray = np.asarray(J_pseudo_A_m2, dtype=float) + finite = np.isfinite(v_arr) & np.isfinite(j_arr) + mask = ( + finite + & (v_arr > 0.0) + & (v_arr < V_oc_ref_V) + & (j_arr > 0.0) + & (j_arr < J_sc_ref_A_m2) + ) + if not np.any(mask): + return float("nan"), "no_valid_power_quadrant_points" + + v_quad = np.concatenate(([0.0], v_arr[mask], [V_oc_ref_V])) + j_quad = np.concatenate(([J_sc_ref_A_m2], j_arr[mask], [0.0])) + order = np.argsort(v_quad) + v_sorted = v_quad[order] + j_sorted = j_quad[order] + + v_grid = np.linspace(0.0, V_oc_ref_V, 500) + j_grid = np.interp(v_grid, v_sorted, j_sorted) + p_max = float(np.max(v_grid * j_grid)) + return float(p_max / (V_oc_ref_V * J_sc_ref_A_m2)), None + + +def _normalize_suns_levels(suns_levels: Sequence[float] | np.ndarray) -> np.ndarray: + raw = [float(level) for level in suns_levels] + if not raw: + raise ValueError("suns_levels must be non-empty") + if any(not math.isfinite(val) or val <= 0.0 for val in raw): + raise ValueError(f"suns_levels must be finite and positive, got {raw}") + return np.array(sorted(set(raw)), dtype=float) + + +def _electronic_output_and_spread( + solution: SteadyState1D, polarity: float +) -> tuple[float, float]: + currents = np.asarray(solution.current_density_A_m2, dtype=float) + return float(-polarity * currents[0]), float(np.ptp(currents)) + + +def _solve_electronic_step_with_continuation( + compiled: CompiledDevice1D, + seed: SteadyState1D, + target_V: float, + generation_scale: float, + options: SteadyOptions, + max_subdivisions: int, +) -> SteadyState1D: + """Advance from an accepted DC solution to ``target_V`` with bounded halving.""" + v_curr = seed.voltage_V + current_sol = seed + try: + sol = solve_steady_state( + compiled, + voltage_V=target_V, + generation_scale=generation_scale, + initial_state=current_sol.state, + options=options, + ) + if sol.converged: + return sol + except SteadyStateError as first_err: + last_err = first_err + else: + last_err = SteadyStateError(f"unconverged at {target_V} V", sol.newton) + + subdivisions = 2 + while subdivisions <= max_subdivisions: + v_base = v_curr + step_sol = current_sol + chain_ok = True + for step in range(1, subdivisions + 1): + v_mid = v_base + (target_V - v_base) * (step / subdivisions) + try: + mid_sol = solve_steady_state( + compiled, + voltage_V=v_mid, + generation_scale=generation_scale, + initial_state=step_sol.state, + options=options, + ) + except SteadyStateError as err: + last_err = err + chain_ok = False + break + if not mid_sol.converged: + last_err = SteadyStateError(f"unconverged at {v_mid} V", mid_sol.newton) + chain_ok = False + break + step_sol = mid_sol + current_sol = step_sol + v_curr = v_mid + if chain_ok: + return step_sol + subdivisions *= 2 + raise last_err + + +def _solve_electronic_voc_point( + compiled: CompiledDevice1D, + suns: float, + sol_zero: SteadyState1D, + warm_voc_V: float, + options: SunsVocOptions, +) -> tuple[float, bool, bool, str | None, float]: + """Bracket and refine ``V_oc(suns)`` via ``solve_direct_voc``.""" + polarity = float(compiled.voltage_polarity) + j_zero, spread_max = _electronic_output_and_spread(sol_zero, polarity) + if abs(j_zero) <= options.voc_current_tol_A_m2: + return 0.0, True, True, None, spread_max + if j_zero < 0.0: + return ( + float("nan"), + True, + False, + "voc_not_bracketed:nonpositive_short_circuit_current", + spread_max, + ) + + low_sol = sol_zero + step_v = options.voc_bracket_step_V + v_probe = max(step_v, warm_voc_V - step_v) + if v_probe > step_v: + # Step smoothly from 0 V to just below warm_voc_V so Newton stays in basin. + n_coarse = max(1, int(math.ceil(v_probe / max(step_v, 0.1)))) + for idx in range(1, n_coarse + 1): + v_next = v_probe * (idx / n_coarse) + try: + cand = _solve_electronic_step_with_continuation( + compiled, + low_sol, + v_next, + suns, + options.steady, + options.max_continuation_subdivisions, + ) + except SteadyStateError as exc: + return ( + float("nan"), + False, + False, + f"voc_not_converged:{exc}", + spread_max, + ) + j_cand, sp_cand = _electronic_output_and_spread(cand, polarity) + spread_max = max(spread_max, sp_cand) + if j_cand <= 0.0: + high_sol = cand + break + low_sol = cand + else: + high_sol = None + else: + high_sol = None + + v_cursor = low_sol.voltage_V + while high_sol is None and v_cursor < options.voc_bracket_max_V - 1e-12: + v_next = min(options.voc_bracket_max_V, v_cursor + step_v) + try: + cand = _solve_electronic_step_with_continuation( + compiled, + low_sol, + v_next, + suns, + options.steady, + options.max_continuation_subdivisions, + ) + except SteadyStateError as exc: + return ( + float("nan"), + False, + False, + f"voc_not_converged:{exc}", + spread_max, + ) + j_cand, sp_cand = _electronic_output_and_spread(cand, polarity) + spread_max = max(spread_max, sp_cand) + if j_cand <= 0.0: + high_sol = cand + break + low_sol = cand + v_cursor = v_next + + if high_sol is None: + return ( + float("nan"), + True, + False, + f"voc_not_bracketed:exceeded_max_voltage_{options.voc_bracket_max_V:.4g}V", + spread_max, + ) + + voltages = np.array([low_sol.voltage_V, high_sol.voltage_V], dtype=float) + currents = np.array( + [low_sol.current_density_A_m2, high_sol.current_density_A_m2], dtype=float + ) + outputs = -polarity * currents[:, 0] + bracket = SteadyJVResult( + voltage_V=voltages, + current_density_A_m2=currents, + output_current_A_m2=outputs, + solutions=(low_sol, high_sol), + metrics=steady_jv_metrics(voltages, outputs), + generation_scale=suns, + incident_power_W_m2=None, + voltage_polarity=polarity, + compiled_identity=compiled.identity, + nodes_m=compiled.nodes_m, + solver_controls=asdict(options.steady), + ) + try: + refined = solve_direct_voc( + compiled, + bracket, + voltage_tolerance_V=options.voc_voltage_tol_V, + max_solve_calls=options.max_voc_solve_calls, + max_continuation_subdivisions=options.max_continuation_subdivisions, + options=options.steady, + ) + except (VocBracketError, DirectVocError) as exc: + return float("nan"), False, True, f"voc_refinement_failed:{exc}", spread_max + + _, sp_voc = _electronic_output_and_spread(refined.solution, polarity) + return float(refined.voltage_V), True, True, None, max(spread_max, sp_voc) + + +def _dc_problem( + device: CompiledDevice1D, voltage_V: float, generation_scale: float +) -> DCProblem: + if use_assembled(): + return AssembledDC1DProblem(device, voltage_V, generation_scale) + return DC1DProblem(device, voltage_V, generation_scale) + + +def _rebase_ionic_state( + compiled: CompiledIonicDevice1D, state: IonicState1D, voltage_V: float +) -> IonicState1D: + if state.voltage_V == voltage_V: + return state + coords = state.u.copy() + n_elec = 3 * compiled.node_count + coords[:n_elec] = compiled.electronic_component.rebase_coordinates( + coords[:n_elec], state.voltage_V, voltage_V + ) + return compiled.state(coords, voltage_V=voltage_V) + + +def _solve_ionic_voltage_step( + compiled: CompiledIonicDevice1D, + seed_state: IonicState1D, + target_V: float, + generation_scale: float, + ionic_controls: IonicSteadyOptions, + max_subdivisions: int = 16, +) -> IonicSteadyResult: + """Advance coupled ionic DC from ``seed_state`` to ``target_V`` with bounded halving.""" + v_curr = float(seed_state.voltage_V) + curr_state = seed_state + cand = solve_ionic_steady_state( + compiled, + voltage_V=target_V, + generation_scale=generation_scale, + options=ionic_controls, + initial_state=_rebase_ionic_state(compiled, curr_state, target_V), + ) + if cand.accepted and cand.state is not None: + return cand + + subdivisions = 2 + last_failed = cand + while subdivisions <= max_subdivisions: + step_state = curr_state + v_base = v_curr + ok_chain = True + for step in range(1, subdivisions + 1): + v_mid = v_base + (target_V - v_base) * (step / subdivisions) + mid_res = solve_ionic_steady_state( + compiled, + voltage_V=v_mid, + generation_scale=generation_scale, + options=ionic_controls, + initial_state=_rebase_ionic_state(compiled, step_state, v_mid), + ) + last_failed = mid_res + if not mid_res.accepted or mid_res.state is None: + ok_chain = False + break + step_state = mid_res.state + curr_state = step_state + v_curr = v_mid + if ok_chain: + return last_failed + subdivisions *= 2 + return last_failed + + +def solve_ionic_dc_operating_point( + compiled: CompiledIonicDevice1D, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: IonicSteadyOptions, + base_state: IonicState1D | None = None, + base_generation_scale: float = 0.0, + max_subdivisions: int = 16, +) -> IonicSteadyResult: + """Solve a coupled ionic DC operating point using physical-density light seeding.""" + target_v = float(voltage_V) + target_gen = float(generation_scale) + n_elec = 3 * compiled.node_count + max_gen_source = float( + np.max(np.abs(compiled.electronic_component.generation.source_m3_s)) + ) + + if base_state is None: + if target_gen == 0.0 and target_v == 0.0: + return solve_ionic_steady_state( + compiled, voltage_V=0.0, generation_scale=0.0, options=options + ) + dark_zero = solve_ionic_steady_state( + compiled, voltage_V=0.0, generation_scale=0.0, options=options + ) + if not dark_zero.accepted or dark_zero.state is None: + return dark_zero + curr_state = dark_zero.state + curr_gen = 0.0 + last_res: IonicSteadyResult | None = dark_zero + else: + curr_state = base_state + curr_gen = float(base_generation_scale) + last_res = None + + if target_gen != curr_gen: + if target_gen == 0.0 or max_gen_source == 0.0: + res_gen = solve_ionic_steady_state( + compiled, + voltage_V=float(curr_state.voltage_V), + generation_scale=target_gen, + options=options, + initial_state=curr_state, + ) + if not res_gen.accepted or res_gen.state is None: + return res_gen + curr_state = res_gen.state + curr_gen = target_gen + last_res = res_gen + else: + light_steps = ( + [frac * target_gen for frac in (1e-8, 1e-6, 1e-4, 1e-2, 1.0)] + if curr_gen == 0.0 + else [target_gen] + ) + for light in light_steps: + v_hold = float(curr_state.voltage_V) + prob = _dc_problem(compiled.electronic_component, v_hold, light) + try: + seeded_elec = density_basin_seed(prob, curr_state.u[:n_elec]) + joined = np.r_[seeded_elec, curr_state.u[n_elec:]] + seed_ion = compiled.state(joined, voltage_V=v_hold) + except ValueError: + seed_ion = curr_state + res_light = solve_ionic_steady_state( + compiled, + voltage_V=v_hold, + generation_scale=light, + options=options, + initial_state=seed_ion, + ) + if not res_light.accepted or res_light.state is None: + return res_light + curr_state = res_light.state + curr_gen = light + last_res = res_light + + v_curr = float(curr_state.voltage_V) + if v_curr == target_v and last_res is not None: + return last_res + + max_step = max(float(options.electronic.max_bias_step_V), 0.02) + n_bias = max(1, int(math.ceil(abs(target_v - v_curr) / max_step))) + res_bias: IonicSteadyResult | None = None + for idx in range(1, n_bias + 1): + v_step = v_curr + (target_v - v_curr) * (idx / n_bias) + res_bias = _solve_ionic_voltage_step( + compiled, + curr_state, + v_step, + target_gen, + options, + max_subdivisions=max_subdivisions, + ) + if not res_bias.accepted or res_bias.state is None: + return res_bias + curr_state = res_bias.state + assert res_bias is not None + return res_bias + + +def _ionic_output_and_spread( + result: IonicSteadyResult, polarity: float +) -> tuple[float, float]: + assert result.diagnostics is not None + currents = np.asarray(result.diagnostics["total_current_density_A_m2"], dtype=float) + return float(-polarity * currents[0]), float(np.ptp(currents)) + + +def _solve_ionic_voc_point( + compiled: CompiledIonicDevice1D, + suns: float, + sol_zero: IonicSteadyResult, + warm_voc_V: float, + options: SunsVocOptions, + ionic_controls: IonicSteadyOptions, +) -> tuple[float, bool, bool, str | None, float]: + """Bracket and bisect coupled ionic DC ``V_oc(suns)``.""" + polarity = float(compiled.electronic_component.voltage_polarity) + j_zero, spread_max = _ionic_output_and_spread(sol_zero, polarity) + if abs(j_zero) <= options.voc_current_tol_A_m2: + return 0.0, True, True, None, spread_max + if j_zero < 0.0: + return ( + float("nan"), + True, + False, + "voc_not_bracketed:nonpositive_short_circuit_current", + spread_max, + ) + + assert sol_zero.state is not None + low_state = sol_zero.state + low_v = 0.0 + low_j = j_zero + high_state: IonicState1D | None = None + high_v = 0.0 + high_j = 0.0 + + step_v = options.voc_bracket_step_V + v_cursor = 0.0 + target_start = max(0.0, warm_voc_V - step_v) + if target_start > step_v: + n_coarse = max(1, int(math.ceil(target_start / max(step_v, 0.1)))) + for idx in range(1, n_coarse + 1): + v_next = target_start * (idx / n_coarse) + cand = _solve_ionic_voltage_step( + compiled, + low_state, + v_next, + suns, + ionic_controls, + max_subdivisions=options.max_continuation_subdivisions, + ) + if not cand.accepted or cand.state is None: + reason = cand.error or cand.termination + return ( + float("nan"), + False, + False, + f"voc_not_converged:{reason}", + spread_max, + ) + j_cand, sp_cand = _ionic_output_and_spread(cand, polarity) + spread_max = max(spread_max, sp_cand) + if j_cand <= 0.0: + high_state, high_v, high_j = cand.state, v_next, j_cand + break + low_state, low_v, low_j = cand.state, v_next, j_cand + v_cursor = v_next + + while high_state is None and v_cursor < options.voc_bracket_max_V - 1e-12: + v_next = min(options.voc_bracket_max_V, v_cursor + step_v) + cand = _solve_ionic_voltage_step( + compiled, + low_state, + v_next, + suns, + ionic_controls, + max_subdivisions=options.max_continuation_subdivisions, + ) + if not cand.accepted or cand.state is None: + reason = cand.error or cand.termination + return ( + float("nan"), + False, + False, + f"voc_not_converged:{reason}", + spread_max, + ) + j_cand, sp_cand = _ionic_output_and_spread(cand, polarity) + spread_max = max(spread_max, sp_cand) + if j_cand <= 0.0: + high_state, high_v, high_j = cand.state, v_next, j_cand + break + low_state, low_v, low_j = cand.state, v_next, j_cand + v_cursor = v_next + + if high_state is None: + return ( + float("nan"), + True, + False, + f"voc_not_bracketed:exceeded_max_voltage_{options.voc_bracket_max_V:.4g}V", + spread_max, + ) + + calls = 0 + while (high_v - low_v) > options.voc_voltage_tol_V: + if calls >= options.max_voc_solve_calls: + return ( + float("nan"), + False, + True, + "voc_refinement_failed:exhausted_solve_calls", + spread_max, + ) + calls += 1 + mid_v = 0.5 * (low_v + high_v) + seed_base = low_state if (mid_v - low_v) <= (high_v - mid_v) else high_state + mid_res = _solve_ionic_voltage_step( + compiled, + seed_base, + mid_v, + suns, + ionic_controls, + max_subdivisions=options.max_continuation_subdivisions, + ) + if not mid_res.accepted or mid_res.state is None: + reason = mid_res.error or mid_res.termination + return ( + float("nan"), + False, + True, + f"voc_refinement_failed:{reason}", + spread_max, + ) + j_mid, sp_mid = _ionic_output_and_spread(mid_res, polarity) + spread_max = max(spread_max, sp_mid) + if abs(j_mid) <= options.voc_current_tol_A_m2: + return mid_v, True, True, None, spread_max + if j_mid > 0.0: + low_state, low_v, low_j = mid_res.state, mid_v, j_mid + else: + high_state, high_v, high_j = mid_res.state, mid_v, j_mid + + best_v = low_v if abs(low_j) <= abs(high_j) else high_v + return float(best_v), True, True, None, spread_max + + +def run_suns_voc( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + suns_levels: Sequence[float] | np.ndarray = DEFAULT_SUNS, + *, + options: SunsVocOptions | None = None, + progress: ProgressCallback | None = None, +) -> SunsVocResult: + """Run a genuine DC Suns-V_oc sweep on an electronic or coupled ionic device.""" + opts = SunsVocOptions() if options is None else options + suns_sorted = _normalize_suns_levels(suns_levels) + n_pts = int(suns_sorted.size) + + voc_arr: np.ndarray = np.full(n_pts, np.nan, dtype=float) + jsc_arr: np.ndarray = np.full(n_pts, np.nan, dtype=float) + conv_mask: np.ndarray = np.zeros(n_pts, dtype=bool) + brack_mask: np.ndarray = np.zeros(n_pts, dtype=bool) + reasons: list[str | None] = [None] * n_pts + spread_max = 0.0 + warm_voc = 0.0 + + if isinstance(compiled, CompiledDevice1D): + polarity = float(compiled.voltage_polarity) + temperature_K = float( + compiled.thermal_voltage_V * ELEMENTARY_CHARGE_C / BOLTZMANN_J_K + ) + controls_record: dict[str, Any] = { + "mode": "electronic_dc", + "steady": asdict(opts.steady), + "voc_voltage_tol_V": opts.voc_voltage_tol_V, + "voc_bracket_step_V": opts.voc_bracket_step_V, + "voc_bracket_max_V": opts.voc_bracket_max_V, + } + j_dark = 0.0 + if opts.subtract_dark_offset_at_jsc: + try: + dark_sol = solve_steady_state( + compiled, voltage_V=0.0, generation_scale=0.0, options=opts.steady + ) + if dark_sol.converged: + j_dark, sp_dark = _electronic_output_and_spread(dark_sol, polarity) + spread_max = max(spread_max, sp_dark) + else: + j_dark = float("nan") + except SteadyStateError: + j_dark = float("nan") + + for k, suns in enumerate(suns_sorted): + try: + sol_zero = solve_steady_state( + compiled, + voltage_V=0.0, + generation_scale=float(suns), + options=opts.steady, + ) + if not sol_zero.converged: + reasons[k] = "jsc_not_converged:unconverged_steady_result" + continue + except SteadyStateError as exc: + reasons[k] = f"jsc_not_converged:{exc}" + continue + + j_tot, sp_zero = _electronic_output_and_spread(sol_zero, polarity) + spread_max = max(spread_max, sp_zero) + jsc_arr[k] = ( + j_tot - j_dark + if (opts.subtract_dark_offset_at_jsc and math.isfinite(j_dark)) + else j_tot + ) + voc_k, conv_k, brack_k, reason_k, sp_voc = _solve_electronic_voc_point( + compiled, float(suns), sol_zero, warm_voc, opts + ) + spread_max = max(spread_max, sp_voc) + voc_arr[k] = voc_k + conv_mask[k] = conv_k + brack_mask[k] = brack_k + reasons[k] = reason_k + if conv_k and brack_k and math.isfinite(voc_k): + warm_voc = max(warm_voc, voc_k) + if progress is not None: + progress( + "suns_voc", + k + 1, + n_pts, + f"X={suns:.3g}, V_oc={voc_k:.4f} V, J_sc={jsc_arr[k]:.2f} A/m^2", + ) + + elif isinstance(compiled, CompiledIonicDevice1D): + polarity = float(compiled.electronic_component.voltage_polarity) + temperature_K = float( + compiled.electronic_component.thermal_voltage_V + * ELEMENTARY_CHARGE_C + / BOLTZMANN_J_K + ) + ionic_controls = ( + default_ionic_steady_options( + compiled.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + controls_record = { + "mode": "ionic_dc", + "ionic_steady": asdict(ionic_controls), + "voc_voltage_tol_V": opts.voc_voltage_tol_V, + "voc_bracket_step_V": opts.voc_bracket_step_V, + "voc_bracket_max_V": opts.voc_bracket_max_V, + } + j_dark = 0.0 + prev_ionic_zero: IonicState1D | None = None + prev_suns = 0.0 + if opts.subtract_dark_offset_at_jsc: + dark_res = solve_ionic_steady_state( + compiled, + voltage_V=0.0, + generation_scale=0.0, + options=ionic_controls, + ) + if dark_res.accepted and dark_res.state is not None: + j_dark, sp_dark = _ionic_output_and_spread(dark_res, polarity) + spread_max = max(spread_max, sp_dark) + prev_ionic_zero = dark_res.state + prev_suns = 0.0 + else: + j_dark = float("nan") + + for k, suns in enumerate(suns_sorted): + sol_zero_ion = solve_ionic_dc_operating_point( + compiled, + voltage_V=0.0, + generation_scale=float(suns), + options=ionic_controls, + base_state=prev_ionic_zero, + base_generation_scale=prev_suns, + max_subdivisions=opts.max_continuation_subdivisions, + ) + if not sol_zero_ion.accepted or sol_zero_ion.state is None: + reason = sol_zero_ion.error or sol_zero_ion.termination + reasons[k] = f"jsc_not_converged:{reason}" + continue + + prev_ionic_zero = sol_zero_ion.state + prev_suns = float(suns) + j_tot, sp_zero = _ionic_output_and_spread(sol_zero_ion, polarity) + spread_max = max(spread_max, sp_zero) + jsc_arr[k] = ( + j_tot - j_dark + if (opts.subtract_dark_offset_at_jsc and math.isfinite(j_dark)) + else j_tot + ) + voc_k, conv_k, brack_k, reason_k, sp_voc = _solve_ionic_voc_point( + compiled, float(suns), sol_zero_ion, warm_voc, opts, ionic_controls + ) + spread_max = max(spread_max, sp_voc) + voc_arr[k] = voc_k + conv_mask[k] = conv_k + brack_mask[k] = brack_k + reasons[k] = reason_k + if conv_k and brack_k and math.isfinite(voc_k): + warm_voc = max(warm_voc, voc_k) + if progress is not None: + progress( + "suns_voc", + k + 1, + n_pts, + f"X={suns:.3g}, V_oc={voc_k:.4f} V, J_sc={jsc_arr[k]:.2f} A/m^2", + ) + else: + raise TypeError( + "compiled must be a CompiledDevice1D or CompiledIonicDevice1D" + ) + + valid_mask = conv_mask & brack_mask + if opts.require_all_bracketed and not bool(np.all(valid_mask)): + bad = [ + f"X={suns_sorted[i]:.4g} ({reasons[i]})" + for i in range(n_pts) + if not valid_mask[i] + ] + raise RuntimeError( + "Suns-V_oc failed to converge and bracket every intensity: " + + ", ".join(bad) + ) + + local_n, n_fit, r_sq = compute_suns_voc_ideality( + suns_sorted, voc_arr, temperature_K=temperature_K, valid_mask=valid_mask + ) + + ref_idx = int(np.argmin(np.abs(suns_sorted - 1.0))) + voc_ref = float(voc_arr[ref_idx]) if valid_mask[ref_idx] else float("nan") + jsc_ref = float(jsc_arr[ref_idx]) if valid_mask[ref_idx] else float("nan") + + j_pseudo_v = np.where(valid_mask, voc_arr, np.nan) + j_pseudo_j = ( + np.where(valid_mask, jsc_ref - jsc_arr, np.nan) + if math.isfinite(jsc_ref) + else np.full(n_pts, np.nan, dtype=float) + ) + pff, pff_reason = compute_pseudo_ff( + j_pseudo_v, + j_pseudo_j, + V_oc_ref_V=voc_ref, + J_sc_ref_A_m2=jsc_ref, + ) + + return SunsVocResult( + suns_levels=suns_sorted, + V_oc_V=voc_arr, + J_sc_A_m2=jsc_arr, + dark_short_circuit_A_m2=float(j_dark), + converged_mask=conv_mask, + voc_bracketed_mask=brack_mask, + point_reasons=tuple(reasons), + local_ideality_factor=local_n, + ideality_factor_fit=n_fit, + ideality_r_squared=r_sq, + J_pseudo_V=j_pseudo_v, + J_pseudo_A_m2=j_pseudo_j, + pseudo_FF=pff, + pseudo_ff_reason=pff_reason, + reference_index=ref_idx, + max_current_spread_A_m2=float(spread_max), + temperature_K=temperature_K, + voltage_polarity=polarity, + compiled_identity=compiled.identity, + solver_controls=controls_record, + ) diff --git a/src/solarlab/experiments/voc_t.py b/src/solarlab/experiments/voc_t.py new file mode 100644 index 00000000..d0d31e49 --- /dev/null +++ b/src/solarlab/experiments/voc_t.py @@ -0,0 +1,328 @@ +"""Temperature-dependent open-circuit voltage V_oc(T) and 0 K activation energy. + +Each requested temperature ``T_k`` cold-rebinds ``PreparedDevice`` with +``settings.T = T_k`` and compiles a fresh 1D device with zero cross-temperature +carrier or ionic state hand-off. Every point is solved as a genuine DC +operating point via ``run_suns_voc(..., suns_levels=[generation_scale])``; +unbracketed or non-converged temperatures record ``np.nan`` and are excluded +from the linear 0 K extrapolation ``V_oc(T) = slope * T + E_A / q``. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +import json +import math +from typing import Any +import warnings + +import numpy as np + +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.suns_voc import SunsVocOptions, run_suns_voc +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.reproducibility.sources import SourceDocument + +__all__ = [ + "VocTOptions", + "VocTResult", + "fit_voc_t_extrapolation", + "rebind_prepared_temperature", + "run_voc_t", +] + +ProgressCallback = Callable[[str, int, int, str], None] + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class VocTOptions: + """Explicit grid, mode, and DC root-finding controls for V_oc(T).""" + + intervals_per_layer: int = 20 + generation_scale: float = 1.0 + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + suns_voc: SunsVocOptions = field(default_factory=SunsVocOptions) + allow_partial: bool = False + + def __post_init__(self) -> None: + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if not math.isfinite(self.generation_scale) or self.generation_scale <= 0.0: + raise ValueError("generation_scale must be finite and positive") + if not isinstance(self.suns_voc, SunsVocOptions): + raise ValueError("suns_voc must be an explicit SunsVocOptions instance") + + +@dataclass(frozen=True) +class VocTResult: + """Genuine DC V_oc(T) sweep with 0 K linear activation-energy fit.""" + + temperatures_K: np.ndarray + V_oc_V: np.ndarray + J_sc_A_m2: np.ndarray + converged_mask: np.ndarray + voc_bracketed_mask: np.ndarray + point_reasons: tuple[str | None, ...] + slope_V_K: float + intercept_0K_V: float + activation_energy_eV: float + r_squared: float + fit_failure_reason: str | None + generation_scale: float + compiled_identities: tuple[str, ...] + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "temperatures_K", + "V_oc_V", + "J_sc_A_m2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for mask_name in ("converged_mask", "voc_bracketed_mask"): + object.__setattr__(self, mask_name, _ro_bool(getattr(self, mask_name))) + + @property + def T_arr(self) -> np.ndarray: + return self.temperatures_K + + @property + def V_oc_arr(self) -> np.ndarray: + return self.V_oc_V + + @property + def J_sc_arr(self) -> np.ndarray: + return self.J_sc_A_m2 + + @property + def E_A_eV(self) -> float: + return self.activation_energy_eV + + @property + def V_oc_0K(self) -> float: + return self.intercept_0K_V + + @property + def completed(self) -> bool: + return bool(np.all(self.converged_mask & self.voc_bracketed_mask)) + + +def rebind_prepared_temperature( + prepared: PreparedDevice, temperature_K: float +) -> PreparedDevice: + """Return a fresh ``PreparedDevice`` bound at ``settings.T = temperature_K``.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice instance") + t_val = float(temperature_K) + if not math.isfinite(t_val) or t_val <= 0.0: + raise ValueError(f"temperature_K must be finite and positive, got {temperature_K}") + + editing = prepared.to_input().editing_data() + settings = dict(editing.get("settings") or {}) + settings["T"] = t_val + editing["settings"] = settings + + payload = json.dumps( + editing, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + source = SourceDocument(f"voc_t.T_{t_val:.6g}K", payload) + return resolve_device( + DeviceInput.model_validate(editing), + prepared.defaults, + prepared.resources, + sources=(*prepared.sources, source), + ) + + +def fit_voc_t_extrapolation( + temperatures_K: Sequence[float] | np.ndarray, + V_oc_V: Sequence[float] | np.ndarray, + *, + converged_mask: Sequence[bool] | np.ndarray, + voc_bracketed_mask: Sequence[bool] | np.ndarray, + allow_partial: bool = False, +) -> tuple[float, float, float, float, str | None]: + """Fit ``V_oc(T) = slope * T + intercept_0K`` over valid bracketed points. + + Unbracketed or non-converged points are never substituted with ``0.0``. + When fewer than 2 valid distinct temperatures exist, raises ``ValueError`` + unless ``allow_partial=True`` (which returns ``np.nan`` fit parameters and + an explicit ``fit_failure_reason``). + """ + temps: np.ndarray = np.asarray(temperatures_K, dtype=float) + voc: np.ndarray = np.asarray(V_oc_V, dtype=float) + conv: np.ndarray = np.asarray(converged_mask, dtype=bool) + brack: np.ndarray = np.asarray(voc_bracketed_mask, dtype=bool) + if ( + temps.ndim != 1 + or voc.shape != temps.shape + or conv.shape != temps.shape + or brack.shape != temps.shape + ): + raise ValueError("V_oc(T) arrays and masks must have matching 1D shapes") + + valid = conv & brack & np.isfinite(temps) & (temps > 0.0) & np.isfinite(voc) + n_valid = int(np.count_nonzero(valid)) + n_total = int(temps.size) + + if n_valid < 2 or np.unique(temps[valid]).size < 2: + reason = f"insufficient_valid_bracketed_points:{n_valid}_of_{n_total}" + if not allow_partial: + raise ValueError( + f"run_voc_t requires >= 2 valid bracketed temperatures to " + f"extrapolate E_A, got {n_valid}/{n_total}" + ) + return float("nan"), float("nan"), float("nan"), float("nan"), reason + + if n_valid < n_total: + excluded = [f"{temps[i]:.1f}K" for i in range(n_total) if not valid[i]] + warnings.warn( + f"V_oc(T) fit excluded {n_total - n_valid}/{n_total} non-converged or " + f"unbracketed temperatures ({', '.join(excluded)}).", + RuntimeWarning, + stacklevel=2, + ) + + t_fit = temps[valid] + v_fit = voc[valid] + slope, intercept = np.polyfit(t_fit, v_fit, 1) + v_pred = slope * t_fit + intercept + ss_res = float(np.sum((v_fit - v_pred) ** 2)) + ss_tot = float(np.sum((v_fit - np.mean(v_fit)) ** 2)) + r_sq = float(1.0 - ss_res / ss_tot) if ss_tot > 0.0 else 1.0 + # E_A [eV] numerically equals q * V_oc(0 K) / q = intercept [V]. + return ( + float(slope), + float(intercept), + float(intercept), + r_sq, + None, + ) + + +def _normalize_temperatures( + temperatures_K: Sequence[float] | np.ndarray | None, + *, + T_min: float, + T_max: float, + n_points: int, +) -> np.ndarray: + if temperatures_K is not None: + arr: np.ndarray = np.asarray([float(t) for t in temperatures_K], dtype=float) + if arr.ndim != 1 or arr.size < 2: + raise ValueError("temperatures_K must contain at least 2 temperatures") + if np.any(~np.isfinite(arr)) or np.any(arr <= 0.0): + raise ValueError("temperatures_K must be finite and positive") + return np.array(sorted(set(arr.tolist())), dtype=float) + if type(n_points) is not int or n_points < 2: + raise ValueError(f"n_points must be an integer >= 2, got {n_points}") + if not math.isfinite(T_min) or not math.isfinite(T_max) or T_min <= 0.0: + raise ValueError(f"T_min and T_max must be finite and > 0, got {T_min}, {T_max}") + if T_max <= T_min: + raise ValueError(f"T_max ({T_max}) must exceed T_min ({T_min})") + return np.linspace(float(T_min), float(T_max), n_points, dtype=float) + + +def run_voc_t( + prepared: PreparedDevice, + *, + temperatures_K: Sequence[float] | np.ndarray | None = None, + T_min: float = 250.0, + T_max: float = 350.0, + n_points: int = 5, + options: VocTOptions | None = None, + progress: ProgressCallback | None = None, +) -> VocTResult: + """Sweep temperature via cold device rebinding and extrapolate E_A at 0 K.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice instance") + opts = VocTOptions() if options is None else options + temps = _normalize_temperatures( + temperatures_K, T_min=T_min, T_max=T_max, n_points=n_points + ) + if temps.size < 2: + raise ValueError("At least 2 distinct temperatures are required for V_oc(T)") + + count = int(temps.size) + voc_arr: np.ndarray = np.full(count, np.nan, dtype=float) + jsc_arr: np.ndarray = np.full(count, np.nan, dtype=float) + conv_mask: np.ndarray = np.zeros(count, dtype=bool) + brack_mask: np.ndarray = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + identities: list[str] = [] + + for idx, t_k in enumerate(temps): + rebound = rebind_prepared_temperature(prepared, float(t_k)) + if opts.ion_domain_layer is not None: + compiled: Any = compile_ionic_device_1d( + rebound, + intervals_per_layer=opts.intervals_per_layer, + ion_domain_layer=opts.ion_domain_layer, + ion_domain_endpoints=opts.ion_domain_endpoints, + ) + else: + compiled = compile_device_1d( + rebound, intervals_per_layer=opts.intervals_per_layer + ) + identities.append(str(compiled.identity)) + + point_res = run_suns_voc( + compiled, + [opts.generation_scale], + options=opts.suns_voc, + ) + voc_arr[idx] = float(point_res.V_oc_V[0]) + jsc_arr[idx] = float(point_res.J_sc_A_m2[0]) + conv_mask[idx] = bool(point_res.converged_mask[0]) + brack_mask[idx] = bool(point_res.voc_bracketed_mask[0]) + reasons[idx] = point_res.point_reasons[0] + + if progress is not None: + msg = ( + f"T={t_k:.1f} K, V_oc={voc_arr[idx]:.4f} V" + if conv_mask[idx] and brack_mask[idx] + else f"T={t_k:.1f} K ({reasons[idx]})" + ) + progress("voc_t", idx + 1, count, msg) + + slope, intercept_0k, e_a_ev, r_sq, fit_reason = fit_voc_t_extrapolation( + temps, + voc_arr, + converged_mask=conv_mask, + voc_bracketed_mask=brack_mask, + allow_partial=opts.allow_partial, + ) + + return VocTResult( + temperatures_K=temps, + V_oc_V=voc_arr, + J_sc_A_m2=jsc_arr, + converged_mask=conv_mask, + voc_bracketed_mask=brack_mask, + point_reasons=tuple(reasons), + slope_V_K=slope, + intercept_0K_V=intercept_0k, + activation_energy_eV=e_a_ev, + r_squared=r_sq, + fit_failure_reason=fit_reason, + generation_scale=opts.generation_scale, + compiled_identities=tuple(identities), + ) diff --git a/src/solarlab/experiments/waveform_jv.py b/src/solarlab/experiments/waveform_jv.py new file mode 100644 index 00000000..c48ad7f8 --- /dev/null +++ b/src/solarlab/experiments/waveform_jv.py @@ -0,0 +1,954 @@ +"""Arbitrary piecewise-linear / triangular / hold V(t) waveform J-V recipes. + +Integrates arbitrary piecewise-linear voltage and illumination waveforms using +the conservative Backward Euler 1D transient solvers (``solve_transient`` for +ion-free devices and ``solve_ionic_transient`` for coupled ionic-electronic +devices; Backward Euler remains the default time integrator). + +Key numerical contracts (P05-02b): + +1. **Exact segment/corner event boundaries**: Every segment endpoint is placed + explicitly in ``TransientProtocol.times_s`` (``corner_indices``); no time + step ever straddles a slope or illumination discontinuity. +2. **Displacement-inclusive total terminal current with explicit sign names**: + - ``pv_output_current_A_m2``: photovoltaic output convention (``> 0`` in the + PV power quadrant, ``-C * dV/dt`` capacitive shift on ascending ramps). + - ``voltage_conjugate_current_A_m2``: passive port input convention (``> 0`` + under forward injection and ``+C * dV/dt`` capacitive charging on + ascending ramps). +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass, field, fields, is_dataclass, replace +import hashlib +import json +import math +from typing import Any, Literal + +import numpy as np + +from solarlab.equations.dc_1d import CompiledDevice1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, Ionic1DProblem +from solarlab.experiments.ionic_transient import ( + IonicTransientAttempt, + IonicTransientInitial, + IonicTransientOptions, + IonicTransientResult, + solve_ionic_transient, +) +from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics +from solarlab.experiments.suns_voc import ( + default_ionic_steady_options, + solve_ionic_dc_operating_point, +) +from solarlab.experiments.transient import ( + TransientAttempt, + TransientOptions, + TransientProtocol, + TransientResult1D, + solve_transient, +) +from solarlab.reproducibility.job_provenance import current_provenance +from solarlab.solvers.nonlinear.ionic_1d import ( + IonicSteadyOptions, + IonicSteadyResult, +) +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + solve_steady_state, +) + +__all__ = [ + "JVWaveform", + "PiecewiseWaveform", + "WaveformJVOptions", + "WaveformJVResult", + "WaveformSegment", + "build_piecewise_waveform", + "build_triangular_jv_waveform", + "package_ionic_steady_initial", + "run_waveform_jv", +] + + +def _ro_float(value: Any) -> np.ndarray: + arr = np.array(value, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _finite_float(value: Any, name: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, np.floating)): + raise TypeError(f"{name} must be a real number") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{name} must be finite") + return result + + +@dataclass(frozen=True) +class JVWaveform: + """Explicit triangular hysteresis protocol specification.""" + + start_voltage_V: float = 0.0 + dark_seed_s: float = 0.0 + dark_prep_s: float = 0.0 + branch_dwell_s: float = 0.0 + turnaround_s: float = 0.0 + turnaround_dark: bool = False + + def __post_init__(self) -> None: + object.__setattr__( + self, "start_voltage_V", _finite_float(self.start_voltage_V, "start_voltage_V") + ) + for name in ("dark_seed_s", "dark_prep_s", "branch_dwell_s", "turnaround_s"): + val = _finite_float(getattr(self, name), name) + if val < 0.0: + raise ValueError(f"{name} must be >= 0") + object.__setattr__(self, name, val) + if not isinstance(self.turnaround_dark, bool): + raise TypeError("turnaround_dark must be a bool") + + def to_dict(self) -> dict[str, Any]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> JVWaveform: + if not isinstance(value, Mapping): + raise TypeError("waveform must be a mapping") + expected = {f.name for f in fields(cls)} + if set(value.keys()) != expected: + raise ValueError(f"JVWaveform requires exact keys {sorted(expected)}") + return cls(**value) + + +@dataclass(frozen=True) +class WaveformSegment: + """One linear voltage ramp or hold interval with exact endpoint boundaries.""" + + name: str + duration_s: float + start_voltage_V: float + stop_voltage_V: float + generation_scale: float = 1.0 + n_steps: int = 10 + role: Literal["preconditioning", "hold", "forward_ramp", "reverse_ramp", "custom"] = ( + "custom" + ) + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("segment name must be a non-empty string") + dur = _finite_float(self.duration_s, "duration_s") + if dur <= 0.0: + raise ValueError("segment duration_s must be finite and positive") + v0 = _finite_float(self.start_voltage_V, "start_voltage_V") + v1 = _finite_float(self.stop_voltage_V, "stop_voltage_V") + gen = _finite_float(self.generation_scale, "generation_scale") + if gen < 0.0: + raise ValueError("segment generation_scale must be >= 0") + if type(self.n_steps) is not int or self.n_steps < 1: + raise ValueError("segment n_steps must be an integer >= 1") + if self.role not in { + "preconditioning", + "hold", + "forward_ramp", + "reverse_ramp", + "custom", + }: + raise ValueError(f"unsupported segment role: {self.role!r}") + object.__setattr__(self, "duration_s", dur) + object.__setattr__(self, "start_voltage_V", v0) + object.__setattr__(self, "stop_voltage_V", v1) + object.__setattr__(self, "generation_scale", gen) + + +@dataclass(frozen=True) +class PiecewiseWaveform: + """Discretized piecewise-linear V(t) protocol with exact corner indices.""" + + segments: tuple[WaveformSegment, ...] + initial_voltage_V: float + initial_generation_scale: float + protocol: TransientProtocol + corner_times_s: np.ndarray + corner_indices: tuple[int, ...] + segment_step_slices: tuple[slice, ...] + step_dV_dt_V_s: np.ndarray + protocol_sha256: str + + def __post_init__(self) -> None: + object.__setattr__(self, "corner_times_s", _ro_float(self.corner_times_s)) + object.__setattr__(self, "step_dV_dt_V_s", _ro_float(self.step_dV_dt_V_s)) + + +@dataclass(frozen=True) +class WaveformJVOptions: + """Numerical controls for conservative Backward Euler waveform J-V.""" + + steady: SteadyOptions = field(default_factory=SteadyOptions) + ionic_steady: IonicSteadyOptions | None = None + transient: TransientOptions | None = None + ionic_transient: IonicTransientOptions | None = None + method: Literal["backward_euler"] | None = None + incident_power_W_m2: float | None = None + require_completed: bool = True + + def __post_init__(self) -> None: + if not isinstance(self.steady, SteadyOptions): + raise ValueError("steady must be an explicit SteadyOptions instance") + if self.ionic_steady is not None and not isinstance( + self.ionic_steady, IonicSteadyOptions + ): + raise ValueError( + "ionic_steady must be None or an explicit IonicSteadyOptions" + ) + if self.method not in (None, "backward_euler"): + raise ValueError( + "WaveformJVOptions supports only Backward Euler (None or 'backward_euler')" + ) + if self.incident_power_W_m2 is not None and ( + not math.isfinite(self.incident_power_W_m2) + or self.incident_power_W_m2 <= 0.0 + ): + raise ValueError("incident_power_W_m2 must be finite and positive") + + +@dataclass(frozen=True) +class WaveformJVResult: + """Full step-resolved and branch-resolved waveform J-V result.""" + + waveform: PiecewiseWaveform + completed: bool + accepted_steps: int + requested_steps: int + step_times_s: np.ndarray + step_dt_s: np.ndarray + step_voltage_V: np.ndarray + step_dV_dt_V_s: np.ndarray + step_generation_scale: np.ndarray + pv_output_current_A_m2: np.ndarray + pv_conduction_current_A_m2: np.ndarray + pv_displacement_current_A_m2: np.ndarray + voltage_conjugate_current_A_m2: np.ndarray + voltage_conjugate_conduction_A_m2: np.ndarray + voltage_conjugate_displacement_A_m2: np.ndarray + V_fwd: np.ndarray | None + J_fwd: np.ndarray | None + V_rev: np.ndarray | None + J_rev: np.ndarray | None + metrics_fwd: SteadyJVMetrics | None + metrics_rev: SteadyJVMetrics | None + hysteresis_index_rev_norm: float | None + hysteresis_index_fwd_norm: float | None + inventory_relative_drift: tuple[float, ...] + voltage_polarity: float + compiled_identity: str + transient_result: TransientResult1D | IonicTransientResult + failure_reason: str | None = None + job_provenance: dict[str, Any] | None = field(default_factory=current_provenance) + + def __post_init__(self) -> None: + for name in ( + "step_times_s", + "step_dt_s", + "step_voltage_V", + "step_dV_dt_V_s", + "step_generation_scale", + "pv_output_current_A_m2", + "pv_conduction_current_A_m2", + "pv_displacement_current_A_m2", + "voltage_conjugate_current_A_m2", + "voltage_conjugate_conduction_A_m2", + "voltage_conjugate_displacement_A_m2", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + for opt_name in ("V_fwd", "J_fwd", "V_rev", "J_rev"): + arr = getattr(self, opt_name) + if arr is not None: + object.__setattr__(self, opt_name, _ro_float(arr)) + + @property + def hysteresis_index(self) -> float | None: + return self.hysteresis_index_rev_norm + + @property + def hysteresis_index_paper(self) -> float | None: + return self.hysteresis_index_fwd_norm + + +def build_piecewise_waveform( + segments: Sequence[WaveformSegment], + *, + initial_voltage_V: float | None = None, + initial_generation_scale: float | None = None, + continuity_tol_V: float = 1e-12, +) -> PiecewiseWaveform: + """Construct a ``PiecewiseWaveform`` with exact segment corner nodes.""" + seg_tuple = tuple(segments) + if not seg_tuple: + raise ValueError("segments must contain at least one WaveformSegment") + for idx in range(len(seg_tuple) - 1): + left, right = seg_tuple[idx], seg_tuple[idx + 1] + if abs(right.start_voltage_V - left.stop_voltage_V) > continuity_tol_V: + raise ValueError( + f"discontinuous waveform voltage between segment {left.name!r} " + f"({left.stop_voltage_V} V) and {right.name!r} ({right.start_voltage_V} V); " + f"insert an explicit transition segment instead of a step jump" + ) + + v_init = ( + seg_tuple[0].start_voltage_V + if initial_voltage_V is None + else _finite_float(initial_voltage_V, "initial_voltage_V") + ) + if abs(v_init - seg_tuple[0].start_voltage_V) > continuity_tol_V: + raise ValueError( + "initial_voltage_V must match the first segment's start_voltage_V" + ) + g_init = ( + seg_tuple[0].generation_scale + if initial_generation_scale is None + else _finite_float(initial_generation_scale, "initial_generation_scale") + ) + if g_init < 0.0: + raise ValueError("initial_generation_scale must be >= 0") + + times_list: list[float] = [0.0] + volt_list: list[float] = [v_init] + gen_list: list[float] = [g_init] + corner_times: list[float] = [0.0] + corner_indices: list[int] = [0] + step_slices: list[slice] = [] + dv_dt_list: list[float] = [] + + t_cursor = 0.0 + step_cursor = 0 + for seg in seg_tuple: + n_s = seg.n_steps + slope = (seg.stop_voltage_V - seg.start_voltage_V) / seg.duration_s + for k in range(1, n_s + 1): + frac = k / n_s + t_k = t_cursor + seg.duration_s * frac + v_k = seg.start_voltage_V + (seg.stop_voltage_V - seg.start_voltage_V) * frac + times_list.append(t_k) + volt_list.append(v_k) + gen_list.append(seg.generation_scale) + dv_dt_list.append(slope) + t_cursor += seg.duration_s + corner_times.append(t_cursor) + corner_indices.append(len(times_list) - 1) + step_slices.append(slice(step_cursor, step_cursor + n_s)) + step_cursor += n_s + + protocol = TransientProtocol( + times_s=np.asarray(times_list, dtype=float), + voltage_V=np.asarray(volt_list, dtype=float), + generation_scale=np.asarray(gen_list, dtype=float), + ) + canonical = json.dumps( + { + "initial_voltage_V": v_init, + "initial_generation_scale": g_init, + "segments": [asdict(s) for s in seg_tuple], + }, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ) + digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest() + return PiecewiseWaveform( + segments=seg_tuple, + initial_voltage_V=v_init, + initial_generation_scale=g_init, + protocol=protocol, + corner_times_s=np.asarray(corner_times, dtype=float), + corner_indices=tuple(corner_indices), + segment_step_slices=tuple(step_slices), + step_dV_dt_V_s=np.asarray(dv_dt_list, dtype=float), + protocol_sha256=digest, + ) + + +def build_triangular_jv_waveform( + waveform: JVWaveform | None = None, + *, + V_max: float = 1.2, + v_rate: float = 0.04, + n_points: int = 61, + generation_scale: float = 1.0, +) -> PiecewiseWaveform: + """Build a triangular forward/reverse J-V waveform with exact corner events.""" + wf = JVWaveform() if waveform is None else waveform + v_stop = _finite_float(V_max, "V_max") + rate = _finite_float(v_rate, "v_rate") + gen = _finite_float(generation_scale, "generation_scale") + if rate <= 0.0: + raise ValueError("v_rate must be positive") + if gen < 0.0: + raise ValueError("generation_scale must be nonnegative") + if type(n_points) is not int or n_points < 2: + raise ValueError("n_points must be an integer >= 2") + if v_stop <= wf.start_voltage_V: + raise ValueError("V_max must exceed waveform.start_voltage_V") + + ramp_steps = n_points - 1 + ramp_duration = (v_stop - wf.start_voltage_V) / rate + segments: list[WaveformSegment] = [] + + if wf.dark_seed_s > 0.0 and wf.start_voltage_V == 0.0: + segments.append( + WaveformSegment( + "dark_seed_0V", + wf.dark_seed_s, + 0.0, + 0.0, + 0.0, + n_steps=max(2, min(10, ramp_steps)), + role="preconditioning", + ) + ) + if wf.dark_prep_s > 0.0: + segments.append( + WaveformSegment( + "dark_prebias", + wf.dark_prep_s, + wf.start_voltage_V, + wf.start_voltage_V, + 0.0, + n_steps=max(2, min(10, ramp_steps)), + role="preconditioning", + ) + ) + if wf.branch_dwell_s > 0.0: + segments.append( + WaveformSegment( + "forward_dwell", + wf.branch_dwell_s, + wf.start_voltage_V, + wf.start_voltage_V, + gen, + n_steps=max(2, min(10, ramp_steps)), + role="hold", + ) + ) + + segments.append( + WaveformSegment( + "forward_ramp", + ramp_duration, + wf.start_voltage_V, + v_stop, + gen, + n_steps=ramp_steps, + role="forward_ramp", + ) + ) + if wf.turnaround_s > 0.0: + segments.append( + WaveformSegment( + "turnaround_hold", + wf.turnaround_s, + v_stop, + v_stop, + 0.0 if wf.turnaround_dark else gen, + n_steps=max(2, min(10, ramp_steps)), + role="hold", + ) + ) + if wf.branch_dwell_s > 0.0: + segments.append( + WaveformSegment( + "reverse_dwell", + wf.branch_dwell_s, + v_stop, + v_stop, + gen, + n_steps=max(2, min(10, ramp_steps)), + role="hold", + ) + ) + segments.append( + WaveformSegment( + "reverse_ramp", + ramp_duration, + v_stop, + wf.start_voltage_V, + gen, + n_steps=ramp_steps, + role="reverse_ramp", + ) + ) + + init_gen = 0.0 if (wf.dark_seed_s > 0.0 or wf.dark_prep_s > 0.0) else gen + return build_piecewise_waveform( + segments, + initial_voltage_V=wf.start_voltage_V, + initial_generation_scale=init_gen, + ) + + +def _json_strict(value: Any) -> Any: + if is_dataclass(value) and not isinstance(value, type): + return {f.name: _json_strict(getattr(value, f.name)) for f in fields(value)} + if isinstance(value, np.ndarray): + return _json_strict(value.tolist()) + if isinstance(value, np.generic): + return _json_strict(value.item()) + if isinstance(value, dict): + return {str(k): _json_strict(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_json_strict(v) for v in value] + if isinstance(value, float) and not math.isfinite(value): + raise ValueError("accepted steady state cannot contain nonfinite floats") + return value + + +def package_ionic_steady_initial( + compiled: CompiledIonicDevice1D, + point: IonicSteadyResult, + *, + voltage_V: float, + generation_scale: float, + controls: IonicSteadyOptions, + source_label: str = "in_memory://waveform_jv_initial_steady.json", +) -> IonicTransientInitial: + """Package an accepted ``IonicSteadyResult`` into an admitted ``IonicTransientInitial``.""" + if not point.accepted or point.state is None: + reason = point.error or point.termination + raise RuntimeError( + f"cannot initialize ionic transient from unaccepted steady result ({reason})" + ) + summary = { + "accepted": True, + "compiled_identity": compiled.identity, + "voltage_V": float(voltage_V), + "generation_scale": float(generation_scale), + } + evidence_json = ( + json.dumps( + _json_strict({"summary": summary, "result": point}), + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ) + + "\n" + ) + digest = hashlib.sha256(evidence_json.encode("utf-8")).hexdigest() + return IonicTransientInitial( + state=point.state, + generation_scale=float(generation_scale), + steady_controls=controls, + source_path=source_label, + source_sha256=digest, + evidence_json=evidence_json, + ) + + +def _default_transient_options(max_steps: int) -> TransientOptions: + return TransientOptions( + poisson_tolerance=1e-11, + continuity_tolerance_A_m2=1e-8, + contact_log_tolerance=1e-11, + potential_step_V=0.1, + quasi_fermi_step=2.0, + newton_budget=SolveBudget(50, 1000, 50, 24), + max_steps=max(max_steps, 1), + wall_s=120.0, + predictor="previous", + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + + +def _unpack_accepted_attempts( + attempts: Sequence[TransientAttempt | IonicTransientAttempt], + polarity: float, +) -> tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, +]: + accepted = [a for a in attempts if a.accepted and a.accounting is not None] + n_acc = len(accepted) + t_end: np.ndarray = np.empty(n_acc, dtype=float) + dt_arr: np.ndarray = np.empty(n_acc, dtype=float) + v_arr: np.ndarray = np.empty(n_acc, dtype=float) + gen_arr: np.ndarray = np.empty(n_acc, dtype=float) + pv_tot: np.ndarray = np.empty(n_acc, dtype=float) + pv_cond: np.ndarray = np.empty(n_acc, dtype=float) + pv_disp: np.ndarray = np.empty(n_acc, dtype=float) + conj_tot: np.ndarray = np.empty(n_acc, dtype=float) + conj_cond: np.ndarray = np.empty(n_acc, dtype=float) + conj_disp: np.ndarray = np.empty(n_acc, dtype=float) + + conj_idx = 0 if polarity > 0.0 else -1 + for idx, att in enumerate(accepted): + assert att.accounting is not None + acc = att.accounting + term_tot = np.asarray( + acc["terminal_total_current_density_A_m2"], dtype=float + ) + if "terminal_conduction_current_density_A_m2" in acc: + term_cond = np.asarray( + acc["terminal_conduction_current_density_A_m2"], dtype=float + ) + else: + term_cond = np.asarray( + acc["conduction_current_density_A_m2"], dtype=float + )[[0, -1]] + if "terminal_displacement_current_density_A_m2" in acc: + term_disp = np.asarray( + acc["terminal_displacement_current_density_A_m2"], dtype=float + ) + else: + term_disp = np.asarray( + acc["displacement_current_density_A_m2"], dtype=float + )[[0, -1]] + t_end[idx] = float(att.end_s) + dt_arr[idx] = float(att.end_s - att.start_s) + v_arr[idx] = float(att.voltage_V) + gen_arr[idx] = float(att.generation_scale) + + pv_tot[idx] = float(-polarity * term_tot[0]) + pv_cond[idx] = float(-polarity * term_cond[0]) + pv_disp[idx] = float(-polarity * term_disp[0]) + + conj_tot[idx] = float(polarity * term_tot[conj_idx]) + conj_cond[idx] = float(polarity * term_cond[conj_idx]) + conj_disp[idx] = float(polarity * term_disp[conj_idx]) + + return ( + t_end, + dt_arr, + v_arr, + gen_arr, + pv_tot, + pv_cond, + pv_disp, + conj_tot, + conj_cond, + conj_disp, + ) + + +def _compute_ionic_inventory_drift( + compiled: CompiledIonicDevice1D, + result: IonicTransientResult, +) -> tuple[float, ...]: + if not result.states: + return () + init_state = result.states[0] + measures = compiled.ion_geometry.cell_measures_m + drifts: list[float] = [] + for species in compiled.ion_species_names: + attr = f"{species}_ion_density_m3" + n0 = float(np.dot(measures, getattr(init_state, attr))) + scale = max(abs(n0), 1e-30) + max_rel = max( + abs(float(np.dot(measures, getattr(st, attr))) - n0) / scale + for st in result.states + ) + drifts.append(float(max_rel)) + return tuple(drifts) + + +def _extract_ramp_branch( + seg: WaveformSegment, + slc: slice, + v_arr: np.ndarray, + gen_arr: np.ndarray, + pv_tot: np.ndarray, + *, + init_voltage_V: float, + init_generation_scale: float, + init_pv_A_m2: float, +) -> tuple[np.ndarray, np.ndarray]: + v_seg: np.ndarray = v_arr[slc] + j_seg: np.ndarray = pv_tot[slc] + if slc.start > 0: + prev_idx = slc.start - 1 + if abs(float(gen_arr[prev_idx]) - seg.generation_scale) <= 1e-12 and ( + v_seg.size == 0 or abs(float(v_arr[prev_idx]) - float(v_seg[0])) > 1e-14 + ): + v_seg = np.r_[float(v_arr[prev_idx]), v_seg] + j_seg = np.r_[float(pv_tot[prev_idx]), j_seg] + elif abs(init_generation_scale - seg.generation_scale) <= 1e-12 and ( + v_seg.size == 0 or abs(init_voltage_V - float(v_seg[0])) > 1e-14 + ): + v_seg = np.r_[init_voltage_V, v_seg] + j_seg = np.r_[init_pv_A_m2, j_seg] + return v_seg, j_seg + + +def run_waveform_jv( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + waveform: PiecewiseWaveform | JVWaveform | Sequence[WaveformSegment], + *, + V_max: float = 1.2, + v_rate: float = 0.04, + n_points: int = 61, + generation_scale: float = 1.0, + initial: SteadyState1D | IonicTransientInitial | None = None, + options: WaveformJVOptions | None = None, +) -> WaveformJVResult: + """Execute a piecewise-linear or triangular V(t) waveform on Backward Euler.""" + opts = WaveformJVOptions() if options is None else options + if isinstance(waveform, PiecewiseWaveform): + pw = waveform + elif isinstance(waveform, JVWaveform): + pw = build_triangular_jv_waveform( + waveform, + V_max=V_max, + v_rate=v_rate, + n_points=n_points, + generation_scale=generation_scale, + ) + else: + pw = build_piecewise_waveform(waveform) + + n_req = int(pw.protocol.times_s.size - 1) + base_trans_opts = ( + _default_transient_options(n_req) + if opts.transient is None + else ( + replace(opts.transient, max_steps=max(opts.transient.max_steps, n_req)) + if opts.transient.max_steps < n_req + else opts.transient + ) + ) + + if isinstance(compiled, CompiledDevice1D): + polarity = float(compiled.voltage_polarity) + if initial is None: + dc_init = solve_steady_state( + compiled, + voltage_V=pw.initial_voltage_V, + generation_scale=pw.initial_generation_scale, + options=opts.steady, + ) + if not dc_init.converged: + raise RuntimeError("waveform initial DC solve failed to converge") + elif isinstance(initial, SteadyState1D): + dc_init = initial + else: + raise TypeError( + "electronic waveform J-V requires initial=None or SteadyState1D" + ) + + init_pv_A_m2 = float( + -polarity * np.asarray(dc_init.current_density_A_m2, dtype=float)[0] + ) + trans_res: TransientResult1D | IonicTransientResult = solve_transient( + compiled, + dc_init, + pw.protocol, + options=base_trans_opts, + initial_options=opts.steady, + method="backward_euler", + ) + inv_drift: tuple[float, ...] = () + + elif isinstance(compiled, CompiledIonicDevice1D): + polarity = float(compiled.electronic_component.voltage_polarity) + ionic_steady_opts = ( + default_ionic_steady_options( + compiled.ion_node_count, electronic=opts.steady + ) + if opts.ionic_steady is None + else opts.ionic_steady + ) + if initial is None: + ion_dc = solve_ionic_dc_operating_point( + compiled, + voltage_V=pw.initial_voltage_V, + generation_scale=pw.initial_generation_scale, + options=ionic_steady_opts, + ) + ion_init = package_ionic_steady_initial( + compiled, + ion_dc, + voltage_V=pw.initial_voltage_V, + generation_scale=pw.initial_generation_scale, + controls=ionic_steady_opts, + ) + elif isinstance(initial, IonicTransientInitial): + ion_init = initial + else: + raise TypeError( + "ionic waveform J-V requires initial=None or IonicTransientInitial" + ) + + elec_prob = Ionic1DProblem( + compiled, pw.initial_voltage_V, pw.initial_generation_scale + ).electronic_problem + init_contacts = np.asarray( + elec_prob.contact_current_density( + ion_init.state.u[: 3 * compiled.node_count] + ), + dtype=float, + ) + init_pv_A_m2 = float(-polarity * init_contacts[0]) + + ion_trans_opts = ( + IonicTransientOptions( + electronic=base_trans_opts, + ion_balance_tolerance_m2_s=1e6, + ion_logit_step=1.0, + ) + if opts.ionic_transient is None + else ( + replace( + opts.ionic_transient, + electronic=replace( + opts.ionic_transient.electronic, + max_steps=max( + opts.ionic_transient.electronic.max_steps, n_req + ), + ), + ) + if opts.ionic_transient.electronic.max_steps < n_req + else opts.ionic_transient + ) + ) + trans_res = solve_ionic_transient( + compiled, + ion_init, + pw.protocol, + options=ion_trans_opts, + method="backward_euler", + ) + assert isinstance(trans_res, IonicTransientResult) + inv_drift = _compute_ionic_inventory_drift(compiled, trans_res) + else: + raise TypeError( + "compiled must be a CompiledDevice1D or CompiledIonicDevice1D" + ) + + assert isinstance(trans_res, (TransientResult1D, IonicTransientResult)) + completed = bool(trans_res.completed) + fail_reason: str | None = None + if not completed: + failed = trans_res.failed_attempts + if failed: + first = failed[0] + fail_reason = ( + f"step_failed_at_{first.end_s:.6g}s:{first.error or first.termination}" + ) + else: + fail_reason = "incomplete_transient_history" + if opts.require_completed: + raise RuntimeError(f"Waveform J-V failed to complete: {fail_reason}") + + ( + t_end, + dt_arr, + v_arr, + gen_arr, + pv_tot, + pv_cond, + pv_disp, + conj_tot, + conj_cond, + conj_disp, + ) = _unpack_accepted_attempts(trans_res.attempts, polarity) + n_acc = int(t_end.size) + dv_dt_acc = pw.step_dV_dt_V_s[:n_acc] + + v_fwd: np.ndarray | None = None + j_fwd: np.ndarray | None = None + v_rev: np.ndarray | None = None + j_rev: np.ndarray | None = None + metrics_fwd: SteadyJVMetrics | None = None + metrics_rev: SteadyJVMetrics | None = None + + for seg, slc in zip(pw.segments, pw.segment_step_slices, strict=True): + if slc.stop > n_acc: + break + if seg.role == "forward_ramp" and v_fwd is None: + v_fwd, j_fwd = _extract_ramp_branch( + seg, + slc, + v_arr, + gen_arr, + pv_tot, + init_voltage_V=pw.initial_voltage_V, + init_generation_scale=pw.initial_generation_scale, + init_pv_A_m2=init_pv_A_m2, + ) + if v_fwd.size >= 2 and np.unique(v_fwd).size == v_fwd.size: + metrics_fwd = steady_jv_metrics( + v_fwd, j_fwd, incident_power_W_m2=opts.incident_power_W_m2 + ) + elif seg.role == "reverse_ramp" and v_rev is None: + v_rev, j_rev = _extract_ramp_branch( + seg, + slc, + v_arr, + gen_arr, + pv_tot, + init_voltage_V=pw.initial_voltage_V, + init_generation_scale=pw.initial_generation_scale, + init_pv_A_m2=init_pv_A_m2, + ) + if v_rev.size >= 2 and np.unique(v_rev).size == v_rev.size: + metrics_rev = steady_jv_metrics( + v_rev, j_rev, incident_power_W_m2=opts.incident_power_W_m2 + ) + + hi_rev: float | None = None + hi_fwd: float | None = None + if ( + metrics_fwd is not None + and metrics_rev is not None + and metrics_fwd.maximum_power_W_m2 is not None + and metrics_rev.maximum_power_W_m2 is not None + ): + p_fwd = metrics_fwd.maximum_power_W_m2 + p_rev = metrics_rev.maximum_power_W_m2 + if p_rev > 0.0: + hi_rev = float((p_rev - p_fwd) / p_rev) + if p_fwd > 0.0: + hi_fwd = float(p_rev / p_fwd - 1.0) + + return WaveformJVResult( + waveform=pw, + completed=completed, + accepted_steps=n_acc, + requested_steps=n_req, + step_times_s=t_end, + step_dt_s=dt_arr, + step_voltage_V=v_arr, + step_dV_dt_V_s=dv_dt_acc, + step_generation_scale=gen_arr, + pv_output_current_A_m2=pv_tot, + pv_conduction_current_A_m2=pv_cond, + pv_displacement_current_A_m2=pv_disp, + voltage_conjugate_current_A_m2=conj_tot, + voltage_conjugate_conduction_A_m2=conj_cond, + voltage_conjugate_displacement_A_m2=conj_disp, + V_fwd=v_fwd, + J_fwd=j_fwd, + V_rev=v_rev, + J_rev=j_rev, + metrics_fwd=metrics_fwd, + metrics_rev=metrics_rev, + hysteresis_index_rev_norm=hi_rev, + hysteresis_index_fwd_norm=hi_fwd, + inventory_relative_drift=inv_drift, + voltage_polarity=polarity, + compiled_identity=compiled.identity, + transient_result=trans_res, + failure_reason=fail_reason, + ) diff --git a/tests/integration/test_eqe_el_spectrum.py b/tests/integration/test_eqe_el_spectrum.py new file mode 100644 index 00000000..deea2b55 --- /dev/null +++ b/tests/integration/test_eqe_el_spectrum.py @@ -0,0 +1,438 @@ +"""T2/T4 integration and perovskite_sim parity tests for EQE(lambda) and EL spectra.""" + +from __future__ import annotations + +from dataclasses import replace +import importlib +import json +import math +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.experiments.el_spectrum import ( + run_el_spectrum as legacy_run_el_spectrum, +) +from perovskite_sim.experiments.eqe import compute_eqe as legacy_compute_eqe +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.el_spectrum import ( + BOLTZMANN_J_K, + ELOptions, + blackbody_photon_flux_m2_s_m, + run_el_spectrum, +) +from solarlab.experiments.eqe import EQEOptions, compute_eqe +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument as MaterialSourceDocument +from solarlab.reproducibility.sources import SourceDocument +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state + +ROOT = Path(__file__).resolve().parents[2] + + +def _import_example(mod_name: str) -> Any: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + return importlib.import_module(mod_name) + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +def _spectral_resource_library() -> ResourceLibrary: + nk_path = ROOT / "perovskite-sim" / "perovskite_sim" / "data" / "nk" / "MAPbI3.csv" + nk_bytes = nk_path.read_bytes() + + am15g_path = ROOT / "perovskite-sim" / "perovskite_sim" / "data" / "am15g.csv" + data_lines: list[str] = [] + for line in am15g_path.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + wl_val = float(stripped.split(",", 1)[0]) + if 300.0 <= wl_val <= 1100.0: + data_lines.append(stripped) + spec_bytes = ( + "wavelength_nm,spectral_flux_m-2_s-1_m-1\n" + "\n".join(data_lines) + "\n" + ).encode("utf-8") + + return ResourceLibrary( + ( + ResourceTable( + "MAPbI3", + "nk", + MaterialSourceDocument("MAPbI3.csv", nk_bytes), + ), + ResourceTable( + "am15g", + "spectrum", + MaterialSourceDocument("am15g.csv", spec_bytes), + ), + ) + ) + + +def _prepare_spectral_device( + base_prepared: PreparedDevice, + *, + absorber_overrides: dict[str, Any] | None = None, +) -> PreparedDevice: + editing = base_prepared.to_input().editing_data() + editing["spectrum"] = "am15g" + editing["fixed_generation"] = None + settings = dict(editing.get("settings") or {}) + settings["Phi"] = 2.54e21 + editing["settings"] = settings + editing["electrical_grid"] = [ + {"layer": layer["id"], "interval_weight": 1.0, "alpha": 3.0} + for layer in editing["layers"] + if layer["role"] != "substrate" + ] + + ni_abs = 363572901223.5858 + for layer in editing["layers"]: + params = dict(layer.get("parameters") or {}) + params.update( + { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1e25, + "Nv300": 1e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + } + ) + if layer["role"] == "absorber": + params["optical_material"] = "MAPbI3" + params.pop("n_optical", None) + params["alpha"] = 0.0 + if absorber_overrides: + params.update(absorber_overrides) + else: + params["n_optical"] = 1.8 + params["alpha"] = 0.0 + layer["parameters"] = params + + src = SourceDocument( + "test.spectral_mapbi3_binding", + json.dumps(editing, sort_keys=True, separators=(",", ":")).encode("utf-8"), + ) + return resolve_device( + DeviceInput.model_validate(editing), + base_prepared.defaults, + _spectral_resource_library(), + sources=(*base_prepared.sources, src), + ) + + +def _legacy_stack_from_prepared(prepared: PreparedDevice) -> DeviceStack: + mapping = prepared.to_mapping() + settings = mapping["settings"] + layers: list[LayerSpec] = [] + for layer in prepared.layers: + p = dict(layer.parameters) + opt_mat = layer.optical.name if layer.optical is not None else None + n_opt = None if p["n_optical"] is None else float(p["n_optical"]) + mp = MaterialParams( + eps_r=float(p["eps_r"]), + mu_n=float(p["mu_n"]), + mu_p=float(p["mu_p"]), + D_ion=float(p["D_ion"]), + P_lim=float(p["P_lim"]), + P0=float(p["P0"]), + ni=float(p["ni"]), + tau_n=float(p["tau_n"]), + tau_p=float(p["tau_p"]), + n1=float(p["n1"]), + p1=float(p["p1"]), + B_rad=float(p["B_rad"]), + C_n=float(p["C_n"]), + C_p=float(p["C_p"]), + alpha=float(p["alpha"]), + N_A=float(p["N_A"]), + N_D=float(p["N_D"]), + chi=float(p["chi"]), + Eg=float(p["Eg"]), + A_star_n=float(p["A_star_n"]), + A_star_p=float(p["A_star_p"]), + v_th=float(p["v_th"]), + D_ion_neg=float(p["D_ion_neg"]), + P0_neg=float(p["P0_neg"]), + P_lim_neg=float(p["P_lim_neg"]), + Nc300=float(p["Nc300"]), + Nv300=float(p["Nv300"]), + mu_T_gamma=float(p["mu_T_gamma"]), + B_rad_T_gamma=float(p["B_rad_T_gamma"]), + varshni_alpha=float(p["varshni_alpha"]), + varshni_beta=float(p["varshni_beta"]), + optical_material=opt_mat, + n_optical=n_opt, + incoherent=bool(p["incoherent"]), + ) + layers.append( + LayerSpec( + name=layer.id, + thickness=float(layer.thickness), + params=mp, + role=layer.role, + ) + ) + return DeviceStack( + layers=tuple(layers), + V_bi=float(settings["V_bi"]), + Phi=float(settings["Phi"]), + T=float(settings["T"]), + mode=str(settings["mode"]), + built_in_potential_mode=str(settings["built_in_potential_mode"]), + dos_band_potentials=bool(settings["dos_band_potentials"]), + ) + + +def test_eqe_finite_flux_linear_response_photon_budget_and_jsc_closure() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_spectral_device(steady_ex.load_device()) + + wl_coarse = np.array([350.0, 450.0, 550.0, 650.0, 750.0, 950.0]) + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + eqe_ff = compute_eqe( + prepared, + wl_coarse, + Phi_incident=1e18, + options=EQEOptions( + intervals_per_layer=12, + perturbation_mode="finite_flux", + generation_discretization="cell_flux", + steady=steady_opts, + ), + ) + eqe_lr = compute_eqe( + prepared, + wl_coarse, + Phi_incident=1e18, + options=EQEOptions( + intervals_per_layer=12, + perturbation_mode="linear_response", + generation_discretization="cell_flux", + steady=steady_opts, + ), + ) + + assert np.all(eqe_ff.converged_mask) + assert np.all(eqe_lr.converged_mask) + assert np.max(np.abs(eqe_ff.photon_budget.spectral_closure_residual())) <= 1e-12 + assert np.all(eqe_ff.EQE >= -1e-9) + assert np.all(eqe_ff.EQE <= eqe_ff.electrical_absorptance + 1e-6) + assert eqe_ff.EQE[-1] < 1e-4 # sub-bandgap 850 nm MAPbI3 k -> 0 + + # Small-flux finite perturbation agrees with exact linearized DC Jacobian tangent! + np.testing.assert_allclose(eqe_ff.EQE, eqe_lr.EQE, rtol=5e-4, atol=5e-4) + + # Fine-grid J_sc_eqe closure against full-spectrum TMM 1-sun DC J_sc + wl_fine = np.linspace(300.0, 900.0, 61) + eqe_fine = compute_eqe( + prepared, + wl_fine, + Phi_incident=1e18, + options=EQEOptions( + intervals_per_layer=12, + perturbation_mode="linear_response", + generation_discretization="cell_flux", + steady=steady_opts, + require_reference_spectrum=True, + ), + ) + compiled_full = compile_device_1d(prepared, intervals_per_layer=12) + sol_full = solve_steady_state( + compiled_full, + voltage_V=0.0, + generation_scale=1.0, + options=steady_opts, + ) + jsc_full = float( + -compiled_full.voltage_polarity * sol_full.current_density_A_m2[0] + ) + assert math.isfinite(eqe_fine.J_sc_eqe_A_m2) + assert eqe_fine.integration_failure_reason is None + assert eqe_fine.J_sc_eqe_A_m2 == pytest.approx(jsc_full, rel=2e-2) + + +def test_eqe_legacy_engine_parity_and_coupled_ionic_support() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_spectral_device(steady_ex.load_device()) + legacy_stack = _legacy_stack_from_prepared(prepared) + + wl_parity = np.array([450.0, 650.0, 950.0]) + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + res_node = compute_eqe( + prepared, + wl_parity, + Phi_incident=4e21, + options=EQEOptions( + intervals_per_layer=8, + perturbation_mode="finite_flux", + generation_discretization="node_profile", + steady=steady_opts, + ), + ) + leg_eqe = legacy_compute_eqe( + legacy_stack, + wavelengths_nm=wl_parity, + Phi_incident=4e21, + N_grid=24, + t_settle=1e-3, + rtol=1e-4, + atol=1e-6, + ) + np.testing.assert_allclose(res_node.EQE, leg_eqe.EQE, atol=2e-3, rtol=2e-3) + assert res_node.J_sc_eqe_A_m2 == pytest.approx(leg_eqe.J_sc_integrated, rel=5e-3) + + # Coupled confined ionic EQE around genuine ionic DC operating point + ion_multi = _import_example("examples.research_1d.ionic_multilayer") + ion_steady = _import_example("examples.research_1d.ionic_steady") + prepared_ion_spec = _prepare_spectral_device( + ion_multi.prepare_confined_ion_device() + ) + base_controls = ion_steady.controls(7) + controls = replace( + base_controls, + electronic=replace( + base_controls.electronic, + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ), + ) + res_ion = compute_eqe( + prepared_ion_spec, + [500.0, 650.0, 950.0], + Phi_incident=1e20, + options=EQEOptions( + intervals_per_layer=6, + ion_domain_layer="absorber", + ionic_steady=controls, + ), + ) + assert np.all(res_ion.converged_mask) + assert res_ion.EQE[0] > 0.2 + assert res_ion.EQE[2] < 1e-4 + + +def test_el_spectrum_reciprocity_boltzmann_scaling_and_legacy_parity() -> None: + steady_ex = _import_example("examples.research_1d.steady") + base_dev = steady_ex.load_device() + prepared_srh = _prepare_spectral_device( + base_dev, absorber_overrides={"tau_n": 1e-8, "tau_p": 1e-8} + ) + prepared_rad = _prepare_spectral_device( + base_dev, + absorber_overrides={"tau_n": 1.0, "tau_p": 1.0, "C_n": 0.0, "C_p": 0.0}, + ) + legacy_stack = _legacy_stack_from_prepared(prepared_srh) + + wl_el = np.linspace(650.0, 900.0, 26) + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + el_low = run_el_spectrum( + prepared_srh, + V_inj_V=0.95, + wavelengths_nm=wl_el, + options=ELOptions( + intervals_per_layer=16, + absorptance_mode="exact_layer", + steady=steady_opts, + ), + ) + el_high = run_el_spectrum( + prepared_srh, + V_inj_V=1.05, + wavelengths_nm=wl_el, + options=ELOptions( + intervals_per_layer=16, + absorptance_mode="exact_layer", + steady=steady_opts, + ), + ) + + # Exact Rau reciprocity identity check: Phi_EL = A_abs * phi_bb * exp(q V / kT) + v_t = BOLTZMANN_J_K * el_high.temperature_K / ELEMENTARY_CHARGE_C + expected_ratio = math.exp((1.05 - 0.95) / v_t) + pos = el_low.Phi_EL_m2_s_m > 0.0 + np.testing.assert_allclose( + el_high.Phi_EL_m2_s_m[pos] / el_low.Phi_EL_m2_s_m[pos], + expected_ratio, + rtol=1e-12, + ) + phi_bb = blackbody_photon_flux_m2_s_m(wl_el * 1e-9, el_high.temperature_K) + np.testing.assert_allclose( + el_high.Phi_EL_m2_s_m, + el_high.absorber_absorptance * phi_bb * math.exp(1.05 / v_t), + rtol=1e-12, + ) + + # Suppressing SRH & Auger boosts luminescent efficiency and cuts non-radiative V_oc loss + el_rad = run_el_spectrum( + prepared_rad, + V_inj_V=1.0, + wavelengths_nm=wl_el, + options=ELOptions(intervals_per_layer=16, steady=steady_opts), + ) + el_srh_1v = run_el_spectrum( + prepared_srh, + V_inj_V=1.0, + wavelengths_nm=wl_el, + options=ELOptions(intervals_per_layer=16, steady=steady_opts), + ) + assert el_rad.EQE_EL > 50.0 * el_srh_1v.EQE_EL + assert el_rad.delta_V_nr_mV < el_srh_1v.delta_V_nr_mV - 100.0 + + # Live parity against perovskite_sim.experiments.el_spectrum (node_trapezoid quadrature) + el_node = run_el_spectrum( + prepared_srh, + V_inj_V=1.0, + wavelengths_nm=wl_el, + options=ELOptions( + intervals_per_layer=8, + absorptance_mode="node_trapezoid", + steady=steady_opts, + ), + ) + leg_el = legacy_run_el_spectrum( + legacy_stack, + V_inj=1.0, + wavelengths_nm=wl_el, + N_grid=24, + n_points_dark=15, + v_rate=1.0, + rtol=1e-4, + atol=1e-6, + ) + np.testing.assert_allclose( + el_node.absorber_absorptance, leg_el.absorber_absorptance, rtol=1e-10, atol=1e-12 + ) + np.testing.assert_allclose( + el_node.EL_spectrum_m2_s_nm, leg_el.EL_spectrum, rtol=1e-10, atol=1e-20 + ) + assert el_node.J_inj_pv_A_m2 == pytest.approx(leg_el.J_inj, rel=2e-3) + assert el_node.EQE_EL == pytest.approx(leg_el.EQE_EL, rel=2e-3) + assert el_node.delta_V_nr_mV == pytest.approx(leg_el.delta_V_nr_mV, abs=0.2) diff --git a/tests/integration/test_mott_schottky_cv_cf.py b/tests/integration/test_mott_schottky_cv_cf.py new file mode 100644 index 00000000..d0ffc3ae --- /dev/null +++ b/tests/integration/test_mott_schottky_cv_cf.py @@ -0,0 +1,341 @@ +"""T2/T4 integration and parity tests for CF, CV, and Mott-Schottky recipes.""" + +from __future__ import annotations + +import importlib +import math +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.experiments.mott_schottky import ( + run_mott_schottky as legacy_run_mott_schottky, +) +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.experiments.mott_schottky import ( + CFOptions, + MottSchottkyOptions, + run_capacitance_frequency, + run_capacitance_voltage, + run_mott_schottky, +) +from solarlab.materials.resources import ResourceLibrary +from solarlab.reproducibility.sources import SourceDocument + +ROOT = Path(__file__).resolve().parents[2] + + +def _import_example(mod_name: str) -> Any: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + return importlib.import_module(mod_name) + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +def _legacy_stack_from_prepared(prepared: PreparedDevice) -> DeviceStack: + mapping = prepared.to_mapping() + settings = mapping["settings"] + layers: list[LayerSpec] = [] + for layer in prepared.layers: + p = dict(layer.parameters) + mp = MaterialParams( + eps_r=float(p["eps_r"]), + mu_n=float(p["mu_n"]), + mu_p=float(p["mu_p"]), + D_ion=float(p["D_ion"]), + P_lim=float(p["P_lim"]), + P0=float(p["P0"]), + ni=float(p["ni"]), + tau_n=float(p["tau_n"]), + tau_p=float(p["tau_p"]), + n1=float(p["n1"]), + p1=float(p["p1"]), + B_rad=float(p["B_rad"]), + C_n=float(p["C_n"]), + C_p=float(p["C_p"]), + alpha=float(p["alpha"]), + N_A=float(p["N_A"]), + N_D=float(p["N_D"]), + chi=float(p["chi"]), + Eg=float(p["Eg"]), + A_star_n=float(p["A_star_n"]), + A_star_p=float(p["A_star_p"]), + v_th=float(p["v_th"]), + D_ion_neg=float(p["D_ion_neg"]), + P0_neg=float(p["P0_neg"]), + P_lim_neg=float(p["P_lim_neg"]), + Nc300=float(p["Nc300"]), + Nv300=float(p["Nv300"]), + mu_T_gamma=float(p["mu_T_gamma"]), + B_rad_T_gamma=float(p["B_rad_T_gamma"]), + varshni_alpha=float(p["varshni_alpha"]), + varshni_beta=float(p["varshni_beta"]), + incoherent=bool(p["incoherent"]), + ) + layers.append( + LayerSpec( + name=layer.id, + thickness=float(layer.thickness), + params=mp, + role=layer.role, + ) + ) + no_thermionic = all( + float(dict(layer.parameters)["A_star_n"]) == 0.0 + and float(dict(layer.parameters)["A_star_p"]) == 0.0 + for layer in prepared.layers + ) + return DeviceStack( + layers=tuple(layers), + V_bi=float(settings["V_bi"]), + Phi=float(settings["Phi"]), + T=float(settings["T"]), + mode="legacy" if no_thermionic else str(settings["mode"]), + built_in_potential_mode=str(settings["built_in_potential_mode"]), + dos_band_potentials=bool(settings["dos_band_potentials"]), + ) + + +def _prepare_doped_pn_homojunction(base_prepared: PreparedDevice) -> PreparedDevice: + import json + from solarlab.contracts.units import ELEMENTARY_CHARGE_C + from solarlab.experiments.mott_schottky import BOLTZMANN_J_K + + ni_si = math.sqrt(2.8e25 * 1.04e25) * math.exp( + -1.12 * ELEMENTARY_CHARGE_C / (2.0 * BOLTZMANN_J_K * 300.0) + ) + editing = base_prepared.to_input().editing_data() + editing["id"] = "doped_pn_homojunction" + editing["electrical_grid"] = [ + {"layer": "emitter", "interval_weight": 40.0, "alpha": 3.0}, + {"layer": "absorber", "interval_weight": 80.0, "alpha": 3.0}, + ] + editing["interfaces"] = [] + editing["layers"] = [ + { + "id": "emitter", + "name": "n+ emitter", + "role": "ETL", + "thickness": 8e-8, + "parameters": { + "chi": 4.05, + "Eg": 1.12, + "Nc300": 2.8e25, + "Nv300": 1.04e25, + "eps_r": 11.7, + "N_D": 1e23, + "N_A": 0.0, + "ni": ni_si, + "n1": ni_si, + "p1": ni_si, + "mu_n": 0.05, + "mu_p": 0.02, + "tau_n": 1e-5, + "tau_p": 1e-5, + "alpha": 0.0, + "D_ion": 0.0, + "D_ion_neg": 0.0, + "P0": 0.0, + "P0_neg": 0.0, + }, + }, + { + "id": "absorber", + "name": "p base", + "role": "absorber", + "thickness": 2.0e-6, + "parameters": { + "chi": 4.05, + "Eg": 1.12, + "Nc300": 2.8e25, + "Nv300": 1.04e25, + "eps_r": 11.7, + "N_D": 0.0, + "N_A": 2e22, + "ni": ni_si, + "n1": ni_si, + "p1": ni_si, + "mu_n": 0.05, + "mu_p": 0.02, + "tau_n": 1e-5, + "tau_p": 1e-5, + "alpha": 0.0, + "D_ion": 0.0, + "D_ion_neg": 0.0, + "P0": 0.0, + "P0_neg": 0.0, + }, + }, + ] + src = SourceDocument( + "test.doped_pn_homojunction", + json.dumps(editing, sort_keys=True, separators=(",", ":")).encode("utf-8"), + ) + return resolve_device( + DeviceInput.model_validate(editing), + base_prepared.defaults, + ResourceLibrary(), + sources=(*base_prepared.sources, src), + ) + + +def test_electronic_cf_cv_and_mott_schottky_legacy_parity() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = steady_ex.load_device() + compiled = compile_device_1d(prepared, intervals_per_layer=8) + + # 1) CF including 0 Hz (masked as 'zero_frequency', never 0.0!) + cf = run_capacitance_frequency( + compiled, + [0.0, 1e2, 1e4, 1e6], + bias_voltage_V=0.0, + ) + assert cf.active_species == ("electrons", "holes") + assert cf.frozen_species == () + assert not cf.valid_capacitive_mask[0] + assert cf.point_reasons[0] == "zero_frequency" + assert math.isnan(cf.capacitance_F_m2[0]) + assert np.all(cf.valid_capacitive_mask[1:]) + assert np.all(cf.capacitance_F_m2[1:] > 0.0) + + # 2) Mott-Schottky parity against legacy quasi_fermi_frequency engine on doped p-n diode + pn_prepared = _prepare_doped_pn_homojunction(prepared) + pn_compiled = compile_device_1d(pn_prepared, intervals_per_layer=60) + pn_legacy = _legacy_stack_from_prepared(pn_prepared) + + v_grid = np.linspace(-0.2, 0.3, 6) + ms = run_mott_schottky( + pn_compiled, + voltage_V=v_grid, + frequency_Hz=1e5, + prepared=pn_prepared, + options=MottSchottkyOptions(), + ) + leg_ms = legacy_run_mott_schottky( + pn_legacy, + V_range=v_grid, + frequency=1e5, + N_grid=120, + impedance_method="quasi_fermi_frequency", + ) + + assert np.all(ms.valid_capacitive_mask) + assert ms.fit_failure_reason is None + np.testing.assert_allclose(ms.capacitance_F_m2, leg_ms.C, rtol=1e-3, atol=1e-12) + assert ms.eps_r_used == pytest.approx(leg_ms.eps_r_used) + assert ms.apparent_built_in_voltage_V == pytest.approx(leg_ms.V_bi_fit, abs=2e-3) + assert ms.apparent_doping_m3 == pytest.approx(leg_ms.N_eff_fit, rel=5e-3) + assert ms.r_squared > 0.999 + + +def test_single_domain_ionic_mobile_vs_frozen_species_dispersion() -> None: + ion_ac_ex = _import_example("examples.research_1d.ionic_impedance") + ion_steady_ex = _import_example("examples.research_1d.ionic_steady") + compiled_ion = ion_ac_ex.compile_case("shared") + controls = ion_steady_ex.controls(compiled_ion.ion_node_count) + freqs = [0.01, 1.0, 1e3, 1e6] + + cf_mob = run_capacitance_frequency( + compiled_ion, + freqs, + bias_voltage_V=0.002, + options=CFOptions(ionic_steady=controls, ion_mode="mobile"), + ) + cf_frz = run_capacitance_frequency( + compiled_ion, + freqs, + bias_voltage_V=0.002, + options=CFOptions(ionic_steady=controls, ion_mode="frozen"), + ) + + assert "ion:positive" in cf_mob.active_species + assert cf_mob.frozen_species == () + assert cf_frz.active_species == ("electrons", "holes") + assert "ion:positive" in cf_frz.frozen_species + + assert np.all(cf_mob.valid_capacitive_mask) + assert np.all(cf_frz.valid_capacitive_mask) + # At 0.01 Hz mobile ions enhance low-frequency capacitance above frozen ions; + # at 1 MHz ions freeze out dynamically and mobile -> frozen! + assert cf_mob.capacitance_F_m2[0] > cf_frz.capacitance_F_m2[0] + assert cf_mob.capacitance_F_m2[-1] == pytest.approx( + cf_frz.capacitance_F_m2[-1], rel=1e-3 + ) + + # CV on coupled ionic device + cv_mob = run_capacitance_voltage( + compiled_ion, + [-0.05, 0.0, 0.05], + frequency_Hz=1e5, + options=CFOptions(ionic_steady=controls, ion_mode="mobile"), + ) + assert np.all(cv_mob.dc_converged_mask) + assert np.all(cv_mob.valid_capacitive_mask) + + +def test_multiple_domain_ionic_cf_and_cv() -> None: + mult_dom = _import_example("examples.research_1d.multiple_ionic_domains") + ion_steady_ex = _import_example("examples.research_1d.ionic_steady") + device = compile_multiple_ionic_device_1d( + mult_dom.prepare_multiple_ionic_device(), + intervals_per_layer=mult_dom.INTERVALS, + ion_domains=mult_dom.DOMAINS, + ) + controls = ion_steady_ex.controls(4) + + cf_mult = run_capacitance_frequency( + device, + [0.1, 100.0, 1e5], + bias_voltage_V=0.0, + options=CFOptions( + ionic_steady=controls, + ion_mode="mobile", + voltage_phasor_V=2e-6 + 1e-6j, + ), + ) + assert len(cf_mult.active_species) >= 4 # electrons, holes + 2 domains + assert cf_mult.frozen_species == () + assert np.all(cf_mult.ac_accepted_mask) + assert np.all(cf_mult.valid_capacitive_mask) + + # Two-domain AC explicitly refuses unsupported frozen mode via CapabilityError + with pytest.raises(CapabilityError, match="mobile positive ions"): + run_capacitance_frequency( + device, + [0.1, 100.0, 1e5], + bias_voltage_V=0.0, + options=CFOptions( + ionic_steady=controls, + ion_mode="frozen", + voltage_phasor_V=2e-6 + 1e-6j, + ), + ) + + cv_mult = run_capacitance_voltage( + device, + [0.0, 0.002, 0.005], + frequency_Hz=1e4, + options=CFOptions( + ionic_steady=controls, + ion_mode="mobile", + voltage_phasor_V=2e-6 + 1e-6j, + ), + ) + assert np.all(cv_mult.dc_converged_mask) + assert np.all(cv_mult.valid_capacitive_mask) diff --git a/tests/integration/test_suns_voc_voc_t.py b/tests/integration/test_suns_voc_voc_t.py new file mode 100644 index 00000000..3920cfb6 --- /dev/null +++ b/tests/integration/test_suns_voc_voc_t.py @@ -0,0 +1,284 @@ +"""T2/T4 integration and perovskite_sim parity tests for Suns-V_oc and V_oc(T).""" + +from __future__ import annotations + +import importlib +import math +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.experiments.protocol import VocSearchProtocol +from perovskite_sim.experiments.suns_voc import run_suns_voc as legacy_run_suns_voc +from perovskite_sim.experiments.voc_t import run_voc_t as legacy_run_voc_t +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.suns_voc import SunsVocOptions, run_suns_voc +from solarlab.experiments.voc_t import VocTOptions, run_voc_t +from solarlab.reproducibility.sources import SourceDocument + +ROOT = Path(__file__).resolve().parents[2] + + +def _import_example(mod_name: str) -> Any: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + return importlib.import_module(mod_name) + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +def _legacy_stack_from_prepared(prepared: PreparedDevice) -> DeviceStack: + mapping = prepared.to_mapping() + settings = mapping["settings"] + layers: list[LayerSpec] = [] + for layer in prepared.layers: + p = dict(layer.parameters) + mp = MaterialParams( + eps_r=float(p["eps_r"]), + mu_n=float(p["mu_n"]), + mu_p=float(p["mu_p"]), + D_ion=float(p["D_ion"]), + P_lim=float(p["P_lim"]), + P0=float(p["P0"]), + ni=float(p["ni"]), + tau_n=float(p["tau_n"]), + tau_p=float(p["tau_p"]), + n1=float(p["n1"]), + p1=float(p["p1"]), + B_rad=float(p["B_rad"]), + C_n=float(p["C_n"]), + C_p=float(p["C_p"]), + alpha=float(p["alpha"]), + N_A=float(p["N_A"]), + N_D=float(p["N_D"]), + chi=float(p["chi"]), + Eg=float(p["Eg"]), + A_star_n=float(p["A_star_n"]), + A_star_p=float(p["A_star_p"]), + v_th=float(p["v_th"]), + D_ion_neg=float(p["D_ion_neg"]), + P0_neg=float(p["P0_neg"]), + P_lim_neg=float(p["P_lim_neg"]), + Nc300=float(p["Nc300"]), + Nv300=float(p["Nv300"]), + mu_T_gamma=float(p["mu_T_gamma"]), + B_rad_T_gamma=float(p["B_rad_T_gamma"]), + varshni_alpha=float(p["varshni_alpha"]), + varshni_beta=float(p["varshni_beta"]), + incoherent=bool(p["incoherent"]), + ) + layers.append( + LayerSpec( + name=layer.id, + thickness=float(layer.thickness), + params=mp, + role=layer.role, + ) + ) + return DeviceStack( + layers=tuple(layers), + V_bi=float(settings["V_bi"]), + Phi=float(settings["Phi"]), + T=float(settings["T"]), + mode=str(settings["mode"]), + built_in_potential_mode=str(settings["built_in_potential_mode"]), + dos_band_potentials=bool(settings["dos_band_potentials"]), + ) + + +def _prepare_homojunction_pin(base_prepared: PreparedDevice) -> PreparedDevice: + import json + + editing = base_prepared.to_input().editing_data() + ni_abs = 363572901223.5858 + for layer in editing["layers"]: + params = dict(layer["parameters"]) + params.update( + { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1e25, + "Nv300": 1e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + } + ) + layer["parameters"] = params + editing["electrical_grid"] = [ + {"layer": layer["id"], "interval_weight": 1.0, "alpha": 3.0} + for layer in editing["layers"] + ] + src = SourceDocument("test.homojunction_pin", json.dumps(editing).encode("utf-8")) + return resolve_device( + DeviceInput.model_validate(editing), + base_prepared.defaults, + base_prepared.resources, + sources=(*base_prepared.sources, src), + ) + + +def test_suns_voc_parity_with_legacy_engine_and_dc_ideality() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_homojunction_pin(steady_ex.load_device()) + compiled = compile_device_1d(prepared, intervals_per_layer=8) + legacy_stack = _legacy_stack_from_prepared(prepared) + parity_suns = (0.1, 1.0, 5.0) + + res = run_suns_voc( + compiled, + parity_suns, + options=SunsVocOptions(voc_voltage_tol_V=1e-7), + ) + leg = legacy_run_suns_voc( + legacy_stack, + suns_levels=parity_suns, + N_grid=24, + t_settle=2e-3, + rtol=1e-4, + atol=1e-6, + voc_search=VocSearchProtocol( + coarse_dwell_s=2e-3, + bisection_dwell_s=2e-3, + final_settle_s=2e-3, + bisection_tolerance_V=1e-5, + bisection_max_steps=45, + ), + ) + + assert res.completed + assert all(r is None for r in res.point_reasons) + assert res.pseudo_ff_reason is None + assert np.all(np.diff(res.V_oc_V) > 0.0) + assert 1.0 <= res.ideality_factor_fit <= 2.5 + assert res.ideality_r_squared > 0.99 + assert np.all((res.local_ideality_factor >= 0.9) & (res.local_ideality_factor <= 2.5)) + + # T4 parity: |dVoc| <= 1e-4 V and relative J_sc <= 2e-4 across 0.1..5.0 suns! + np.testing.assert_allclose(res.V_oc_V, leg.V_oc, atol=1e-4, rtol=0.0) + np.testing.assert_allclose(res.J_sc_A_m2, leg.J_sc, rtol=2e-4, atol=1e-6) + assert res.pseudo_FF == pytest.approx(leg.pseudo_FF, rel=2e-4, abs=2e-4) + + +def test_suns_voc_unbracketed_cap_records_nan_and_explicit_reason() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = steady_ex.load_device() + compiled = compile_device_1d(prepared, intervals_per_layer=8) + + # Cap voc_bracket_max_V at 0.5 V so V_oc (~1.2 V) cannot be bracketed. + res = run_suns_voc( + compiled, + [0.1, 1.0], + options=SunsVocOptions(voc_bracket_step_V=0.25, voc_bracket_max_V=0.5), + ) + assert not res.completed + assert np.all(res.converged_mask) + assert not np.any(res.voc_bracketed_mask) + assert np.all(np.isnan(res.V_oc_V)) + assert np.all(np.isfinite(res.J_sc_A_m2) & (res.J_sc_A_m2 > 0.0)) + assert all( + r is not None and r.startswith("voc_not_bracketed:") for r in res.point_reasons + ) + assert math.isnan(res.pseudo_FF) + assert res.pseudo_ff_reason == "missing_or_nonpositive_reference" + + with pytest.raises(RuntimeError, match="failed to converge and bracket"): + run_suns_voc( + compiled, + [1.0], + options=SunsVocOptions( + voc_bracket_step_V=0.25, + voc_bracket_max_V=0.5, + require_all_bracketed=True, + ), + ) + + +def test_voc_t_cold_rebind_and_legacy_parity() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_homojunction_pin(steady_ex.load_device()) + legacy_stack = _legacy_stack_from_prepared(prepared) + + res = run_voc_t( + prepared, + T_min=280.0, + T_max=320.0, + n_points=3, + options=VocTOptions( + intervals_per_layer=8, + suns_voc=SunsVocOptions(voc_voltage_tol_V=1e-7), + ), + ) + leg = legacy_run_voc_t( + legacy_stack, + T_min=280.0, + T_max=320.0, + n_points=3, + N_grid=24, + v_rate=0.5, + V_max=1.3, + jv_n_points=66, + rtol=1e-4, + atol=1e-6, + ) + + assert res.completed + assert res.fit_failure_reason is None + assert len(set(res.compiled_identities)) == 3 # distinct cold-compiled device per T + assert np.all(np.diff(res.V_oc_V) < 0.0) + assert res.slope_V_K < 0.0 + assert 1.4 <= res.activation_energy_eV <= 1.8 + assert res.r_squared > 0.999 + + np.testing.assert_allclose(res.V_oc_V, leg.V_oc_arr, atol=2.5e-3, rtol=0.0) + assert res.activation_energy_eV == pytest.approx(leg.E_A_eV, abs=5e-3) + + +def test_coupled_ionic_suns_voc_solves_genuine_ionic_dc_operating_points() -> None: + from dataclasses import replace + + ion_multi = _import_example("examples.research_1d.ionic_multilayer") + ion_steady = _import_example("examples.research_1d.ionic_steady") + prepared_ion = ion_multi.prepare_confined_ion_device() + compiled_ion = compile_ionic_device_1d( + prepared_ion, + intervals_per_layer=6, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + base_controls = ion_steady.controls(compiled_ion.ion_node_count) + controls = replace( + base_controls, + electronic=replace( + base_controls.electronic, + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ), + ) + res_ion = run_suns_voc( + compiled_ion, + [0.01, 0.05], + options=SunsVocOptions( + ionic_steady=controls, + voc_voltage_tol_V=2e-4, + voc_bracket_step_V=0.2, + ), + ) + assert res_ion.completed + assert np.all(np.isfinite(res_ion.V_oc_V)) + assert res_ion.V_oc_V[1] > res_ion.V_oc_V[0] > 0.5 + assert res_ion.J_sc_A_m2[1] > res_ion.J_sc_A_m2[0] > 0.0 diff --git a/tests/integration/test_waveform_dark_jv.py b/tests/integration/test_waveform_dark_jv.py new file mode 100644 index 00000000..9b6783ae --- /dev/null +++ b/tests/integration/test_waveform_dark_jv.py @@ -0,0 +1,331 @@ +"""T2/T4 integration and perovskite_sim parity tests for dark J-V and waveform J-V.""" + +from __future__ import annotations + +from dataclasses import replace +import importlib +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.experiments.dark_jv import run_dark_jv as legacy_run_dark_jv +from perovskite_sim.experiments.waveform_jv import ( + JVWaveform as LegacyJVWaveform, + run_waveform_jv as legacy_run_waveform_jv, +) +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.dark_jv import DarkJVOptions, run_dark_jv +from solarlab.experiments.waveform_jv import ( + JVWaveform, + WaveformJVOptions, + WaveformSegment, + build_piecewise_waveform, + run_waveform_jv, +) +from solarlab.reproducibility.sources import SourceDocument +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + +ROOT = Path(__file__).resolve().parents[2] + + +def _import_example(mod_name: str) -> Any: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + return importlib.import_module(mod_name) + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +def _legacy_stack_from_prepared(prepared: PreparedDevice) -> DeviceStack: + mapping = prepared.to_mapping() + settings = mapping["settings"] + layers: list[LayerSpec] = [] + for layer in prepared.layers: + p = dict(layer.parameters) + mp = MaterialParams( + eps_r=float(p["eps_r"]), + mu_n=float(p["mu_n"]), + mu_p=float(p["mu_p"]), + D_ion=float(p["D_ion"]), + P_lim=float(p["P_lim"]), + P0=float(p["P0"]), + ni=float(p["ni"]), + tau_n=float(p["tau_n"]), + tau_p=float(p["tau_p"]), + n1=float(p["n1"]), + p1=float(p["p1"]), + B_rad=float(p["B_rad"]), + C_n=float(p["C_n"]), + C_p=float(p["C_p"]), + alpha=float(p["alpha"]), + N_A=float(p["N_A"]), + N_D=float(p["N_D"]), + chi=float(p["chi"]), + Eg=float(p["Eg"]), + A_star_n=float(p["A_star_n"]), + A_star_p=float(p["A_star_p"]), + v_th=float(p["v_th"]), + D_ion_neg=float(p["D_ion_neg"]), + P0_neg=float(p["P0_neg"]), + P_lim_neg=float(p["P_lim_neg"]), + Nc300=float(p["Nc300"]), + Nv300=float(p["Nv300"]), + mu_T_gamma=float(p["mu_T_gamma"]), + B_rad_T_gamma=float(p["B_rad_T_gamma"]), + varshni_alpha=float(p["varshni_alpha"]), + varshni_beta=float(p["varshni_beta"]), + incoherent=bool(p["incoherent"]), + ) + layers.append( + LayerSpec( + name=layer.id, + thickness=float(layer.thickness), + params=mp, + role=layer.role, + ) + ) + return DeviceStack( + layers=tuple(layers), + V_bi=float(settings["V_bi"]), + Phi=float(settings["Phi"]), + T=float(settings["T"]), + mode=str(settings["mode"]), + built_in_potential_mode=str(settings["built_in_potential_mode"]), + dos_band_potentials=bool(settings["dos_band_potentials"]), + ) + + +def _prepare_homojunction_pin(base_prepared: PreparedDevice) -> PreparedDevice: + import json + + editing = base_prepared.to_input().editing_data() + ni_abs = 363572901223.5858 + for layer in editing["layers"]: + params = dict(layer["parameters"]) + params.update( + { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1e25, + "Nv300": 1e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + } + ) + layer["parameters"] = params + editing["electrical_grid"] = [ + {"layer": layer["id"], "interval_weight": 1.0, "alpha": 3.0} + for layer in editing["layers"] + ] + src = SourceDocument("test.homojunction_pin", json.dumps(editing).encode("utf-8")) + return resolve_device( + DeviceInput.model_validate(editing), + base_prepared.defaults, + base_prepared.resources, + sources=(*base_prepared.sources, src), + ) + + +def test_dark_jv_parity_sign_conventions_and_diode_extraction() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_homojunction_pin(steady_ex.load_device()) + compiled = compile_device_1d(prepared, intervals_per_layer=8) + legacy_stack = _legacy_stack_from_prepared(prepared) + + res = run_dark_jv( + compiled, + V_min=0.0, + V_max=1.05, + n_points=28, + options=DarkJVOptions( + steady=SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + ), + ) + leg = legacy_run_dark_jv( + legacy_stack, + V_max=1.05, + n_points=28, + N_grid=24, + v_rate=0.5, + rtol=1e-4, + atol=1e-6, + ) + + assert res.completed + assert res.fit_failure_reason is None + assert np.allclose( + res.pv_output_current_A_m2, -res.voltage_conjugate_current_A_m2, atol=1e-12 + ) + # Forward dark injection has negative PV output current and positive conjugate current + fwd = res.voltage_V > 0.2 + assert np.all(res.pv_output_current_A_m2[fwd] < 0.0) + assert np.all(res.voltage_conjugate_current_A_m2[fwd] > 0.0) + + assert 1.0 <= res.n_ideality <= 2.5 + assert res.saturation_current_J0_A_m2 > 0.0 + assert res.r_squared > 0.999 + + # T4 parity against quasi-static legacy dark J-V in diode injection regime + high_inj = res.voltage_V >= 0.75 + np.testing.assert_allclose( + res.pv_output_current_A_m2[high_inj], + leg.J[high_inj], + rtol=5e-3, + atol=1e-3, + ) + assert res.n_ideality == pytest.approx(leg.n_ideality, rel=3.5e-2) + + +def test_coupled_ionic_dark_jv_sweep() -> None: + ion_multi = _import_example("examples.research_1d.ionic_multilayer") + ion_steady = _import_example("examples.research_1d.ionic_steady") + prepared_ion = ion_multi.prepare_confined_ion_device() + compiled_ion = compile_ionic_device_1d( + prepared_ion, + intervals_per_layer=6, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + controls = ion_steady.controls(compiled_ion.ion_node_count) + res = run_dark_jv( + compiled_ion, + voltage_V=np.linspace(0.0, 0.85, 18), + options=DarkJVOptions(ionic_steady=controls, min_diode_window_points=5), + ) + assert res.completed + assert np.allclose( + res.pv_output_current_A_m2, -res.voltage_conjugate_current_A_m2, atol=1e-12 + ) + assert res.fit_failure_reason is None + assert 1.0 <= res.n_ideality <= 2.5 + + +def test_waveform_jv_triangular_corner_displacement_and_legacy_parity() -> None: + steady_ex = _import_example("examples.research_1d.steady") + prepared = _prepare_homojunction_pin(steady_ex.load_device()) + compiled = compile_device_1d(prepared, intervals_per_layer=8) + legacy_stack = _legacy_stack_from_prepared(prepared) + + # 1) Fast ramp in the dark verifies exact capacitive displacement jump (+C*dV/dt -> -C*dV/dt) + fast_pw = build_piecewise_waveform( + [ + WaveformSegment("up", 1e-4, 0.0, 0.2, generation_scale=0.0, n_steps=5, role="forward_ramp"), + WaveformSegment("hold_top", 5e-5, 0.2, 0.2, generation_scale=0.0, n_steps=2, role="hold"), + WaveformSegment("down", 1e-4, 0.2, 0.0, generation_scale=0.0, n_steps=5, role="reverse_ramp"), + ] + ) + fast_res = run_waveform_jv(compiled, fast_pw) + assert fast_res.completed + assert fast_res.accepted_steps == 12 + assert fast_res.waveform.corner_indices == (0, 5, 7, 12) + assert np.allclose( + fast_res.pv_output_current_A_m2, + -fast_res.voltage_conjugate_current_A_m2, + atol=1e-12, + ) + # On ascending ramp dV/dt > 0, voltage-conjugate displacement current is positive (+C dV/dt); + # on descending ramp dV/dt < 0, voltage-conjugate displacement current is negative (-C |dV/dt|). + assert fast_res.voltage_conjugate_displacement_A_m2[4] > 0.0 + assert fast_res.voltage_conjugate_displacement_A_m2[7] < 0.0 + + # 2) Illuminated slow triangular J-V parity against legacy run_waveform_jv + wf = JVWaveform( + start_voltage_V=0.0, + dark_seed_s=0.0, + dark_prep_s=0.0, + branch_dwell_s=1e-3, + turnaround_dark=False, + ) + leg_wf = LegacyJVWaveform( + start_voltage_V=0.0, + dark_seed_s=0.0, + dark_prep_s=0.0, + branch_dwell_s=1e-3, + turnaround_dark=False, + ) + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ) + res_jv = run_waveform_jv( + compiled, + wf, + V_max=1.25, + v_rate=0.5, + n_points=26, + generation_scale=1.0, + options=WaveformJVOptions(steady=steady_opts), + ) + leg_jv = legacy_run_waveform_jv( + legacy_stack, + leg_wf, + N_grid=24, + n_points=26, + v_rate=0.5, + V_max=1.25, + illuminated=True, + rtol=1e-4, + atol=1e-6, + ) + assert res_jv.completed + assert res_jv.metrics_fwd is not None and res_jv.metrics_rev is not None + assert res_jv.metrics_fwd.open_circuit_voltage_V is not None + assert res_jv.metrics_rev.open_circuit_voltage_V is not None + assert abs(res_jv.metrics_fwd.open_circuit_voltage_V - leg_jv.metrics_fwd.V_oc) <= 2e-3 + assert abs(res_jv.metrics_rev.open_circuit_voltage_V - leg_jv.metrics_rev.V_oc) <= 2e-3 + assert res_jv.hysteresis_index_rev_norm is not None + assert abs(res_jv.hysteresis_index_rev_norm) < 2e-3 # ion-free quasi-static has ~0 hysteresis + + +def test_coupled_ionic_waveform_jv_conserves_domain_inventory() -> None: + ion_multi = _import_example("examples.research_1d.ionic_multilayer") + ion_steady = _import_example("examples.research_1d.ionic_steady") + prepared_ion = ion_multi.prepare_confined_ion_device() + compiled_ion = compile_ionic_device_1d( + prepared_ion, + intervals_per_layer=6, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + base_controls = ion_steady.controls(compiled_ion.ion_node_count) + controls = replace( + base_controls, + electronic=replace( + base_controls.electronic, + continuity_tolerance_A_m2=1e-7, + current_spread_tolerance_A_m2=1e-7, + ), + ) + pw_ion = build_piecewise_waveform( + [ + WaveformSegment("fwd", 0.05, 0.0, 0.4, generation_scale=0.0, n_steps=8, role="forward_ramp"), + WaveformSegment("hold", 0.02, 0.4, 0.4, generation_scale=0.0, n_steps=3, role="hold"), + WaveformSegment("rev", 0.05, 0.4, 0.0, generation_scale=0.0, n_steps=8, role="reverse_ramp"), + ] + ) + res_ion = run_waveform_jv( + compiled_ion, + pw_ion, + options=WaveformJVOptions(ionic_steady=controls), + ) + assert res_ion.completed + assert len(res_ion.inventory_relative_drift) == len(compiled_ion.ion_species_names) + assert all(drift <= 1e-12 for drift in res_ion.inventory_relative_drift) diff --git a/tests/unit/experiments/test_characterization_p05.py b/tests/unit/experiments/test_characterization_p05.py new file mode 100644 index 00000000..11a464b8 --- /dev/null +++ b/tests/unit/experiments/test_characterization_p05.py @@ -0,0 +1,396 @@ +"""T1 analytic and contract unit tests for P05-02b and P05-03a characterization.""" + +from __future__ import annotations + +import importlib +import math +from pathlib import Path +import sys +from typing import Any +import warnings + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M +from solarlab.experiments.dark_jv import ( + DarkJVOptions, + extract_dark_diode_parameters, + select_dark_diode_window, +) +from solarlab.experiments.el_spectrum import ( + ELOptions, + blackbody_photon_flux_m2_s_m, + run_el_spectrum, +) +from solarlab.experiments.eqe import EQEOptions, compute_eqe +from solarlab.experiments.mott_schottky import ( + CFOptions, + MottSchottkyOptions, + _capacitance_from_admittance, + fit_mott_schottky_curve, + select_mott_schottky_window, +) +from solarlab.experiments.suns_voc import ( + SunsVocOptions, + compute_pseudo_ff, + compute_suns_voc_ideality, +) +from solarlab.experiments.voc_t import ( + VocTOptions, + fit_voc_t_extrapolation, + rebind_prepared_temperature, +) +from solarlab.experiments.waveform_jv import ( + JVWaveform, + WaveformJVOptions, + WaveformSegment, + build_piecewise_waveform, + build_triangular_jv_waveform, +) + +K_B = 1.380649e-23 + + +ROOT = Path(__file__).resolve().parents[3] + + +def load_device() -> Any: + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + mod = importlib.import_module("examples.research_1d.steady") + return mod.load_device() + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +@pytest.mark.parametrize("n_true", [1.0, 1.5, 2.0]) +def test_suns_voc_analytic_ideality_and_missing_point_exclusion(n_true: float) -> None: + temperature_K = 300.0 + v_thermal = K_B * temperature_K / ELEMENTARY_CHARGE_C + suns = np.array([0.01, 0.05, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0], dtype=float) + voc_1sun = 1.08 + voc = voc_1sun + n_true * v_thermal * np.log(suns) + + local_n, n_fit, r_sq = compute_suns_voc_ideality( + suns, voc, temperature_K=temperature_K + ) + np.testing.assert_allclose(local_n, np.full_like(suns, n_true), rtol=1e-12) + assert n_fit == pytest.approx(n_true, rel=1e-12) + assert r_sq == pytest.approx(1.0, abs=1e-14) + + # Masking an unbracketed point preserves NaN at that index without corrupting fit. + voc_masked = voc.copy() + voc_masked[2] = np.nan + valid_mask = np.ones(suns.shape, dtype=bool) + valid_mask[2] = False + local_masked, n_fit_masked, r_sq_masked = compute_suns_voc_ideality( + suns, voc_masked, temperature_K=temperature_K, valid_mask=valid_mask + ) + assert math.isnan(local_masked[2]) + np.testing.assert_allclose( + local_masked[valid_mask], np.full(suns.size - 1, n_true), rtol=1e-11 + ) + assert n_fit_masked == pytest.approx(n_true, rel=1e-12) + assert r_sq_masked == pytest.approx(1.0, abs=1e-14) + + +def test_suns_voc_pseudo_ff_matches_analytic_ideal_diode_and_refuses_empty_quadrant() -> None: + temperature_K = 300.0 + v_thermal = K_B * temperature_K / ELEMENTARY_CHARGE_C + suns = np.geomspace(1e-4, 10.0, 400) + voc_ref = 1.05 + jsc_ref = 220.0 + voc = voc_ref + v_thermal * np.log(suns) + jsc = jsc_ref * suns + j_pseudo = jsc_ref - jsc + + pff, reason = compute_pseudo_ff( + voc, j_pseudo, V_oc_ref_V=voc_ref, J_sc_ref_A_m2=jsc_ref + ) + assert reason is None + voc_norm = voc_ref / v_thermal + ff_green = (voc_norm - math.log(voc_norm + 0.72)) / (voc_norm + 1.0) + assert pff == pytest.approx(ff_green, abs=5e-4) + + # Without valid sub-1-sun points in the power quadrant, never fabricate 0.25. + pff_bad, reason_bad = compute_pseudo_ff( + np.array([voc_ref, voc_ref + 0.04]), + np.array([0.0, -jsc_ref]), + V_oc_ref_V=voc_ref, + J_sc_ref_A_m2=jsc_ref, + ) + assert math.isnan(pff_bad) + assert reason_bad == "no_valid_power_quadrant_points" + + +def test_voc_t_extrapolation_recovers_exact_activation_energy_and_excludes_unbracketed() -> None: + temps = np.array([240.0, 270.0, 300.0, 330.0, 360.0], dtype=float) + e_a_true = 1.58 + beta = 1.65e-3 + voc_exact = e_a_true - beta * temps + all_ok = np.ones(temps.shape, dtype=bool) + + slope, intercept_0k, e_a, r_sq, reason = fit_voc_t_extrapolation( + temps, voc_exact, converged_mask=all_ok, voc_bracketed_mask=all_ok + ) + assert reason is None + assert slope == pytest.approx(-beta, rel=1e-12) + assert intercept_0k == pytest.approx(e_a_true, rel=1e-12) + assert e_a == pytest.approx(e_a_true, rel=1e-12) + assert r_sq == pytest.approx(1.0, abs=1e-14) + + # Critical regression: an unbracketed high-T point is NaN + masked False, never 0.0. + voc_partial = voc_exact.copy() + voc_partial[-1] = np.nan + brack_partial = np.array([True, True, True, True, False], dtype=bool) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + slope_p, int_p, ea_p, rsq_p, reason_p = fit_voc_t_extrapolation( + temps, + voc_partial, + converged_mask=all_ok, + voc_bracketed_mask=brack_partial, + ) + assert len(caught) == 1 + assert "360.0K" in str(caught[0].message) + assert reason_p is None + assert slope_p == pytest.approx(-beta, rel=1e-12) + assert int_p == pytest.approx(e_a_true, rel=1e-12) + assert ea_p == pytest.approx(e_a_true, rel=1e-12) + assert rsq_p == pytest.approx(1.0, abs=1e-14) + + # Fewer than 2 valid bracketed points refuses by default and records NaN when partial. + one_ok = np.array([True, False, False, False, False], dtype=bool) + with pytest.raises(ValueError, match="requires >= 2 valid bracketed temperatures"): + fit_voc_t_extrapolation( + temps, voc_partial, converged_mask=all_ok, voc_bracketed_mask=one_ok + ) + s_nan, i_nan, ea_nan, r_nan, fail_reason = fit_voc_t_extrapolation( + temps, + voc_partial, + converged_mask=all_ok, + voc_bracketed_mask=one_ok, + allow_partial=True, + ) + assert all(math.isnan(v) for v in (s_nan, i_nan, ea_nan, r_nan)) + assert fail_reason == "insufficient_valid_bracketed_points:1_of_5" + + +def test_rebind_prepared_temperature_updates_temperature_and_identity() -> None: + base = load_device() + rebound = rebind_prepared_temperature(base, 275.0) + assert rebound.to_mapping()["settings"]["T"] == 275.0 + assert rebound.content_sha256 != base.content_sha256 + + +def test_dark_jv_analytic_shockley_diode_with_series_resistance() -> None: + temperature_K = 300.0 + v_thermal = K_B * temperature_K / ELEMENTARY_CHARGE_C + n_true = 1.45 + j0_true = 2.5e-9 + rs_true = 2.0e-4 # Ohm * m^2 + + # Construct parametric Shockley curve with R_s: V_term = V_j + J_conj * R_s. + v_j = np.linspace(0.0, 1.05, 140) + j_conj = j0_true * (np.exp(v_j / (n_true * v_thermal)) - 1.0) + v_term = v_j + j_conj * rs_true + v_uniform = np.linspace(0.0, 1.15, 80) + j_conj_uniform = np.interp(v_uniform, v_term, j_conj) + j_pv_uniform = -j_conj_uniform + + ( + local_n, + fit_mask, + n_fit, + j0_fit, + v_lo, + v_hi, + r_sq, + rs_est, + reason, + ) = extract_dark_diode_parameters( + v_uniform, j_pv_uniform, temperature_K=temperature_K + ) + assert reason is None + assert np.count_nonzero(fit_mask) >= 8 + assert 0.1 < v_lo < v_hi < 0.95 + assert n_fit == pytest.approx(n_true, rel=1.5e-2) + assert math.log10(j0_fit) == pytest.approx(math.log10(j0_true), abs=0.08) + assert r_sq > 0.9999 + assert rs_est == pytest.approx(rs_true, rel=0.15) + assert np.nanmedian(local_n[fit_mask]) == pytest.approx(n_true, rel=1.5e-2) + + # Non-injecting curve returns explicit failure reason and NaNs (never 0.0). + empty_mask, empty_reason = select_dark_diode_window( + np.linspace(0.0, 0.5, 10), np.zeros(10) + ) + assert not np.any(empty_mask) + assert empty_reason is not None and "insufficient_forward_injection" in empty_reason + + +def test_piecewise_and_triangular_waveform_exact_corners_and_continuity() -> None: + wf_dict = { + "start_voltage_V": -0.1, + "dark_seed_s": 0.0, + "dark_prep_s": 0.05, + "branch_dwell_s": 0.02, + "turnaround_s": 0.03, + "turnaround_dark": True, + } + spec = JVWaveform.from_dict(wf_dict) + assert spec.to_dict() == wf_dict + + tri = build_triangular_jv_waveform( + spec, V_max=1.1, v_rate=0.4, n_points=13, generation_scale=1.0 + ) + # Every corner index lands on an exact segment transition in protocol.times_s. + for idx, t_corner in zip(tri.corner_indices, tri.corner_times_s, strict=True): + assert tri.protocol.times_s[idx] == pytest.approx(t_corner, abs=1e-15) + + roles = [seg.role for seg in tri.segments] + assert roles == [ + "preconditioning", + "hold", + "forward_ramp", + "hold", + "hold", + "reverse_ramp", + ] + fwd_slice = tri.segment_step_slices[2] + rev_slice = tri.segment_step_slices[5] + np.testing.assert_allclose(tri.step_dV_dt_V_s[fwd_slice], 0.4, rtol=1e-12) + np.testing.assert_allclose(tri.step_dV_dt_V_s[rev_slice], -0.4, rtol=1e-12) + + # Discontinuous voltage jump between segments is refused explicitly. + with pytest.raises(ValueError, match="discontinuous waveform voltage"): + build_piecewise_waveform( + [ + WaveformSegment("s1", 0.1, 0.0, 0.5, n_steps=4), + WaveformSegment("s2", 0.1, 0.6, 1.0, n_steps=4), + ] + ) + + +def test_mott_schottky_analytic_abrupt_junction_and_inductive_guards() -> None: + temperature_K = 300.0 + v_thermal = K_B * temperature_K / ELEMENTARY_CHARGE_C + eps_r = 24.0 + v_bi_true = 1.05 + n_d_true = 3.5e22 # m^-3 + + v_bias = np.linspace(-0.4, 0.75, 24) + # Linear depletion region over [-0.4, 0.45] V, followed by exponential + # chemical-capacitance surge above 0.5 V so 1/C^2 bends sharply downward. + w_sq_factor = 2.0 / ( + ELEMENTARY_CHARGE_C * eps_r * VACUUM_PERMITTIVITY_F_M * n_d_true + ) + one_over_c2_ideal = w_sq_factor * (v_bi_true - v_bias - 2.0 * v_thermal) + c_depl = 1.0 / np.sqrt(one_over_c2_ideal) + c_chem = np.where( + v_bias > 0.48, 4e-3 * (np.exp((v_bias - 0.48) / (2.0 * v_thermal)) - 1.0), 0.0 + ) + c_total = c_depl + c_chem + + ( + one_over_c2, + fit_mask, + app_vbi, + app_n, + slope, + _intercept, + v_lo, + v_hi, + r_sq, + reason, + ) = fit_mott_schottky_curve( + v_bias, c_total, eps_r=eps_r, temperature_K=temperature_K + ) + assert reason is None + assert slope < 0.0 + assert v_hi <= 0.50 + assert v_lo == pytest.approx(-0.4, abs=1e-12) + assert np.count_nonzero(fit_mask) >= 15 + assert app_vbi == pytest.approx(v_bi_true, abs=1e-4) + assert app_n == pytest.approx(n_d_true, rel=1e-4) + assert r_sq > 0.999999 + + # Flat and nearly-flat geometric capacitors are rejected rather than fabricating V_bi. + c_const = np.full(12, 2.5e-4, dtype=float) + _, _, vbi_const, n_const, _, _, _, _, _, const_reason = fit_mott_schottky_curve( + np.linspace(-0.3, 0.3, 12), c_const, eps_r=eps_r, temperature_K=temperature_K + ) + assert math.isnan(vbi_const) and math.isnan(n_const) + assert const_reason == "no_contiguous_linear_depletion_window" + + v_near = np.linspace(-0.3, 0.3, 12) + c_near_flat = 2.5e-4 / np.sqrt(1.0 - 0.02 * v_near) + _, _, vbi_flat, n_flat, _, _, _, _, _, flat_reason = fit_mott_schottky_curve( + v_near, c_near_flat, eps_r=eps_r, temperature_K=temperature_K + ) + assert math.isnan(vbi_flat) and math.isnan(n_flat) + assert flat_reason == "flat_geometric_capacitance_insufficient_variation" + assert ( + select_mott_schottky_window(np.linspace(0.0, 0.2, 3), np.array([1.0, 2.0, 3.0])) + is None + ) + + # Inductive and 0 Hz susceptance points return NaN (never abs(Im(Y))) or raise if strict. + c_ind, g_ind, loss_ind, ok_ind, r_ind = _capacitance_from_admittance( + 1000.0, 0.5 - 2.0j, strict_capacitive=False + ) + assert math.isnan(c_ind) and math.isnan(loss_ind) + assert g_ind == 0.5 and not ok_ind and r_ind == "inductive_susceptance" + with pytest.raises(RuntimeError, match="inductive susceptance"): + _capacitance_from_admittance(1000.0, 0.5 - 2.0j, strict_capacitive=True) + + c_dc, _, _, ok_dc, r_dc = _capacitance_from_admittance( + 0.0, 0.5 + 0.0j, strict_capacitive=False + ) + assert math.isnan(c_dc) and not ok_dc and r_dc == "zero_frequency" + + +def test_blackbody_reciprocity_and_optical_refusal_guards() -> None: + wl_m = np.linspace(400e-9, 900e-9, 11) + bb_300 = blackbody_photon_flux_m2_s_m(wl_m, 300.0) + bb_350 = blackbody_photon_flux_m2_s_m(wl_m, 350.0) + assert np.all(np.isfinite(bb_300)) and np.all(bb_300 > 0.0) + assert np.all(bb_350 > bb_300) + + # Scalar Beer-Lambert PreparedDevice (no nk optical_material table) is refused + # before solver work by both compute_eqe and run_el_spectrum. + scalar_alpha_device = load_device() + with pytest.raises(ValueError, match="tabulated wavelength-resolved optical_material"): + compute_eqe(scalar_alpha_device) + with pytest.raises(ValueError, match="tabulated wavelength-resolved optical_material"): + run_el_spectrum(scalar_alpha_device, V_inj_V=1.0) + with pytest.raises(ValueError, match="Phi_incident must be finite and positive"): + compute_eqe(scalar_alpha_device, Phi_incident=0.0) + with pytest.raises(ValueError, match="V_inj_V must be finite and positive"): + run_el_spectrum(scalar_alpha_device, V_inj_V=0.0) + with pytest.raises(ValueError, match=">= 2 distinct wavelengths"): + run_el_spectrum(scalar_alpha_device, V_inj_V=1.0, wavelengths_nm=[550.0]) + + # Option validation guards. + with pytest.raises(ValueError, match="voc_voltage_tol_V"): + SunsVocOptions(voc_voltage_tol_V=0.0) + with pytest.raises(ValueError, match="intervals_per_layer"): + VocTOptions(intervals_per_layer=1) + with pytest.raises(ValueError, match="min_diode_window_points"): + DarkJVOptions(min_diode_window_points=2) + with pytest.raises(ValueError, match="Backward Euler"): + WaveformJVOptions(method="bdf") # type: ignore[arg-type] + with pytest.raises(ValueError, match="ion_mode"): + CFOptions(ion_mode="invalid") # type: ignore[arg-type] + with pytest.raises(ValueError, match="min_window_points"): + MottSchottkyOptions(min_window_points=2) + with pytest.raises(ValueError, match="perturbation_mode"): + EQEOptions(perturbation_mode="invalid") # type: ignore[arg-type] + with pytest.raises(ValueError, match="absorptance_mode"): + ELOptions(absorptance_mode="invalid") # type: ignore[arg-type] From 4774221c59b60881ad55991dd084d5bcf93913ee Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 16:37:19 +0800 Subject: [PATCH 08/46] N(2d): implement P06-01 periodic geometry, P06-02 mobile-ion BE/experiments, and P06-03 4-axis refinement --- src/solarlab/device/compile_2d.py | 19 +- src/solarlab/device/compile_ionic_2d.py | 473 +++++ src/solarlab/device/grain_2d.py | 3 +- src/solarlab/device/optical_generation_2d.py | 6 +- src/solarlab/equations/assembly/ionic_2d.py | 921 ++++++++++ src/solarlab/equations/dc_2d.py | 6 +- src/solarlab/equations/field_transport_2d.py | 6 +- src/solarlab/equations/ionic_2d.py | 1156 ++++++++++++ .../two_dimensional/jv_protocol_2d.py | 787 +++++++++ .../two_dimensional/jv_sweep_2d.py | 1557 +++++++++++++++++ .../two_dimensional/refinement_2d.py | 630 +++++++ .../two_dimensional/voc_grain_sweep.py | 570 ++++++ src/solarlab/mesh/geometry_2d.py | 64 +- src/solarlab/solvers/nonlinear/ionic_2d.py | 414 +++++ src/solarlab/solvers/nonlinear/steady_2d.py | 26 +- .../solvers/time/backward_euler_2d.py | 510 ++++++ .../solvers/time/ionic_backward_euler_2d.py | 781 +++++++++ tests/integration/test_contacts_2d.py | 2 +- tests/integration/test_dc_2d.py | 2 +- ...test_ionic_transient_and_experiments_2d.py | 699 ++++++++ .../test_periodic_and_ionic_assembly_2d.py | 612 +++++++ 21 files changed, 9212 insertions(+), 32 deletions(-) create mode 100644 src/solarlab/device/compile_ionic_2d.py create mode 100644 src/solarlab/equations/assembly/ionic_2d.py create mode 100644 src/solarlab/equations/ionic_2d.py create mode 100644 src/solarlab/experiments/two_dimensional/jv_protocol_2d.py create mode 100644 src/solarlab/experiments/two_dimensional/jv_sweep_2d.py create mode 100644 src/solarlab/experiments/two_dimensional/refinement_2d.py create mode 100644 src/solarlab/experiments/two_dimensional/voc_grain_sweep.py create mode 100644 src/solarlab/solvers/nonlinear/ionic_2d.py create mode 100644 src/solarlab/solvers/time/backward_euler_2d.py create mode 100644 src/solarlab/solvers/time/ionic_backward_euler_2d.py create mode 100644 tests/integration/test_ionic_transient_and_experiments_2d.py create mode 100644 tests/unit/assembly/test_periodic_and_ionic_assembly_2d.py diff --git a/src/solarlab/device/compile_2d.py b/src/solarlab/device/compile_2d.py index bfc7a487..99dad151 100644 --- a/src/solarlab/device/compile_2d.py +++ b/src/solarlab/device/compile_2d.py @@ -30,6 +30,8 @@ CLASSICAL_2D_DC_V1 = "classical_mb_fixed_reservoir_neumann_2d_dc_v1" CLASSICAL_2D_CONTACTS_V1 = "classical_mb_carrier_exchange_neumann_2d_dc_v1" +CLASSICAL_2D_PERIODIC_DC_V1 = "classical_mb_fixed_reservoir_periodic_2d_dc_v1" +CLASSICAL_2D_PERIODIC_CONTACTS_V1 = "classical_mb_carrier_exchange_periodic_2d_dc_v1" _GEOMETRY_FIELDS = frozenset({"kind", "lateral_length", "Nx", "Ny_per_layer", "lateral_bc", "microstructure"}) @@ -49,8 +51,8 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD raise CapabilityError("unsupported_classical_2d_dc: execution field " + name) if spatial.lateral_length is None or spatial.Nx is None or spatial.Ny_per_layer is None: raise CapabilityError("2D DC requires explicit lateral_length, Nx and Ny_per_layer") - if spatial.lateral_bc != "neumann": - raise CapabilityError("2D DC requires explicit zero-normal-flux neumann lateral boundaries") + if spatial.lateral_bc not in ("neumann", "periodic"): + raise CapabilityError("2D DC requires explicit 'neumann' or 'periodic' lateral boundaries") if spatial.Ny_per_layer < 2: raise ValueError("Ny_per_layer must be at least two intervals") data = prepared.to_mapping() @@ -83,7 +85,9 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD raise CapabilityError("unsupported_classical_2d_dc: explicit defect populations are not bound") length = normalize_quantity(spatial.lateral_length, "m") y_geometry = half_endpoint_geometry(column.nodes_m, [plane.position_m for plane in column.geometry.interfaces]) - geometry = RectangularGeometry2D(np.linspace(0.0, length, spatial.Nx + 1), y_geometry) + geometry = RectangularGeometry2D( + np.linspace(0.0, length, spatial.Nx + 1), y_geometry, lateral_bc=spatial.lateral_bc + ) alpha, eps = np.empty(column.node_count), np.empty(column.node_count) for layer, mask in zip(prepared.layers, column.parameters.layer_masks): values = dict(layer.parameters) @@ -94,7 +98,7 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD grains = bind_grain_regions_2d(prepared, spatial, geometry) faceD = [] for carrier in ("electron", "hole"): - faceD.append(np.r_[np.repeat(getattr(column.parameters, carrier + "_diffusivity_m2_s"), geometry.nx - 1), + faceD.append(np.r_[np.repeat(getattr(column.parameters, carrier + "_diffusivity_m2_s"), geometry.x_faces_per_row), np.repeat(getattr(column, carrier + "_diffusivity_faces_m2_s"), geometry.nx)]) empirical: dict[str, np.ndarray] = {} for name in ("v_sat_n", "v_sat_p", "ct_beta_n", "ct_beta_p", "pf_gamma_n", "pf_gamma_p"): @@ -107,8 +111,11 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD ct_beta_n=empirical["ct_beta_n"], ct_beta_p=empirical["ct_beta_p"], pf_gamma_n=empirical["pf_gamma_n"], pf_gamma_p=empirical["pf_gamma_p"]) declaration = spatial.model_dump_json().encode() - contact_model = (CLASSICAL_2D_DC_V1 if all(channel.kind == "fixed_reservoir" for channel in column.channels) - else CLASSICAL_2D_CONTACTS_V1) + fixed_contacts = all(channel.kind == "fixed_reservoir" for channel in column.channels) + if spatial.lateral_bc == "neumann": + contact_model = CLASSICAL_2D_DC_V1 if fixed_contacts else CLASSICAL_2D_CONTACTS_V1 + else: + contact_model = CLASSICAL_2D_PERIODIC_DC_V1 if fixed_contacts else CLASSICAL_2D_PERIODIC_CONTACTS_V1 identity = hashlib.sha256(json.dumps((contact_model, prepared.content_sha256, column.identity, geometry.sha256, generation.binding_sha256, declaration.decode()), separators=(",", ":")).encode()).hexdigest() diff --git a/src/solarlab/device/compile_ionic_2d.py b/src/solarlab/device/compile_ionic_2d.py new file mode 100644 index 00000000..fe5a1304 --- /dev/null +++ b/src/solarlab/device/compile_ionic_2d.py @@ -0,0 +1,473 @@ +"""Compile one four-side-blocking 2D single-positive-ion finite-site device. + +Dual-ion, shared-site, periodic-x, selective/Robin carrier contacts, and +dynamic-interface modes fail closed with ``CapabilityError``. Bounded +absorber radiative reabsorption and clamp-passive two-sided cross-node +interface SRH are compiled when explicitly enabled and validated. +""" + +from __future__ import annotations + +from collections.abc import Mapping +import hashlib +import json +import math +from typing import Any, cast + +import numpy as np +from numpy.typing import NDArray + +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_1d import ION_INPUTS +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.ionic_2d import ( + CompiledIonicDevice2D, RadiativeReabsorptionSpec2D, TwoSidedInterfaceSRHCoupling2D, +) +from solarlab.experiments.two_dimensional.inputs import JV2DInput +from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry_2d import RectangularGeometry2D +from solarlab.mesh.grid import LEFT_LAYER_WINS, node_owner +from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature +from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, WHOLE_FLUX_STERIC_V1 + +__all__ = [ + "CompiledIonicDevice2D", + "build_radiative_reabsorption_2d", + "build_two_sided_interface_srh_2d", + "compile_ionic_device_2d", +] + + +def _select_ion_layer(prepared: PreparedDevice, ion_domain_layer: str | None) -> tuple[Any, tuple[Any, ...]]: + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + if ion_domain_layer is not None: + selected = [layer for layer in layers if layer.id == ion_domain_layer] + if len(selected) != 1: + raise CapabilityError("ionic_2d: ion_domain_layer must name one electrical layer") + return selected[0], layers + active = [ + layer for layer in layers + if any(float(cast(float, dict(layer.parameters)[k])) != 0.0 for k in ("P0", "D_ion", "P0_neg", "D_ion_neg")) + ] + if len(active) == 1: + return active[0], layers + if len(layers) == 1: + return layers[0], layers + raise CapabilityError( + "ionic_2d: declare exactly one active ion-bearing electrical layer or pass ion_domain_layer explicitly" + ) + + +def build_radiative_reabsorption_2d( + prepared: PreparedDevice, + electronic_2d: Any, + *, + enabled: bool | None = None, +) -> tuple[RadiativeReabsorptionSpec2D, ...]: + """Build 2D absorber radiative-reabsorption specs when enabled (`mode=='full'` or explicit).""" + data = prepared.to_mapping() + settings = data["settings"] + is_enabled = (settings.get("mode") == "full") if enabled is None else bool(enabled) + if not is_enabled: + return () + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + owners = node_owner( + electronic_2d.geometry.y_geometry.nodes_m, + [layer.thickness for layer in layers], + LEFT_LAYER_WINS, + ) + b_rad_y = electronic_2d.column.recombination.coefficients.radiative_m3_s + specs: list[RadiativeReabsorptionSpec2D] = [] + lateral_len = electronic_2d.geometry.lateral_length_m + for idx, layer in enumerate(layers): + if layer.role != "absorber": + continue + params = dict(layer.parameters) + # Critical-angle internal reflection escape probability 1 / (4 n^2) when n_optical or eps_r given + n_opt = params.get("n_optical") + eps_val = float(cast(Any, params["eps_r"])) + refractive = ( + float(cast(Any, n_opt)) + if isinstance(n_opt, (int, float)) and not isinstance(n_opt, bool) and float(n_opt) > 1.0 + else math.sqrt(max(eps_val, 1.0)) + ) + p_esc_raw = params.get("photon_escape_probability") + p_esc = ( + float(cast(Any, p_esc_raw)) + if isinstance(p_esc_raw, (int, float)) and not isinstance(p_esc_raw, bool) + else min(1.0 / (4.0 * refractive * refractive), 0.999999) + ) + rows = np.flatnonzero(owners == idx) + if rows.size < 2 or not np.any(b_rad_y[rows] > 0.0) or p_esc >= 1.0: + continue + y_lo, y_hi = int(rows[0]), int(rows[-1]) + 1 + area = float(layer.thickness) * lateral_len + if area > 0.0: + specs.append(RadiativeReabsorptionSpec2D( + layer_id=layer.id, + y_start=y_lo, + y_stop=y_hi, + escape_probability=p_esc, + area_m2=area, + )) + return tuple(specs) + + +def build_two_sided_interface_srh_2d( + prepared: PreparedDevice, + electronic_2d: Any, + *, + interface_srh_mode: str = "off", +) -> tuple[TwoSidedInterfaceSRHCoupling2D, ...]: + """Validate and build clamp-passive two-sided cross-node interface SRH sheets.""" + data = prepared.to_mapping() + settings = data["settings"] + unsupported_flags = [ + name for name in ( + "interface_plane_projection", + "interface_shared_occupancy", + "interface_plane_closure", + "interface_plane_generation", + "interface_tunneling", + ) + if settings.get(name) + ] + if float(settings.get("het_recomb_despike", 0.0)) != 0.0: + unsupported_flags.append("het_recomb_despike") + if settings.get("interface_charge_closure", "off") != "off": + unsupported_flags.append("interface_charge_closure") + if unsupported_flags: + raise CapabilityError( + "dynamic_interface_2d_unsupported: 2D solver refuses dynamic/projected interface modes: " + + ", ".join(unsupported_flags) + ) + + electrical_ifaces = [iface for iface in prepared.interfaces if iface.electrical] + active_declared = [ + iface for iface in electrical_ifaces + if iface.to_mapping().get("defect") is not None + or any((iface.to_mapping().get(k) or 0.0) != 0.0 for k in ("v_n", "v_p")) + ] + if interface_srh_mode == "off": + if active_declared or settings.get("interface_two_sided"): + raise CapabilityError( + "interface_srh_2d_not_enabled: active electrical interface recombination cannot be silently ignored" + ) + return () + if interface_srh_mode != "two_sided_cross_node": + raise CapabilityError(f"unsupported_interface_srh_2d: {interface_srh_mode}") + if not settings.get("interface_two_sided"): + raise CapabilityError( + "two_sided_interface_srh_2d: requires explicit settings.interface_two_sided=True" + ) + if electronic_2d.geometry.lateral_bc != "neumann": + raise CapabilityError("two_sided_interface_srh_2d: requires Neumann lateral geometry") + if any(ch.kind != "fixed_reservoir" for ch in electronic_2d.column.channels): + raise CapabilityError("two_sided_interface_srh_2d: requires ohmic fixed-reservoir contacts") + + planes = electronic_2d.column.geometry.interfaces + if len(electrical_ifaces) != len(planes): + raise CapabilityError("two_sided_interface_srh_2d: electrical interface count disagrees with stack planes") + + elec_layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + ny = electronic_2d.geometry.ny + thermal_V = electronic_2d.column.thermal_voltage_V + + def _doping_eq_n_p(params: Mapping[str, Any]) -> tuple[float, float]: + n_d = float(cast(Any, params.get("N_D", 0.0))) + n_a = float(cast(Any, params.get("N_A", 0.0))) + ni_val = float(cast(Any, params["ni"])) + net = 0.5 * (n_d - n_a) + disc = math.sqrt(net * net + ni_val * ni_val) + if net >= 0.0: + n_eq = net + disc + p_eq = (ni_val * ni_val) / n_eq + else: + p_eq = -net + disc + n_eq = (ni_val * ni_val) / p_eq + return n_eq, p_eq + + couplings: list[TwoSidedInterfaceSRHCoupling2D] = [] + for idx, (iface, plane) in enumerate(zip(electrical_ifaces, planes)): + entry = iface.to_mapping() + defect = entry.get("defect") + v_n_decl = float(entry.get("v_n") or 0.0) + v_p_decl = float(entry.get("v_p") or 0.0) + mic_pair = entry.get("microscopic_capture_velocities_m_s") + mic_vn = float(mic_pair[0]) if isinstance(mic_pair, (list, tuple)) and len(mic_pair) == 2 else 0.0 + mic_vp = float(mic_pair[1]) if isinstance(mic_pair, (list, tuple)) and len(mic_pair) == 2 else 0.0 + v_n_raw = v_n_decl if v_n_decl > 0.0 else mic_vn + v_p_raw = v_p_decl if v_p_decl > 0.0 else mic_vp + if defect is None and v_n_decl == 0.0 and v_p_decl == 0.0: + continue + if v_n_raw == 0.0 or v_p_raw == 0.0: + if defect is None: + raise CapabilityError( + "two_sided_interface_srh_2d: each active sheet requires a microscopic interface defect" + ) + continue + if defect is None: + raise CapabilityError( + "two_sided_interface_srh_2d: each active sheet requires a microscopic interface defect" + ) + row = plane.shared_node + if row is None or row <= 0 or row >= ny - 1: + raise CapabilityError("two_sided_interface_srh_2d: requires interior shared interface row") + calibration = float(cast(Any, defect.get("calibration_factor", 1.0))) + if not math.isfinite(calibration) or calibration <= 0.0: + raise CapabilityError("two_sided_interface_srh_2d: positive calibration_factor is required") + v_n = v_n_raw * calibration + v_p = v_p_raw * calibration + + left_layer, right_layer = elec_layers[idx], elec_layers[idx + 1] + left_p, right_p = dict(left_layer.parameters), dict(right_layer.parameters) + if left_layer.role == "absorber" and right_layer.role != "absorber": + ref_p = left_p + elif right_layer.role == "absorber" and left_layer.role != "absorber": + ref_p = right_p + else: + ref_p = left_p if float(cast(Any, left_p["Eg"])) <= float(cast(Any, right_p["Eg"])) else right_p + + gap_eV = float(cast(Any, ref_p["Eg"])) + ni_ref = float(cast(Any, ref_p["ni"])) + depth_eV = float(cast(Any, defect["trap_depth_eV"])) + energy_ref = str(defect.get("energy_reference", "below_conduction_band")) + shift_eV = (0.5 * gap_eV - depth_eV) if energy_ref == "below_conduction_band" else (depth_eV - 0.5 * gap_eV) + n1 = ni_ref * math.exp(shift_eV / thermal_V) + p1 = ni_ref * math.exp(-shift_eV / thermal_V) + + n_l_eq, p_l_eq = _doping_eq_n_p(left_p) + n_r_eq, p_r_eq = _doping_eq_n_p(right_p) + pair_a_eq = float(n_r_eq * p_l_eq) + pair_b_eq = float(n_l_eq * p_r_eq) + couplings.append(TwoSidedInterfaceSRHCoupling2D( + interface_index=idx, + interface_row=int(row), + left_sample_row=int(row - 1), + right_sample_row=int(row + 1), + electron_capture_velocity_m_s=v_n, + hole_capture_velocity_m_s=v_p, + n1_m3=n1, + p1_m3=p1, + pair_a_equilibrium_product_m6=pair_a_eq, + pair_b_equilibrium_product_m6=pair_b_eq, + )) + if not couplings: + raise CapabilityError("two_sided_interface_srh_2d: no active capture sheet found") + return tuple(couplings) + + +def compile_ionic_device_2d( + prepared: PreparedDevice, + spatial: JV2DInput, + *, + ion_domain_layer: str | None = None, + ion_domain_endpoints: tuple[str, str] | None = None, + enable_radiative_reabsorption: bool | None = None, +) -> CompiledIonicDevice2D: + """Compile a 2D single-positive-ion device with four-side blocking boundaries.""" + if not isinstance(prepared, PreparedDevice) or not isinstance(spatial, JV2DInput): + raise TypeError("compile_ionic_device_2d requires PreparedDevice and JV2DInput") + if spatial.lateral_length is None or spatial.Nx is None or spatial.Ny_per_layer is None: + raise CapabilityError("ionic_2d: requires explicit lateral_length, Nx, and Ny_per_layer") + if spatial.lateral_bc != "neumann": + raise CapabilityError( + "periodic_ionic_2d_unsupported: 2D mobile-ion requires explicit 'neumann' lateral boundaries" + ) + if spatial.ion_dynamics not in (None, "single_mobile"): + raise CapabilityError( + f"ionic_2d_unsupported_dynamics: compile_ionic_device_2d requires single_mobile (got {spatial.ion_dynamics!r})" + ) + + data = prepared.to_mapping() + settings = data["settings"] + if settings.get("ion_steric_shared_site"): + raise CapabilityError("dual_ion_2d_unsupported: shared-site dual ions are unsupported in 2D") + for contact in data["contacts"]: + if contact.get("S_n") is not None or contact.get("S_p") is not None: + raise CapabilityError( + "selective_robin_ionic_2d_unsupported: 2D mobile-ion requires ohmic carrier contacts" + ) + + domain_layer, layers = _select_ion_layer(prepared, ion_domain_layer) + if ion_domain_endpoints is None: + if len(layers) != 1 and ion_domain_layer is not None: + raise CapabilityError("ionic_2d: multilayer ion_domain_layer requires explicit ('blocking', 'blocking') endpoints") + endpoints = ("blocking", "blocking") + else: + if ion_domain_endpoints != ("blocking", "blocking"): + raise CapabilityError("ionic_2d: ion interface exchange is unsupported; declare ('blocking', 'blocking')") + endpoints = ion_domain_endpoints + + declarations = [ + {"layer": layer.id, **{name: dict(layer.parameters)[name] for name in ION_INPUTS}} + for layer in prepared.layers + ] + for layer in prepared.layers: + p = dict(layer.parameters) + if p["P0_neg"] != 0.0 or p["D_ion_neg"] != 0.0: + raise CapabilityError("dual_ion_2d_unsupported: 2D mobile-ion supports one positive species only") + if layer.role == "substrate" and (p["P0"] != 0.0 or p["D_ion"] != 0.0): + raise CapabilityError("ionic_2d: substrate ion populations are unsupported") + if layer.id != domain_layer.id and (p["P0"] != 0.0 or p["D_ion"] != 0.0): + raise CapabilityError("ionic_2d: multiple active ion layers are unsupported in 2D") + + dom_params = dict(domain_layer.parameters) + reference = float(cast(float, dom_params["P0"])) + capacity = float(cast(float, dom_params["P_lim"])) + diffusion = float(cast(float, dom_params["D_ion"])) + activation = float(cast(float, dom_params["E_a_ion"])) + if not all(math.isfinite(v) for v in (reference, capacity, diffusion, activation)): + raise CapabilityError("ionic_2d: finite ionic parameters are required") + if not 0.0 < reference < capacity: + raise CapabilityError("ionic_2d: strictly positive unsaturated finite-site reference 0 < P0 < P_lim is required") + if diffusion < 0.0 or activation < 0.0: + raise CapabilityError("ionic_2d: diffusivity and activation energy must be non-negative") + if spatial.ion_dynamics == "single_mobile" and diffusion <= 0.0: + raise CapabilityError("mobile_ion_2d_requires_positive_diffusivity: single_mobile requires D_ion > 0") + + interface_srh_mode = spatial.interface_srh or "off" + # Validate dynamic interface flags BEFORE projecting away interface declarations + unsupported_iface = [ + name for name in ( + "interface_plane_projection", + "interface_shared_occupancy", + "interface_plane_closure", + "interface_plane_generation", + "interface_tunneling", + ) + if settings.get(name) + ] + if float(settings.get("het_recomb_despike", 0.0)) != 0.0: + unsupported_iface.append("het_recomb_despike") + if settings.get("interface_charge_closure", "off") != "off": + unsupported_iface.append("interface_charge_closure") + if unsupported_iface: + raise CapabilityError( + "dynamic_interface_2d_unsupported: " + ", ".join(unsupported_iface) + ) + + # Project electronic component cleanly (stripping only the bound ionic & optional two-sided SRH fields, + # recording every projection change in the immutable manifest) + projection = prepared.to_input().editing_data() + changes: list[dict[str, object]] = [] + for layer_dict in projection["layers"]: + for name in ("P0", "P0_neg", "D_ion", "D_ion_neg"): + layer_dict.setdefault("parameters", {})[name] = 0.0 + changes.append({"path": f"layers.{layer_dict['id']}.{name}", "component_value": 0.0}) + for name in ("ion_steric_diffusion_only", "ion_steric_shared_site"): + projection.setdefault("settings", {})[name] = False + changes.append({"path": f"settings.{name}", "component_value": False}) + if interface_srh_mode == "two_sided_cross_node": + projection.setdefault("settings", {})["interface_two_sided"] = False + projection["interfaces"] = [] + changes.append({"path": "interfaces", "component_value": "bound_in_two_sided_cross_node_2d"}) + + component_prepared = resolve_device( + DeviceInput.model_validate(projection), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + geometry_spatial = JV2DInput( + kind="jv_2d", + lateral_length=spatial.lateral_length, + Nx=spatial.Nx, + Ny_per_layer=spatial.Ny_per_layer, + lateral_bc=spatial.lateral_bc, + microstructure=spatial.microstructure, + ) + electronic_2d = compile_device_2d(component_prepared, geometry_spatial) + if any(ch.kind != "fixed_reservoir" for ch in electronic_2d.column.channels): + raise CapabilityError( + "selective_robin_ionic_2d_unsupported: 2D mobile-ion requires ohmic fixed-reservoir contacts" + ) + + iface_couplings = build_two_sided_interface_srh_2d( + prepared, electronic_2d, interface_srh_mode=interface_srh_mode + ) + reabsorption_specs = build_radiative_reabsorption_2d( + prepared, electronic_2d, enabled=enable_radiative_reabsorption + ) + + domain_index = layers.index(domain_layer) + planes = electronic_2d.column.geometry.interfaces + left = 0 if domain_index == 0 else planes[domain_index - 1].shared_node + right = electronic_2d.geometry.ny - 1 if domain_index == len(layers) - 1 else planes[domain_index].shared_node + if left is None or right is None: + raise CapabilityError("ionic_2d: domain endpoints require shared electrostatic stack nodes") + row_indices: NDArray[np.intp] = np.arange(left, right + 1, dtype=np.intp) + ion_y_geometry = half_endpoint_geometry(electronic_2d.column.nodes_m[row_indices]) + ion_geometry = RectangularGeometry2D(electronic_2d.geometry.x_m, ion_y_geometry, lateral_bc="neumann") + ion_count = ion_geometry.node_count + ion_face_count = ion_geometry.face_spacing_m.size + + scaled_diffusion = ion_diffusivity_at_temperature( + diffusion, electronic_2d.column.parameters.temperature_K, activation + ) + if not math.isfinite(scaled_diffusion) or scaled_diffusion < 0.0: + raise CapabilityError("ionic_2d: temperature-scaled ion diffusivity is outside the finite envelope") + + occupancy = reference / capacity + logit = math.log(occupancy) - math.log1p(-occupancy) + steric_model = ( + DIFFUSION_ONLY_STERIC_V1 if settings.get("ion_steric_diffusion_only") else WHOLE_FLUX_STERIC_V1 + ) + ref_arr: NDArray[np.float64] = np.full(ion_count, reference, dtype=float) + lim_arr: NDArray[np.float64] = np.full(ion_count, capacity, dtype=float) + logit_arr: NDArray[np.float64] = np.full(ion_count, logit, dtype=float) + faces_arr: NDArray[np.float64] = np.full(ion_face_count, scaled_diffusion, dtype=float) + ref_inventory = math.fsum((ion_geometry.contract_geometry.volumes * ref_arr).tolist()) + + manifest: dict[str, Any] = { + "binding": "single_positive_ion_classical_2d_residual_v1", + "original_prepared_sha256": prepared.content_sha256, + "original_ionic_inputs": declarations, + "electronic_component": { + "compiled_sha256": electronic_2d.identity, + "projection_changes": changes, + }, + "ion_domain": { + "layer": domain_layer.id, + "contacts": [endpoints[0], endpoints[1], "blocking_x_min", "blocking_x_max"], + "row_indices": row_indices.tolist(), + "x_m": ion_geometry.x_m.tolist(), + "y_m": ion_geometry.y_geometry.nodes_m.tolist(), + "cell_areas_m2": ion_geometry.contract_geometry.volumes.tolist(), + "reference_inventory_m1": ref_inventory, + }, + "ion_model": { + "site_contract": "independent_finite_sites", + "steric_model": steric_model, + "scaled_nodal_diffusivity_m2_s": scaled_diffusion, + "face_diffusivity_m2_s": faces_arr.tolist(), + }, + "extensions_2d": { + "interface_srh_mode": interface_srh_mode, + "interface_srh_rows": [c.interface_row for c in iface_couplings], + "radiative_reabsorption_layers": [s.layer_id for s in reabsorption_specs], + }, + "spatial_declaration": json.loads(spatial.model_dump_json()), + } + manifest_json = json.dumps(manifest, sort_keys=True, separators=(",", ":"), allow_nan=False) + sha = hashlib.sha256(manifest_json.encode()).hexdigest() + return CompiledIonicDevice2D( + device_id=str(data.get("id") or "ionic_2d"), + sha256=sha, + original_prepared_sha256=prepared.content_sha256, + electronic_component=electronic_2d, + ion_geometry=ion_geometry, + domain_layer_id=domain_layer.id, + ion_row_indices=row_indices, + positive_ion_reference_m3=ref_arr, + positive_ion_site_limit_m3=lim_arr, + positive_ion_logit_reference=logit_arr, + positive_ion_diffusivity_faces_m2_s=faces_arr, + steric_model=steric_model, + binding_manifest_json=manifest_json, + radiative_reabsorption=reabsorption_specs, + interface_srh_couplings=iface_couplings, + ) diff --git a/src/solarlab/device/grain_2d.py b/src/solarlab/device/grain_2d.py index 75cebc4b..068d520a 100644 --- a/src/solarlab/device/grain_2d.py +++ b/src/solarlab/device/grain_2d.py @@ -19,6 +19,7 @@ from solarlab.contracts import frozen_array from solarlab.device.inputs import GrainBoundaryInput from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError from solarlab.experiments.two_dimensional.inputs import JV2DInput from solarlab.mesh.geometry_2d import RectangularGeometry2D from solarlab.mesh.grid import LEFT_LAYER_WINS, node_owner @@ -44,7 +45,7 @@ def grain_declarations(prepared: PreparedDevice, spatial: JV2DInput) -> tuple[Gr if not grains: return () if spatial.lateral_bc != "neumann" or spatial.lateral_length is None: - raise ValueError("grain regions require explicit Neumann lateral geometry") + raise CapabilityError("grain regions require explicit Neumann lateral geometry") length = normalize_quantity(spatial.lateral_length, "m") layer_ids = {layer.id for layer in prepared.layers if layer.role != "substrate"} seen: set[str] = set() diff --git a/src/solarlab/device/optical_generation_2d.py b/src/solarlab/device/optical_generation_2d.py index ec631e83..ab5b9f5c 100644 --- a/src/solarlab/device/optical_generation_2d.py +++ b/src/solarlab/device/optical_generation_2d.py @@ -20,7 +20,7 @@ PHOTON_BUDGET_RTOL, OpticalGeneration1D, bind_optical_generation_1d, ) from solarlab.device.resolved import PreparedDevice -from solarlab.mesh.geometry_2d import RECTANGULAR_HALF_ENDPOINT_2D_V1, RectangularGeometry2D +from solarlab.mesh.geometry_2d import RECTANGULAR_2D_NAMES, RectangularGeometry2D from solarlab.physics.generation.profile import StaleGenerationProfileError OPTICAL_BINDING_2D_V1 = "uniform_lateral_coherent_front_tmm_half_cells_2d_v1" @@ -43,8 +43,8 @@ class OpticalGeneration2D: identity_sha256: str = field(init=False) def __post_init__(self) -> None: - if not isinstance(self.geometry, RectangularGeometry2D) or self.geometry.name != RECTANGULAR_HALF_ENDPOINT_2D_V1: - raise ValueError("optical2D requires the explicit nonperiodic half-endpoint geometry") + if not isinstance(self.geometry, RectangularGeometry2D) or self.geometry.name not in RECTANGULAR_2D_NAMES: + raise ValueError("optical2D requires a supported half-endpoint 2D geometry") if not isinstance(self.optical_y, OpticalGeneration1D): raise TypeError("optical2D requires the actual existing1D optical binding") if not self.prepared_sha256: diff --git a/src/solarlab/equations/assembly/ionic_2d.py b/src/solarlab/equations/assembly/ionic_2d.py new file mode 100644 index 00000000..74e81ee0 --- /dev/null +++ b/src/solarlab/equations/assembly/ionic_2d.py @@ -0,0 +1,921 @@ +"""2D classical storage and single-positive-ion finite-site assembly on Assembler. + +Provides: +* :class:`ClassicalTransient2D` / :class:`AssembledStorage2D`: adds physical + carrier ``STORAGE`` terms (``S = area * density``, cancellation-free ``expm1`` + increments) to the existing 2D electronic system without mutating DC-only + :class:`ClassicalDC2D`. +* :class:`IonicSystem2D`, :class:`AssembledIonic2DProblem`, and + :class:`AssembledConstrainedIonic2DProblem`: binds the four-side-blocking 2D + ion support ``ion:`` onto the shared :class:`Assembler` with + ``M = -S_u``, cancellation-free ``finite_site_secant_2d_m3``, steady inventory + closure, and exact sparse tangents for optional absorber radiative + reabsorption and two-sided cross-node interface SRH. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from hashlib import sha256 +import json +import math +from typing import Mapping, TypeAlias, cast + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix + +from solarlab.contracts.terms import Geometry +from solarlab.contracts.units import ( + AREA, COULOMB, ELEMENTARY_CHARGE_C, LENGTH, ONE, PARTICLE, SECOND, VOLUME, Unit, +) +from solarlab.equations.assembly.assembler import AssembledSystem, Assembler, Mesh, SupportGeometry +from solarlab.equations.assembly.layout import Block, ConstraintRows, NodeSet, SystemLayout +from solarlab.equations.assembly.two_dimensional import ( + BLOCKS, COORDINATE_FORM, ELECTRON, HOLE, NODES, POTENTIAL, SIDES, + ClassicalDC2D, SpaceCharge2D, classical_dc_2d, +) +from solarlab.equations.assembly.terms import ( + CELL_SOURCE, CONSTRAINT, FACE_FLUX, SCATTER_DIVERGENCE, STORAGE, Contribution, + EvaluationState, FaceValue, FieldValues, LocalValue, OperatingInputs, ReductionValue, + Term, TermValue, +) +from solarlab.equations.assembly.weighted import MEASURE +from solarlab.equations.dc_2d import CompiledDevice2D +from solarlab.equations.ionic_2d import ( + CompiledIonicDevice2D, RadiativeReabsorptionSpec2D, TwoSidedInterfaceSRHCoupling2D, + _interface_srh_sheet_rate_and_partials, evaluate_two_sided_interface_srh_2d, + finite_site_secant_2d_m3, ion_pair_flux_jacobian_2d, recompute_g_with_rad_2d, + trapezoid_weights_1d, +) +from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, IonFaceFluxJacobian +from solarlab.physics.recombination.bulk import RecombinationRate +from solarlab.physics.transport.electrochemical_flux import CarrierFaceFluxes + +__all__ = [ + "AssembledConstrainedIonic2DProblem", + "AssembledIonic2DProblem", + "AssembledIonicDC2DProblem", + "AssembledIonicTransient2DProblem", + "AssembledStorage2D", + "CarrierStorage2D", + "ClassicalTransient2D", + "InventoryReduction2D", + "IonDomain2D", + "IonStorage2D", + "IonTransport2D", + "IonicFields2D", + "IonicSpaceCharge2D", + "IonicSystem2D", + "classical_transient_2d", + "ionic_system_2d", +] + +Q = ELEMENTARY_CHARGE_C +CHARGE_UNIT = COULOMB / VOLUME +FLUX_UNIT = PARTICLE / (AREA * SECOND) +SOURCE_UNIT = PARTICLE / (VOLUME * SECOND) +DENSITY_UNIT = PARTICLE / VOLUME +INVENTORY_2D_UNIT = PARTICLE / LENGTH +BALANCE_2D_UNIT = PARTICLE / (LENGTH * SECOND) +TERM_SCHEMA_2D = "solarlab.ionic_2d.terms.v1" + +Vector: TypeAlias = NDArray[np.float64] + + +def _identity(*parts: object) -> str: + return sha256(json.dumps((TERM_SCHEMA_2D, *parts), separators=(",", ":")).encode()).hexdigest() + + +def _density(state: EvaluationState, block: str) -> Vector: + return state.field("electron_density_m3" if block == ELECTRON else "hole_density_m3") + + +@dataclass(frozen=True) +class CarrierStorage2D: + """Physical 2D carrier inventories ``S = area * density`` and cancellation-free increment.""" + + device: CompiledDevice2D + id: str = "carrier.storage_2d" + kind: str = STORAGE + support: str = NODES + equations: tuple[str, ...] = (ELECTRON, HOLE) + dependencies: tuple[str, ...] = BLOCKS + unit: Unit = DENSITY_UNIT + port: str | None = None + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, COORDINATE_FORM) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + n, p = _density(state, ELECTRON), _density(state, HOLE) + if not derivatives: + return {ELECTRON: LocalValue(n), HOLE: LocalValue(p)} + thermal = self.device.thermal_voltage_V + return { + ELECTRON: LocalValue(n, {POTENTIAL: MEASURE * n / thermal, ELECTRON: MEASURE * n}), + HOLE: LocalValue(p, {POTENTIAL: -(MEASURE * p) / thermal, HOLE: -(MEASURE * p)}), + } + + def increment(self, state: EvaluationState, previous: EvaluationState) -> Mapping[str, Contribution]: + """``S_old * expm1(log(c_new / c_old))`` with exact voltage-reference shift.""" + device = self.device + thermal = device.thermal_voltage_V + delta = {block: state.block(block) - previous.block(block) for block in BLOCKS} + old_ref = device.reference_potentials(previous.inputs.voltage_V) + new_ref = device.reference_potentials(state.inputs.voltage_V) + log_n = (delta[POTENTIAL] - (new_ref[0] - old_ref[0])) / thermal + delta[ELECTRON] + log_p = -(delta[POTENTIAL] - (new_ref[1] - old_ref[1])) / thermal - delta[HOLE] + return { + ELECTRON: _density(previous, ELECTRON) * MEASURE * np.expm1(log_n), + HOLE: _density(previous, HOLE) * MEASURE * np.expm1(log_p), + } + + +@dataclass(frozen=True) +class ClassicalTransient2D: + """Classical 2D DC assembly augmented with physical carrier ``STORAGE`` terms.""" + + device: CompiledDevice2D + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = () + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = () + dc: ClassicalDC2D = field(init=False, repr=False, compare=False) + assembler: Assembler = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + dc = classical_dc_2d(self.device) + storage = CarrierStorage2D(self.device) + extra: list[Term] = [] + if self.radiative_reabsorption or self.interface_srh_couplings: + extra.append( + CoupledSourceCorrection2D( + self.device, self.radiative_reabsorption, self.interface_srh_couplings + ) + ) + terms = (*dc.assembler.terms, *extra, storage) + assembler = Assembler(dc.assembler.layout, dc.assembler.mesh, dc.assembler.fields, terms) + object.__setattr__(self, "dc", dc) + object.__setattr__(self, "assembler", assembler) + + @property + def identity(self) -> str: + return self.assembler.identity + + +def classical_transient_2d( + device: CompiledDevice2D, + *, + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = (), + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = (), +) -> ClassicalTransient2D: + return ClassicalTransient2D(device, radiative_reabsorption, interface_srh_couplings) + + +@dataclass(frozen=True) +class AssembledStorage2D: + """Storage-enabled 2D classical electronic problem adapter for BDF/BE steppers.""" + + device: CompiledDevice2D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = () + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = () + binding: ClassicalTransient2D = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + self.device.column.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and nonnegative") + object.__setattr__( + self, + "binding", + classical_transient_2d( + self.device, + radiative_reabsorption=self.radiative_reabsorption, + interface_srh_couplings=self.interface_srh_couplings, + ), + ) + + @property + def inputs(self) -> OperatingInputs: + return OperatingInputs(voltage_V=float(self.voltage_V), generation_scale=float(self.generation_scale)) + + def evaluate(self, u: ArrayLike, *, derivatives: bool = True) -> AssembledSystem: + return self.binding.assembler.evaluate(u, self.inputs, derivatives=derivatives) + + def residual(self, u: ArrayLike) -> Vector: + system = self.evaluate(u, derivatives=False) + if not system.admissible: + return np.full(3 * self.device.node_count, np.nan) + return system.F + + def jacobian(self, u: ArrayLike) -> csc_matrix: + system = self.evaluate(u, derivatives=True) + if not system.admissible or system.J is None: + raise FloatingPointError("2D electronic Jacobian evaluated outside admissible domain") + ext = _electronic_extension_off_diagonal_jacobian( + self.device, + np.asarray(u, dtype=np.float64)[:3 * self.device.node_count], + self.voltage_V, + self.radiative_reabsorption, + self.interface_srh_couplings, + matrix_size=3 * self.device.node_count, + ) + return system.J if ext is None else cast(csc_matrix, (system.J + ext).tocsc()) + + def storage(self, u: ArrayLike) -> Vector: + s_vec, _ = self.binding.assembler.storage(u, self.inputs, derivatives=False) + return s_vec + + def storage_tangent(self, u: ArrayLike) -> csc_matrix: + _, s_u = self.binding.assembler.storage(u, self.inputs, derivatives=True) + if s_u is None: + raise FloatingPointError("2D electronic storage tangent evaluated outside admissible domain") + return s_u + + def mass_matrix(self, u: ArrayLike) -> csc_matrix: + return -self.storage_tangent(u) + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + return self.mass_matrix(u) + + def storage_increment(self, u: ArrayLike, old_problem: AssembledStorage2D, old_u: ArrayLike) -> Vector: + if old_problem.binding.identity != self.binding.identity: + raise ValueError("2D storage increment requires the same bound 2D system") + return self.binding.assembler.storage_increment(u, self.inputs, old_u, old_problem.inputs, physical=False) + + def physical_storage(self, u: ArrayLike) -> Vector: + return self.binding.assembler.physical_storage(u, self.inputs) + + def physical_increment(self, u: ArrayLike, old_problem: AssembledStorage2D, old_u: ArrayLike) -> Vector: + if old_problem.binding.identity != self.binding.identity: + raise ValueError("2D physical storage increment requires the same bound 2D system") + return self.binding.assembler.storage_increment(u, self.inputs, old_u, old_problem.inputs, physical=True) + + +@dataclass(frozen=True) +class IonDomain2D: + """Closed 4-side-blocking 2D positive-ion domain metadata.""" + + device: CompiledIonicDevice2D + + @property + def name(self) -> str: + return self.device.domain_layer_id + + @property + def node_set(self) -> str: + return "ion:" + self.name + + @property + def block(self) -> str: + return self.node_set + ":positive" + + @property + def mass_field(self) -> str: + return "ion_coordinate_jacobian_m3:" + self.name + + def coordinate_jacobian(self, density: Vector) -> Vector: + return density * (1.0 - density / self.device.positive_ion_site_limit_m3) + + +@dataclass(frozen=True) +class IonicFields2D: + """Field map for ``(phi, z_n, z_p, y_ion)`` on the 2D ionic layout.""" + + device: CompiledIonicDevice2D + + @property + def identity(self) -> str: + return _identity("finite_site_ionic_fields_2d_v1", self.device.identity) + + def evaluate(self, layout: SystemLayout, u: Vector, inputs: OperatingInputs) -> FieldValues: + domain = IonDomain2D(self.device) + ordered = np.concatenate([layout.view(u, b) for b in (*BLOCKS, domain.block)]) + try: + phi, n, p, ion_p = self.device.fields(ordered, voltage_V=inputs.voltage_V) + except (ValueError, FloatingPointError): + return FieldValues({}, False) + admissible = bool( + np.all(np.isfinite(n)) and np.all(np.isfinite(p)) + and np.all(n > 0.0) and np.all(p > 0.0) + and np.all(np.isfinite(ion_p)) and np.all(ion_p > 0.0) + ) + if not admissible: + return FieldValues({}, False) + return FieldValues({ + "potential_V": phi, + "electron_density_m3": n, + "hole_density_m3": p, + domain.block: ion_p, + domain.mass_field: domain.coordinate_jacobian(ion_p), + }, True) + + +@dataclass(frozen=True) +class IonicSpaceCharge2D: + """Full 2D space-charge density with embedded half-cell ion excess tangents.""" + + device: CompiledIonicDevice2D + id: str = "potential.space_charge" + kind: str = CELL_SOURCE + support: str = NODES + equations: tuple[str, ...] = (POTENTIAL,) + unit: Unit = CHARGE_UNIT + port: str | None = None + + @property + def dependencies(self) -> tuple[str, ...]: + return (*BLOCKS, IonDomain2D(self.device).block) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, COORDINATE_FORM) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + domain = IonDomain2D(self.device) + n, p = state.field("electron_density_m3"), state.field("hole_density_m3") + ion_p = state.field(domain.block) + rho = self.device.charge_ledger(n, p, ion_p).space_charge_C_m3() + if not derivatives: + return {POTENTIAL: LocalValue(rho)} + thermal = self.device.electronic_component.thermal_voltage_V + nodes = self.device.ion_node_indices + ratio = np.zeros(n.size, dtype=float) + ratio[nodes] = state.embedding_ratio(domain.node_set) + partial = np.zeros(n.size, dtype=float) + partial[nodes] = state.field(domain.mass_field) + return {POTENTIAL: LocalValue(rho, { + POTENTIAL: -Q * MEASURE * (n + p) / thermal, + ELECTRON: -Q * MEASURE * n, + HOLE: -Q * MEASURE * p, + domain.block: Q * MEASURE * ratio * partial, + })} + + +@dataclass(frozen=True) +class CoupledSourceCorrection2D: + """Optional 2D absorber radiative reabsorption and cross-node interface SRH cell source.""" + + electronic_component: CompiledDevice2D + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] + id: str = "carrier.coupled_2d_extensions" + kind: str = CELL_SOURCE + support: str = NODES + equations: tuple[str, ...] = (ELECTRON, HOLE) + dependencies: tuple[str, ...] = () + unit: Unit = SOURCE_UNIT + port: str | None = None + + @property + def identity(self) -> str: + return _identity( + self.id, + self.electronic_component.identity, + [(s.layer_id, s.escape_probability) for s in self.radiative_reabsorption], + [c.interface_row for c in self.interface_srh_couplings], + ) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + _ = derivatives + comp = self.electronic_component + n, p = state.field("electron_density_m3"), state.field("hole_density_m3") + correction = np.zeros_like(n) + shape = comp.geometry.shape + if self.radiative_reabsorption: + base = state.inputs.generation_scale * comp.generation_source_m3_s + b_rad = comp.recombination.coefficients.radiative_m3_s.reshape(shape) + ni_sq = comp.recombination.coefficients.ni_sq_m6.reshape(shape) + augmented = recompute_g_with_rad_2d( + G_optical=base.reshape(shape), + n=n.reshape(shape), + p=p.reshape(shape), + B_rad=b_rad, + ni_sq=ni_sq, + x=comp.geometry.x_m, + y=comp.geometry.y_geometry.nodes_m, + absorber_y_ranges=tuple((s.y_start, s.y_stop) for s in self.radiative_reabsorption), + absorber_p_esc=tuple(s.escape_probability for s in self.radiative_reabsorption), + absorber_areas=tuple(s.area_m2 for s in self.radiative_reabsorption), + ) + correction = correction + (augmented.ravel() - base) + if self.interface_srh_couplings: + report = evaluate_two_sided_interface_srh_2d( + n.reshape(shape), p.reshape(shape), + comp.geometry.y_geometry.nodes_m, + self.interface_srh_couplings, + ) + correction = correction - report.volumetric_sink_m3_s.ravel() + return {ELECTRON: LocalValue(correction), HOLE: LocalValue(correction)} + + +@dataclass(frozen=True) +class IonTransport2D: + """Four-side-blocking 2D SG positive-ion flux and exact coordinate tangents.""" + + domain: IonDomain2D + kind: str = FACE_FLUX + unit: Unit = FLUX_UNIT + port: str | None = None + divergence: str = SCATTER_DIVERGENCE + + @property + def id(self) -> str: + return self.domain.block + ".transport" + + @property + def support(self) -> str: + return self.domain.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.domain.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (POTENTIAL, self.domain.block) + + @property + def identity(self) -> str: + return _identity(self.id, self.domain.device.identity) + + def flux_evaluation(self, state: EvaluationState) -> IonFaceFluxJacobian: + d = self.domain.device + phi_ion = state.field("potential_V")[d.ion_node_indices] + ion_p = state.field(self.domain.block) + return ion_pair_flux_jacobian_2d( + phi_ion, + ion_p, + d.ion_geometry.contract_geometry.pairs, + d.ion_geometry.face_spacing_m, + d.positive_ion_diffusivity_faces_m2_s, + d.electronic_component.thermal_voltage_V, + d.positive_ion_site_limit_m3, + steric_diffusion_only=(d.steric_model == DIFFUSION_ONLY_STERIC_V1), + drift_sign=1.0, + ) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + evaluated = self.flux_evaluation(state) + if not derivatives: + return {self.domain.block: FaceValue(evaluated.flux)} + d = self.domain.device + pairs = d.ion_geometry.contract_geometry.pairs + left, right = pairs[:, 0], pairs[:, 1] + dp_dy = state.field(self.domain.mass_field) + return { + self.domain.block: FaceValue( + evaluated.flux, + { + POTENTIAL: evaluated.potential_left_derivative, + self.domain.block: evaluated.density_left_derivative * dp_dy[left], + }, + { + POTENTIAL: evaluated.potential_right_derivative, + self.domain.block: evaluated.density_right_derivative * dp_dy[right], + }, + ) + } + + +@dataclass(frozen=True) +class IonStorage2D: + """Physical 2D ion storage ``S = area * P`` and cancellation-free site secants.""" + + domain: IonDomain2D + kind: str = STORAGE + unit: Unit = DENSITY_UNIT + port: str | None = None + + @property + def id(self) -> str: + return self.domain.node_set + ".storage" + + @property + def support(self) -> str: + return self.domain.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.domain.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.domain.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.domain.device.identity) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + ion_p = state.field(self.domain.block) + if not derivatives: + return {self.domain.block: LocalValue(ion_p)} + dp_dy = state.field(self.domain.mass_field) + return {self.domain.block: LocalValue(ion_p, {self.domain.block: MEASURE * dp_dy})} + + def increment(self, state: EvaluationState, previous: EvaluationState) -> Mapping[str, Contribution]: + d = self.domain.device + secant = finite_site_secant_2d_m3( + d.positive_ion_site_limit_m3, + d.positive_ion_logit_reference, + previous.block(self.domain.block), + state.block(self.domain.block), + ) + return {self.domain.block: secant} + + +@dataclass(frozen=True) +class InventoryReduction2D: + """Whole-domain 2D ion inventory closure row ``fsum(area * P) - fsum(area * P0)``.""" + + domain: IonDomain2D + kind: str = CONSTRAINT + unit: Unit = DENSITY_UNIT + port: str | None = None + measure: str = "cell" + + @property + def id(self) -> str: + return self.domain.block + ".inventory" + + @property + def support(self) -> str: + return self.domain.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.domain.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.domain.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.domain.device.identity) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + d = self.domain.device + density = state.field(self.domain.block) + reference = d.positive_ion_reference_m3 + summand = MEASURE * density + offset = MEASURE * reference + tangents: dict[str, Contribution] = {} + if derivatives: + tangents = {self.domain.block: MEASURE * state.field(self.domain.mass_field)} + return {self.domain.block: ReductionValue(summand, offset, tangents)} + + +@dataclass(frozen=True) +class IonicSystem2D: + """Unified Assembler binding for 2D single-mobile-ion transient & constrained steady.""" + + device: CompiledIonicDevice2D + inventory_row_node: int | None = None + assembler: Assembler = field(init=False, repr=False, compare=False) + electronic: ClassicalDC2D = field(init=False, repr=False, compare=False) + ion_transport: IonTransport2D = field(init=False, repr=False, compare=False) + closure_rows: NDArray[np.bool_] = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + d = self.device + comp = d.electronic_component + electronic = classical_dc_2d(comp) + domain = IonDomain2D(d) + base = electronic.assembler.layout + node_sets = [ + *base.node_sets, + NodeSet(domain.node_set, d.ion_node_count, NODES, tuple(int(n) for n in d.ion_node_indices)), + ] + blocks = [ + *base.blocks, + Block(domain.block, domain.node_set, ONE, BALANCE_2D_UNIT), + ] + constraints = list(base.constraints) + closure_terms: list[Term] = [] + if self.inventory_row_node is not None: + if type(self.inventory_row_node) is not int or not 0 <= self.inventory_row_node < d.ion_node_count: + raise ValueError("inventory_row_node must name a 2D ion-domain node") + inv_term = InventoryReduction2D(domain) + constraints.append(ConstraintRows(domain.block, (self.inventory_row_node,), inv_term.id, INVENTORY_2D_UNIT)) + closure_terms.append(inv_term) + + ion_contract = d.ion_geometry.contract_geometry + ion_support = SupportGeometry( + domain.node_set, + Geometry( + ion_contract.volumes, + ion_contract.pairs, + ion_contract.face_measures, + AREA, + LENGTH, + cell_support=domain.node_set, + face_support=domain.node_set + ".faces", + ), + ) + mesh = Mesh((*electronic.assembler.mesh.supports, ion_support)) + layout = SystemLayout(tuple(node_sets), tuple(blocks), tuple(constraints)) + + # Replace electronic SpaceCharge2D with IonicSpaceCharge2D, add optional coupled extensions, + # CarrierStorage2D, IonTransport2D, IonStorage2D, and optional InventoryReduction2D. + terms: list[Term] = [] + for term in electronic.assembler.terms: + if isinstance(term, SpaceCharge2D): + terms.append(IonicSpaceCharge2D(d)) + else: + terms.append(term) + if d.radiative_reabsorption or d.interface_srh_couplings: + terms.append( + CoupledSourceCorrection2D(comp, d.radiative_reabsorption, d.interface_srh_couplings) + ) + ion_transport = IonTransport2D(domain) + terms.extend((CarrierStorage2D(comp), ion_transport, IonStorage2D(domain), *closure_terms)) + + assembler = Assembler(layout, mesh, IonicFields2D(d), tuple(terms)) + mask: NDArray[np.bool_] = np.zeros(layout.size, dtype=bool) + if self.inventory_row_node is not None: + mask[3 * d.node_count + self.inventory_row_node] = True + mask.setflags(write=False) + + object.__setattr__(self, "electronic", electronic) + object.__setattr__(self, "assembler", assembler) + object.__setattr__(self, "ion_transport", ion_transport) + object.__setattr__(self, "closure_rows", mask) + + @property + def identity(self) -> str: + return self.assembler.identity + + +def ionic_system_2d(device: CompiledIonicDevice2D, inventory_row_node: int | None = None) -> IonicSystem2D: + return IonicSystem2D(device, inventory_row_node) + + +def _electronic_extension_off_diagonal_jacobian( + comp: CompiledDevice2D, + elec_u: ArrayLike, + voltage_V: float, + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...], + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...], + *, + matrix_size: int, +) -> csc_matrix | None: + """Exact sparse off-diagonal CSC contribution for optional reabsorption / cross-node SRH.""" + if not radiative_reabsorption and not interface_srh_couplings: + return None + count = comp.node_count + _, n, p = comp.fields(elec_u, voltage_V=voltage_V) + thermal = comp.thermal_voltage_V + vol = comp.geometry.contract_geometry.volumes + shape = comp.geometry.shape + n_2d, p_2d = n.reshape(shape), p.reshape(shape) + fixed_mask = comp.fixed_carrier_mask + + row_chunks: list[NDArray[np.intp]] = [] + col_chunks: list[NDArray[np.intp]] = [] + val_chunks: list[Vector] = [] + + def emit_carrier(carrier_idx: int, offset: int, r: ArrayLike, c: ArrayLike, v: ArrayLike) -> None: + r_arr = np.asarray(r, dtype=np.intp).ravel() + c_arr = np.asarray(c, dtype=np.intp).ravel() + v_arr = np.asarray(v, dtype=float).ravel() + keep = ~fixed_mask[carrier_idx, r_arr] + if np.any(keep): + row_chunks.append(offset + r_arr[keep]) + col_chunks.append(c_arr[keep]) + val_chunks.append(v_arr[keep]) + + if radiative_reabsorption: + b_2d = comp.recombination.coefficients.radiative_m3_s.reshape(shape) + ni_2d = comp.recombination.coefficients.ni_sq_m6.reshape(shape) + wx_trap = trapezoid_weights_1d(comp.geometry.x_m) + for spec in radiative_reabsorption: + y_slice = slice(spec.y_start, spec.y_stop) + emission = b_2d[y_slice, :] * (n_2d[y_slice, :] * p_2d[y_slice, :] - ni_2d[y_slice, :]) + r_tot = float(np.trapezoid(np.trapezoid(emission, comp.geometry.y_geometry.nodes_m[y_slice], axis=0), + comp.geometry.x_m)) + if r_tot <= 0.0: + continue + wy_trap = trapezoid_weights_1d(comp.geometry.y_geometry.nodes_m[y_slice]) + quad_w = (wy_trap[:, None] * wx_trap[None, :]).ravel() + abs_nodes = (np.arange(spec.y_start, spec.y_stop, dtype=np.intp)[:, None] * comp.geometry.nx + + np.arange(comp.geometry.nx, dtype=np.intp)[None, :]).ravel() + grad_zn = (1.0 - spec.escape_probability) / spec.area_m2 * quad_w * b_2d[y_slice, :].ravel() * ( + n_2d[y_slice, :].ravel() * p_2d[y_slice, :].ravel() + ) + rr: NDArray[np.intp] + cc: NDArray[np.intp] + rr, cc = np.meshgrid(abs_nodes, abs_nodes, indexing="ij") + outer = vol[abs_nodes][:, None] * grad_zn[None, :] + for carrier_idx, offset in ((0, count), (1, 2 * count)): + emit_carrier(carrier_idx, offset, rr, count + cc, outer) + emit_carrier(carrier_idx, offset, rr, 2 * count + cc, -outer) + + if interface_srh_couplings: + nx = comp.geometry.nx + normal_widths = trapezoid_weights_1d(comp.geometry.y_geometry.nodes_m) + cols_x: NDArray[np.intp] = np.arange(nx, dtype=np.intp) + for c in interface_srh_couplings: + row_nodes: NDArray[np.intp] = c.interface_row * nx + cols_x + left_nodes: NDArray[np.intp] = c.left_sample_row * nx + cols_x + right_nodes: NDArray[np.intp] = c.right_sample_row * nx + cols_x + scale = vol[row_nodes] / normal_widths[c.interface_row] + + raw_a, da_dn, da_dp = _interface_srh_sheet_rate_and_partials( + n_2d[c.right_sample_row, :], p_2d[c.left_sample_row, :], + c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + act_a = (raw_a > 0.0).astype(float) + dn_r = -scale * act_a * da_dn * n_2d[c.right_sample_row, :] + dp_l = -scale * act_a * da_dp * p_2d[c.left_sample_row, :] + + raw_b, db_dn, db_dp = _interface_srh_sheet_rate_and_partials( + n_2d[c.left_sample_row, :], p_2d[c.right_sample_row, :], + c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + act_b = (raw_b > 0.0).astype(float) + dn_l = -scale * act_b * db_dn * n_2d[c.left_sample_row, :] + dp_r = -scale * act_b * db_dp * p_2d[c.right_sample_row, :] + + for carrier_idx, offset in ((0, count), (1, 2 * count)): + emit_carrier(carrier_idx, offset, row_nodes, right_nodes, (dn_r - dp_r) / thermal) + emit_carrier(carrier_idx, offset, row_nodes, count + right_nodes, dn_r) + emit_carrier(carrier_idx, offset, row_nodes, 2 * count + right_nodes, -dp_r) + emit_carrier(carrier_idx, offset, row_nodes, left_nodes, (dn_l - dp_l) / thermal) + emit_carrier(carrier_idx, offset, row_nodes, count + left_nodes, dn_l) + emit_carrier(carrier_idx, offset, row_nodes, 2 * count + left_nodes, -dp_l) + + if not row_chunks: + return None + return csc_matrix( + (np.concatenate(val_chunks), (np.concatenate(row_chunks), np.concatenate(col_chunks))), + shape=(matrix_size, matrix_size), + ) + + +def _extension_off_diagonal_jacobian(device: CompiledIonicDevice2D, u: ArrayLike, voltage_V: float, + generation_scale: float) -> csc_matrix | None: + _ = generation_scale + comp = device.electronic_component + return _electronic_extension_off_diagonal_jacobian( + comp, + np.asarray(u, dtype=np.float64)[:3 * comp.node_count], + voltage_V, + device.radiative_reabsorption, + device.interface_srh_couplings, + matrix_size=device.state_size, + ) + + +@dataclass(frozen=True) +class AssembledIonic2DProblem: + """Production Assembler-backed 2D single-mobile-ion DAE problem.""" + + device: CompiledIonicDevice2D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + binding: IonicSystem2D = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + self.device.electronic_component.column.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and nonnegative") + object.__setattr__(self, "binding", ionic_system_2d(self.device)) + + @property + def inputs(self) -> OperatingInputs: + return OperatingInputs(voltage_V=float(self.voltage_V), generation_scale=float(self.generation_scale)) + + def evaluate(self, u: ArrayLike, *, derivatives: bool = True) -> AssembledSystem: + return self.binding.assembler.evaluate(u, self.inputs, derivatives=derivatives) + + def residual(self, u: ArrayLike) -> Vector: + system = self.evaluate(u, derivatives=False) + if not system.admissible: + return np.full(self.device.state_size, np.nan) + return system.F + + def jacobian(self, u: ArrayLike) -> csc_matrix: + system = self.evaluate(u, derivatives=True) + if not system.admissible or system.J is None: + raise FloatingPointError("2D ionic Jacobian evaluated outside admissible domain") + ext = _extension_off_diagonal_jacobian(self.device, u, self.voltage_V, self.generation_scale) + return system.J if ext is None else cast(csc_matrix, (system.J + ext).tocsc()) + + def storage(self, u: ArrayLike) -> Vector: + s_vec, _ = self.binding.assembler.storage(u, self.inputs, derivatives=False) + return s_vec + + def storage_tangent(self, u: ArrayLike) -> csc_matrix: + _, s_u = self.binding.assembler.storage(u, self.inputs, derivatives=True) + if s_u is None: + raise FloatingPointError("2D ionic storage tangent evaluated outside admissible domain") + return s_u + + def mass_matrix(self, u: ArrayLike) -> csc_matrix: + return -self.storage_tangent(u) + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + return self.mass_matrix(u) + + def storage_increment(self, u: ArrayLike, old_problem: AssembledIonic2DProblem, old_u: ArrayLike) -> Vector: + if old_problem.binding.identity != self.binding.identity: + raise ValueError("2D ionic storage increment requires the same bound 2D system") + return self.binding.assembler.storage_increment(u, self.inputs, old_u, old_problem.inputs, physical=False) + + def physical_storage(self, u: ArrayLike) -> Vector: + return self.binding.assembler.physical_storage(u, self.inputs) + + def physical_increment(self, u: ArrayLike, old_problem: AssembledIonic2DProblem, old_u: ArrayLike) -> Vector: + if old_problem.binding.identity != self.binding.identity: + raise ValueError("2D ionic physical increment requires the same bound 2D system") + return self.binding.assembler.storage_increment(u, self.inputs, old_u, old_problem.inputs, physical=True) + + def carrier_fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: + state = self.binding.assembler.state(u, self.inputs) + if state is None: + raise FloatingPointError("2D carrier fluxes evaluated outside admissible domain") + return self.binding.electronic.transport.fluxes(state) + + def ion_flux_evaluation(self, u: ArrayLike) -> IonFaceFluxJacobian: + state = self.binding.assembler.state(u, self.inputs) + if state is None: + raise FloatingPointError("2D ion fluxes evaluated outside admissible domain") + return self.binding.ion_transport.flux_evaluation(state) + + def recombination_rate(self, n: Vector, p: Vector, *, derivatives: bool = True) -> RecombinationRate: + return self.binding.electronic.recombination.rate(n, p, derivatives=derivatives) + + def contact_particle_fluxes(self, u: ArrayLike, *, storage_rate: Vector | None = None) -> tuple[Vector, Vector]: + """Stack y_min/y_max carrier particle fluxes along +y closing contact cells.""" + system = self.evaluate(u, derivatives=False) + if not system.admissible: + raise FloatingPointError("2D contact particle fluxes evaluated outside admissible domain") + assembler = self.binding.assembler + result: list[Vector] = [] + for block in (ELECTRON, HOLE): + port_rows = [ + assembler.reaction_flux(system, block, port_id, storage_rate=storage_rate) + for _, port_id in SIDES + ] + result.append(np.stack(port_rows)) + return result[0], result[1] + + def contact_displacement_C_m2(self, u: ArrayLike) -> Vector: + """Stack y_min/y_max electric displacement ``D_y`` along +y closing Gauss contact cells.""" + system = self.evaluate(u, derivatives=False) + if not system.admissible: + raise FloatingPointError("2D contact displacement evaluated outside admissible domain") + assembler = self.binding.assembler + return np.stack([ + assembler.reaction_flux(system, POTENTIAL, port_id) + for _, port_id in SIDES + ]) + + +@dataclass(frozen=True) +class AssembledConstrainedIonic2DProblem: + """Assembler-backed steady 2D ionic problem with domain-inventory closure.""" + + original: AssembledIonic2DProblem + inventory_row_node: int + binding: IonicSystem2D = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + d = self.original.device + if type(self.inventory_row_node) is not int or not 0 <= self.inventory_row_node < d.ion_node_count: + raise ValueError("inventory_row_node must name a 2D ion-domain node") + object.__setattr__(self, "binding", ionic_system_2d(d, self.inventory_row_node)) + + @property + def constraint_row(self) -> int: + return 3 * self.original.device.node_count + self.inventory_row_node + + @property + def inventory_target_m1(self) -> float: + return self.original.device.reference_inventory_m1 + + def residual(self, u: ArrayLike) -> Vector: + system = self.binding.assembler.evaluate(u, self.original.inputs, derivatives=False) + if not system.admissible: + return np.full(self.original.device.state_size, np.nan) + return system.F + + def jacobian(self, u: ArrayLike) -> csc_matrix: + system = self.binding.assembler.evaluate(u, self.original.inputs, derivatives=True) + if not system.admissible or system.J is None: + raise FloatingPointError("2D constrained ionic Jacobian evaluated outside admissible domain") + ext = _extension_off_diagonal_jacobian( + self.original.device, u, self.original.voltage_V, self.original.generation_scale + ) + return system.J if ext is None else cast(csc_matrix, (system.J + ext).tocsc()) + + +AssembledIonicDC2DProblem = AssembledIonic2DProblem +AssembledIonicTransient2DProblem = AssembledIonic2DProblem + diff --git a/src/solarlab/equations/dc_2d.py b/src/solarlab/equations/dc_2d.py index 04f106e8..078d23ca 100644 --- a/src/solarlab/equations/dc_2d.py +++ b/src/solarlab/equations/dc_2d.py @@ -132,7 +132,7 @@ def __post_init__(self) -> None: for carrier in ("electron", "hole"): nodal = getattr(column.parameters, carrier + "_diffusivity_m2_s") vertical = getattr(column, carrier + "_diffusivity_faces_m2_s") - values = np.r_[np.repeat(nodal, geometry.nx - 1), np.repeat(vertical, geometry.nx)] + values = np.r_[np.repeat(nodal, geometry.x_faces_per_row), np.repeat(vertical, geometry.nx)] if np.any(values <= 0.0): raise ValueError("2D DC requires positive finite carrier diffusivities") object.__setattr__(self, carrier + "_diffusivity_faces_m2_s", frozen_array(values)) @@ -142,7 +142,9 @@ def __post_init__(self) -> None: or not np.array_equal(model.base_electron_diffusivity_m2_s, self.electron_diffusivity_faces_m2_s) or not np.array_equal(model.base_hole_diffusivity_m2_s, self.hole_diffusivity_faces_m2_s)): raise ValueError("field transport must match the exact2D grid, temperature and baseD") - horizontal_capacitance = (VACUUM_PERMITTIVITY_F_M * eps[:, None] / np.diff(geometry.x_m)[None, :]).ravel() + dx_row = (np.diff(geometry.x_m) if geometry.lateral_bc == "neumann" + else geometry.face_spacing_m[:geometry.nx]) + horizontal_capacitance = (VACUUM_PERMITTIVITY_F_M * eps[:, None] / dx_row[None, :]).ravel() object.__setattr__(self, "face_capacitance_F_m2", frozen_array(np.r_[ horizontal_capacitance, np.repeat(column.poisson.face_capacitance_F_m2, geometry.nx)])) faces = geometry.face_spacing_m.size diff --git a/src/solarlab/equations/field_transport_2d.py b/src/solarlab/equations/field_transport_2d.py index 538a190f..a24adb6d 100644 --- a/src/solarlab/equations/field_transport_2d.py +++ b/src/solarlab/equations/field_transport_2d.py @@ -16,7 +16,7 @@ from numpy.typing import ArrayLike from solarlab.contracts import frozen_array -from solarlab.mesh.geometry_2d import RECTANGULAR_HALF_ENDPOINT_2D_V1, RectangularGeometry2D +from solarlab.mesh.geometry_2d import RECTANGULAR_2D_NAMES, RectangularGeometry2D from solarlab.physics.transport.electrochemical_flux import CarrierFaceFlux, CarrierFaceFluxes, stable_sg_particle_flux from solarlab.physics.transport.field_mobility import FieldMobilityFaceParameters, linearize_field_mobility from solarlab.physics.transport.field_mobility_tangents import ( @@ -49,8 +49,8 @@ def __post_init__(self) -> None: require_field_measure(self.field_measure) if self.field_measure != FACE_NORMAL_COMPONENT_2D: raise FieldMobilityCapabilityError("2D CT requires the declared normal-face-component field") - if not isinstance(self.geometry, RectangularGeometry2D) or self.geometry.name != RECTANGULAR_HALF_ENDPOINT_2D_V1: - raise FieldMobilityCapabilityError("2D CT requires the nonperiodic half-endpoint face geometry") + if not isinstance(self.geometry, RectangularGeometry2D) or self.geometry.name not in RECTANGULAR_2D_NAMES: + raise FieldMobilityCapabilityError("2D CT requires a supported half-endpoint 2D face geometry") if not np.isfinite(self.thermal_voltage_V) or self.thermal_voltage_V <= 0: raise ValueError("field transport requires positive finite thermal voltage") count = self.geometry.face_spacing_m.size diff --git a/src/solarlab/equations/ionic_2d.py b/src/solarlab/equations/ionic_2d.py new file mode 100644 index 00000000..e4c53e5e --- /dev/null +++ b/src/solarlab/equations/ionic_2d.py @@ -0,0 +1,1156 @@ +"""Executable single-positive-ion finite-site 2D equations and bounded 2D extensions. + +Unknowns are ``(phi, z_n, z_p, y_ion)`` where ``phi, z_n, z_p`` live on the +complete ``(Ny, Nx)`` rectangular Neumann-x support and ``y_ion`` lives on the +closed four-side-blocking 2D ion support ``(Ny_ion, Nx)`` via the shifted +finite-site logistic coordinate ``P = P_lim * expit(logit_ref + y_ion)``. +Dual-ion, shared-site, periodic-x mobile-ion, Robin-contact mobile-ion, and +dynamic-interface 2D bindings are explicitly refused. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import json +import math +from typing import Any, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix +from scipy.special import expit + +from solarlab.contracts import ( + AREA, COULOMB, LENGTH, PARTICLE, SECOND, VOLUME, CellSource, EquationSpec, + FaceFlux, Geometry, Layout, Support, TermSink, frozen_array, integer_indices, +) +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.discretization.bernoulli import bernoulli, bernoulli_derivative +from solarlab.equations.dc_1d import CapabilityError, quasi_fermi_potential_tangents +from solarlab.equations.dc_2d import CompiledDevice2D, State2D +from solarlab.mesh.geometry_2d import RECTANGULAR_HALF_ENDPOINT_2D_V1, RectangularGeometry2D +from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger +from solarlab.physics.ions import ( + DIFFUSION_ONLY_STERIC_V1, WHOLE_FLUX_STERIC_V1, IonFaceFluxJacobian, + ion_face_flux, single_site_density, +) +from solarlab.physics.recombination.bulk import RecombinationRate +from solarlab.physics.transport.electrochemical_flux import CarrierFaceFlux, CarrierFaceFluxes, stable_sg_particle_flux + +__all__ = [ + "CompiledIonicDevice2D", + "Ionic2DProblem", + "IonicState2D", + "IonFluxes2D", + "MobileIonDiagnostics2D", + "RadiativeReabsorptionSpec2D", + "TwoSidedInterfaceSRHCoupling2D", + "TwoSidedInterfaceSRHReport2D", + "assess_mobile_ion_terminal_2d", + "control_volume_areas_2d", + "evaluate_two_sided_interface_srh_2d", + "finite_site_secant_2d_m3", + "ion_inventory_2d", + "ion_pair_flux_jacobian_2d", + "positive_ion_fluxes_2d", + "recompute_g_with_rad_2d", + "trapezoid_weights_1d", +] + +Vector: TypeAlias = NDArray[np.float64] +Q = ELEMENTARY_CHARGE_C + + +def _read_only(values: ArrayLike) -> Vector: + arr = np.asarray(values, dtype=float).copy() + arr.setflags(write=False) + return arr + + +def trapezoid_weights_1d(coords: ArrayLike) -> Vector: + """Exact 1D composite trapezoidal weights matching ``np.trapezoid``.""" + x = np.asarray(coords, dtype=float) + if x.ndim != 1 or x.size < 2 or not np.all(np.isfinite(x)) or np.any(np.diff(x) <= 0.0): + raise ValueError("trapezoid coordinates must be finite, 1D, and strictly increasing") + dx = np.diff(x) + w = np.empty_like(x) + w[0] = 0.5 * dx[0] + w[-1] = 0.5 * dx[-1] + if x.size > 2: + w[1:-1] = 0.5 * (dx[:-1] + dx[1:]) + return w + + +@dataclass(frozen=True, slots=True) +class RadiativeReabsorptionSpec2D: + """Self-consistent uniform absorber radiative recycling spec on 2D stack.""" + + layer_id: str + y_start: int + y_stop: int + escape_probability: float + area_m2: float + + def __post_init__(self) -> None: + if not self.layer_id or self.y_stop - self.y_start < 2 or self.y_start < 0: + raise ValueError("radiative reabsorption requires at least two contiguous absorber rows") + if not math.isfinite(self.escape_probability) or not 0.0 <= self.escape_probability < 1.0: + raise ValueError("escape_probability must lie in [0, 1)") + if not math.isfinite(self.area_m2) or self.area_m2 <= 0.0: + raise ValueError("absorber 2D area must be finite and positive") + + +def recompute_g_with_rad_2d( + *, + G_optical: ArrayLike, + n: ArrayLike, + p: ArrayLike, + B_rad: ArrayLike, + ni_sq: ArrayLike, + x: ArrayLike, + y: ArrayLike, + absorber_y_ranges: tuple[tuple[int, int], ...], + absorber_p_esc: tuple[float, ...], + absorber_areas: tuple[float, ...], +) -> Vector: + """Return a new ``(Ny, Nx)`` optical+reabsorption generation array.""" + x_arr = np.asarray(x, dtype=float) + y_arr = np.asarray(y, dtype=float) + if x_arr.ndim != 1 or y_arr.ndim != 1: + raise ValueError("x and y must be 1D coordinate vectors") + shape = (y_arr.size, x_arr.size) + g_opt = np.asarray(G_optical, dtype=float) + n_arr = np.asarray(n, dtype=float) + p_arr = np.asarray(p, dtype=float) + b_arr = np.asarray(B_rad, dtype=float) + ni_arr = np.asarray(ni_sq, dtype=float) + for name, arr in (("G_optical", g_opt), ("n", n_arr), ("p", p_arr), ("B_rad", b_arr), ("ni_sq", ni_arr)): + if arr.shape != shape: + raise ValueError(f"shape mismatch for {name}: got {arr.shape}, expected {shape}") + if not (len(absorber_y_ranges) == len(absorber_p_esc) == len(absorber_areas)): + raise ValueError("per-absorber reabsorption tuple lengths must match") + result = g_opt.copy() + for (y_lo, y_hi), p_esc, area in zip(absorber_y_ranges, absorber_p_esc, absorber_areas): + if area <= 0.0 or p_esc >= 1.0 or y_hi - y_lo < 2 or x_arr.size < 2: + continue + emission = b_arr[y_lo:y_hi, :] * (n_arr[y_lo:y_hi, :] * p_arr[y_lo:y_hi, :] - ni_arr[y_lo:y_hi, :]) + emission_x = np.trapezoid(emission, y_arr[y_lo:y_hi], axis=0) + r_tot = float(np.trapezoid(emission_x, x_arr)) + if r_tot <= 0.0: + continue + result[y_lo:y_hi, :] += r_tot * (1.0 - p_esc) / area + return result + + +@dataclass(frozen=True, slots=True) +class TwoSidedInterfaceSRHCoupling2D: + """Validated horizontal clamp-passive two-sided cross-node SRH sheet.""" + + interface_index: int + interface_row: int + left_sample_row: int + right_sample_row: int + electron_capture_velocity_m_s: float + hole_capture_velocity_m_s: float + n1_m3: float + p1_m3: float + pair_a_equilibrium_product_m6: float + pair_b_equilibrium_product_m6: float + + def __post_init__(self) -> None: + if (self.interface_row <= 0 + or self.left_sample_row != self.interface_row - 1 + or self.right_sample_row != self.interface_row + 1): + raise ValueError("2D two-sided interface SRH requires interior idx-1/idx+1 sampling") + for name in ("electron_capture_velocity_m_s", "hole_capture_velocity_m_s"): + val = float(getattr(self, name)) + if not math.isfinite(val) or val <= 0.0: + raise ValueError(f"{name} must be finite and positive") + for name in ("n1_m3", "p1_m3", "pair_a_equilibrium_product_m6", "pair_b_equilibrium_product_m6"): + val = float(getattr(self, name)) + if not math.isfinite(val) or val < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + + +@dataclass(frozen=True, slots=True) +class TwoSidedInterfaceSRHReport2D: + """Surface rates for both capture pairs and area-conservative volumetric sink.""" + + interface_rows: tuple[int, ...] + pair_a_surface_rate_m2_s: Vector + pair_b_surface_rate_m2_s: Vector + total_surface_rate_m2_s: Vector + pair_a_clamped: NDArray[np.bool_] + pair_b_clamped: NDArray[np.bool_] + volumetric_sink_m3_s: Vector + + +def _interface_srh_sheet_rate_and_partials( + n_sample: Vector, + p_sample: Vector, + eq_product: float, + n1: float, + p1: float, + v_n: float, + v_p: float, +) -> tuple[Vector, Vector, Vector]: + """Raw surface SRH rate ``(n*p - ni_eff^2) / ((n+n1)/v_p + (p+p1)/v_n)`` and partials.""" + denom = (n_sample + n1) / v_p + (p_sample + p1) / v_n + numer = n_sample * p_sample - eq_product + raw = numer / denom + d_raw_dn = (p_sample * denom - numer / v_p) / (denom * denom) + d_raw_dp = (n_sample * denom - numer / v_n) / (denom * denom) + return raw, d_raw_dn, d_raw_dp + + +def evaluate_two_sided_interface_srh_2d( + n: ArrayLike, + p: ArrayLike, + y: ArrayLike, + couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...], +) -> TwoSidedInterfaceSRHReport2D: + """Evaluate both cross-node capture directions and construct volumetric sink.""" + electrons = np.asarray(n, dtype=float) + holes = np.asarray(p, dtype=float) + y_arr = np.asarray(y, dtype=float) + if (electrons.ndim != 2 or electrons.shape != holes.shape + or electrons.shape[0] != y_arr.size or y_arr.size < 3 + or not np.all(np.isfinite(electrons)) or not np.all(np.isfinite(holes))): + raise ValueError("2D interface-SRH carrier arrays must be finite and shape matched") + if not couplings: + raise ValueError("at least one two-sided interface-SRH coupling is required") + rows = tuple(c.interface_row for c in couplings) + indices = tuple(c.interface_index for c in couplings) + if len(set(rows)) != len(rows) or len(set(indices)) != len(indices): + raise ValueError("2D interface-SRH coupling rows and indices must be unique") + normal_widths = trapezoid_weights_1d(y_arr) + pair_a = np.empty((len(couplings), electrons.shape[1]), dtype=float) + pair_b = np.empty_like(pair_a) + clamped_a = np.empty(pair_a.shape, dtype=bool) + clamped_b = np.empty(pair_b.shape, dtype=bool) + sink = np.zeros_like(electrons) + for idx, c in enumerate(couplings): + if c.interface_row <= 0 or c.interface_row >= electrons.shape[0] - 1: + raise ValueError("interface-SRH sheet must use interior idx-1/idx+1 sampling") + raw_a, _, _ = _interface_srh_sheet_rate_and_partials( + electrons[c.right_sample_row, :], holes[c.left_sample_row, :], + c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + raw_b, _, _ = _interface_srh_sheet_rate_and_partials( + np.maximum(electrons[c.left_sample_row, :], 0.0), + np.maximum(holes[c.right_sample_row, :], 0.0), + c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + if not np.all(np.isfinite(raw_a)) or not np.all(np.isfinite(raw_b)): + raise ValueError("2D interface SRH produced a non-finite surface rate") + clamped_a[idx, :] = raw_a <= 0.0 + clamped_b[idx, :] = raw_b <= 0.0 + pair_a[idx, :] = np.maximum(raw_a, 0.0) + pair_b[idx, :] = np.maximum(raw_b, 0.0) + sink[c.interface_row, :] += (pair_a[idx, :] + pair_b[idx, :]) / normal_widths[c.interface_row] + total = pair_a + pair_b + clamped_a.setflags(write=False) + clamped_b.setflags(write=False) + return TwoSidedInterfaceSRHReport2D( + interface_rows=rows, + pair_a_surface_rate_m2_s=_read_only(pair_a), + pair_b_surface_rate_m2_s=_read_only(pair_b), + total_surface_rate_m2_s=_read_only(total), + pair_a_clamped=clamped_a, + pair_b_clamped=clamped_b, + volumetric_sink_m3_s=_read_only(sink), + ) + + +@dataclass(frozen=True, slots=True) +class IonFluxes2D: + """Positive-ion particle fluxes on x and y faces [m^-2 s^-1].""" + + x: Vector + y: Vector + + +@dataclass(frozen=True, slots=True) +class MobileIonDiagnostics2D: + """Terminal conservation and physical-bound report for one 2D ion solve.""" + + initial_inventory_m1: float + terminal_inventory_m1: float + relative_inventory_drift: float + terminal_min_electron_density_m3: float + terminal_min_hole_density_m3: float + terminal_min_density_m3: float + terminal_max_site_fraction: float + inventory_rtol: float + passed: bool + violations: tuple[str, ...] + + +def control_volume_areas_2d(x: ArrayLike, y: ArrayLike) -> Vector: + """Return Neumann-domain nodal control-volume areas [m^2].""" + return np.outer(trapezoid_weights_1d(y), trapezoid_weights_1d(x)) + + +def ion_inventory_2d(x: ArrayLike, y: ArrayLike, density: ArrayLike) -> float: + """Return discrete 2D ion inventory per out-of-plane depth [m^-1].""" + areas = control_volume_areas_2d(x, y) + values = np.asarray(density, dtype=float) + if values.shape != areas.shape or not np.all(np.isfinite(values)): + raise ValueError(f"ion density must be finite with shape {areas.shape}") + return math.fsum((values * areas).ravel().tolist()) + + +def _harmonic_faces_2d(values: Vector, axis: int) -> Vector: + left = values[:, :-1] if axis == 1 else values[:-1, :] + right = values[:, 1:] if axis == 1 else values[1:, :] + denom = left + right + return np.divide(2.0 * left * right, denom, out=np.zeros_like(denom), where=denom > 0.0) + + +def positive_ion_fluxes_2d( + x: ArrayLike, + y: ArrayLike, + phi: ArrayLike, + density: ArrayLike, + diffusion: ArrayLike, + thermal_voltage: float, + site_limit: ArrayLike, + *, + steric_diffusion_only: bool = False, +) -> IonFluxes2D: + """Positive-ion SG particle fluxes on a tensor-product 2D grid.""" + x_arr = np.asarray(x, dtype=float) + y_arr = np.asarray(y, dtype=float) + _ = trapezoid_weights_1d(x_arr), trapezoid_weights_1d(y_arr) + shape = (y_arr.size, x_arr.size) + pot = np.asarray(phi, dtype=float) + ions = np.asarray(density, dtype=float) + diff = np.asarray(diffusion, dtype=float) + lim = np.asarray(site_limit, dtype=float) + for name, arr in (("phi", pot), ("density", ions), ("diffusion", diff), ("site_limit", lim)): + if arr.shape != shape or not np.all(np.isfinite(arr)): + raise ValueError(f"{name} must be finite with shape {shape}") + if np.any(diff < 0.0) or np.any(lim <= 0.0) or not math.isfinite(thermal_voltage) or thermal_voltage <= 0.0: + raise ValueError("ionic parameters must have D >= 0, P_lim > 0, and V_T > 0") + dx = np.diff(x_arr) + dy = np.diff(y_arr) + diff_x = _harmonic_faces_2d(diff, axis=1) + diff_y = _harmonic_faces_2d(diff, axis=0) + flux_x = np.empty((y_arr.size, x_arr.size - 1), dtype=float) + for row in range(y_arr.size): + flux_x[row, :] = ion_face_flux( + pot[row, :], ions[row, :], dx, diff_x[row, :], thermal_voltage, + 0.5 * (lim[row, :-1] + lim[row, 1:]), + steric_diffusion_only=steric_diffusion_only, P_lim_node=lim[row, :], + ) + flux_y = np.empty((y_arr.size - 1, x_arr.size), dtype=float) + for col in range(x_arr.size): + flux_y[:, col] = ion_face_flux( + pot[:, col], ions[:, col], dy, diff_y[:, col], thermal_voltage, + 0.5 * (lim[:-1, col] + lim[1:, col]), + steric_diffusion_only=steric_diffusion_only, P_lim_node=lim[:, col], + ) + return IonFluxes2D(x=_read_only(flux_x), y=_read_only(flux_y)) + + +def assess_mobile_ion_terminal_2d( + x: ArrayLike, + y: ArrayLike, + initial_density: ArrayLike, + terminal_density: ArrayLike, + site_limit: ArrayLike, + *, + terminal_electron_density: ArrayLike, + terminal_hole_density: ArrayLike, + inventory_rtol: float = 1.0e-12, + active_mask: ArrayLike | None = None, + control_volume_areas_m2: ArrayLike | None = None, +) -> MobileIonDiagnostics2D: + """Assess physical conservation and positivity/site gates at terminal 2D state.""" + areas = ( + control_volume_areas_2d(x, y) + if control_volume_areas_m2 is None + else np.asarray(control_volume_areas_m2, dtype=float) + ) + init_p = np.asarray(initial_density, dtype=float) + term_p = np.asarray(terminal_density, dtype=float) + lim = np.asarray(site_limit, dtype=float) + n_arr = np.asarray(terminal_electron_density, dtype=float) + p_arr = np.asarray(terminal_hole_density, dtype=float) + if any(arr.shape != areas.shape for arr in (init_p, term_p, lim)): + raise ValueError("ion arrays must match the 2D ion control-volume grid") + if n_arr.shape != p_arr.shape or n_arr.ndim != 2: + raise ValueError("carrier density arrays must be matching 2D arrays") + initial_inv = math.fsum((init_p * areas).ravel().tolist()) + terminal_inv = math.fsum((term_p * areas).ravel().tolist()) + rel_drift = abs(terminal_inv - initial_inv) / max(abs(initial_inv), 1.0e-30) + min_n = float(np.min(n_arr)) + min_p = float(np.min(p_arr)) + active = lim > 0.0 if active_mask is None else (np.asarray(active_mask, dtype=bool) & (lim > 0.0)) + min_ion = float(np.min(term_p[active])) if np.any(active) else float(np.min(term_p)) + max_frac = float(np.max(np.divide(term_p, lim, out=np.zeros_like(term_p), where=lim > 0.0))) + violations: list[str] = [] + if not np.all(np.isfinite(n_arr)) or min_n < 0.0: + violations.append("negative_terminal_electron_density") + if not np.all(np.isfinite(p_arr)) or min_p < 0.0: + violations.append("negative_terminal_hole_density") + if not np.all(np.isfinite(term_p)) or min_ion < 0.0: + violations.append("negative_terminal_density") + if not math.isfinite(max_frac) or max_frac > 1.0: + violations.append("terminal_site_limit_exceeded") + if not math.isfinite(rel_drift) or rel_drift > inventory_rtol: + violations.append("inventory_drift_exceeded") + return MobileIonDiagnostics2D( + initial_inventory_m1=initial_inv, + terminal_inventory_m1=terminal_inv, + relative_inventory_drift=rel_drift, + terminal_min_electron_density_m3=min_n, + terminal_min_hole_density_m3=min_p, + terminal_min_density_m3=min_ion, + terminal_max_site_fraction=max_frac, + inventory_rtol=float(inventory_rtol), + passed=len(violations) == 0, + violations=tuple(violations), + ) + + +def finite_site_secant_2d_m3( + capacity_m3: ArrayLike, + logit_reference: ArrayLike, + old_coordinate: ArrayLike, + new_coordinate: ArrayLike, +) -> Vector: + """Cancellation-free ``P(new) - P(old)`` for ``P = P_lim * expit(a0 + y)``.""" + cap = np.asarray(capacity_m3, dtype=float) + a0 = np.asarray(logit_reference, dtype=float) + y_old = np.asarray(old_coordinate, dtype=float) + y_new = np.asarray(new_coordinate, dtype=float) + return _stable_logistic_diff(cap, a0, y_old, y_new) + + +def _stable_logistic_diff(cap: Vector, a0: Vector, y_old: Vector, y_new: Vector) -> Vector: + """Exact cancellation-free identity: ``sig(b) - sig(a) = sig(a)*(1 - sig(b))*expm1(b - a)``.""" + dy = y_new - y_old + sig_old: Vector = np.asarray(expit(a0 + y_old), dtype=np.float64) + vac_new: Vector = np.asarray(expit(-(a0 + y_new)), dtype=np.float64) + vac_old: Vector = np.asarray(expit(-(a0 + y_old)), dtype=np.float64) + sig_new: Vector = np.asarray(expit(a0 + y_new), dtype=np.float64) + pos = dy >= 0.0 + # For dy >= 0, expm1(-dy) is bounded in [-1, 0]: sig(b) - sig(a) = -sig(b)*(1 - sig(a))*expm1(-dy) + # For dy < 0, expm1(dy) is bounded in (-1, 0): sig(b) - sig(a) = sig(a)*(1 - sig(b))*expm1(dy) + result: Vector = np.empty_like(dy, dtype=np.float64) + result[pos] = -cap[pos] * sig_new[pos] * vac_old[pos] * np.expm1(-dy[pos]) + result[~pos] = cap[~pos] * sig_old[~pos] * vac_new[~pos] * np.expm1(dy[~pos]) + return result + + +def ion_pair_flux_jacobian_2d( + phi: Vector, + density: Vector, + pairs: NDArray[np.int64], + spacing: Vector, + diffusion_faces: Vector, + thermal_voltage_V: float, + site_limit: Vector, + *, + steric_diffusion_only: bool = False, + drift_sign: float = 1.0, +) -> IonFaceFluxJacobian: + """Vectorized SG ionic flux and exact local derivatives on arbitrary 2D face pairs.""" + left, right = pairs[:, 0], pairs[:, 1] + pot_l, pot_r = phi[left], phi[right] + den_l, den_r = density[left], density[right] + lim_l, lim_r = site_limit[left], site_limit[right] + prefactor = diffusion_faces / spacing + zero = np.zeros_like(spacing) + + if steric_diffusion_only: + occ = density / site_limit + clipped = np.clip(occ, 0.0, 0.999999) + mu_ex = -np.log1p(-clipped) + xi = drift_sign * (pot_r - pot_l) / thermal_voltage_V + (mu_ex[right] - mu_ex[left]) + B_pos = bernoulli(xi) + B_neg = bernoulli(-xi) + flux = prefactor * (B_pos * den_l - B_neg * den_r) + interior = (occ > 0.0) & (occ < 0.999999) + chem_deriv = np.divide(1.0, site_limit * (1.0 - occ), out=np.zeros_like(density), where=interior) + node_diff = (occ != 0.0) & (occ != 0.999999) + differentiable = (diffusion_faces == 0.0) | (node_diff[left] & node_diff[right]) + xi_deriv = bernoulli_derivative(xi) * den_l + bernoulli_derivative(-xi) * den_r + density_left = prefactor * (B_pos - xi_deriv * chem_deriv[left]) + density_right = prefactor * (-B_neg + xi_deriv * chem_deriv[right]) + else: + face_limit = 0.5 * (lim_l + lim_r) + avg_den = 0.5 * (den_l + den_r) + occ = avg_den / face_limit + clipped = np.clip(occ, 0.0, 0.999999) + denom = np.maximum(1.0 - clipped, 1.0e-6) + steric = 1.0 / denom + xi = drift_sign * (pot_r - pot_l) / thermal_voltage_V + B_pos = bernoulli(xi) + B_neg = bernoulli(-xi) + flux_core = B_pos * den_l - B_neg * den_r + flux = prefactor * steric * flux_core + xi_deriv_raw = bernoulli_derivative(xi) * den_l + bernoulli_derivative(-xi) * den_r + active_clip = (occ > 0.0) & (occ < 0.999999) + active_max = (1.0 - clipped) > 1.0e-6 + steric_den_deriv = np.divide(0.5, face_limit * denom * denom, out=np.zeros_like(spacing), + where=active_clip & active_max) + differentiable = (diffusion_faces == 0.0) | ( + (occ != 0.0) & (occ != 0.999999) & ((1.0 - clipped) != 1.0e-6) + ) + density_left = prefactor * (steric * B_pos + flux_core * steric_den_deriv) + density_right = prefactor * (-steric * B_neg + flux_core * steric_den_deriv) + xi_deriv = steric * xi_deriv_raw + + potential_scale = prefactor * xi_deriv * drift_sign / thermal_voltage_V + for arr in (flux, density_left, density_right, potential_scale): + if not np.all(np.isfinite(arr)): + raise ValueError("2D ion-flux Jacobian produced a non-finite derivative") + return IonFaceFluxJacobian( + flux=flux, + density_left_derivative=density_left, + density_right_derivative=density_right, + partner_left_derivative=zero, + partner_right_derivative=zero.copy(), + potential_left_derivative=-potential_scale, + potential_right_derivative=potential_scale, + differentiable_faces=differentiable, + ) + + +@dataclass(frozen=True) +class IonicState2D: + """Physical trial state bound to the complete 2D single-mobile-ion device.""" + + u: Vector + electronic_state: State2D + positive_ion_density_m3: Vector + device_sha256: str + domain_inventory_m1: float + + def __post_init__(self) -> None: + object.__setattr__(self, "u", frozen_array(self.u)) + object.__setattr__(self, "positive_ion_density_m3", frozen_array(self.positive_ion_density_m3)) + elec_count = self.electronic_state.potential_V.size + ion_count = self.positive_ion_density_m3.size + if (self.u.shape != (3 * elec_count + ion_count,) + or not np.array_equal(self.u[:3 * elec_count], self.electronic_state.u)): + raise ValueError("2D ionic coordinates must include their complete electronic component") + if (self.positive_ion_density_m3.ndim != 2 + or self.positive_ion_density_m3.shape[1] != self.electronic_state.potential_V.shape[1] + or self.positive_ion_density_m3.shape[0] < 3 + or np.any(self.positive_ion_density_m3 <= 0.0)): + raise ValueError("2D positive-ion density must be positive on its declared (Ny_ion, Nx) domain") + if not self.device_sha256 or not math.isfinite(self.domain_inventory_m1) or self.domain_inventory_m1 <= 0.0: + raise ValueError("2D ionic state requires complete device identity and finite positive inventory") + + @property + def voltage_V(self) -> float: + return self.electronic_state.voltage_V + + +@dataclass(frozen=True) +class CompiledIonicDevice2D: + """One 2D Neumann electronic component and one closed 4-side-blocking 2D ion domain.""" + + device_id: str + sha256: str + original_prepared_sha256: str + electronic_component: CompiledDevice2D + ion_geometry: RectangularGeometry2D + domain_layer_id: str + ion_row_indices: NDArray[np.intp] + positive_ion_reference_m3: Vector + positive_ion_site_limit_m3: Vector + positive_ion_logit_reference: Vector + positive_ion_diffusivity_faces_m2_s: Vector + steric_model: str + binding_manifest_json: str + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = () + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = () + capabilities: tuple[str, ...] = ( + "classical_2d_electronic_component", + "single_positive_ion_2d_residual", + "finite_sites", + "blocking_4_side_ion_contacts", + "physical_ion_storage_2d", + ) + ion_node_indices: NDArray[np.intp] = field(init=False) + layout: Layout = field(init=False, repr=False) + + def __post_init__(self) -> None: + comp = self.electronic_component + if comp.geometry.name != RECTANGULAR_HALF_ENDPOINT_2D_V1 or self.ion_geometry.name != RECTANGULAR_HALF_ENDPOINT_2D_V1: + raise CapabilityError("2D mobile-ion requires Neumann half-endpoint rectangular geometry") + if any(ch.kind != "fixed_reservoir" for ch in comp.column.channels): + raise CapabilityError("selective_robin_ionic_2d_unsupported: 2D mobile-ion requires ohmic fixed-reservoir contacts") + rows = integer_indices(self.ion_row_indices) + if (rows.ndim != 1 or rows.size != self.ion_geometry.ny or rows.size < 3 + or np.any(np.diff(rows) != 1) or rows[0] < 0 or rows[-1] >= comp.geometry.ny): + raise ValueError("ion_row_indices must be ordered, contiguous and inside the electronic stack") + if not np.array_equal(self.ion_geometry.x_m, comp.geometry.x_m): + raise ValueError("ion and electronic lateral grids must coincide") + if not np.array_equal(self.ion_geometry.y_geometry.nodes_m, comp.geometry.y_geometry.nodes_m[rows]): + raise ValueError("ion and electronic vertical nodes must coincide on ion_row_indices") + object.__setattr__(self, "ion_row_indices", np.frombuffer(rows.tobytes(), dtype=np.intp)) + nx = comp.geometry.nx + nodes = (rows[:, None] * nx + np.arange(nx, dtype=np.intp)[None, :]).ravel() + object.__setattr__(self, "ion_node_indices", np.frombuffer(nodes.tobytes(), dtype=np.intp)) + ion_count = self.ion_geometry.node_count + for name in ("positive_ion_reference_m3", "positive_ion_site_limit_m3", "positive_ion_logit_reference"): + arr = frozen_array(getattr(self, name)) + if arr.shape != (ion_count,): + raise ValueError(f"{name} must match the 2D ion node count") + object.__setattr__(self, name, arr) + if (np.any(self.positive_ion_reference_m3 <= 0.0) + or np.any(self.positive_ion_reference_m3 >= self.positive_ion_site_limit_m3)): + raise ValueError("finite-site ion reference must lie strictly between 0 and P_lim") + faces = frozen_array(self.positive_ion_diffusivity_faces_m2_s) + expected_faces = self.ion_geometry.face_spacing_m.size + if faces.shape != (expected_faces,) or np.any(faces < 0.0): + raise ValueError("positive_ion_diffusivity_faces_m2_s must match 2D ion faces and be non-negative") + object.__setattr__(self, "positive_ion_diffusivity_faces_m2_s", faces) + if self.steric_model not in {WHOLE_FLUX_STERIC_V1, DIFFUSION_ONLY_STERIC_V1}: + raise ValueError("unsupported 2D ionic steric model") + if not self.sha256 or not self.original_prepared_sha256 or not self.domain_layer_id: + raise ValueError("2D ionic device requires complete provenance identities") + elec_faces = comp.geometry.face_spacing_m.size + object.__setattr__(self, "layout", Layout( + ( + Support("cells", "cell", (comp.node_count,)), + Support("faces", "face", (elec_faces,)), + Support("ion_cells", "cell", (ion_count,)), + Support("ion_faces", "face", (expected_faces,)), + ), + (), + ( + EquationSpec("gauss", "electrostatics", "cells", (comp.node_count,), COULOMB / LENGTH, role="constraint"), + EquationSpec("electron", "electron", "cells", (comp.node_count,), PARTICLE / (LENGTH * SECOND)), + EquationSpec("hole", "hole", "cells", (comp.node_count,), PARTICLE / (LENGTH * SECOND)), + EquationSpec("positive_ion", "positive_ion", "ion_cells", (ion_count,), PARTICLE / (LENGTH * SECOND)), + ), + )) + + @property + def identity(self) -> str: + return self.sha256 + + @property + def node_count(self) -> int: + return self.electronic_component.node_count + + @property + def ion_node_count(self) -> int: + return self.ion_geometry.node_count + + @property + def state_size(self) -> int: + return 3 * self.node_count + self.ion_node_count + + @property + def ion_species_names(self) -> tuple[str, ...]: + return ("positive",) + + @property + def ion_species_slices(self) -> tuple[slice, ...]: + start = 3 * self.node_count + return (slice(start, start + self.ion_node_count),) + + @property + def binding_manifest(self) -> dict[str, Any]: + loaded = json.loads(self.binding_manifest_json) + if not isinstance(loaded, dict): + raise ValueError("binding_manifest_json must decode to an object") + return loaded + + @property + def ion_charge_weight_ratio(self) -> Vector: + elec_vol = self.electronic_component.geometry.contract_geometry.volumes[self.ion_node_indices] + return frozen_array(self.ion_geometry.contract_geometry.volumes / elec_vol) + + @property + def reference_inventory_m1(self) -> float: + return math.fsum( + (self.ion_geometry.contract_geometry.volumes * self.positive_ion_reference_m3).tolist() + ) + + def at_temperature(self, temperature_K: float) -> CompiledIonicDevice2D: + """Verify or evaluate at the compiled device temperature.""" + if not math.isclose(temperature_K, self.electronic_component.column.parameters.temperature_K, rel_tol=0.0, abs_tol=1e-12): + raise CapabilityError("2D ionic device is bound to its compiled temperature; recompile for a new T") + return self + + def fields(self, u: ArrayLike, *, voltage_V: float = 0.0) -> tuple[Vector, Vector, Vector, Vector]: + values = np.asarray(u, dtype=float) + if values.shape != (self.state_size,) or not np.all(np.isfinite(values)): + raise ValueError("coordinates must be finite and match the 2D ionic state layout") + elec_size = 3 * self.node_count + phi, n, p = self.electronic_component.fields(values[:elec_size], voltage_V=voltage_V) + y_ion = values[elec_size:] + try: + ion_p = single_site_density( + self.positive_ion_reference_m3, + self.positive_ion_site_limit_m3, + self.positive_ion_logit_reference, + y_ion, + ) + except ValueError as exc: + raise FloatingPointError(str(exc)) from exc + if not np.all(np.isfinite(ion_p)) or np.any(ion_p <= 0.0) or np.any(ion_p >= self.positive_ion_site_limit_m3): + raise FloatingPointError("2D ion coordinate is outside the open finite-site interval (0, P_lim)") + return phi, n, p, ion_p + + def state(self, u: ArrayLike, *, voltage_V: float = 0.0) -> IonicState2D: + values = np.asarray(u, dtype=float) + elec_size = 3 * self.node_count + elec_state = self.electronic_component.state(values[:elec_size], voltage_V=voltage_V) + _, _, _, ion_p = self.fields(values, voltage_V=voltage_V) + inventory = math.fsum((self.ion_geometry.contract_geometry.volumes * ion_p).tolist()) + return IonicState2D( + values, + elec_state, + ion_p.reshape(self.ion_geometry.shape), + self.sha256, + inventory, + ) + + def full_grid_ion_density(self, ion_density_domain: ArrayLike) -> Vector: + """Embed ``(Ny_ion, Nx)`` or ``(N_ion,)`` ion density onto ``(Ny, Nx)`` stack.""" + full: Vector = np.zeros(self.electronic_component.geometry.shape, dtype=np.float64) + full[self.ion_row_indices, :] = np.asarray(ion_density_domain, dtype=np.float64).reshape(self.ion_geometry.shape) + return full + + def full_grid_ion_diffusivity_m2_s(self) -> Vector: + """Nodal ion diffusivity on ``(Ny, Nx)`` stack for current/diagnostic helpers.""" + full: Vector = np.zeros(self.electronic_component.geometry.shape, dtype=np.float64) + manifest = self.binding_manifest + d_nodal = float(manifest["ion_model"]["scaled_nodal_diffusivity_m2_s"]) + full[self.ion_row_indices, :] = d_nodal + return full + + def full_grid_ion_site_limit_m3(self) -> Vector: + """Positive site limit on ``(Ny, Nx)`` stack (positive floor outside ion domain).""" + cap = float(self.positive_ion_site_limit_m3[0]) + full: Vector = np.full(self.electronic_component.geometry.shape, cap, dtype=np.float64) + full[self.ion_row_indices, :] = self.positive_ion_site_limit_m3.reshape(self.ion_geometry.shape) + return full + + def charge_ledger(self, n: Vector, p: Vector, ion_density_m3: Vector) -> ChargeLedger: + comp = self.electronic_component + ion_pos: Vector = np.zeros(self.node_count, dtype=np.float64) + ion_ref: Vector = np.zeros(self.node_count, dtype=np.float64) + ratio = self.ion_charge_weight_ratio + ion_pos[self.ion_node_indices] = ion_density_m3 * ratio + ion_ref[self.ion_node_indices] = self.positive_ion_reference_m3 * ratio + return ChargeLedger(self.node_count, 0, ( + ChargeEntry("hole", "hole", 1, p), + ChargeEntry("electron", "electron", -1, n), + ChargeEntry("positive_ion", "ion_charge_projection", 1, ion_pos, ion_ref), + ChargeEntry("acceptor", "dopant", -1, comp.extrude(comp.column.parameters.acceptor_density_m3)), + ChargeEntry("donor", "dopant", 1, comp.extrude(comp.column.parameters.donor_density_m3)), + )) + + +@dataclass(frozen=True) +class Ionic2DProblem: + """Reference legacy-free 2D single-mobile-ion DAE residual and tangent matrices.""" + + device: CompiledIonicDevice2D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + + def __post_init__(self) -> None: + self.device.electronic_component.column.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and nonnegative") + + def carrier_fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: + comp = self.device.electronic_component + values = np.asarray(u, dtype=float)[:3 * comp.node_count] + phi, n, p = comp.fields(values, voltage_V=self.voltage_V) + left, right = comp.geometry.contract_geometry.pairs.T + potentials = comp.band_structure.transport_potentials(phi) + if comp.field_transport is not None: + return comp.field_transport.fluxes( + phi, n, p, potentials[0], potentials[1], + electron_electrochemical_step=values[comp.node_count + right] - values[comp.node_count + left], + hole_electrochemical_step=-(values[2 * comp.node_count + right] - values[2 * comp.node_count + left]), + ) + fluxes = [] + for density, potential, diffusivity, offset, sign in ( + (n, potentials[0], comp.electron_diffusivity_faces_m2_s, comp.node_count, 1.0), + (p, potentials[1], comp.hole_diffusivity_faces_m2_s, 2 * comp.node_count, -1.0), + ): + step = -sign * (potential[right] - potential[left]) / comp.thermal_voltage_V + coefficient = diffusivity / comp.geometry.face_spacing_m + drive = sign * (values[offset + right] - values[offset + left]) + evaluated = stable_sg_particle_flux(density[left], density[right], step, coefficient, + electrochemical_step=drive) + per_volt = -sign / comp.thermal_voltage_V * evaluated.energy_step_derivative + fluxes.append(CarrierFaceFlux( + evaluated.flux, evaluated.left_density_derivative, evaluated.right_density_derivative, + -per_volt, per_volt, step, coefficient, + )) + return CarrierFaceFluxes(fluxes[0], fluxes[1]) + + def ion_flux_evaluation(self, u: ArrayLike) -> IonFaceFluxJacobian: + d = self.device + phi, _, _, ion_p = d.fields(u, voltage_V=self.voltage_V) + phi_ion = phi[d.ion_node_indices] + return ion_pair_flux_jacobian_2d( + phi_ion, + ion_p, + d.ion_geometry.contract_geometry.pairs, + d.ion_geometry.face_spacing_m, + d.positive_ion_diffusivity_faces_m2_s, + d.electronic_component.thermal_voltage_V, + d.positive_ion_site_limit_m3, + steric_diffusion_only=(d.steric_model == DIFFUSION_ONLY_STERIC_V1), + drift_sign=1.0, + ) + + def effective_generation_m3_s(self, n: Vector, p: Vector) -> Vector: + d = self.device + comp = d.electronic_component + base = self.generation_scale * comp.generation_source_m3_s + if not d.radiative_reabsorption: + return base + shape = comp.geometry.shape + b_rad = comp.recombination.coefficients.radiative_m3_s.reshape(shape) + ni_sq = comp.recombination.coefficients.ni_sq_m6.reshape(shape) + augmented = recompute_g_with_rad_2d( + G_optical=base.reshape(shape), + n=n.reshape(shape), + p=p.reshape(shape), + B_rad=b_rad, + ni_sq=ni_sq, + x=comp.geometry.x_m, + y=comp.geometry.y_geometry.nodes_m, + absorber_y_ranges=tuple((s.y_start, s.y_stop) for s in d.radiative_reabsorption), + absorber_p_esc=tuple(s.escape_probability for s in d.radiative_reabsorption), + absorber_areas=tuple(s.area_m2 for s in d.radiative_reabsorption), + ) + return augmented.ravel() + + def recombination_rate(self, n: Vector, p: Vector, *, derivatives: bool = True) -> RecombinationRate: + comp = self.device.electronic_component + evaluation = comp.recombination.evaluate(n, p, derivatives=derivatives) + evaluation.require_domain() + if comp.grain_recombination is not None: + return comp.grain_recombination.evaluate(evaluation, comp.recombination.coefficients) + return evaluation.total + + def interface_srh_sink_m3_s(self, n: Vector, p: Vector) -> Vector: + d = self.device + if not d.interface_srh_couplings: + return np.zeros_like(n) + shape = d.electronic_component.geometry.shape + report = evaluate_two_sided_interface_srh_2d( + n.reshape(shape), p.reshape(shape), + d.electronic_component.geometry.y_geometry.nodes_m, + d.interface_srh_couplings, + ) + return report.volumetric_sink_m3_s.ravel() + + def displacement(self, u: ArrayLike) -> Vector: + comp = self.device.electronic_component + phi, _, _, _ = self.device.fields(u, voltage_V=self.voltage_V) + left, right = comp.geometry.contract_geometry.pairs.T + return -comp.face_capacitance_F_m2 * (phi[right] - phi[left]) + + def residual(self, u: ArrayLike) -> Vector: + d = self.device + comp = d.electronic_component + count = comp.node_count + values = np.asarray(u, dtype=float) + try: + phi, n, p, ion_p = d.fields(values, voltage_V=self.voltage_V) + except (ValueError, FloatingPointError): + return np.full(d.state_size, np.nan) + if not (np.all(np.isfinite(n)) and np.all(np.isfinite(p)) and np.all(n > 0.0) and np.all(p > 0.0)): + return np.full(d.state_size, np.nan) + c_fluxes = self.carrier_fluxes(values) + ion_eval = self.ion_flux_evaluation(values) + gen = self.effective_generation_m3_s(n, p) + rec = self.recombination_rate(n, p, derivatives=False).rate + self.interface_srh_sink_m3_s(n, p) + source = gen - rec + outputs: list[Vector] = [] + for name, flux, flux_unit, cell_source, source_unit, geom in ( + ("gauss", self.displacement(values), COULOMB / AREA, + d.charge_ledger(n, p, ion_p).space_charge_C_m3(), COULOMB / VOLUME, comp.geometry.contract_geometry), + ("electron", c_fluxes.electron.flux, PARTICLE / (AREA * SECOND), + source, PARTICLE / (VOLUME * SECOND), comp.geometry.contract_geometry), + ("hole", c_fluxes.hole.flux, PARTICLE / (AREA * SECOND), + source, PARTICLE / (VOLUME * SECOND), comp.geometry.contract_geometry), + ): + sink = TermSink(d.layout, name, geom) + sink.add(FaceFlux(name + ".transport", "faces", flux, flux_unit)) + sink.add(CellSource(name + ".source", "cells", cell_source, source_unit)) + outputs.append(np.array(sink.value(), copy=True)) + ig = d.ion_geometry.contract_geometry + ion_geom = Geometry( + ig.volumes, ig.pairs, ig.face_measures, AREA, LENGTH, + cell_support="ion_cells", face_support="ion_faces", + ) + ion_sink = TermSink(d.layout, "positive_ion", ion_geom) + ion_sink.add(FaceFlux("positive_ion.transport", "ion_faces", ion_eval.flux, PARTICLE / (AREA * SECOND))) + outputs.append(np.array(ion_sink.value(), copy=True)) + + bottom, top = comp.column.contact_potentials(self.voltage_V) + outputs[0][:comp.geometry.nx] = phi[:comp.geometry.nx] - bottom + outputs[0][-comp.geometry.nx:] = phi[-comp.geometry.nx:] - top + sides = comp.geometry.contact_nodes.reshape(2, comp.geometry.nx) + for rows, offset, sign, reference in zip( + outputs[1:3], (count, 2 * count), (1.0, -1.0), comp.reference_potentials(self.voltage_V) + ): + for nodes in sides: + rows[nodes] = sign * ((phi[nodes] - reference[nodes]) / comp.thermal_voltage_V + values[offset + nodes]) + return np.concatenate(outputs) + + def storage(self, u: ArrayLike, *, physical: bool = False) -> Vector: + d = self.device + comp = d.electronic_component + count = comp.node_count + _, n, p, ion_p = d.fields(u, voltage_V=self.voltage_V) + elec_vol = comp.geometry.contract_geometry.volumes + ion_vol = d.ion_geometry.contract_geometry.volumes + s_n = elec_vol * n + s_p = elec_vol * p + if not physical: + mask = comp.fixed_carrier_mask + s_n[mask[0]] = 0.0 + s_p[mask[1]] = 0.0 + return np.concatenate((np.zeros(count), s_n, s_p, ion_vol * ion_p)) + + def storage_tangent(self, u: ArrayLike) -> csc_matrix: + """``S_u`` on non-constraint rows; ``mass_matrix = -S_u``.""" + d = self.device + comp = d.electronic_component + count = comp.node_count + _, n, p, ion_p = d.fields(u, voltage_V=self.voltage_V) + thermal = comp.thermal_voltage_V + elec_vol = comp.geometry.contract_geometry.volumes + ion_vol = d.ion_geometry.contract_geometry.volumes + mask = comp.fixed_carrier_mask + active_n = ~mask[0] + active_p = ~mask[1] + nodes: NDArray[np.intp] = np.arange(count, dtype=np.intp) + n_nodes = nodes[active_n] + p_nodes = nodes[active_p] + ion_nodes: NDArray[np.intp] = np.arange(d.ion_node_count, dtype=np.intp) + dp_dy = ion_p * (1.0 - ion_p / d.positive_ion_site_limit_m3) + rows = np.concatenate(( + count + n_nodes, count + n_nodes, + 2 * count + p_nodes, 2 * count + p_nodes, + 3 * count + ion_nodes, + )) + cols = np.concatenate(( + n_nodes, count + n_nodes, + p_nodes, 2 * count + p_nodes, + 3 * count + ion_nodes, + )) + vals = np.concatenate(( + elec_vol[active_n] * n[active_n] / thermal, + elec_vol[active_n] * n[active_n], + -elec_vol[active_p] * p[active_p] / thermal, + -elec_vol[active_p] * p[active_p], + ion_vol * dp_dy, + )) + return csc_matrix((vals, (rows, cols)), shape=(d.state_size, d.state_size)) + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + """Signed DAE mass matrix ``M = -S_u``.""" + return -self.storage_tangent(u) + + def jacobian(self, u: ArrayLike) -> csc_matrix: + """Full sparse analytic Jacobian via vectorized COO-to-CSC assembly (no dense matrix).""" + d = self.device + comp = d.electronic_component + count = comp.node_count + values = np.asarray(u, dtype=float) + phi, n, p, ion_p = d.fields(values, voltage_V=self.voltage_V) + thermal = comp.thermal_voltage_V + geom = comp.geometry.contract_geometry + left, right = geom.pairs[:, 0], geom.pairs[:, 1] + + row_chunks: list[NDArray[np.intp]] = [] + col_chunks: list[NDArray[np.intp]] = [] + val_chunks: list[Vector] = [] + + def emit(r: ArrayLike, c: ArrayLike, v: ArrayLike) -> None: + row_chunks.append(np.asarray(r, dtype=np.intp).ravel()) + col_chunks.append(np.asarray(c, dtype=np.intp).ravel()) + val_chunks.append(np.asarray(v, dtype=float).ravel()) + + # 1. Gauss rows (interior only; contact rows are Dirichlet) + cap_w = comp.face_capacitance_F_m2 * geom.face_measures + emit(left, left, -cap_w) + emit(left, right, cap_w) + emit(right, left, cap_w) + emit(right, right, -cap_w) + + nodes: NDArray[np.intp] = np.arange(count, dtype=np.intp) + vol = geom.volumes + emit(nodes, nodes, -Q * vol * (n + p) / thermal) + emit(nodes, count + nodes, -Q * vol * n) + emit(nodes, 2 * count + nodes, -Q * vol * p) + dp_dy = ion_p * (1.0 - ion_p / d.positive_ion_site_limit_m3) + ion_vol = d.ion_geometry.contract_geometry.volumes + emit(d.ion_node_indices, 3 * count + np.arange(d.ion_node_count, dtype=np.intp), Q * ion_vol * dp_dy) + + # 2. Carrier transport + bulk/grain recombination + optional reabsorption + optional cross-node SRH + c_fluxes = self.carrier_fluxes(values) + rate = self.recombination_rate(n, p, derivatives=True) + assert rate.d_rate_dn is not None and rate.d_rate_dp is not None + source_n = -np.asarray(rate.d_rate_dn) * n + source_p = np.asarray(rate.d_rate_dp) * p + source_phi = (source_n + source_p) / thermal + + evaluated_transport = None if comp.field_transport is None else comp.field_transport.evaluate(phi) + for offset, sign, density, flux in ( + (count, 1.0, n, c_fluxes.electron), + (2 * count, -1.0, p, c_fluxes.hole), + ): + drive = sign * (values[offset + right] - values[offset + left]) + phi_left, phi_right = quasi_fermi_potential_tangents(flux, drive, sign, thermal) + if evaluated_transport is not None: + diff = (evaluated_transport.electron_diffusivity_m2_s if offset == count + else evaluated_transport.hole_diffusivity_m2_s) + slope = (evaluated_transport.electron_d_diffusivity_d_field if offset == count + else evaluated_transport.hole_d_diffusivity_d_field) + field_chain = (flux.flux / diff) * slope / comp.geometry.face_spacing_m + phi_left = phi_left + field_chain + phi_right = phi_right - field_chain + z_left = sign * flux.left_density_derivative * density[left] + z_right = sign * flux.right_density_derivative * density[right] + fm = geom.face_measures + emit(offset + left, left, -fm * phi_left) + emit(offset + left, right, -fm * phi_right) + emit(offset + left, offset + left, -fm * z_left) + emit(offset + left, offset + right, -fm * z_right) + emit(offset + right, left, fm * phi_left) + emit(offset + right, right, fm * phi_right) + emit(offset + right, offset + left, fm * z_left) + emit(offset + right, offset + right, fm * z_right) + emit(offset + nodes, nodes, vol * source_phi) + emit(offset + nodes, count + nodes, vol * source_n) + emit(offset + nodes, 2 * count + nodes, vol * source_p) + + # Optional self-consistent radiative reabsorption nonlocal rank-1 coupling + if d.radiative_reabsorption: + shape = comp.geometry.shape + n_2d, p_2d = n.reshape(shape), p.reshape(shape) + b_2d = comp.recombination.coefficients.radiative_m3_s.reshape(shape) + ni_2d = comp.recombination.coefficients.ni_sq_m6.reshape(shape) + wx_trap = trapezoid_weights_1d(comp.geometry.x_m) + for spec in d.radiative_reabsorption: + y_slice = slice(spec.y_start, spec.y_stop) + emission = b_2d[y_slice, :] * (n_2d[y_slice, :] * p_2d[y_slice, :] - ni_2d[y_slice, :]) + r_tot = float(np.trapezoid(np.trapezoid(emission, comp.geometry.y_geometry.nodes_m[y_slice], axis=0), + comp.geometry.x_m)) + if r_tot <= 0.0: + continue + wy_trap = trapezoid_weights_1d(comp.geometry.y_geometry.nodes_m[y_slice]) + quad_w = (wy_trap[:, None] * wx_trap[None, :]).ravel() + abs_nodes = (np.arange(spec.y_start, spec.y_stop, dtype=np.intp)[:, None] * comp.geometry.nx + + np.arange(comp.geometry.nx, dtype=np.intp)[None, :]).ravel() + # d(n*p)/dphi == 0 identically; d(n*p)/dz_n = +n*p; d(n*p)/dz_p = -n*p + grad_zn = (1.0 - spec.escape_probability) / spec.area_m2 * quad_w * b_2d[y_slice, :].ravel() * ( + n_2d[y_slice, :].ravel() * p_2d[y_slice, :].ravel() + ) + row_areas = vol[abs_nodes] + rr: NDArray[np.intp] + cc: NDArray[np.intp] + rr, cc = np.meshgrid(abs_nodes, abs_nodes, indexing="ij") + outer = row_areas[:, None] * grad_zn[None, :] + for offset in (count, 2 * count): + emit(offset + rr, count + cc, outer) + emit(offset + rr, 2 * count + cc, -outer) + + # Optional clamp-passive two-sided cross-node interface SRH derivatives + if d.interface_srh_couplings: + shape = comp.geometry.shape + nx = comp.geometry.nx + n_2d, p_2d = n.reshape(shape), p.reshape(shape) + normal_widths = trapezoid_weights_1d(comp.geometry.y_geometry.nodes_m) + cols_x: NDArray[np.intp] = np.arange(nx, dtype=np.intp) + for c in d.interface_srh_couplings: + row_nodes: NDArray[np.intp] = c.interface_row * nx + cols_x + left_nodes: NDArray[np.intp] = c.left_sample_row * nx + cols_x + right_nodes: NDArray[np.intp] = c.right_sample_row * nx + cols_x + scale = vol[row_nodes] / normal_widths[c.interface_row] + + raw_a, da_dn, da_dp = _interface_srh_sheet_rate_and_partials( + n_2d[c.right_sample_row, :], p_2d[c.left_sample_row, :], + c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + act_a = (raw_a > 0.0).astype(float) + # Sink enters carrier row with minus sign (-sink * area) + dn_r = -scale * act_a * da_dn * n_2d[c.right_sample_row, :] + dp_l = -scale * act_a * da_dp * p_2d[c.left_sample_row, :] + + raw_b, db_dn, db_dp = _interface_srh_sheet_rate_and_partials( + n_2d[c.left_sample_row, :], p_2d[c.right_sample_row, :], + c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, + c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, + ) + act_b = (raw_b > 0.0).astype(float) + dn_l = -scale * act_b * db_dn * n_2d[c.left_sample_row, :] + dp_r = -scale * act_b * db_dp * p_2d[c.right_sample_row, :] + + for offset in (count, 2 * count): + emit(offset + row_nodes, right_nodes, (dn_r - dp_r) / thermal) + emit(offset + row_nodes, count + right_nodes, dn_r) + emit(offset + row_nodes, 2 * count + right_nodes, -dp_r) + emit(offset + row_nodes, left_nodes, (dn_l - dp_l) / thermal) + emit(offset + row_nodes, count + left_nodes, dn_l) + emit(offset + row_nodes, 2 * count + left_nodes, -dp_l) + + # 3. Positive-ion 4-side-blocking face divergence derivatives + ion_eval = self.ion_flux_evaluation(values) + ion_geom = d.ion_geometry.contract_geometry + i_left, i_right = ion_geom.pairs[:, 0], ion_geom.pairs[:, 1] + i_fm = ion_geom.face_measures + e_left = d.ion_node_indices[i_left] + e_right = d.ion_node_indices[i_right] + ion_offset = 3 * count + y_left = ion_eval.density_left_derivative * dp_dy[i_left] + y_right = ion_eval.density_right_derivative * dp_dy[i_right] + emit(ion_offset + i_left, e_left, -i_fm * ion_eval.potential_left_derivative) + emit(ion_offset + i_left, e_right, -i_fm * ion_eval.potential_right_derivative) + emit(ion_offset + i_left, ion_offset + i_left, -i_fm * y_left) + emit(ion_offset + i_left, ion_offset + i_right, -i_fm * y_right) + emit(ion_offset + i_right, e_left, i_fm * ion_eval.potential_left_derivative) + emit(ion_offset + i_right, e_right, i_fm * ion_eval.potential_right_derivative) + emit(ion_offset + i_right, ion_offset + i_left, i_fm * y_left) + emit(ion_offset + i_right, ion_offset + i_right, i_fm * y_right) + + # Zero replaced Dirichlet / fixed-reservoir rows and insert exact constraints + constraint_mask: NDArray[np.bool_] = np.zeros(d.state_size, dtype=bool) + contact_nodes = comp.geometry.contact_nodes.astype(np.intp) + constraint_mask[contact_nodes] = True + fixed_mask = comp.fixed_carrier_mask + constraint_mask[count:2 * count] = fixed_mask[0] + constraint_mask[2 * count:3 * count] = fixed_mask[1] + + all_r = np.concatenate(row_chunks) + all_c = np.concatenate(col_chunks) + all_v = np.concatenate(val_chunks) + keep = ~constraint_mask[all_r] + kept_r = [all_r[keep], contact_nodes] + kept_c = [all_c[keep], contact_nodes] + kept_v = [all_v[keep], np.ones(contact_nodes.size, dtype=float)] + for offset, sign, mask_row in ((count, 1.0, fixed_mask[0]), (2 * count, -1.0, fixed_mask[1])): + c_nodes = nodes[mask_row] + kept_r.extend((offset + c_nodes, offset + c_nodes)) + kept_c.extend((c_nodes, offset + c_nodes)) + kept_v.extend((np.full(c_nodes.size, sign / thermal), np.full(c_nodes.size, sign))) + + return csc_matrix( + (np.concatenate(kept_v), (np.concatenate(kept_r), np.concatenate(kept_c))), + shape=(d.state_size, d.state_size), + ) diff --git a/src/solarlab/experiments/two_dimensional/jv_protocol_2d.py b/src/solarlab/experiments/two_dimensional/jv_protocol_2d.py new file mode 100644 index 00000000..a40c048d --- /dev/null +++ b/src/solarlab/experiments/two_dimensional/jv_protocol_2d.py @@ -0,0 +1,787 @@ +"""Canonical execution protocols for 2D J-V dwell sweeps and dynamic forward/reverse pairs. + +Provides legacy-free protocol declarations, SHA-256 canonical JSON hashing, strict +key/type validation, ``compatibility`` vs ``research_strict`` resolution, and +explicit forward/reverse dynamic scan state-chain protocols. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +import dataclasses +from dataclasses import dataclass +import hashlib +import json +from numbers import Integral, Real +from typing import Any, Literal, Self, TypeAlias + +import numpy as np + +from solarlab.experiments.two_dimensional.inputs import ( + ComponentwiseAtolInput, + JV2DAtolInput, + JV2DProtocolInput, +) + +__all__ = [ + "AbsoluteToleranceSpec", + "ComponentwiseAtolSpec", + "DYNAMIC_JV_PAIR_2D_SCHEMA", + "DynamicJVPairProtocol2D", + "ImplicitProtocolError", + "JV2DAtolProtocol", + "JV2DGrainBoundaryProtocol", + "JV2DProtocol", + "JV2D_PROTOCOL_SCHEMA", + "ProtocolError", + "ProtocolMismatchError", + "ProtocolMode", + "build_jv_2d_protocol", + "resolve_jv_2d_protocol", +] + +JV2D_PROTOCOL_SCHEMA: Literal["jv-2d-execution-protocol-v1"] = "jv-2d-execution-protocol-v1" +DYNAMIC_JV_PAIR_2D_SCHEMA: Literal["jv-2d-dynamic-pair-protocol-v1"] = "jv-2d-dynamic-pair-protocol-v1" +ProtocolMode: TypeAlias = Literal["compatibility", "research_strict"] + + +class ProtocolError(ValueError): + """Base error for 2D execution protocol validation or binding failures.""" + + +class ImplicitProtocolError(ProtocolError): + """Raised when ``research_strict`` execution lacks an explicit protocol.""" + + +class ProtocolMismatchError(ProtocolError): + """Raised when a supplied protocol disagrees with effective execution controls.""" + + +def _finite(value: object, field: str) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): + raise TypeError(f"{field} must be a real number") + number = float(value) + if not np.isfinite(number): + raise ValueError(f"{field} must be finite") + return number + + +def _positive(value: object, field: str) -> float: + number = _finite(value, field) + if number <= 0.0: + raise ValueError(f"{field} must be positive") + return number + + +def _nonnegative(value: object, field: str) -> float: + number = _finite(value, field) + if number < 0.0: + raise ValueError(f"{field} must be non-negative") + return number + + +def _positive_integer(value: object, field: str) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral): + raise TypeError(f"{field} must be an integer") + integer = int(value) + if integer < 1: + raise ValueError(f"{field} must be positive") + return integer + + +def _nonnegative_integer(value: object, field: str) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral): + raise TypeError(f"{field} must be an integer") + integer = int(value) + if integer < 0: + raise ValueError(f"{field} must be non-negative") + return integer + + +def _strict_keys(payload: Mapping[str, Any], cls: type[Any]) -> None: + expected = {f.name for f in dataclasses.fields(cls)} + actual = set(payload) + if actual != expected: + raise ValueError( + f"{cls.__name__} keys do not match schema; " + f"missing={sorted(expected - actual)}, extra={sorted(actual - expected)}" + ) + + +def _finite_tuple(values: object, field: str, *, minimum_size: int) -> tuple[float, ...]: + if isinstance(values, (str, bytes)) or not isinstance(values, Iterable): + raise TypeError(f"{field} must be an iterable of real numbers") + result = tuple(_finite(v, f"{field}[{idx}]") for idx, v in enumerate(values)) + if len(result) < minimum_size: + raise ValueError(f"{field} must contain at least {minimum_size} values") + return result + + +@dataclass(frozen=True, slots=True) +class ComponentwiseAtolSpec: + """Componentwise absolute tolerance ratios for 2D transient states.""" + + carrier_fraction: float = 1.0e-4 + ion_fraction: float = 1.0e-4 + interface_fraction: float = 1.0e-4 + minimum_atol: float = 1.0e6 + refinement_factor: float = 1.0 + + def __post_init__(self) -> None: + for name in ( + "carrier_fraction", + "ion_fraction", + "interface_fraction", + "minimum_atol", + "refinement_factor", + ): + object.__setattr__(self, name, _positive(getattr(self, name), name)) + + +AbsoluteToleranceSpec: TypeAlias = float | ComponentwiseAtolSpec + + +@dataclass(frozen=True, slots=True) +class JV2DAtolProtocol: + """JSON-stable scalar or componentwise absolute-tolerance declaration.""" + + mode: Literal["scalar", "componentwise"] + scalar_atol: float | None + carrier_fraction: float | None + ion_fraction: float | None + interface_fraction: float | None + minimum_atol: float | None + refinement_factor: float | None + + def __post_init__(self) -> None: + component_fields = ( + "carrier_fraction", + "ion_fraction", + "interface_fraction", + "minimum_atol", + "refinement_factor", + ) + if self.mode == "scalar": + if self.scalar_atol is None: + raise ValueError("scalar atol mode requires scalar_atol") + object.__setattr__(self, "scalar_atol", _positive(self.scalar_atol, "scalar_atol")) + if any(getattr(self, name) is not None for name in component_fields): + raise ValueError("scalar atol mode cannot carry componentwise fields") + return + if self.mode != "componentwise": + raise ValueError(f"unsupported 2D atol mode {self.mode!r}") + if self.scalar_atol is not None: + raise ValueError("componentwise atol mode cannot carry scalar_atol") + for name in component_fields: + val = getattr(self, name) + if val is None: + raise ValueError(f"componentwise atol mode requires {name}") + object.__setattr__(self, name, _positive(val, name)) + + @classmethod + def from_absolute_tolerance(cls, value: object) -> Self: + if isinstance(value, cls): + return value + if isinstance(value, JV2DAtolInput): + norm = value.normalized_data() + return cls( + mode=norm["mode"], + scalar_atol=norm.get("scalar_atol"), + carrier_fraction=norm.get("carrier_fraction"), + ion_fraction=norm.get("ion_fraction"), + interface_fraction=norm.get("interface_fraction"), + minimum_atol=norm.get("minimum_atol"), + refinement_factor=norm.get("refinement_factor"), + ) + if isinstance(value, ComponentwiseAtolInput): + norm = value.normalized_data() + return cls( + mode="componentwise", + scalar_atol=None, + carrier_fraction=norm["carrier_fraction"], + ion_fraction=norm["ion_fraction"], + interface_fraction=norm["interface_fraction"], + minimum_atol=norm["minimum_atol"], + refinement_factor=norm["refinement_factor"], + ) + if isinstance(value, ComponentwiseAtolSpec) or all( + hasattr(value, attr) + for attr in ( + "carrier_fraction", + "ion_fraction", + "interface_fraction", + "minimum_atol", + "refinement_factor", + ) + ): + return cls( + mode="componentwise", + scalar_atol=None, + carrier_fraction=getattr(value, "carrier_fraction"), + ion_fraction=getattr(value, "ion_fraction"), + interface_fraction=getattr(value, "interface_fraction"), + minimum_atol=getattr(value, "minimum_atol"), + refinement_factor=getattr(value, "refinement_factor"), + ) + return cls( + mode="scalar", + scalar_atol=_positive(value, "atol"), + carrier_fraction=None, + ion_fraction=None, + interface_fraction=None, + minimum_atol=None, + refinement_factor=None, + ) + + def to_absolute_tolerance(self) -> AbsoluteToleranceSpec: + if self.mode == "scalar": + assert self.scalar_atol is not None + return self.scalar_atol + assert self.carrier_fraction is not None + assert self.ion_fraction is not None + assert self.interface_fraction is not None + assert self.minimum_atol is not None + assert self.refinement_factor is not None + return ComponentwiseAtolSpec( + carrier_fraction=self.carrier_fraction, + ion_fraction=self.ion_fraction, + interface_fraction=self.interface_fraction, + minimum_atol=self.minimum_atol, + refinement_factor=self.refinement_factor, + ) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("JV2DAtolProtocol must be a mapping") + _strict_keys(payload, cls) + return cls(**dict(payload)) + + +@dataclass(frozen=True, slots=True) +class JV2DGrainBoundaryProtocol: + """Physical grain-boundary geometry and SRH lifetime declaration.""" + + x_position_m: float + width_m: float + tau_n_s: float + tau_p_s: float + layer_role: str + + def __post_init__(self) -> None: + object.__setattr__( + self, "x_position_m", _finite(self.x_position_m, "grain boundary x_position_m") + ) + for name in ("width_m", "tau_n_s", "tau_p_s"): + object.__setattr__( + self, name, _positive(getattr(self, name), f"grain boundary {name}") + ) + if not isinstance(self.layer_role, str) or not self.layer_role.strip(): + raise ValueError("grain boundary layer_role must be non-empty") + + @classmethod + def from_declaration(cls, value: object, *, default_layer_role: str = "absorber") -> Self: + if isinstance(value, cls): + return value + if isinstance(value, Mapping): + if "x_position_m" in value: + return cls.from_dict(value) + return cls( + x_position_m=float(value["x_position"]), + width_m=float(value["width"]), + tau_n_s=float(value["tau_n"]), + tau_p_s=float(value["tau_p"]), + layer_role=str(value.get("layer_role", default_layer_role)), + ) + if all(hasattr(value, k) for k in ("x_position", "width", "tau_n", "tau_p")): + return cls( + x_position_m=float(getattr(value, "x_position")), + width_m=float(getattr(value, "width")), + tau_n_s=float(getattr(value, "tau_n")), + tau_p_s=float(getattr(value, "tau_p")), + layer_role=str(getattr(value, "layer_role", default_layer_role)), + ) + raise TypeError(f"unsupported grain boundary declaration {type(value)!r}") + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("JV2DGrainBoundaryProtocol must be a mapping") + _strict_keys(payload, cls) + return cls(**dict(payload)) + + +@dataclass(frozen=True, slots=True) +class JV2DProtocol: + """Physical history, topology, mesh, and numerical policy for one 2D J-V sweep.""" + + temperature_K: float + illuminated: bool + illumination_source: str | None + initial_state_source: Literal[ + "one_dimensional_illuminated_finite_time", + "one_dimensional_dark_equilibrium", + ] + initial_state_voltage_V: float + initial_state_settle_s: float | None + voltage_values_V: tuple[float, ...] + dwell_time_per_voltage_s: float + state_topology: Literal["frozen_ion_background", "single_positive_mobile_ion"] + ion_boundary_condition: Literal["frozen", "blocking"] + carrier_boundary_condition: Literal["ohmic", "selective_robin"] + interface_srh: Literal["off", "two_sided_cross_node"] + lateral_bc: Literal["periodic", "neumann"] + x_coordinates_m: tuple[float, ...] + y_coordinates_m: tuple[float, ...] + grain_boundaries: tuple[JV2DGrainBoundaryProtocol, ...] + current_composition: Literal[ + "electron_hole_conduction", + "electron_hole_positive_ion_displacement", + ] + current_sampling: Literal["instantaneous_dwell_endpoint"] + applied_voltage_rate_at_sampling_V_s: float + solver_method: Literal["Radau", "backward_euler"] + solver_rtol: float + solver_atol: JV2DAtolProtocol + solver_max_step_divisor: int + max_nfev_per_solve: int + max_bisect: int + ion_inventory_rtol: float + save_snapshots: bool + implicit_legacy_protocol: bool = False + schema_version: Literal["jv-2d-execution-protocol-v1"] = JV2D_PROTOCOL_SCHEMA + + def __post_init__(self) -> None: + object.__setattr__(self, "temperature_K", _positive(self.temperature_K, "temperature_K")) + if not isinstance(self.illuminated, bool): + raise TypeError("illuminated must be boolean") + if self.illuminated: + if not isinstance(self.illumination_source, str) or not self.illumination_source.strip(): + raise ValueError("illuminated 2D J-V requires illumination_source") + if self.initial_state_source != "one_dimensional_illuminated_finite_time": + raise ValueError("illuminated 2D J-V requires illuminated 1D initial state") + if self.initial_state_settle_s is None: + raise ValueError("illuminated 1D initial state requires settle time") + object.__setattr__( + self, + "initial_state_settle_s", + _positive(self.initial_state_settle_s, "initial_state_settle_s"), + ) + else: + if self.illumination_source is not None: + raise ValueError("dark 2D J-V cannot carry illumination_source") + if self.initial_state_source != "one_dimensional_dark_equilibrium": + raise ValueError("dark 2D J-V requires dark-equilibrium initial state") + if self.initial_state_settle_s is not None: + raise ValueError("dark-equilibrium initial state has no settle time") + + object.__setattr__( + self, + "initial_state_voltage_V", + _finite(self.initial_state_voltage_V, "initial_state_voltage_V"), + ) + if self.initial_state_voltage_V != 0.0: + raise ValueError("2D J-V v1 initial state voltage must be 0 V") + + voltages = _finite_tuple(self.voltage_values_V, "voltage_values_V", minimum_size=1) + if voltages[0] != 0.0 or any(right <= left for left, right in zip(voltages, voltages[1:])): + raise ValueError("voltage_values_V must start at 0 and increase") + object.__setattr__(self, "voltage_values_V", voltages) + object.__setattr__( + self, + "dwell_time_per_voltage_s", + _positive(self.dwell_time_per_voltage_s, "dwell_time_per_voltage_s"), + ) + + x = _finite_tuple(self.x_coordinates_m, "x_coordinates_m", minimum_size=2) + y = _finite_tuple(self.y_coordinates_m, "y_coordinates_m", minimum_size=3) + if any(right <= left for left, right in zip(x, x[1:])): + raise ValueError("x_coordinates_m must be strictly increasing") + if any(right <= left for left, right in zip(y, y[1:])): + raise ValueError("y_coordinates_m must be strictly increasing") + object.__setattr__(self, "x_coordinates_m", x) + object.__setattr__(self, "y_coordinates_m", y) + + boundaries = tuple(self.grain_boundaries) + if not all(isinstance(item, JV2DGrainBoundaryProtocol) for item in boundaries): + raise TypeError("grain_boundaries must contain JV2DGrainBoundaryProtocol values") + object.__setattr__(self, "grain_boundaries", boundaries) + + if self.lateral_bc not in {"periodic", "neumann"}: + raise ValueError(f"unsupported lateral_bc {self.lateral_bc!r}") + if boundaries and self.lateral_bc != "neumann": + raise ValueError("grain boundaries require Neumann-x topology") + if self.interface_srh not in {"off", "two_sided_cross_node"}: + raise ValueError(f"unsupported interface_srh {self.interface_srh!r}") + if self.interface_srh != "off" and self.lateral_bc != "neumann": + raise ValueError("two-sided interface SRH requires Neumann-x topology") + if self.carrier_boundary_condition not in {"ohmic", "selective_robin"}: + raise ValueError("carrier_boundary_condition must be 'ohmic' or 'selective_robin'") + if self.interface_srh != "off" and self.carrier_boundary_condition != "ohmic": + raise ValueError("two-sided interface-SRH J-V requires ohmic contacts") + + if self.state_topology == "single_positive_mobile_ion": + if self.ion_boundary_condition != "blocking": + raise ValueError("mobile-ion 2D J-V requires blocking ion boundaries") + if self.lateral_bc != "neumann": + raise ValueError("mobile-ion 2D J-V requires Neumann-x topology") + if self.carrier_boundary_condition != "ohmic": + raise ValueError("mobile-ion 2D J-V requires ohmic contacts") + expected_current = "electron_hole_positive_ion_displacement" + elif self.state_topology == "frozen_ion_background": + if self.ion_boundary_condition != "frozen": + raise ValueError("frozen-ion topology requires frozen ion boundary label") + expected_current = "electron_hole_conduction" + else: + raise ValueError(f"unsupported state_topology {self.state_topology!r}") + if self.current_composition != expected_current: + raise ValueError("current_composition does not match the declared state topology") + if self.current_sampling != "instantaneous_dwell_endpoint": + raise ValueError("unsupported 2D current sampling mode") + object.__setattr__( + self, + "applied_voltage_rate_at_sampling_V_s", + _finite(self.applied_voltage_rate_at_sampling_V_s, "applied_voltage_rate_at_sampling_V_s"), + ) + if self.applied_voltage_rate_at_sampling_V_s != 0.0: + raise ValueError("fixed-voltage dwell endpoint must have dV/dt = 0") + + if self.solver_method not in {"Radau", "backward_euler"}: + raise ValueError("2D J-V v1 supports only 'Radau' or 'backward_euler'") + object.__setattr__(self, "solver_rtol", _positive(self.solver_rtol, "solver_rtol")) + if not isinstance(self.solver_atol, JV2DAtolProtocol): + raise TypeError("solver_atol must be JV2DAtolProtocol") + object.__setattr__( + self, + "solver_max_step_divisor", + _positive_integer(self.solver_max_step_divisor, "solver_max_step_divisor"), + ) + object.__setattr__( + self, + "max_nfev_per_solve", + _positive_integer(self.max_nfev_per_solve, "max_nfev_per_solve"), + ) + object.__setattr__( + self, + "max_bisect", + _nonnegative_integer(self.max_bisect, "max_bisect"), + ) + object.__setattr__( + self, + "ion_inventory_rtol", + _nonnegative(self.ion_inventory_rtol, "ion_inventory_rtol"), + ) + for name in ("save_snapshots", "implicit_legacy_protocol"): + if not isinstance(getattr(self, name), bool): + raise TypeError(f"{name} must be boolean") + if self.schema_version != JV2D_PROTOCOL_SCHEMA: + raise ValueError("unsupported 2D J-V protocol schema") + + def to_dict(self) -> dict[str, Any]: + payload = dataclasses.asdict(self) + payload["voltage_values_V"] = list(self.voltage_values_V) + payload["x_coordinates_m"] = list(self.x_coordinates_m) + payload["y_coordinates_m"] = list(self.y_coordinates_m) + payload["grain_boundaries"] = [dataclasses.asdict(item) for item in self.grain_boundaries] + return payload + + def canonical_json(self) -> str: + return json.dumps( + self.to_dict(), + allow_nan=False, + ensure_ascii=True, + separators=(",", ":"), + sort_keys=True, + ) + + @property + def protocol_hash(self) -> str: + return hashlib.sha256(self.canonical_json().encode("ascii")).hexdigest() + + @property + def sha256(self) -> str: + return self.protocol_hash + + def as_explicit(self) -> Self: + return dataclasses.replace(self, implicit_legacy_protocol=False) + + @classmethod + def from_protocol_input(cls, inp: JV2DProtocolInput) -> Self: + if not isinstance(inp, JV2DProtocolInput): + raise TypeError("JV2DProtocolInput is required") + return cls.from_dict(inp.normalized_data()) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("2D J-V protocol must be a mapping") + _strict_keys(payload, cls) + values = dict(payload) + for name in ("voltage_values_V", "x_coordinates_m", "y_coordinates_m"): + values[name] = tuple(values[name]) + boundaries = values["grain_boundaries"] + if not isinstance(boundaries, (list, tuple)): + raise TypeError("grain_boundaries must be a JSON array") + values["grain_boundaries"] = tuple( + JV2DGrainBoundaryProtocol.from_dict(item) for item in boundaries + ) + values["solver_atol"] = JV2DAtolProtocol.from_dict(values["solver_atol"]) + return cls(**values) + + @classmethod + def from_json(cls, payload: str) -> Self: + parsed = json.loads(payload) + if not isinstance(parsed, Mapping): + raise TypeError("2D J-V protocol JSON must contain an object") + return cls.from_dict(parsed) + + +@dataclass(frozen=True, slots=True) +class DynamicJVPairProtocol2D: + """Explicit 2D preconditioning/hold + forward/reverse dynamic scan state-chain protocol.""" + + temperature_K: float + illuminated: bool + precondition_voltage_V: float + precondition_hold_s: float + forward_voltages_V: tuple[float, ...] + turnaround_hold_s: float + reverse_voltages_V: tuple[float, ...] + step_mode: Literal["dwell", "linear_ramp"] + dwell_or_step_time_s: float + state_topology: Literal["frozen_ion_background", "single_positive_mobile_ion"] + lateral_bc: Literal["periodic", "neumann"] + carrier_boundary_condition: Literal["ohmic", "selective_robin"] + interface_srh: Literal["off", "two_sided_cross_node"] + x_coordinates_m: tuple[float, ...] + y_coordinates_m: tuple[float, ...] + grain_boundaries: tuple[JV2DGrainBoundaryProtocol, ...] + substeps_per_point: int = 12 + ion_inventory_rtol: float = 1.0e-9 + save_snapshots: bool = False + schema_version: Literal["jv-2d-dynamic-pair-protocol-v1"] = DYNAMIC_JV_PAIR_2D_SCHEMA + + def __post_init__(self) -> None: + object.__setattr__(self, "temperature_K", _positive(self.temperature_K, "temperature_K")) + if not isinstance(self.illuminated, bool): + raise TypeError("illuminated must be boolean") + object.__setattr__( + self, "precondition_voltage_V", _finite(self.precondition_voltage_V, "precondition_voltage_V") + ) + object.__setattr__( + self, "precondition_hold_s", _nonnegative(self.precondition_hold_s, "precondition_hold_s") + ) + fwd = _finite_tuple(self.forward_voltages_V, "forward_voltages_V", minimum_size=2) + rev = _finite_tuple(self.reverse_voltages_V, "reverse_voltages_V", minimum_size=2) + fwd_diffs: np.ndarray = np.diff(np.asarray(fwd, dtype=np.float64)) + rev_diffs: np.ndarray = np.diff(np.asarray(rev, dtype=np.float64)) + if not (np.all(fwd_diffs > 0.0) or np.all(fwd_diffs < 0.0)): + raise ValueError("forward_voltages_V must be strictly monotonic") + if not (np.all(rev_diffs > 0.0) or np.all(rev_diffs < 0.0)): + raise ValueError("reverse_voltages_V must be strictly monotonic") + if (fwd_diffs[0] > 0.0) == (rev_diffs[0] > 0.0): + raise ValueError("reverse_voltages_V must reverse the forward scan direction") + if abs(rev[0] - fwd[-1]) > 1.0e-12: + raise ValueError("reverse_voltages_V must start at forward_voltages_V[-1] to preserve state continuity") + object.__setattr__(self, "forward_voltages_V", fwd) + object.__setattr__(self, "reverse_voltages_V", rev) + object.__setattr__( + self, "turnaround_hold_s", _nonnegative(self.turnaround_hold_s, "turnaround_hold_s") + ) + if self.step_mode not in {"dwell", "linear_ramp"}: + raise ValueError("step_mode must be 'dwell' or 'linear_ramp'") + object.__setattr__( + self, "dwell_or_step_time_s", _positive(self.dwell_or_step_time_s, "dwell_or_step_time_s") + ) + + x = _finite_tuple(self.x_coordinates_m, "x_coordinates_m", minimum_size=2) + y = _finite_tuple(self.y_coordinates_m, "y_coordinates_m", minimum_size=3) + if any(right <= left for left, right in zip(x, x[1:])) or any( + right <= left for left, right in zip(y, y[1:]) + ): + raise ValueError("x_coordinates_m and y_coordinates_m must be strictly increasing") + object.__setattr__(self, "x_coordinates_m", x) + object.__setattr__(self, "y_coordinates_m", y) + + boundaries = tuple(self.grain_boundaries) + if not all(isinstance(item, JV2DGrainBoundaryProtocol) for item in boundaries): + raise TypeError("grain_boundaries must contain JV2DGrainBoundaryProtocol values") + object.__setattr__(self, "grain_boundaries", boundaries) + + mobile = self.state_topology == "single_positive_mobile_ion" + if (boundaries or mobile or self.interface_srh != "off") and self.lateral_bc != "neumann": + raise ValueError("grain, mobile-ion, or two-sided SRH dynamic scan requires Neumann-x") + if (mobile or self.interface_srh != "off") and self.carrier_boundary_condition != "ohmic": + raise ValueError("mobile-ion or two-sided SRH dynamic scan requires ohmic contacts") + object.__setattr__( + self, "substeps_per_point", _positive_integer(self.substeps_per_point, "substeps_per_point") + ) + object.__setattr__( + self, "ion_inventory_rtol", _nonnegative(self.ion_inventory_rtol, "ion_inventory_rtol") + ) + if not isinstance(self.save_snapshots, bool): + raise TypeError("save_snapshots must be boolean") + if self.schema_version != DYNAMIC_JV_PAIR_2D_SCHEMA: + raise ValueError("unsupported 2D dynamic pair protocol schema") + + def to_dict(self) -> dict[str, Any]: + payload = dataclasses.asdict(self) + payload["forward_voltages_V"] = list(self.forward_voltages_V) + payload["reverse_voltages_V"] = list(self.reverse_voltages_V) + payload["x_coordinates_m"] = list(self.x_coordinates_m) + payload["y_coordinates_m"] = list(self.y_coordinates_m) + payload["grain_boundaries"] = [dataclasses.asdict(item) for item in self.grain_boundaries] + return payload + + def canonical_json(self) -> str: + return json.dumps( + self.to_dict(), + allow_nan=False, + ensure_ascii=True, + separators=(",", ":"), + sort_keys=True, + ) + + @property + def protocol_hash(self) -> str: + return hashlib.sha256(self.canonical_json().encode("ascii")).hexdigest() + + @property + def sha256(self) -> str: + return self.protocol_hash + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("DynamicJVPairProtocol2D must be a mapping") + _strict_keys(payload, cls) + values = dict(payload) + for name in ("forward_voltages_V", "reverse_voltages_V", "x_coordinates_m", "y_coordinates_m"): + values[name] = tuple(values[name]) + values["grain_boundaries"] = tuple( + JV2DGrainBoundaryProtocol.from_dict(item) for item in values["grain_boundaries"] + ) + return cls(**values) + + @classmethod + def from_json(cls, payload: str) -> Self: + parsed = json.loads(payload) + if not isinstance(parsed, Mapping): + raise TypeError("DynamicJVPairProtocol2D JSON must contain an object") + return cls.from_dict(parsed) + + +def build_jv_2d_protocol( + *, + temperature_K: float, + illuminated: bool, + x_coordinates_m: Iterable[float], + y_coordinates_m: Iterable[float], + voltages_V: Iterable[float], + dwell_time_per_voltage_s: float, + ion_dynamics: Literal["frozen", "single_mobile"], + carrier_boundary_condition: Literal["ohmic", "selective_robin"], + interface_srh: Literal["off", "two_sided_cross_node"], + lateral_bc: Literal["periodic", "neumann"], + solver_rtol: float, + solver_atol: object, + max_nfev_per_solve: int, + max_bisect: int, + ion_inventory_rtol: float, + save_snapshots: bool, + grain_boundaries: Iterable[object] = (), + initial_state_settle_s: float = 1.0e-3, + solver_method: Literal["Radau", "backward_euler"] = "Radau", + solver_max_step_divisor: int = 50, + implicit_legacy_protocol: bool = False, +) -> JV2DProtocol: + """Build the canonical 2D J-V protocol declaration.""" + if ion_dynamics not in {"frozen", "single_mobile"}: + raise ValueError("ion_dynamics must be 'frozen' or 'single_mobile'") + state_topology: Literal["frozen_ion_background", "single_positive_mobile_ion"] = ( + "single_positive_mobile_ion" if ion_dynamics == "single_mobile" else "frozen_ion_background" + ) + return JV2DProtocol( + temperature_K=temperature_K, + illuminated=illuminated, + illumination_source=("stack_baseline_generation" if illuminated else None), + initial_state_source=( + "one_dimensional_illuminated_finite_time" + if illuminated + else "one_dimensional_dark_equilibrium" + ), + initial_state_voltage_V=0.0, + initial_state_settle_s=(initial_state_settle_s if illuminated else None), + voltage_values_V=tuple(float(v) for v in voltages_V), + dwell_time_per_voltage_s=dwell_time_per_voltage_s, + state_topology=state_topology, + ion_boundary_condition=("blocking" if ion_dynamics == "single_mobile" else "frozen"), + carrier_boundary_condition=carrier_boundary_condition, + interface_srh=interface_srh, + lateral_bc=lateral_bc, + x_coordinates_m=tuple(float(v) for v in x_coordinates_m), + y_coordinates_m=tuple(float(v) for v in y_coordinates_m), + grain_boundaries=tuple( + JV2DGrainBoundaryProtocol.from_declaration(item) for item in grain_boundaries + ), + current_composition=( + "electron_hole_positive_ion_displacement" + if ion_dynamics == "single_mobile" + else "electron_hole_conduction" + ), + current_sampling="instantaneous_dwell_endpoint", + applied_voltage_rate_at_sampling_V_s=0.0, + solver_method=solver_method, + solver_rtol=solver_rtol, + solver_atol=JV2DAtolProtocol.from_absolute_tolerance(solver_atol), + solver_max_step_divisor=solver_max_step_divisor, + max_nfev_per_solve=max_nfev_per_solve, + max_bisect=max_bisect, + ion_inventory_rtol=ion_inventory_rtol, + save_snapshots=save_snapshots, + implicit_legacy_protocol=implicit_legacy_protocol, + ) + + +def resolve_jv_2d_protocol( + supplied: JV2DProtocol | JV2DProtocolInput | None, + expected_legacy: JV2DProtocol, + *, + mode: ProtocolMode, +) -> JV2DProtocol: + """Bind a supplied 2D J-V protocol declaration to exact execution controls.""" + if mode not in {"compatibility", "research_strict"}: + raise ValueError(f"unsupported 2D J-V protocol mode {mode!r}") + if not isinstance(expected_legacy, JV2DProtocol): + raise TypeError("expected_legacy must be a JV2DProtocol") + if not expected_legacy.implicit_legacy_protocol: + raise ValueError("expected_legacy must be marked implicit") + + converted: JV2DProtocol | None + if isinstance(supplied, JV2DProtocolInput): + converted = JV2DProtocol.from_protocol_input(supplied) + else: + converted = supplied + + resolved = expected_legacy if converted is None else converted + if not isinstance(resolved, JV2DProtocol): + raise TypeError("jv_2d_protocol must be a JV2DProtocol") + if converted is not None: + expected = expected_legacy.to_dict() + actual = converted.to_dict() + expected.pop("implicit_legacy_protocol") + actual.pop("implicit_legacy_protocol") + # Allow explicit solver_method="backward_euler" when matching native BE execution + if actual.get("solver_method") == "backward_euler" and expected.get("solver_method") == "Radau": + expected["solver_method"] = "backward_euler" + mismatches = tuple(name for name in sorted(expected) if actual[name] != expected[name]) + if mismatches: + raise ProtocolMismatchError( + "jv_2d_protocol does not match the requested execution; " + f"mismatched fields: {', '.join(mismatches)}" + ) + if mode == "research_strict" and resolved.implicit_legacy_protocol: + raise ImplicitProtocolError( + "research_strict 2D J-V requires an explicit execution protocol" + ) + return resolved diff --git a/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py b/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py new file mode 100644 index 00000000..aa022a10 --- /dev/null +++ b/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py @@ -0,0 +1,1557 @@ +"""Native 2D J-V dwell sweeps and forward/reverse dynamic state-chain scans. + +Executes 2D J-V protocols on ``solarlab``'s unified sparse 2D ``Assembler`` and +conservative Backward Euler steppers (``run_backward_euler_2d`` for +``frozen_ion_background`` and ``run_ionic_backward_euler_2d`` for +``single_positive_mobile_ion``), with: +- 1D dark-equilibrium or finite-time illuminated preconditioning (freezing + equilibrated ``P_1d`` on ``frozen_ion_background`` ionic stacks), +- instantaneous Maxwell port current decomposition (carrier + ion + true + Gauss-Maxwell displacement ``dD_y/dt``), +- explicit failure / partial result disposition (never seeding from a failed + state or silently dropping physics), +- continuous preconditioning/hold + forward/reverse dynamic scan state chains, +- lossless JSON serialization with ``scientific_qualification=False``. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import asdict, dataclass, field, replace +import hashlib +import json +import math +from pathlib import Path +import time +from typing import Any, Literal, TypeAlias, cast + +import numpy as np +from numpy.typing import NDArray + +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_1d import ION_INPUTS, compile_ionic_device_1d +from solarlab.device.compile_ionic_2d import ( + build_radiative_reabsorption_2d, + build_two_sided_interface_srh_2d, + compile_ionic_device_2d, +) +from solarlab.device.grain_2d import grain_declarations +from solarlab.device.inputs import DeviceInput, GrainBoundaryInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dc_2d import CompiledDevice2D, DC2DProblem, State2D +from solarlab.equations.ionic_2d import ( + CompiledIonicDevice2D, + IonicState2D, + MobileIonDiagnostics2D, + RadiativeReabsorptionSpec2D, + TwoSidedInterfaceSRHCoupling2D, + TwoSidedInterfaceSRHReport2D, + assess_mobile_ion_terminal_2d, + evaluate_two_sided_interface_srh_2d, + recompute_g_with_rad_2d, +) +from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics +from solarlab.experiments.transient_results import _decode, _encode +from solarlab.experiments.two_dimensional.inputs import ( + JV2DInput, + JV2DProtocolInput, + MicrostructureInput, +) +from solarlab.experiments.two_dimensional.jv_protocol_2d import ( + DynamicJVPairProtocol2D, + ImplicitProtocolError, + JV2DGrainBoundaryProtocol, + JV2DProtocol, + ProtocolMode, + build_jv_2d_protocol, + resolve_jv_2d_protocol, +) +from solarlab.experiments.two_dimensional.preparation import PreparedSpatialExperiment +from solarlab.experiments.worker import _atomic_json +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state +from solarlab.solvers.nonlinear.ionic_2d import solve_ionic_steady_state_2d +from solarlab.solvers.nonlinear.problem import SolveBudget, state_digest +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state +from solarlab.solvers.time.backward_euler_2d import ( + BackwardEuler2DOptions, + compute_carrier_only_terminal_current_2d, + run_backward_euler_2d, +) +from solarlab.solvers.time.ionic_backward_euler_2d import ( + IonicBackwardEuler2DOptions, + MobileIonCurrentComponents2D, + compute_mobile_ion_current_components_2d, + run_ionic_backward_euler_2d, +) +from solarlab.units import normalize_quantity + +__all__ = [ + "JV2DDynamicPairResult", + "JV2DMetrics", + "JV2DPointAttempt", + "JV2DResult", + "JV2D_RESULT_SCHEMA", + "ProgressCallback", + "SpatialSnapshot2D", + "build_jv_2d_execution_protocol", + "compute_jv_2d_metrics", + "extract_snapshot_2d", + "read_jv_2d_result", + "run_dynamic_jv_pair_2d", + "run_jv_sweep_2d", + "write_jv_2d_result", +] + +Vector: TypeAlias = NDArray[np.float64] +ProgressCallback: TypeAlias = Callable[[str, int, int, str], None] +Disposition: TypeAlias = Literal["completed", "partial", "failed"] +JV2D_RESULT_SCHEMA = "solarlab.jv_2d.result.v1" +_DEFAULT_MAX_NFEV = 200_000 + + +@dataclass(frozen=True) +class SpatialSnapshot2D: + """2D field and face-current snapshot at one operating voltage.""" + + V_app: float + x: Vector + y: Vector + phi: Vector + n: Vector + p: Vector + Jx_n: Vector + Jy_n: Vector + Jx_p: Vector + Jy_p: Vector + R_total: Vector + P_ion: Vector | None = None + + def __post_init__(self) -> None: + for name in ("x", "y", "phi", "n", "p", "Jx_n", "Jy_n", "Jx_p", "Jy_p", "R_total"): + object.__setattr__(self, name, frozen_array(getattr(self, name))) + if self.P_ion is not None: + object.__setattr__(self, "P_ion", frozen_array(self.P_ion)) + + +@dataclass(frozen=True) +class JV2DMetrics: + """Extracted J_sc-positive photovoltaic figures of merit (SI units, fraction FF/PCE).""" + + V_oc: float + J_sc: float + FF: float + PCE: float + voc_bracketed: bool + + +@dataclass(frozen=True) +class JV2DPointAttempt: + """Per-voltage execution record with explicit failure/acceptance provenance.""" + + index: int + voltage_V: float + accepted: bool + termination: str + bisections: int + wall_s: float + state_sha256: str | None = None + error: str | None = None + + +@dataclass(frozen=True) +class JV2DResult: + """Result of a 2D J-V sweep with explicit disposition and diagnostics.""" + + V: Vector + J: Vector + snapshots: tuple[SpatialSnapshot2D, ...] + grid_x: Vector + grid_y: Vector + lateral_bc: str + metrics: JV2DMetrics = field( + default_factory=lambda: JV2DMetrics(0.0, 0.0, 0.0, 0.0, voc_bracketed=False) + ) + protocol: JV2DProtocol | None = None + current_components: tuple[MobileIonCurrentComponents2D, ...] = () + ion_diagnostics: tuple[MobileIonDiagnostics2D, ...] = () + interface_srh_diagnostics: tuple[TwoSidedInterfaceSRHReport2D, ...] = () + output_current_A_m2: Vector = field(default_factory=lambda: np.zeros(0, dtype=np.float64)) + steady_metrics: SteadyJVMetrics | None = None + requested_voltages_V: Vector = field(default_factory=lambda: np.zeros(0, dtype=np.float64)) + attempts: tuple[JV2DPointAttempt, ...] = () + disposition: Disposition = "completed" + scientific_qualification: bool = False + + def __post_init__(self) -> None: + for name in ("V", "J", "grid_x", "grid_y"): + object.__setattr__(self, name, frozen_array(getattr(self, name))) + out = self.output_current_A_m2 + if out.size == 0 and self.J.size > 0: + out = -self.J + object.__setattr__(self, "output_current_A_m2", frozen_array(out)) + req = self.requested_voltages_V + if req.size == 0 and self.V.size > 0: + req = self.V + object.__setattr__(self, "requested_voltages_V", frozen_array(req)) + if self.steady_metrics is None and self.V.size >= 2 and np.unique(self.V).size == self.V.size: + object.__setattr__(self, "steady_metrics", steady_jv_metrics(self.V, self.output_current_A_m2)) + + +@dataclass(frozen=True) +class JV2DDynamicPairResult: + """Continuous 2D preconditioning + forward + turnaround-hold + reverse scan result.""" + + protocol: DynamicJVPairProtocol2D + forward: JV2DResult + reverse: JV2DResult + preconditioned_state_sha256: str + turnaround_state_sha256: str | None + hysteresis_voc_delta_V: float | None + disposition: Disposition + scientific_qualification: bool = False + + +def compute_jv_2d_metrics( + voltages_V: NDArray[np.float64], + raw_current_A_m2: NDArray[np.float64], + *, + incident_power_W_m2: float = 1000.0, +) -> JV2DMetrics: + """Extract ``(V_oc, J_sc, FF, PCE, voc_bracketed)`` in the J_sc-positive convention.""" + v = np.asarray(voltages_V, dtype=np.float64) + j_raw = np.asarray(raw_current_A_m2, dtype=np.float64) + if v.size < 2 or j_raw.size != v.size or np.unique(v).size != v.size: + return JV2DMetrics(0.0, 0.0, 0.0, 0.0, voc_bracketed=False) + order = np.argsort(v) + v_s = v[order] + # 2D +y current is negative at V=0 for standard n-i-p stacks; flip when J(0) < 0 + j0 = float(np.interp(0.0, v_s, j_raw[order])) if v_s[0] <= 0.0 <= v_s[-1] else float(j_raw[order][0]) + j_out = -j_raw[order] if j0 < 0.0 else j_raw[order].copy() + sm = steady_jv_metrics(v_s, j_out, incident_power_W_m2=incident_power_W_m2) + jsc = float(sm.short_circuit_current_A_m2 or max(0.0, float(np.interp(0.0, v_s, j_out)))) + if sm.open_circuit_voltage_V is None: + return JV2DMetrics(0.0, jsc, 0.0, 0.0, voc_bracketed=False) + return JV2DMetrics( + V_oc=float(sm.open_circuit_voltage_V), + J_sc=jsc, + FF=float(sm.fill_factor or 0.0), + PCE=float(sm.efficiency or 0.0), + voc_bracketed=True, + ) + + +def _voltage_schedule(v_max: float, v_step: float) -> Vector: + maximum = float(v_max) + step = float(v_step) + if not math.isfinite(maximum) or maximum < 0.0: + raise ValueError("V_max must be finite and non-negative") + if not math.isfinite(step) or step <= 0.0: + raise ValueError("V_step must be finite and positive") + return np.arange(0.0, maximum + step / 2.0, step, dtype=np.float64) + + +def _carrier_bc_label(prepared: PreparedDevice) -> Literal["ohmic", "selective_robin"]: + contacts = prepared.to_mapping()["contacts"] + has_robin = any(c.get(k) is not None for c in contacts for k in ("S_n", "S_p")) + return "selective_robin" if has_robin else "ohmic" + + +def _coerce_microstructure_input( + prepared: PreparedDevice, + microstructure: object, +) -> MicrostructureInput | None: + if microstructure is None or isinstance(microstructure, MicrostructureInput): + return microstructure + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + if isinstance(microstructure, Mapping): + return MicrostructureInput.model_validate(dict(microstructure)) + raw_items = getattr(microstructure, "grain_boundaries", microstructure) + if not isinstance(raw_items, Sequence) or isinstance(raw_items, (str, bytes)): + raise TypeError("microstructure must be MicrostructureInput or sequence of grain boundaries") + gb_inputs: list[GrainBoundaryInput] = [] + for idx, item in enumerate(raw_items): + if isinstance(item, GrainBoundaryInput): + gb_inputs.append(item) + continue + proto = JV2DGrainBoundaryProtocol.from_declaration(item) + target_ids = tuple(lyr.id for lyr in elec_layers if lyr.role == proto.layer_role) + if not target_ids: + raise CapabilityError( + f"grain_boundary_role_missing: no electrical layer has role {proto.layer_role!r}" + ) + gb_inputs.append( + GrainBoundaryInput.model_validate( + { + "id": f"gb_{idx}", + "layer_ids": list(target_ids), + "x_position": proto.x_position_m, + "width": proto.width_m, + "tau_n": proto.tau_n_s, + "tau_p": proto.tau_p_s, + } + ) + ) + return MicrostructureInput(grain_boundaries=tuple(gb_inputs)) + + +def _grain_protocols_from_spatial( + prepared: PreparedDevice, + geom_spatial: JV2DInput, +) -> tuple[JV2DGrainBoundaryProtocol, ...]: + declarations = grain_declarations(prepared, geom_spatial) + role_by_id = {layer.id: layer.role for layer in prepared.layers} + result: list[JV2DGrainBoundaryProtocol] = [] + for decl in declarations: + roles = {role_by_id[lid] for lid in decl.layer_ids} + role = next(iter(roles)) if len(roles) == 1 else "absorber" + result.append( + JV2DGrainBoundaryProtocol( + x_position_m=float(normalize_quantity(decl.x_position, "m")), + width_m=float(normalize_quantity(decl.width, "m")), + tau_n_s=float(normalize_quantity(decl.tau_n, "s")), + tau_p_s=float(normalize_quantity(decl.tau_p, "s")), + layer_role=role, + ) + ) + return tuple(result) + + +def _dwell_time_grid(duration_s: float, divisor: int) -> Vector: + if duration_s <= 0.0: + raise ValueError("duration_s must be positive") + n_unif = max(int(divisor), 4) + dt_unif = duration_s / n_unif + t_early = min(1.0e-10, dt_unif * 0.125) + if t_early < dt_unif * 0.5: + early: Vector = np.geomspace(t_early, dt_unif, 6, dtype=np.float64) + if n_unif == 1: + return np.r_[0.0, early] + tail: Vector = np.linspace(dt_unif, duration_s, n_unif, dtype=np.float64)[1:] + return np.r_[0.0, early, tail] + return np.linspace(0.0, duration_s, n_unif + 1, dtype=np.float64) + + +def _const_fn(val: float) -> Callable[[float], float]: + fval = float(val) + + def _fn(_t: float) -> float: + return fval + + return _fn + + +def _ramp_fn(v_start: float, v_end: float, duration_s: float) -> Callable[[float], float]: + v0 = float(v_start) + dv_dt = (float(v_end) - v0) / float(duration_s) + + def _fn(t: float) -> float: + return v0 + dv_dt * float(t) + + return _fn + + +def _default_ionic_steady_options_1d(ion_node_count: int) -> IonicSteadyOptions: + return IonicSteadyOptions( + SteadyOptions(), 1.0e-12, 1.0e6, 1.0e6, 1.0, ion_node_count - 1, + SolveBudget(60, 600, 60, 24), 30.0, + ) + + +def _device_has_ions(prepared: PreparedDevice) -> tuple[bool, str | None]: + elec = [layer for layer in prepared.layers if layer.role != "substrate"] + ion_layers: list[str] = [] + for layer in elec: + p = dict(layer.parameters) + if p["P0_neg"] != 0.0 or p["D_ion_neg"] != 0.0: + raise CapabilityError("dual_ion_2d_unsupported: 2D execution refuses negative/dual ion species") + if p["P0"] != 0.0 or p["D_ion"] != 0.0: + ion_layers.append(layer.id) + if len(ion_layers) > 1: + raise CapabilityError("multiple_ion_domains_2d_unsupported: 2D supports at most one active ion layer") + return (len(ion_layers) == 1, ion_layers[0] if ion_layers else None) + + +def _project_prepared_for_electronic_2d( + prepared: PreparedDevice, + *, + strip_ions: bool, + strip_interfaces: bool, + strip_grains: bool = False, +) -> PreparedDevice: + raw = prepared.to_input().editing_data() + changed = False + if strip_grains and raw.get("grain_boundaries"): + raw["grain_boundaries"] = [] + changed = True + if strip_ions: + for layer_entry in raw["layers"]: + params = layer_entry.get("parameters") + if isinstance(params, dict): + for key in ION_INPUTS: + if key in params: + params.pop(key) + changed = True + settings = raw.get("settings") + if isinstance(settings, dict) and settings.get("ion_steric_diffusion_only"): + settings["ion_steric_diffusion_only"] = False + changed = True + if strip_interfaces: + settings = raw.get("settings") + if isinstance(settings, dict) and settings.get("interface_two_sided"): + settings["interface_two_sided"] = False + changed = True + if raw.get("interfaces"): + cleaned = [] + for entry in raw["interfaces"]: + item = dict(entry) + for key in ("v_n", "v_p", "defect"): + item.pop(key, None) + cleaned.append(item) + raw["interfaces"] = cleaned + changed = True + if not changed: + return prepared + return resolve_device( + DeviceInput.model_validate(raw), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +def _embed_frozen_ion_excess_2d( + device_2d: CompiledDevice2D, + excess_1d_m3: Vector, +) -> CompiledDevice2D: + if not np.any(excess_1d_m3 != 0.0): + return device_2d + col = device_2d.column + params = col.parameters + new_nd = params.donor_density_m3 + np.maximum(excess_1d_m3, 0.0) + new_na = params.acceptor_density_m3 + np.maximum(-excess_1d_m3, 0.0) + new_params = replace( + params, + donor_density_m3=frozen_array(new_nd), + acceptor_density_m3=frozen_array(new_na), + ) + col_sha = hashlib.sha256( + col.sha256.encode() + b":frozen_ion_1d_v1:" + np.ascontiguousarray(excess_1d_m3, dtype=" SpatialSnapshot2D: + """Extract nodal fields, face currents, and recombination rate into a ``SpatialSnapshot2D``.""" + if isinstance(device, CompiledIonicDevice2D): + assert isinstance(state, IonicState2D) + comp = device.electronic_component + elec_u = state.u[:3 * comp.node_count] + p_ion_2d: Vector | None = device.full_grid_ion_density(state.positive_ion_density_m3) + iface_couplings = device.interface_srh_couplings + else: + assert isinstance(state, State2D) + comp = device + elec_u = state.u + p_ion_2d = None + iface_couplings = interface_srh_couplings + _ = radiative_reabsorption + g = comp.geometry + shape = g.shape + phi, n, p = comp.fields(elec_u, voltage_V=state.voltage_V) + prob = DC2DProblem(comp, state.voltage_V, generation_scale) + c_flux = prob.fluxes(elec_u) + je = -Q * c_flux.electron.flux + jh = Q * c_flux.hole.flux + x_cols = g.x_faces_per_row + jx_n = je[:g.x_face_count].reshape(g.ny, x_cols) + jy_n = je[g.x_face_count:].reshape(g.ny - 1, g.nx) + jx_p = jh[:g.x_face_count].reshape(g.ny, x_cols) + jy_p = jh[g.x_face_count:].reshape(g.ny - 1, g.nx) + rec = prob.recombination_rate(n, p, derivatives=False).rate.reshape(shape).copy() + if iface_couplings: + rep = evaluate_two_sided_interface_srh_2d( + n.reshape(shape), p.reshape(shape), g.y_geometry.nodes_m, iface_couplings + ) + rec = rec + rep.volumetric_sink_m3_s + return SpatialSnapshot2D( + V_app=float(state.voltage_V), + x=g.x_m, + y=g.y_geometry.nodes_m, + phi=phi.reshape(shape), + n=n.reshape(shape), + p=p.reshape(shape), + Jx_n=jx_n, + Jy_n=jy_n, + Jx_p=jx_p, + Jy_p=jy_p, + R_total=rec, + P_ion=p_ion_2d, + ) + + +def _precondition_frozen_lane( + prepared: PreparedDevice, + geom_spatial: JV2DInput, + protocol: JV2DProtocol, +) -> tuple[ + CompiledDevice2D, + State2D, + tuple[RadiativeReabsorptionSpec2D, ...], + tuple[TwoSidedInterfaceSRHCoupling2D, ...], +]: + """Compile frozen-ion 2D device and run 1D dark/illuminated preconditioner.""" + has_ions, ion_layer_id = _device_has_ions(prepared) + use_iface = protocol.interface_srh == "two_sided_cross_node" + # Validate dynamic interface flags and two-sided SRH before projecting interfaces + base_clean = _project_prepared_for_electronic_2d( + prepared, strip_ions=has_ions, strip_interfaces=use_iface + ) + device_2d = compile_device_2d(base_clean, geom_spatial) + iface_couplings = build_two_sided_interface_srh_2d( + prepared, device_2d, interface_srh_mode=protocol.interface_srh + ) + rr_specs = build_radiative_reabsorption_2d(prepared, device_2d) if protocol.illuminated else () + + ny_per = int(cast(int, geom_spatial.Ny_per_layer)) + n_layers = len([lyr for lyr in prepared.layers if lyr.role != "substrate"]) + ny_nodes = device_2d.geometry.ny + + # 1. Solve 1D dark equilibrium (and 1D illuminated finite-time settle if requested) + excess_1d: Vector = np.zeros(ny_nodes, dtype=np.float64) + if has_ions and ion_layer_id is not None: + prep_1d_ion = _project_prepared_for_electronic_2d( + prepared, strip_ions=False, strip_interfaces=use_iface, strip_grains=True + ) + # If carrier contacts are ohmic and Neumann-x, use Nx=1 auxiliary 2D ionic solver so + # reabsorption and two-sided SRH participate in the 1D illuminated preconditioner! + if protocol.carrier_boundary_condition == "ohmic": + aux_spatial = JV2DInput( + kind="jv_2d", + lateral_length=geom_spatial.lateral_length, + Nx=1, + Ny_per_layer=ny_per, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="frozen", + interface_srh=protocol.interface_srh, + ) + aux_ionic = compile_ionic_device_2d( + _project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False, strip_grains=True), + aux_spatial, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + dark_elec_f = solve_steady_state( + aux_ionic.electronic_component.column, voltage_V=0.0, generation_scale=0.0 + ) + if dark_elec_f.state is None: + raise RuntimeError("1D dark electronic preconditioner failed") + settled_ion_state = aux_ionic.state( + np.r_[ + aux_ionic.electronic_component.extrude_coordinates(dark_elec_f.state.u), + np.zeros(aux_ionic.ion_node_count, dtype=np.float64), + ], + voltage_V=0.0, + ) + if protocol.illuminated and float(aux_ionic.positive_ion_diffusivity_faces_m2_s[0]) > 0.0: + assert protocol.initial_state_settle_s is not None + t_grid = _dwell_time_grid(protocol.initial_state_settle_s, 20) + run_pre_ion = run_ionic_backward_euler_2d( + aux_ionic, + settled_ion_state, + t_grid, + voltage_fn=_const_fn(0.0), + generation_fn=lambda t: 0.0 if t <= 0.0 else 1.0, + ) + if not run_pre_ion.accepted: + raise RuntimeError(f"1D illuminated ionic preconditioner failed: {run_pre_ion.error}") + settled_ion_state = run_pre_ion.states[-1] + elif protocol.illuminated: + # Immobile positive background (D_ion == 0): settle carriers only + assert protocol.initial_state_settle_s is not None + t_grid = _dwell_time_grid(protocol.initial_state_settle_s, 20) + aux_elec = aux_ionic.electronic_component + elec_s0 = aux_elec.state(settled_ion_state.u[:3 * aux_elec.node_count], voltage_V=0.0) + run_c = run_backward_euler_2d( + aux_elec, + elec_s0, + t_grid, + voltage_fn=lambda _t: 0.0, + generation_fn=lambda t: 0.0 if t <= 0.0 else 1.0, + options=BackwardEuler2DOptions( + radiative_reabsorption=aux_ionic.radiative_reabsorption, + interface_srh_couplings=aux_ionic.interface_srh_couplings, + ), + ) + if not run_c.accepted: + raise RuntimeError(f"1D illuminated frozen-ion preconditioner failed: {run_c.error}") + settled_elec = run_c.states[-1] + settled_ion_state = aux_ionic.state( + np.r_[settled_elec.u, settled_ion_state.u[3 * aux_elec.node_count:]], + voltage_V=0.0, + ) + # Extract column 0 (1D profile) from the 2-column (Nx=1) auxiliary solve + aux_nx = aux_ionic.electronic_component.geometry.nx # 2 + u_elec_2d = settled_ion_state.u[:3 * aux_ionic.node_count].reshape(3, ny_nodes, aux_nx) + col_u_1d = u_elec_2d[:, :, 0].ravel() + ion_p_col0 = settled_ion_state.positive_ion_density_m3[:, 0] + ref_col0 = aux_ionic.positive_ion_reference_m3.reshape(aux_ionic.ion_geometry.ny, aux_nx)[:, 0] + ratio_col0 = aux_ionic.ion_charge_weight_ratio.reshape(aux_ionic.ion_geometry.ny, aux_nx)[:, 0] + excess_1d[aux_ionic.ion_row_indices] = (ion_p_col0 - ref_col0) * ratio_col0 + device_2d = _embed_frozen_ion_excess_2d(device_2d, excess_1d) + init_2d = device_2d.state(device_2d.extrude_coordinates(col_u_1d), voltage_V=0.0) + return device_2d, init_2d, rr_specs, iface_couplings + + # Selective Robin contacts with frozen ion background: solve 1D ionic equilibrium + ionic_1d = compile_ionic_device_1d( + prep_1d_ion, + intervals_per_layer=(ny_per,) * n_layers, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + dark_1d_ion = solve_ionic_steady_state( + ionic_1d, + voltage_V=0.0, + generation_scale=0.0, + options=_default_ionic_steady_options_1d(ionic_1d.ion_node_count), + ) + if not dark_1d_ion.accepted or dark_1d_ion.state is None: + raise RuntimeError(f"1D Robin ionic dark equilibrium failed: {dark_1d_ion.error}") + col_u_1d = dark_1d_ion.state.u[:3 * ionic_1d.node_count] + ion_p_1d = dark_1d_ion.state.positive_ion_density_m3 + excess_1d[ionic_1d.ion_node_indices] = ( + ion_p_1d - ionic_1d.positive_ion_reference_m3 + ) * ionic_1d.ion_charge_weight_ratio + device_2d = _embed_frozen_ion_excess_2d(device_2d, excess_1d) + if not protocol.illuminated: + return device_2d, device_2d.state(device_2d.extrude_coordinates(col_u_1d), voltage_V=0.0), rr_specs, iface_couplings + else: + dark_1d = solve_steady_state(device_2d.column, voltage_V=0.0, generation_scale=0.0) + if dark_1d.state is None: + raise RuntimeError("1D dark equilibrium failed") + col_u_1d = dark_1d.state.u + if not protocol.illuminated: + return device_2d, device_2d.state(device_2d.extrude_coordinates(col_u_1d), voltage_V=0.0), rr_specs, iface_couplings + + # Illuminated finite-time 1D settle on grain-free Nx=1 column pair + assert protocol.initial_state_settle_s is not None + aux_geom = JV2DInput( + kind="jv_2d", + lateral_length=geom_spatial.lateral_length, + Nx=1, + Ny_per_layer=ny_per, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ) + aux_clean = _project_prepared_for_electronic_2d( + prepared, strip_ions=has_ions, strip_interfaces=use_iface, strip_grains=True + ) + aux_dev = _embed_frozen_ion_excess_2d(compile_device_2d(aux_clean, aux_geom), excess_1d) + aux_rr = build_radiative_reabsorption_2d(prepared, aux_dev) + aux_if = build_two_sided_interface_srh_2d(prepared, aux_dev, interface_srh_mode=protocol.interface_srh) + aux_s0 = aux_dev.state(aux_dev.extrude_coordinates(col_u_1d), voltage_V=0.0) + t_grid = _dwell_time_grid(protocol.initial_state_settle_s, 20) + run_pre = run_backward_euler_2d( + aux_dev, + aux_s0, + t_grid, + voltage_fn=lambda _t: 0.0, + generation_fn=lambda t: 0.0 if t <= 0.0 else 1.0, + options=BackwardEuler2DOptions( + radiative_reabsorption=aux_rr, + interface_srh_couplings=aux_if, + ), + ) + if not run_pre.accepted: + raise RuntimeError(f"1D illuminated finite-time preconditioner failed: {run_pre.error}") + u_settled = run_pre.states[-1].u.reshape(3, ny_nodes, aux_dev.geometry.nx)[:, :, 0].ravel() + return device_2d, device_2d.state(device_2d.extrude_coordinates(u_settled), voltage_V=0.0), rr_specs, iface_couplings + + +def _precondition_mobile_ion_lane( + prepared: PreparedDevice, + exec_spatial: JV2DInput, + protocol: JV2DProtocol, +) -> tuple[CompiledIonicDevice2D, IonicState2D]: + """Compile mobile-ion 2D device and run 1D dark/illuminated preconditioner.""" + _, ion_layer_id = _device_has_ions(prepared) + ionic_2d = compile_ionic_device_2d( + prepared, + exec_spatial, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + aux_spatial = JV2DInput( + kind="jv_2d", + lateral_length=exec_spatial.lateral_length, + Nx=1, + Ny_per_layer=exec_spatial.Ny_per_layer, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="single_mobile", + interface_srh=protocol.interface_srh, + ) + aux_prep = _project_prepared_for_electronic_2d( + prepared, strip_ions=False, strip_interfaces=False, strip_grains=True + ) + aux_ionic = compile_ionic_device_2d( + aux_prep, + aux_spatial, + ion_domain_layer=ionic_2d.domain_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + dark_elec = solve_steady_state( + aux_ionic.electronic_component.column, voltage_V=0.0, generation_scale=0.0 + ) + if dark_elec.state is None: + raise RuntimeError("1D mobile-ion electronic dark equilibrium failed") + settled = aux_ionic.state( + np.r_[ + aux_ionic.electronic_component.extrude_coordinates(dark_elec.state.u), + np.zeros(aux_ionic.ion_node_count, dtype=np.float64), + ], + voltage_V=0.0, + ) + if protocol.illuminated: + assert protocol.initial_state_settle_s is not None + t_grid = _dwell_time_grid(protocol.initial_state_settle_s, 24) + run_pre = run_ionic_backward_euler_2d( + aux_ionic, + settled, + t_grid, + voltage_fn=_const_fn(0.0), + generation_fn=lambda t: 0.0 if t <= 0.0 else 1.0, + ) + if not run_pre.accepted: + raise RuntimeError(f"1D mobile-ion illuminated preconditioner failed: {run_pre.error}") + settled = run_pre.states[-1] + ny_elec = ionic_2d.electronic_component.geometry.ny + ny_ion = ionic_2d.ion_geometry.ny + aux_nx = aux_ionic.electronic_component.geometry.nx + u_elec_1d = settled.u[:3 * aux_ionic.node_count].reshape(3, ny_elec, aux_nx)[:, :, 0].ravel() + y_ion_1d = settled.u[3 * aux_ionic.node_count:].reshape(ny_ion, aux_nx)[:, 0] + u_2d = np.r_[ + ionic_2d.electronic_component.extrude_coordinates(u_elec_1d), + np.repeat(y_ion_1d, ionic_2d.ion_geometry.nx), + ] + return ionic_2d, ionic_2d.state(u_2d, voltage_V=0.0) + + +def _bake_electronic_reabsorption_2d( + device: CompiledDevice2D, + state: State2D, + rr_specs: tuple[RadiativeReabsorptionSpec2D, ...], +) -> CompiledDevice2D: + g = device.geometry + shape = g.shape + _, n, p = device.fields(state.u, voltage_V=state.voltage_V) + b_rad = device.recombination.coefficients.radiative_m3_s.reshape(shape) + ni_sq = device.recombination.coefficients.ni_sq_m6.reshape(shape) + base_g = device.generation_source_m3_s.reshape(shape) + aug = recompute_g_with_rad_2d( + G_optical=base_g, + n=n.reshape(shape), + p=p.reshape(shape), + B_rad=b_rad, + ni_sq=ni_sq, + x=g.x_m, + y=g.y_geometry.nodes_m, + absorber_y_ranges=tuple((s.y_start, s.y_stop) for s in rr_specs), + absorber_p_esc=tuple(s.escape_probability for s in rr_specs), + absorber_areas=tuple(s.area_m2 for s in rr_specs), + ) + gen_y = np.mean(aug, axis=1) + new_gen = replace(device.generation_y, source_m3_s=frozen_array(gen_y)) + baked_sha = hashlib.sha256( + device.identity.encode() + b":baked_rr_2d:" + np.ascontiguousarray(gen_y, dtype=" CompiledIonicDevice2D: + if not device.radiative_reabsorption: + return device + baked_elec = _bake_electronic_reabsorption_2d( + device.electronic_component, state.electronic_state, device.radiative_reabsorption + ) + manifest = dict(device.binding_manifest) + manifest["radiative_reabsorption_baked_step"] = True + manifest_json = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode() + return CompiledIonicDevice2D( + device_id=device.device_id, + sha256=hashlib.sha256(manifest_json).hexdigest(), + original_prepared_sha256=device.original_prepared_sha256, + electronic_component=baked_elec, + ion_geometry=device.ion_geometry, + domain_layer_id=device.domain_layer_id, + ion_row_indices=device.ion_row_indices, + positive_ion_reference_m3=device.positive_ion_reference_m3, + positive_ion_site_limit_m3=device.positive_ion_site_limit_m3, + positive_ion_logit_reference=device.positive_ion_logit_reference, + positive_ion_diffusivity_faces_m2_s=device.positive_ion_diffusivity_faces_m2_s, + steric_model=device.steric_model, + binding_manifest_json=manifest_json.decode(), + radiative_reabsorption=(), + interface_srh_couplings=device.interface_srh_couplings, + ) + + +def build_jv_2d_execution_protocol( + prepared: PreparedDevice, + microstructure: object = None, + *, + lateral_length: float, + Nx: int, + V_max: float, + V_step: float, + illuminated: bool = True, + lateral_bc: Literal["periodic", "neumann"] = "periodic", + Ny_per_layer: int = 20, + settle_t: float = 1.0e-7, + save_snapshots: bool = True, + ion_dynamics: Literal["frozen", "single_mobile"] = "frozen", + interface_srh: Literal["off", "two_sided_cross_node"] = "off", + rtol: float = 1.0e-6, + atol: object = 1.0e-8, + max_nfev_per_solve: int = _DEFAULT_MAX_NFEV, + max_bisect: int = 6, + ion_inventory_rtol: float = 1.0e-9, + initial_state_settle_s: float = 1.0e-3, + solver_method: Literal["Radau", "backward_euler"] = "Radau", + implicit_legacy_protocol: bool = False, +) -> JV2DProtocol: + """Build the exact canonical ``JV2DProtocol`` for a ``PreparedDevice`` 2D J-V sweep.""" + ms_input = _coerce_microstructure_input(prepared, microstructure) + geom_spatial = JV2DInput( + kind="jv_2d", + lateral_length=lateral_length, + Nx=Nx, + Ny_per_layer=Ny_per_layer, + lateral_bc=lateral_bc, + microstructure=ms_input, + ) + has_ions, _ = _device_has_ions(prepared) + clean_prep = _project_prepared_for_electronic_2d( + prepared, + strip_ions=has_ions, + strip_interfaces=(interface_srh == "two_sided_cross_node"), + ) + dev_preview = compile_device_2d(clean_prep, geom_spatial) + voltages = _voltage_schedule(V_max, V_step) + grain_protos = _grain_protocols_from_spatial(prepared, geom_spatial) + temp_K = float(prepared.to_mapping()["settings"]["T"]) + return build_jv_2d_protocol( + temperature_K=temp_K, + illuminated=illuminated, + x_coordinates_m=dev_preview.geometry.x_m, + y_coordinates_m=dev_preview.geometry.y_geometry.nodes_m, + voltages_V=voltages, + dwell_time_per_voltage_s=settle_t, + ion_dynamics=ion_dynamics, + carrier_boundary_condition=_carrier_bc_label(prepared), + interface_srh=interface_srh, + lateral_bc=lateral_bc, + solver_rtol=rtol, + solver_atol=atol, + max_nfev_per_solve=max_nfev_per_solve, + max_bisect=max_bisect, + ion_inventory_rtol=ion_inventory_rtol, + save_snapshots=save_snapshots, + grain_boundaries=grain_protos, + initial_state_settle_s=initial_state_settle_s, + solver_method=solver_method, + implicit_legacy_protocol=implicit_legacy_protocol, + ) + + +def _extract_prepared_and_controls( + source: PreparedDevice | PreparedSpatialExperiment, + spatial_input: JV2DInput | None, + kwargs: dict[str, Any], +) -> tuple[PreparedDevice, dict[str, Any], MicrostructureInput | None, JV2DProtocol | JV2DProtocolInput | None]: + if isinstance(source, PreparedSpatialExperiment): + inp = source.to_input() + if not isinstance(inp.experiment, JV2DInput): + raise ValueError("PreparedSpatialExperiment does not contain a jv_2d experiment") + prepared = resolve_device(inp.device, source.defaults, source.resources, sources=source.sources) + spatial_input = inp.experiment + elif isinstance(source, PreparedDevice): + prepared = source + else: + raise TypeError("run_jv_sweep_2d requires PreparedDevice or PreparedSpatialExperiment") + + defaults: dict[str, Any] = { + "lateral_length": 1.0e-6, + "Nx": 10, + "Ny_per_layer": 20, + "V_max": 1.2, + "V_step": 0.05, + "illuminated": True, + "save_snapshots": True, + "settle_t": 1.0e-7, + "rtol": 1.0e-6, + "atol": 1.0e-8, + "max_nfev_per_solve": _DEFAULT_MAX_NFEV, + "max_bisect": 6, + "ion_inventory_rtol": 1.0e-9, + "initial_state_settle_s": 1.0e-3, + "ion_dynamics": "frozen", + "interface_srh": "off", + "protocol_mode": "compatibility", + } + try: + cat_defaults = prepared.defaults.experiment_defaults_for("jv_2d") + defaults.update(cat_defaults) + except Exception: + pass + + ms_input: MicrostructureInput | None = None + supplied_proto: JV2DProtocol | JV2DProtocolInput | None = kwargs.get("jv_2d_protocol") + if spatial_input is not None: + norm = spatial_input.normalized_data() + for k in defaults: + if k in norm and norm[k] is not None: + defaults[k] = norm[k] + if spatial_input.componentwise_atol is not None: + defaults["atol"] = spatial_input.componentwise_atol + if spatial_input.lateral_bc is not None: + defaults["lateral_bc"] = spatial_input.lateral_bc + ms_input = spatial_input.microstructure + if spatial_input.jv_2d_protocol is not None and supplied_proto is None: + supplied_proto = spatial_input.jv_2d_protocol + + for k, v in kwargs.items(): + if k in {"microstructure", "jv_2d_protocol"} or v is None: + continue + if k in {"lateral_length", "V_max", "V_step", "settle_t", "initial_state_settle_s"} and not isinstance(v, (int, float)): + unit = "m" if k == "lateral_length" else ("s" if "settle" in k else "V") + defaults[k] = normalize_quantity(v, unit) + else: + defaults[k] = v + + if "microstructure" in kwargs and kwargs["microstructure"] is not None: + ms_input = _coerce_microstructure_input(prepared, kwargs["microstructure"]) + + # Effective lateral_bc default rule: neumann when grains exist, else periodic + if defaults.get("lateral_bc") is None: + active_override = ms_input is not None and bool(ms_input.editing_data()) + eff_grains = ( + ms_input.grain_boundaries + if active_override and ms_input is not None + else prepared.to_input().grain_boundaries + ) + defaults["lateral_bc"] = "neumann" if eff_grains else "periodic" + + return prepared, defaults, ms_input, supplied_proto + + +def run_jv_sweep_2d( + prepared_or_experiment: PreparedDevice | PreparedSpatialExperiment, + spatial_input: JV2DInput | None = None, + *, + microstructure: object = None, + lateral_length: float | None = None, + Nx: int | None = None, + V_max: float | None = None, + V_step: float | None = None, + illuminated: bool | None = None, + lateral_bc: Literal["periodic", "neumann"] | None = None, + Ny_per_layer: int | None = None, + settle_t: float | None = None, + progress: ProgressCallback | None = None, + save_snapshots: bool | None = None, + ion_dynamics: Literal["frozen", "single_mobile"] | None = None, + interface_srh: Literal["off", "two_sided_cross_node"] | None = None, + rtol: float | None = None, + atol: object = None, + max_nfev_per_solve: int | None = None, + max_bisect: int | None = None, + ion_inventory_rtol: float | None = None, + initial_state_settle_s: float | None = None, + jv_2d_protocol: JV2DProtocol | JV2DProtocolInput | None = None, + protocol_mode: ProtocolMode | None = None, + on_point_failure: Literal["raise", "record_partial"] = "raise", +) -> JV2DResult: + """Execute a 2D J-V dwell sweep on the native ``solarlab`` 2D core.""" + if on_point_failure not in {"raise", "record_partial"}: + raise ValueError("on_point_failure must be 'raise' or 'record_partial'") + prepared, ctrl, ms_input, supplied_proto = _extract_prepared_and_controls( + prepared_or_experiment, + spatial_input, + { + "microstructure": microstructure, + "lateral_length": lateral_length, + "Nx": Nx, + "V_max": V_max, + "V_step": V_step, + "illuminated": illuminated, + "lateral_bc": lateral_bc, + "Ny_per_layer": Ny_per_layer, + "settle_t": settle_t, + "save_snapshots": save_snapshots, + "ion_dynamics": ion_dynamics, + "interface_srh": interface_srh, + "rtol": rtol, + "atol": atol, + "max_nfev_per_solve": max_nfev_per_solve, + "max_bisect": max_bisect, + "ion_inventory_rtol": ion_inventory_rtol, + "initial_state_settle_s": initial_state_settle_s, + "jv_2d_protocol": jv_2d_protocol, + "protocol_mode": protocol_mode, + }, + ) + + eff_ion_dyn = cast(Literal["frozen", "single_mobile"], ctrl["ion_dynamics"]) + eff_iface = cast(Literal["off", "two_sided_cross_node"], ctrl["interface_srh"]) + eff_lat_bc = cast(Literal["periodic", "neumann"], ctrl["lateral_bc"]) + eff_mode = cast(ProtocolMode, ctrl["protocol_mode"]) + + extended = eff_ion_dyn != "frozen" or eff_iface != "off" + if extended and eff_mode != "research_strict": + raise ImplicitProtocolError( + "mobile-ion or interface-SRH 2D J-V requires protocol_mode='research_strict' " + "and an explicit matching jv_2d_protocol" + ) + + # Validate BC / microstructure capability rules fail-closed before solving + geom_spatial = JV2DInput( + kind="jv_2d", + lateral_length=float(ctrl["lateral_length"]), + Nx=int(ctrl["Nx"]), + Ny_per_layer=int(ctrl["Ny_per_layer"]), + lateral_bc=eff_lat_bc, + microstructure=ms_input, + ) + grain_decls = grain_declarations(prepared, geom_spatial) + if grain_decls and eff_lat_bc != "neumann": + raise CapabilityError("periodic_grain_2d_unsupported: grain boundaries require Neumann-x") + if eff_ion_dyn == "single_mobile" and eff_lat_bc != "neumann": + raise CapabilityError("periodic_ionic_2d_unsupported: 2D mobile-ion requires Neumann-x") + if eff_iface != "off" and eff_lat_bc != "neumann": + raise CapabilityError("periodic_interface_srh_2d_unsupported: two-sided SRH requires Neumann-x") + carrier_bc = _carrier_bc_label(prepared) + if extended and carrier_bc != "ohmic": + raise CapabilityError("selective_robin_extended_2d_unsupported: requires ohmic contacts") + + expected_proto = build_jv_2d_execution_protocol( + prepared, + ms_input, + lateral_length=float(ctrl["lateral_length"]), + Nx=int(ctrl["Nx"]), + V_max=float(ctrl["V_max"]), + V_step=float(ctrl["V_step"]), + illuminated=bool(ctrl["illuminated"]), + lateral_bc=eff_lat_bc, + Ny_per_layer=int(ctrl["Ny_per_layer"]), + settle_t=float(ctrl["settle_t"]), + save_snapshots=bool(ctrl["save_snapshots"]), + ion_dynamics=eff_ion_dyn, + interface_srh=eff_iface, + rtol=float(ctrl["rtol"]), + atol=ctrl["atol"], + max_nfev_per_solve=int(ctrl["max_nfev_per_solve"]), + max_bisect=int(ctrl["max_bisect"]), + ion_inventory_rtol=float(ctrl["ion_inventory_rtol"]), + initial_state_settle_s=float(ctrl["initial_state_settle_s"]), + implicit_legacy_protocol=True, + ) + resolved_proto = resolve_jv_2d_protocol(supplied_proto, expected_proto, mode=eff_mode) + mobile_ions = resolved_proto.state_topology == "single_positive_mobile_ion" + gen_scale = 1.0 if resolved_proto.illuminated else 0.0 + + voltages: Vector = np.asarray(resolved_proto.voltage_values_V, dtype=np.float64) + j_vals: list[float] = [] + v_accepted: list[float] = [] + snapshots: list[SpatialSnapshot2D] = [] + curr_reports: list[MobileIonCurrentComponents2D] = [] + ion_reports: list[MobileIonDiagnostics2D] = [] + iface_reports: list[TwoSidedInterfaceSRHReport2D] = [] + attempts: list[JV2DPointAttempt] = [] + + max_it = min(max(resolved_proto.max_nfev_per_solve // 200, 25), 80) + pt_budget = SolveBudget(max_it, max(resolved_proto.max_nfev_per_solve, max_it * 10), max_it * 2, 24) + g_fn = _const_fn(gen_scale) + + if mobile_ions: + exec_spatial = JV2DInput( + kind="jv_2d", + lateral_length=float(ctrl["lateral_length"]), + Nx=int(ctrl["Nx"]), + Ny_per_layer=int(ctrl["Ny_per_layer"]), + lateral_bc=resolved_proto.lateral_bc, + microstructure=ms_input, + ion_dynamics="single_mobile", + interface_srh=resolved_proto.interface_srh, + ) + ionic_dev, ion_state = _precondition_mobile_ion_lane(prepared, exec_spatial, resolved_proto) + polarity = float(ionic_dev.electronic_component.column.voltage_polarity) + grid_x = ionic_dev.electronic_component.geometry.x_m + grid_y = ionic_dev.electronic_component.geometry.y_geometry.nodes_m + d_grid = _dwell_time_grid( + resolved_proto.dwell_time_per_voltage_s, resolved_proto.solver_max_step_divisor + ) + ion_opts = IonicBackwardEuler2DOptions( + budget=pt_budget, + max_bisect=max(resolved_proto.max_bisect, 4), + ion_inventory_rtol=max(resolved_proto.ion_inventory_rtol, 1.0e-12), + ) + ion_x = ionic_dev.ion_geometry.x_m + ion_y = ionic_dev.ion_geometry.y_geometry.nodes_m + ion_areas = ionic_dev.ion_geometry.contract_geometry.volumes.reshape(ionic_dev.ion_geometry.shape) + ion_lim_2d = ionic_dev.positive_ion_site_limit_m3.reshape(ionic_dev.ion_geometry.shape) + for idx, v_val in enumerate(voltages): + pt_start = time.monotonic() + prev_ion_2d = ion_state.positive_ion_density_m3 + v_fn = _const_fn(float(v_val)) + run_pt = run_ionic_backward_euler_2d( + ionic_dev, ion_state, d_grid, voltage_fn=v_fn, generation_fn=g_fn, options=ion_opts + ) + if not run_pt.accepted and ionic_dev.radiative_reabsorption and resolved_proto.illuminated: + baked_dev = _bake_ionic_reabsorption_2d(ionic_dev, ion_state) + baked_s0 = baked_dev.state(ion_state.u, voltage_V=ion_state.voltage_V) + run_baked = run_ionic_backward_euler_2d( + baked_dev, baked_s0, d_grid, voltage_fn=v_fn, generation_fn=g_fn, options=ion_opts + ) + if run_baked.accepted: + settled_u = run_baked.states[-1].u + ion_state = ionic_dev.state(settled_u, voltage_V=float(v_val)) + run_pt = replace(run_baked, states=(*run_baked.states[:-1], ion_state)) + if not run_pt.accepted: + err_msg = run_pt.error or f"2D mobile-ion dwell failed at V={v_val:.4f} V" + attempts.append( + JV2DPointAttempt( + idx, float(v_val), False, run_pt.termination, run_pt.bisections, + time.monotonic() - pt_start, None, err_msg, + ) + ) + if on_point_failure == "raise": + raise RuntimeError(err_msg) + break + + ion_state = run_pt.states[-1] + snap = extract_snapshot_2d(ionic_dev, ion_state, generation_scale=gen_scale) + if ionic_dev.interface_srh_couplings: + iface_reports.append( + evaluate_two_sided_interface_srh_2d( + snap.n, snap.p, grid_y, ionic_dev.interface_srh_couplings + ) + ) + curr = compute_mobile_ion_current_components_2d( + ionic_dev, + ion_state, + generation_scale=gen_scale, + applied_voltage_rate_V_s=resolved_proto.applied_voltage_rate_at_sampling_V_s, + ) + term_ion_2d = ion_state.positive_ion_density_m3 + diag = assess_mobile_ion_terminal_2d( + ion_x, + ion_y, + prev_ion_2d, + term_ion_2d, + ion_lim_2d, + terminal_electron_density=snap.n, + terminal_hole_density=snap.p, + inventory_rtol=max(resolved_proto.ion_inventory_rtol, 1.0e-12), + control_volume_areas_m2=ion_areas, + ) + if not diag.passed: + err_msg = "2D J-V point failed mobile-ion diagnostics: " + ", ".join(diag.violations) + attempts.append( + JV2DPointAttempt( + idx, float(v_val), False, "ion_diagnostics_failed", run_pt.bisections, + time.monotonic() - pt_start, None, err_msg, + ) + ) + if on_point_failure == "raise": + raise RuntimeError(err_msg) + break + + v_accepted.append(float(v_val)) + j_vals.append(curr.terminal_total_A_m2) + curr_reports.append(curr) + ion_reports.append(diag) + if resolved_proto.save_snapshots: + snapshots.append(snap) + attempts.append( + JV2DPointAttempt( + idx, float(v_val), True, "converged", run_pt.bisections, + time.monotonic() - pt_start, state_digest(ion_state.u), None, + ) + ) + if progress is not None: + progress("jv_2d", idx + 1, int(voltages.size), f"V = {v_val:.3f} V") + else: + elec_dev, elec_state, rr_specs, iface_couplings = _precondition_frozen_lane( + prepared, geom_spatial, resolved_proto + ) + polarity = float(elec_dev.column.voltage_polarity) + grid_x = elec_dev.geometry.x_m + grid_y = elec_dev.geometry.y_geometry.nodes_m + d_grid = _dwell_time_grid( + resolved_proto.dwell_time_per_voltage_s, resolved_proto.solver_max_step_divisor + ) + be_opts = BackwardEuler2DOptions( + budget=pt_budget, + max_bisect=max(resolved_proto.max_bisect, 4), + radiative_reabsorption=rr_specs, + interface_srh_couplings=iface_couplings, + ) + for idx, v_val in enumerate(voltages): + pt_start = time.monotonic() + fv = float(v_val) + v_fn = _const_fn(fv) + run_pt_e = run_backward_euler_2d( + elec_dev, + elec_state, + d_grid, + voltage_fn=v_fn, + generation_fn=g_fn, + options=be_opts, + ) + if not run_pt_e.accepted and rr_specs and resolved_proto.illuminated: + baked_elec = _bake_electronic_reabsorption_2d(elec_dev, elec_state, rr_specs) + baked_s0_e = baked_elec.state(elec_state.u, voltage_V=elec_state.voltage_V) + baked_opts = replace(be_opts, radiative_reabsorption=()) + run_baked_e = run_backward_euler_2d( + baked_elec, + baked_s0_e, + d_grid, + voltage_fn=v_fn, + generation_fn=g_fn, + options=baked_opts, + ) + if run_baked_e.accepted: + elec_state = elec_dev.state(run_baked_e.states[-1].u, voltage_V=fv) + run_pt_e = replace(run_baked_e, states=(*run_baked_e.states[:-1], elec_state)) + if not run_pt_e.accepted: + err_msg = run_pt_e.error or f"2D frozen-ion dwell failed at V={fv:.4f} V" + attempts.append( + JV2DPointAttempt( + idx, fv, False, run_pt_e.termination, run_pt_e.bisections, + time.monotonic() - pt_start, None, err_msg, + ) + ) + if on_point_failure == "raise": + raise RuntimeError(err_msg) + break + + elec_state = run_pt_e.states[-1] + snap = extract_snapshot_2d( + elec_dev, + elec_state, + generation_scale=gen_scale, + radiative_reabsorption=rr_specs, + interface_srh_couplings=iface_couplings, + ) + if iface_couplings: + iface_reports.append( + evaluate_two_sided_interface_srh_2d(snap.n, snap.p, grid_y, iface_couplings) + ) + ports_j = compute_carrier_only_terminal_current_2d( + elec_dev, + elec_state, + generation_scale=gen_scale, + radiative_reabsorption=rr_specs, + interface_srh_couplings=iface_couplings, + ) + v_accepted.append(fv) + j_vals.append(float(ports_j[1])) + if resolved_proto.save_snapshots: + snapshots.append(snap) + attempts.append( + JV2DPointAttempt( + idx, fv, True, "converged", run_pt_e.bisections, + time.monotonic() - pt_start, state_digest(elec_state.u), None, + ) + ) + if progress is not None: + progress("jv_2d", idx + 1, int(voltages.size), f"V = {fv:.3f} V") + + v_out: Vector = np.asarray(v_accepted, dtype=np.float64) + j_arr: Vector = np.asarray(j_vals, dtype=np.float64) + j_out = -polarity * j_arr + disp: Disposition = ( + "completed" + if v_out.size == voltages.size + else ("partial" if v_out.size > 0 else "failed") + ) + metrics = compute_jv_2d_metrics(v_out, j_arr) + sm = steady_jv_metrics(v_out, j_out) if v_out.size >= 2 else None + return JV2DResult( + V=v_out, + J=j_arr, + snapshots=tuple(snapshots), + grid_x=grid_x, + grid_y=grid_y, + lateral_bc=resolved_proto.lateral_bc, + metrics=metrics, + protocol=resolved_proto, + current_components=tuple(curr_reports), + ion_diagnostics=tuple(ion_reports), + interface_srh_diagnostics=tuple(iface_reports), + output_current_A_m2=j_out, + steady_metrics=sm, + requested_voltages_V=voltages, + attempts=tuple(attempts), + disposition=disp, + scientific_qualification=False, + ) + + +def run_dynamic_jv_pair_2d( + prepared: PreparedDevice, + protocol: DynamicJVPairProtocol2D, + *, + microstructure: object = None, +) -> JV2DDynamicPairResult: + """Execute a continuous 2D preconditioning + forward + turnaround-hold + reverse scan.""" + if not isinstance(prepared, PreparedDevice) or not isinstance(protocol, DynamicJVPairProtocol2D): + raise TypeError("PreparedDevice and DynamicJVPairProtocol2D are required") + ms_input = _coerce_microstructure_input(prepared, microstructure) + nx_intervals = len(protocol.x_coordinates_m) - 1 + elec_layers = [lyr for lyr in prepared.layers if lyr.role != "substrate"] + ny_per = (len(protocol.y_coordinates_m) - 1) // max(len(elec_layers), 1) + lat_len = float(protocol.x_coordinates_m[-1] - protocol.x_coordinates_m[0]) + gen_scale = 1.0 if protocol.illuminated else 0.0 + mobile = protocol.state_topology == "single_positive_mobile_ion" + + if not mobile: + raise CapabilityError( + "dynamic_pair_2d_requires_mobile_ions: forward/reverse hysteresis pair requires single_positive_mobile_ion" + ) + + exec_spatial = JV2DInput( + kind="jv_2d", + lateral_length=lat_len, + Nx=nx_intervals, + Ny_per_layer=ny_per, + lateral_bc=protocol.lateral_bc, + microstructure=ms_input, + ion_dynamics="single_mobile", + interface_srh=protocol.interface_srh, + ) + _, ion_layer_id = _device_has_ions(prepared) + ionic_dev = compile_ionic_device_2d( + prepared, + exec_spatial, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + if not np.allclose(ionic_dev.electronic_component.geometry.x_m, protocol.x_coordinates_m, rtol=0.0, atol=1.0e-15): + raise ValueError("protocol.x_coordinates_m disagrees with compiled 2D lateral mesh") + if not np.allclose(ionic_dev.electronic_component.geometry.y_geometry.nodes_m, protocol.y_coordinates_m, rtol=0.0, atol=1.0e-15): + raise ValueError("protocol.y_coordinates_m disagrees with compiled 2D vertical mesh") + + # 1. Precondition at precondition_voltage_V + steady_res = solve_ionic_steady_state_2d( + ionic_dev, voltage_V=protocol.precondition_voltage_V, generation_scale=0.0 + ) + if not steady_res.accepted or steady_res.state is None: + raise RuntimeError(f"2D dynamic pair dark preconditioning failed: {steady_res.error}") + curr_state = steady_res.state + ion_opts = IonicBackwardEuler2DOptions( + ion_inventory_rtol=max(protocol.ion_inventory_rtol, 1.0e-12), + ) + if protocol.precondition_hold_s > 0.0: + hold_grid = _dwell_time_grid(protocol.precondition_hold_s, max(protocol.substeps_per_point, 8)) + hold_run = run_ionic_backward_euler_2d( + ionic_dev, + curr_state, + hold_grid, + voltage_fn=_const_fn(protocol.precondition_voltage_V), + generation_fn=lambda t: 0.0 if t <= 0.0 else gen_scale, + options=ion_opts, + ) + if not hold_run.accepted: + raise RuntimeError(f"2D preconditioning hold failed: {hold_run.error}") + curr_state = hold_run.states[-1] + precond_sha = state_digest(curr_state.u) + polarity = float(ionic_dev.electronic_component.column.voltage_polarity) + grid_x = ionic_dev.electronic_component.geometry.x_m + grid_y = ionic_dev.electronic_component.geometry.y_geometry.nodes_m + g_dyn_fn = _const_fn(gen_scale) + + def _run_branch(voltages_seq: tuple[float, ...], seed_state: IonicState2D) -> tuple[JV2DResult, IonicState2D]: + state = seed_state + ion_x = ionic_dev.ion_geometry.x_m + ion_y = ionic_dev.ion_geometry.y_geometry.nodes_m + ion_areas = ionic_dev.ion_geometry.contract_geometry.volumes.reshape(ionic_dev.ion_geometry.shape) + ion_lim_2d = ionic_dev.positive_ion_site_limit_m3.reshape(ionic_dev.ion_geometry.shape) + v_list: list[float] = [] + j_list: list[float] = [] + snaps: list[SpatialSnapshot2D] = [] + comps: list[MobileIonCurrentComponents2D] = [] + diags: list[MobileIonDiagnostics2D] = [] + att: list[JV2DPointAttempt] = [] + for idx, v_target in enumerate(voltages_seq): + t0 = time.monotonic() + prev_p = state.positive_ion_density_m3 + if protocol.step_mode == "dwell": + t_sub = _dwell_time_grid(protocol.dwell_or_step_time_s, protocol.substeps_per_point) + v_sub_fn = _const_fn(float(v_target)) + dv_dt = 0.0 + else: + t_sub = np.linspace(0.0, protocol.dwell_or_step_time_s, protocol.substeps_per_point + 1, dtype=np.float64) + v_start = float(state.voltage_V) + dv_dt = (float(v_target) - v_start) / protocol.dwell_or_step_time_s + v_sub_fn = _ramp_fn(v_start, float(v_target), protocol.dwell_or_step_time_s) + run_b = run_ionic_backward_euler_2d( + ionic_dev, + state, + t_sub, + voltage_fn=v_sub_fn, + generation_fn=g_dyn_fn, + options=ion_opts, + ) + if not run_b.accepted: + raise RuntimeError(run_b.error or f"2D dynamic branch failed at V={v_target:.4f} V") + state = run_b.states[-1] + snap = extract_snapshot_2d(ionic_dev, state, generation_scale=gen_scale) + curr_c = compute_mobile_ion_current_components_2d( + ionic_dev, state, generation_scale=gen_scale, applied_voltage_rate_V_s=dv_dt + ) + term_p = state.positive_ion_density_m3 + diag = assess_mobile_ion_terminal_2d( + ion_x, ion_y, prev_p, term_p, ion_lim_2d, + terminal_electron_density=snap.n, terminal_hole_density=snap.p, + inventory_rtol=max(protocol.ion_inventory_rtol, 1.0e-12), + control_volume_areas_m2=ion_areas, + ) + if not diag.passed: + raise RuntimeError("2D dynamic point failed ion diagnostics: " + ", ".join(diag.violations)) + v_list.append(float(v_target)) + j_list.append(curr_c.terminal_total_A_m2) + comps.append(curr_c) + diags.append(diag) + if protocol.save_snapshots: + snaps.append(snap) + att.append( + JV2DPointAttempt( + idx, float(v_target), True, "converged", run_b.bisections, + time.monotonic() - t0, state_digest(state.u), None, + ) + ) + v_arr: Vector = np.asarray(v_list, dtype=np.float64) + j_arr: Vector = np.asarray(j_list, dtype=np.float64) + j_out = -polarity * j_arr + res = JV2DResult( + V=v_arr, + J=j_arr, + snapshots=tuple(snaps), + grid_x=grid_x, + grid_y=grid_y, + lateral_bc=protocol.lateral_bc, + metrics=compute_jv_2d_metrics(v_arr, j_arr), + protocol=None, + current_components=tuple(comps), + ion_diagnostics=tuple(diags), + output_current_A_m2=j_out, + requested_voltages_V=np.asarray(voltages_seq, dtype=np.float64), + attempts=tuple(att), + disposition="completed", + scientific_qualification=False, + ) + return res, state + + fwd_res, after_fwd = _run_branch(protocol.forward_voltages_V, curr_state) + turn_state = after_fwd + if protocol.turnaround_hold_s > 0.0: + t_turn = _dwell_time_grid(protocol.turnaround_hold_s, max(protocol.substeps_per_point, 8)) + hold_turn = run_ionic_backward_euler_2d( + ionic_dev, + turn_state, + t_turn, + voltage_fn=_const_fn(float(protocol.forward_voltages_V[-1])), + generation_fn=g_dyn_fn, + options=ion_opts, + ) + if not hold_turn.accepted: + raise RuntimeError(f"2D turnaround hold failed: {hold_turn.error}") + turn_state = hold_turn.states[-1] + turn_sha = state_digest(turn_state.u) + rev_res, _ = _run_branch(protocol.reverse_voltages_V, turn_state) + voc_delta = ( + float(rev_res.metrics.V_oc - fwd_res.metrics.V_oc) + if fwd_res.metrics.voc_bracketed and rev_res.metrics.voc_bracketed + else None + ) + return JV2DDynamicPairResult( + protocol=protocol, + forward=fwd_res, + reverse=rev_res, + preconditioned_state_sha256=precond_sha, + turnaround_state_sha256=turn_sha, + hysteresis_voc_delta_V=voc_delta, + disposition="completed", + scientific_qualification=False, + ) + + +def write_jv_2d_result(path: str | Path, result: JV2DResult) -> str: + """Write a lossless JSON artifact for ``JV2DResult`` and return its SHA-256.""" + target = Path(path) + payload: dict[str, Any] = { + "schema": JV2D_RESULT_SCHEMA, + "scientific_qualification": False, + "disposition": result.disposition, + "lateral_bc": result.lateral_bc, + "V": result.V, + "J": result.J, + "output_current_A_m2": result.output_current_A_m2, + "requested_voltages_V": result.requested_voltages_V, + "grid_x": result.grid_x, + "grid_y": result.grid_y, + "metrics": asdict(result.metrics), + "protocol": None if result.protocol is None else result.protocol.to_dict(), + "attempts": [asdict(a) for a in result.attempts], + "ion_diagnostics": [asdict(d) for d in result.ion_diagnostics], + } + _atomic_json(target, _encode(payload)) + return hashlib.sha256(target.read_bytes()).hexdigest() + + +def read_jv_2d_result(path: str | Path, *, expected_sha256: str | None = None) -> JV2DResult: + """Read and verify a lossless JSON ``JV2DResult`` artifact.""" + raw = Path(path).read_bytes() + actual_sha = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and actual_sha != expected_sha256: + raise ValueError("JV2DResult SHA-256 mismatch") + doc = _decode(json.loads(raw)) + if doc.get("schema") != JV2D_RESULT_SCHEMA or doc.get("scientific_qualification") is not False: + raise ValueError("invalid JV2DResult schema or qualification flag") + proto = None if doc["protocol"] is None else JV2DProtocol.from_dict(doc["protocol"]) + return JV2DResult( + V=np.asarray(doc["V"], dtype=np.float64), + J=np.asarray(doc["J"], dtype=np.float64), + snapshots=(), + grid_x=np.asarray(doc["grid_x"], dtype=np.float64), + grid_y=np.asarray(doc["grid_y"], dtype=np.float64), + lateral_bc=str(doc["lateral_bc"]), + metrics=JV2DMetrics(**doc["metrics"]), + protocol=proto, + ion_diagnostics=tuple(MobileIonDiagnostics2D(**d) for d in doc["ion_diagnostics"]), + output_current_A_m2=np.asarray(doc["output_current_A_m2"], dtype=np.float64), + requested_voltages_V=np.asarray(doc["requested_voltages_V"], dtype=np.float64), + attempts=tuple(JV2DPointAttempt(**a) for a in doc["attempts"]), + disposition=cast(Disposition, doc["disposition"]), + scientific_qualification=False, + ) diff --git a/src/solarlab/experiments/two_dimensional/refinement_2d.py b/src/solarlab/experiments/two_dimensional/refinement_2d.py new file mode 100644 index 00000000..bcd0bbab --- /dev/null +++ b/src/solarlab/experiments/two_dimensional/refinement_2d.py @@ -0,0 +1,630 @@ +"""4-axis independent 2D refinement harness and sparse structural/resource metrics (P06-03). + +Exercises 1-axis-at-a-time refinement on ``solarlab``'s unified sparse 2D +``Assembler`` + conservative Backward Euler stepper: +1. ``Nx`` (lateral mesh intervals only), +2. ``Ny_per_layer`` (vertical mesh intervals per electrical layer only), +3. ``dt_s`` (time step size only across a fixed physical ``total_time_s`` window), +4. ``nonlinear_tolerance`` (Newton residual tolerance scale only), +while holding the other three axes strictly fixed at ``baseline``. + +Records per-point ``dof``, ``jacobian_nnz``, SuperLU ``lu_nnz`` fill +(``scipy.sparse.linalg.splu(J).nnz``), ``rss_bytes``, ``wall_seconds``, +acceptance, and observable deltas from the finest point along each axis, with +``scientific_qualification=False`` and ``performance_gate_evaluated=False`` +(exclusive-CPU 3-repeat timing gates are never claimed here). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import asdict, dataclass, replace +import hashlib +import json +import math +from pathlib import Path +import resource +import sys +import time +from typing import Any, Literal, TypeAlias, cast + +import numpy as np +from scipy.sparse import csc_matrix +from scipy.sparse.linalg import splu + +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_2d import compile_ionic_device_2d +from solarlab.device.inputs import GrainBoundaryInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.transient_results import _decode, _encode +from solarlab.experiments.two_dimensional.inputs import JV2DInput, MicrostructureInput +from solarlab.experiments.two_dimensional.jv_sweep_2d import ( + _default_ionic_steady_options_1d, + _device_has_ions, + _embed_frozen_ion_excess_2d, + _project_prepared_for_electronic_2d, +) +from solarlab.experiments.worker import _atomic_json +from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state +from solarlab.solvers.nonlinear.ionic_2d import solve_ionic_steady_state_2d +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state +from solarlab.solvers.time.backward_euler_2d import ( + AssembledStorage2D, + BackwardEuler2DOptions, + BackwardEuler2DStep, + run_backward_euler_2d, +) +from solarlab.solvers.time.ionic_backward_euler_2d import ( + AssembledIonic2DProblem, + IonicBackwardEuler2DOptions, + IonicBackwardEuler2DStep, + compute_mobile_ion_current_components_2d, + run_ionic_backward_euler_2d, +) + +__all__ = [ + "FourAxisRefinementReport2D", + "REFINEMENT_2D_SCHEMA", + "RefinementAxisName", + "RefinementAxisReport2D", + "RefinementBaseline2D", + "RefinementPointMetrics2D", + "current_max_rss_bytes", + "read_refinement_report_2d", + "run_four_axis_refinement_2d", + "write_refinement_report_2d", +] + +RefinementAxisName: TypeAlias = Literal["Nx", "Ny_per_layer", "dt_s", "nonlinear_tolerance"] +REFINEMENT_2D_SCHEMA = "solarlab.refinement_2d.report.v1" + + +def current_max_rss_bytes() -> int: + """Return process peak RSS in bytes (macOS reports bytes; Linux reports KiB).""" + raw = int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) + return raw if sys.platform == "darwin" else raw * 1024 + + +@dataclass(frozen=True, slots=True) +class RefinementBaseline2D: + """Fixed baseline controls held constant on the three non-varied axes.""" + + lateral_length_m: float = 2.0e-7 + Nx: int = 4 + Ny_per_layer: int = 6 + dt_s: float = 2.5e-7 + total_time_s: float = 1.0e-6 + nonlinear_tol_scale: float = 1.0 + voltage_V: float = 0.4 + generation_scale: float = 1.0 + lateral_bc: Literal["neumann", "periodic"] = "neumann" + ion_dynamics: Literal["frozen", "single_mobile"] = "frozen" + gb_width_m: float | None = 2.0e-8 + tau_gb_s: tuple[float, float] = (1.0e-9, 1.0e-9) + + def __post_init__(self) -> None: + if not math.isfinite(self.lateral_length_m) or self.lateral_length_m <= 0.0: + raise ValueError("lateral_length_m must be finite and positive") + if type(self.Nx) is not int or self.Nx < 1: + raise ValueError("Nx must be a positive integer") + if type(self.Ny_per_layer) is not int or self.Ny_per_layer < 2: + raise ValueError("Ny_per_layer must be at least 2") + if not math.isfinite(self.dt_s) or self.dt_s <= 0.0: + raise ValueError("dt_s must be finite and positive") + if not math.isfinite(self.total_time_s) or self.total_time_s < self.dt_s: + raise ValueError("total_time_s must be >= dt_s") + if not math.isfinite(self.nonlinear_tol_scale) or self.nonlinear_tol_scale <= 0.0: + raise ValueError("nonlinear_tol_scale must be finite and positive") + if not math.isfinite(self.voltage_V) or not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("voltage_V must be finite and generation_scale >= 0") + if self.gb_width_m is not None: + if not math.isfinite(self.gb_width_m) or self.gb_width_m <= 0.0 or self.gb_width_m > self.lateral_length_m: + raise ValueError("gb_width_m must be in (0, lateral_length_m]") + if self.lateral_bc != "neumann": + raise ValueError("centered grain-boundary refinement requires lateral_bc='neumann'") + if self.ion_dynamics == "single_mobile" and self.lateral_bc != "neumann": + raise ValueError("single_mobile refinement requires lateral_bc='neumann'") + + +@dataclass(frozen=True, slots=True) +class RefinementPointMetrics2D: + """Structural sparsity, SuperLU fill, RSS, timing, and observable record for one point.""" + + axis: RefinementAxisName + control_value: float + nx_intervals: int + ny_per_layer: int + dt_s: float + nonlinear_tol_scale: float + dof: int + jacobian_nnz: int + lu_nnz: int + rss_bytes: int + wall_seconds: float + newton_iterations: int + accepted: bool + termination: str + terminal_current_A_m2: float + ion_inventory_rel_drift: float | None = None + delta_from_finest_current_A_m2: float | None = None + error: str | None = None + + +@dataclass(frozen=True, slots=True) +class RefinementAxisReport2D: + """Independent 1-axis refinement series holding the other 3 axes fixed.""" + + axis: RefinementAxisName + held_fixed: dict[str, float | int | str] + points: tuple[RefinementPointMetrics2D, ...] + all_accepted: bool + finest_control_value: float + finest_terminal_current_A_m2: float | None + + +@dataclass(frozen=True, slots=True) +class FourAxisRefinementReport2D: + """Complete 4-axis independent 2D refinement report (P06-03 clauses 1-2).""" + + baseline: RefinementBaseline2D + nx_axis: RefinementAxisReport2D + ny_axis: RefinementAxisReport2D + dt_axis: RefinementAxisReport2D + nonlinear_tolerance_axis: RefinementAxisReport2D + scientific_qualification: bool = False + performance_gate_evaluated: bool = False + performance_gate_note: str = ( + "single_run_structural_observation_only; exclusive_cpu_3_repeat_gate_deferred" + ) + + def to_dict(self) -> dict[str, Any]: + return { + "schema": REFINEMENT_2D_SCHEMA, + "scientific_qualification": False, + "performance_gate_evaluated": False, + "performance_gate_note": self.performance_gate_note, + "baseline": asdict(self.baseline), + "nx_axis": asdict(self.nx_axis), + "ny_axis": asdict(self.ny_axis), + "dt_axis": asdict(self.dt_axis), + "nonlinear_tolerance_axis": asdict(self.nonlinear_tolerance_axis), + } + + +def _scaled_steady_options(scale: float) -> SteadyOptions: + base = BackwardEuler2DOptions().electronic + return replace( + base, + poisson_tolerance=base.poisson_tolerance * scale, + continuity_tolerance_A_m2=base.continuity_tolerance_A_m2 * scale, + contact_log_tolerance=base.contact_log_tolerance * scale, + ) + + +def _microstructure_for_baseline( + prepared: PreparedDevice, + baseline: RefinementBaseline2D, +) -> MicrostructureInput: + if baseline.gb_width_m is None: + return MicrostructureInput(grain_boundaries=()) + abs_ids = [lyr.id for lyr in prepared.layers if lyr.role != "substrate" and lyr.role == "absorber"] + if not abs_ids: + return MicrostructureInput(grain_boundaries=()) + gb = GrainBoundaryInput.model_validate( + { + "id": "refinement_gb", + "layer_ids": abs_ids, + "x_position": 0.5 * baseline.lateral_length_m, + "width": baseline.gb_width_m, + "tau_n": baseline.tau_gb_s[0], + "tau_p": baseline.tau_gb_s[1], + } + ) + return MicrostructureInput(grain_boundaries=(gb,)) + + +def _build_time_grid(total_time_s: float, dt_s: float) -> np.ndarray: + n_steps = max(1, int(round(total_time_s / dt_s))) + return np.linspace(0.0, total_time_s, n_steps + 1, dtype=np.float64) + + +def _evaluate_one_point( + prepared: PreparedDevice, + baseline: RefinementBaseline2D, + *, + axis: RefinementAxisName, + control_value: float, + nx_val: int, + ny_val: int, + dt_val: float, + tol_scale: float, +) -> RefinementPointMetrics2D: + t0 = time.monotonic() + ms_input = _microstructure_for_baseline(prepared, baseline) + t_grid = _build_time_grid(baseline.total_time_s, dt_val) + actual_dt = float(t_grid[1] - t_grid[0]) + elec_tol = _scaled_steady_options(tol_scale) + + if baseline.ion_dynamics == "single_mobile": + _, ion_layer_id = _device_has_ions(prepared) + exec_spatial = JV2DInput( + kind="jv_2d", + lateral_length=baseline.lateral_length_m, + Nx=nx_val, + Ny_per_layer=ny_val, + lateral_bc=baseline.lateral_bc, + microstructure=ms_input, + ion_dynamics="single_mobile", + interface_srh="off", + ) + ionic_dev = compile_ionic_device_2d( + prepared, + exec_spatial, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + # Seed from 1D dark equilibrium on grain-free Nx=1 column + aux_prep = _project_prepared_for_electronic_2d( + prepared, strip_ions=False, strip_interfaces=False, strip_grains=True + ) + aux_sp = JV2DInput( + kind="jv_2d", + lateral_length=baseline.lateral_length_m, + Nx=1, + Ny_per_layer=ny_val, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="single_mobile", + interface_srh="off", + ) + aux_dev = compile_ionic_device_2d( + aux_prep, + aux_sp, + ion_domain_layer=ionic_dev.domain_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + dark_aux = solve_ionic_steady_state_2d(aux_dev, voltage_V=0.0, generation_scale=0.0) + if not dark_aux.accepted or dark_aux.state is None: + raise RuntimeError(f"refinement 1D ionic seed failed: {dark_aux.error}") + ny_e = ionic_dev.electronic_component.geometry.ny + ny_i = ionic_dev.ion_geometry.ny + aux_nx = aux_dev.electronic_component.geometry.nx + u_e_1d = dark_aux.state.u[:3 * aux_dev.node_count].reshape(3, ny_e, aux_nx)[:, :, 0].ravel() + y_i_1d = dark_aux.state.u[3 * aux_dev.node_count:].reshape(ny_i, aux_nx)[:, 0] + s0_ion = ionic_dev.state( + np.r_[ + ionic_dev.electronic_component.extrude_coordinates(u_e_1d), + np.repeat(y_i_1d, ionic_dev.ion_geometry.nx), + ], + voltage_V=0.0, + ) + + # Measure sparse Jacobian & SuperLU fill on actual BE step matrix J_BE = J + M / dt + p_curr = AssembledIonic2DProblem(ionic_dev, baseline.voltage_V, baseline.generation_scale) + p_prev = AssembledIonic2DProblem(ionic_dev, 0.0, 0.0) + be_step_ion = IonicBackwardEuler2DStep(p_curr, p_prev, s0_ion.u, actual_dt) + j_be_ion = be_step_ion.jacobian(s0_ion.u) + if not isinstance(j_be_ion, csc_matrix): + raise TypeError("2D ionic BE Jacobian must be a preallocated sparse csc_matrix") + jac_nnz = int(j_be_ion.nnz) + lu_nnz = int(splu(j_be_ion).nnz) + + ion_opts = IonicBackwardEuler2DOptions( + electronic=elec_tol, + ion_step_rtol=max(1.0e-12 * tol_scale, 1.0e-14), + ion_inventory_rtol=1.0e-9, + ) + dv_dt = baseline.voltage_V / baseline.total_time_s + run_i = run_ionic_backward_euler_2d( + ionic_dev, + s0_ion, + t_grid, + voltage_fn=lambda t: dv_dt * t, + generation_fn=lambda _t: baseline.generation_scale, + options=ion_opts, + ) + wall = time.monotonic() - t0 + rss = current_max_rss_bytes() + if not run_i.accepted: + return RefinementPointMetrics2D( + axis=axis, control_value=control_value, nx_intervals=nx_val, ny_per_layer=ny_val, + dt_s=actual_dt, nonlinear_tol_scale=tol_scale, dof=ionic_dev.state_size, + jacobian_nnz=jac_nnz, lu_nnz=lu_nnz, rss_bytes=rss, wall_seconds=wall, + newton_iterations=run_i.total_newton_iterations, accepted=False, termination=run_i.termination, + terminal_current_A_m2=math.nan, ion_inventory_rel_drift=None, error=run_i.error, + ) + curr_c = compute_mobile_ion_current_components_2d( + ionic_dev, + run_i.states[-1], + generation_scale=baseline.generation_scale, + applied_voltage_rate_V_s=dv_dt, + ) + return RefinementPointMetrics2D( + axis=axis, control_value=control_value, nx_intervals=nx_val, ny_per_layer=ny_val, + dt_s=actual_dt, nonlinear_tol_scale=tol_scale, dof=ionic_dev.state_size, + jacobian_nnz=jac_nnz, lu_nnz=lu_nnz, rss_bytes=rss, wall_seconds=wall, + newton_iterations=run_i.total_newton_iterations, accepted=True, termination=run_i.termination, + terminal_current_A_m2=curr_c.terminal_total_A_m2, + ion_inventory_rel_drift=run_i.ion_diagnostics.relative_inventory_drift, + ) + + # Frozen-ion / classical 2D refinement lane + has_ions, ion_layer_id = _device_has_ions(prepared) + clean_prep = _project_prepared_for_electronic_2d(prepared, strip_ions=has_ions, strip_interfaces=False) + geom_sp = JV2DInput( + kind="jv_2d", + lateral_length=baseline.lateral_length_m, + Nx=nx_val, + Ny_per_layer=ny_val, + lateral_bc=baseline.lateral_bc, + microstructure=ms_input, + ) + elec_dev = compile_device_2d(clean_prep, geom_sp) + if has_ions and ion_layer_id is not None: + n_layers = len([lyr for lyr in prepared.layers if lyr.role != "substrate"]) + prep_1d_ion = _project_prepared_for_electronic_2d( + prepared, strip_ions=False, strip_interfaces=False, strip_grains=True + ) + from solarlab.device.compile_ionic_1d import compile_ionic_device_1d + + ion_1d = compile_ionic_device_1d( + prep_1d_ion, + intervals_per_layer=(ny_val,) * n_layers, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + dark_1d_i = solve_ionic_steady_state( + ion_1d, + voltage_V=0.0, + generation_scale=0.0, + options=_default_ionic_steady_options_1d(ion_1d.ion_node_count), + ) + if not dark_1d_i.accepted or dark_1d_i.state is None: + raise RuntimeError(f"refinement 1D frozen-ion seed failed: {dark_1d_i.error}") + exc: np.ndarray = np.zeros(ion_1d.node_count, dtype=np.float64) + exc[ion_1d.ion_node_indices] = ( + dark_1d_i.state.positive_ion_density_m3 - ion_1d.positive_ion_reference_m3 + ) * ion_1d.ion_charge_weight_ratio + elec_dev = _embed_frozen_ion_excess_2d(elec_dev, exc) + u_1d = dark_1d_i.state.u[:3 * ion_1d.node_count] + else: + dark_1d = solve_steady_state(elec_dev.column, voltage_V=0.0, generation_scale=0.0) + if dark_1d.state is None: + raise RuntimeError("refinement 1D dark seed failed") + u_1d = dark_1d.state.u + + s0_elec = elec_dev.state(elec_dev.extrude_coordinates(u_1d), voltage_V=0.0) + st_curr = AssembledStorage2D(elec_dev, baseline.voltage_V, baseline.generation_scale) + st_prev = AssembledStorage2D(elec_dev, 0.0, 0.0) + be_step_e = BackwardEuler2DStep(st_curr, st_prev, s0_elec.u, actual_dt) + j_be_e = be_step_e.jacobian(s0_elec.u) + if not isinstance(j_be_e, csc_matrix): + raise TypeError("2D BE Jacobian must be a preallocated sparse csc_matrix") + jac_nnz = int(j_be_e.nnz) + lu_nnz = int(splu(j_be_e).nnz) + + be_opts = BackwardEuler2DOptions(electronic=elec_tol) + dv_dt = baseline.voltage_V / baseline.total_time_s + run_e = run_backward_euler_2d( + elec_dev, + s0_elec, + t_grid, + voltage_fn=lambda t: dv_dt * t, + generation_fn=lambda _t: baseline.generation_scale, + options=be_opts, + ) + wall = time.monotonic() - t0 + rss = current_max_rss_bytes() + if not run_e.accepted: + return RefinementPointMetrics2D( + axis=axis, control_value=control_value, nx_intervals=nx_val, ny_per_layer=ny_val, + dt_s=actual_dt, nonlinear_tol_scale=tol_scale, dof=3 * elec_dev.node_count, + jacobian_nnz=jac_nnz, lu_nnz=lu_nnz, rss_bytes=rss, wall_seconds=wall, + newton_iterations=run_e.total_newton_iterations, accepted=False, termination=run_e.termination, + terminal_current_A_m2=math.nan, error=run_e.error, + ) + j_term = float(run_e.accountings[-1].terminal_total_A_m2[1]) + return RefinementPointMetrics2D( + axis=axis, control_value=control_value, nx_intervals=nx_val, ny_per_layer=ny_val, + dt_s=actual_dt, nonlinear_tol_scale=tol_scale, dof=3 * elec_dev.node_count, + jacobian_nnz=jac_nnz, lu_nnz=lu_nnz, rss_bytes=rss, wall_seconds=wall, + newton_iterations=run_e.total_newton_iterations, accepted=True, termination=run_e.termination, + terminal_current_A_m2=j_term, + ) + + +def _finalize_axis( + axis: RefinementAxisName, + held_fixed: dict[str, float | int | str], + raw_points: list[RefinementPointMetrics2D], + *, + finest_is_largest: bool, +) -> RefinementAxisReport2D: + ordered = sorted(raw_points, key=lambda p: p.control_value, reverse=not finest_is_largest) + # After sorting: ordered[-1] is always the finest point (largest Nx/Ny or smallest dt/tol) + finest = ordered[-1] + finest_j = finest.terminal_current_A_m2 if finest.accepted else None + enriched = tuple( + replace( + pt, + delta_from_finest_current_A_m2=( + abs(pt.terminal_current_A_m2 - finest_j) + if pt.accepted and finest_j is not None + else None + ), + ) + for pt in ordered + ) + return RefinementAxisReport2D( + axis=axis, + held_fixed=held_fixed, + points=enriched, + all_accepted=all(pt.accepted for pt in enriched), + finest_control_value=finest.control_value, + finest_terminal_current_A_m2=finest_j, + ) + + +def run_four_axis_refinement_2d( + prepared: PreparedDevice, + *, + baseline: RefinementBaseline2D | None = None, + nx_values: Sequence[int] = (4, 8, 12), + ny_per_layer_values: Sequence[int] = (4, 8, 12), + dt_s_values: Sequence[float] = (5.0e-7, 2.5e-7, 1.25e-7), + nonlinear_tol_scales: Sequence[float] = (10.0, 1.0, 0.1), +) -> FourAxisRefinementReport2D: + """Execute independent 1-axis-at-a-time 2D refinements across Nx, Ny, dt, and nonlinear tol.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("PreparedDevice is required") + base = RefinementBaseline2D() if baseline is None else baseline + + nx_seq = [int(v) for v in nx_values] + ny_seq = [int(v) for v in ny_per_layer_values] + dt_seq = [float(v) for v in dt_s_values] + tol_seq = [float(v) for v in nonlinear_tol_scales] + if len(set(nx_seq)) < 2 or any(v < 1 for v in nx_seq): + raise ValueError("nx_values requires at least 2 distinct positive integers") + if len(set(ny_seq)) < 2 or any(v < 2 for v in ny_seq): + raise ValueError("ny_per_layer_values requires at least 2 distinct integers >= 2") + if len(set(dt_seq)) < 2 or any(not math.isfinite(v) or v <= 0.0 or v > base.total_time_s for v in dt_seq): + raise ValueError("dt_s_values requires at least 2 distinct positive steps <= baseline.total_time_s") + if len(set(tol_seq)) < 2 or any(not math.isfinite(v) or v <= 0.0 for v in tol_seq): + raise ValueError("nonlinear_tol_scales requires at least 2 distinct positive scales") + + # Axis 1: Lateral Nx only + nx_pts = [ + _evaluate_one_point( + prepared, base, axis="Nx", control_value=float(nx_v), + nx_val=nx_v, ny_val=base.Ny_per_layer, dt_val=base.dt_s, tol_scale=base.nonlinear_tol_scale, + ) + for nx_v in nx_seq + ] + nx_rep = _finalize_axis( + "Nx", + { + "Ny_per_layer": base.Ny_per_layer, + "dt_s": base.dt_s, + "nonlinear_tol_scale": base.nonlinear_tol_scale, + }, + nx_pts, + finest_is_largest=True, + ) + + # Axis 2: Vertical Ny_per_layer only + ny_pts = [ + _evaluate_one_point( + prepared, base, axis="Ny_per_layer", control_value=float(ny_v), + nx_val=base.Nx, ny_val=ny_v, dt_val=base.dt_s, tol_scale=base.nonlinear_tol_scale, + ) + for ny_v in ny_seq + ] + ny_rep = _finalize_axis( + "Ny_per_layer", + { + "Nx": base.Nx, + "dt_s": base.dt_s, + "nonlinear_tol_scale": base.nonlinear_tol_scale, + }, + ny_pts, + finest_is_largest=True, + ) + + # Axis 3: Temporal dt_s only + dt_pts = [ + _evaluate_one_point( + prepared, base, axis="dt_s", control_value=dt_v, + nx_val=base.Nx, ny_val=base.Ny_per_layer, dt_val=dt_v, tol_scale=base.nonlinear_tol_scale, + ) + for dt_v in dt_seq + ] + dt_rep = _finalize_axis( + "dt_s", + { + "Nx": base.Nx, + "Ny_per_layer": base.Ny_per_layer, + "nonlinear_tol_scale": base.nonlinear_tol_scale, + }, + dt_pts, + finest_is_largest=False, + ) + + # Axis 4: Nonlinear tolerance scale only + tol_pts = [ + _evaluate_one_point( + prepared, base, axis="nonlinear_tolerance", control_value=tol_v, + nx_val=base.Nx, ny_val=base.Ny_per_layer, dt_val=base.dt_s, tol_scale=tol_v, + ) + for tol_v in tol_seq + ] + tol_rep = _finalize_axis( + "nonlinear_tolerance", + { + "Nx": base.Nx, + "Ny_per_layer": base.Ny_per_layer, + "dt_s": base.dt_s, + }, + tol_pts, + finest_is_largest=False, + ) + + return FourAxisRefinementReport2D( + baseline=base, + nx_axis=nx_rep, + ny_axis=ny_rep, + dt_axis=dt_rep, + nonlinear_tolerance_axis=tol_rep, + scientific_qualification=False, + performance_gate_evaluated=False, + ) + + +def write_refinement_report_2d(path: str | Path, report: FourAxisRefinementReport2D) -> str: + """Write a lossless JSON artifact for ``FourAxisRefinementReport2D`` and return SHA-256.""" + target = Path(path) + _atomic_json(target, _encode(report.to_dict())) + return hashlib.sha256(target.read_bytes()).hexdigest() + + +def read_refinement_report_2d( + path: str | Path, *, expected_sha256: str | None = None +) -> FourAxisRefinementReport2D: + """Read and verify a lossless JSON ``FourAxisRefinementReport2D`` artifact.""" + raw = Path(path).read_bytes() + actual_sha = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and actual_sha != expected_sha256: + raise ValueError("FourAxisRefinementReport2D SHA-256 mismatch") + doc = _decode(json.loads(raw)) + if ( + doc.get("schema") != REFINEMENT_2D_SCHEMA + or doc.get("scientific_qualification") is not False + or doc.get("performance_gate_evaluated") is not False + ): + raise ValueError("invalid FourAxisRefinementReport2D schema or qualification flags") + base_d = dict(doc["baseline"]) + base_d["tau_gb_s"] = tuple(base_d["tau_gb_s"]) + + def load_axis(axis_doc: dict[str, Any]) -> RefinementAxisReport2D: + pts = tuple(RefinementPointMetrics2D(**p) for p in axis_doc["points"]) + return RefinementAxisReport2D( + axis=cast(RefinementAxisName, axis_doc["axis"]), + held_fixed=dict(axis_doc["held_fixed"]), + points=pts, + all_accepted=bool(axis_doc["all_accepted"]), + finest_control_value=float(axis_doc["finest_control_value"]), + finest_terminal_current_A_m2=( + None if axis_doc["finest_terminal_current_A_m2"] is None + else float(axis_doc["finest_terminal_current_A_m2"]) + ), + ) + + return FourAxisRefinementReport2D( + baseline=RefinementBaseline2D(**base_d), + nx_axis=load_axis(doc["nx_axis"]), + ny_axis=load_axis(doc["ny_axis"]), + dt_axis=load_axis(doc["dt_axis"]), + nonlinear_tolerance_axis=load_axis(doc["nonlinear_tolerance_axis"]), + scientific_qualification=False, + performance_gate_evaluated=False, + performance_gate_note=str(doc["performance_gate_note"]), + ) diff --git a/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py b/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py new file mode 100644 index 00000000..26b2473c --- /dev/null +++ b/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py @@ -0,0 +1,570 @@ +"""2D V_oc(L_g) grain-boundary sweep via 2D J-V dwell or direct 2D steady V_oc root-finding. + +For each lateral grain size ``L_g``, constructs a Neumann-x unit cell with one +centered vertical absorber grain-boundary band (``x_position = L_g / 2``, +``width = gb_width``). Grain-boundary recombination ALWAYS mixes SRH rates by +exact geometric cell-overlap fraction ``f`` (``R = R_bulk + f * (R_gb - R_bulk)``), +never averaging lifetimes first. + +Supports both: +- ``mode="jv_sweep"`` (default): full 2D J-V sweep extracting ``(V_oc, J_sc, FF)``. +- ``mode="direct_voc"`` / :func:`solve_direct_voc_2d`: direct 2D steady + continuation + safeguarded secant/Dekker root-finding on ``J_out(V) = 0`` + across grain width ``L_g`` and ``tau_gb`` or GB recombination velocity ``S_gb``. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from pathlib import Path +import time +from typing import Any, Literal, TypeAlias, cast + +import numpy as np +from numpy.typing import NDArray + +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts import frozen_array +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.inputs import GrainBoundaryInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dc_2d import CompiledDevice2D, State2D +from solarlab.experiments.transient_results import _decode, _encode +from solarlab.experiments.two_dimensional.inputs import ( + GrainSweepInput, + JV2DInput, + MicrostructureInput, +) +from solarlab.experiments.two_dimensional.jv_sweep_2d import ( + Disposition, + ProgressCallback, + _device_has_ions, + _precondition_frozen_lane, + _project_prepared_for_electronic_2d, + build_jv_2d_execution_protocol, + run_jv_sweep_2d, +) +from solarlab.experiments.two_dimensional.preparation import PreparedSpatialExperiment +from solarlab.experiments.worker import _atomic_json +from solarlab.solvers.nonlinear.steady_1d import solve_steady_state +from solarlab.solvers.nonlinear.steady_2d import Steady2DOptions, solve_steady_state_2d + +__all__ = [ + "DirectVoc2DResult", + "VOC_GRAIN_SWEEP_SCHEMA", + "VocGrainPointResult", + "VocGrainSweepResult", + "read_voc_grain_sweep", + "resolve_gb_lifetimes_s", + "run_voc_grain_sweep", + "solve_direct_voc_2d", + "write_voc_grain_sweep", +] + +Vector: TypeAlias = NDArray[np.float64] +VOC_GRAIN_SWEEP_SCHEMA = "solarlab.voc_grain_sweep_2d.result.v1" + + +@dataclass(frozen=True) +class DirectVoc2DResult: + """Direct 2D steady V_oc bracket + safeguarded secant-Dekker root outcome.""" + + accepted: bool + V_oc_V: float + J_sc_Am2: float + residual_current_A_m2: float + bracket_low_V: float + bracket_high_V: float + steady_solves: int + wall_s: float + termination: str + error: str | None = None + scientific_qualification: bool = False + + +@dataclass(frozen=True) +class VocGrainPointResult: + """Per-grain-size execution record with explicit failure/acceptance provenance.""" + + index: int + grain_size_m: float + accepted: bool + V_oc_V: float + J_sc_Am2: float + FF: float + termination: str + wall_s: float + error: str | None = None + + +@dataclass(frozen=True) +class VocGrainSweepResult: + """Aligned ``(grain_sizes_m, V_oc_V, J_sc_Am2, FF)`` result of ``run_voc_grain_sweep``.""" + + grain_sizes_m: Vector + V_oc_V: Vector + J_sc_Am2: Vector + FF: Vector + points: tuple[VocGrainPointResult, ...] = () + mode: Literal["jv_sweep", "direct_voc"] = "jv_sweep" + disposition: Disposition = "completed" + scientific_qualification: bool = False + + def __post_init__(self) -> None: + object.__setattr__(self, "grain_sizes_m", frozen_array(self.grain_sizes_m)) + for name in ("V_oc_V", "J_sc_Am2", "FF"): + arr: Vector = np.array(getattr(self, name), dtype=np.float64, copy=True) + if arr.ndim != 1 or np.isinf(arr).any(): + raise ValueError(f"{name} must be a 1D array without infinities") + arr.setflags(write=False) + object.__setattr__(self, name, arr) + + +def resolve_gb_lifetimes_s( + *, + gb_width_m: float, + tau_gb: tuple[float, float] | None = (1.0e-9, 1.0e-9), + s_gb_m_s: tuple[float, float] | float | None = None, +) -> tuple[float, float]: + """Resolve effective GB band SRH lifetimes from ``tau_gb`` or velocity ``s_gb_m_s``.""" + if not math.isfinite(gb_width_m) or gb_width_m <= 0.0: + raise ValueError("gb_width_m must be finite and positive") + if s_gb_m_s is not None: + if tau_gb is not None: + raise ValueError("supply either tau_gb or s_gb_m_s, not both") + if isinstance(s_gb_m_s, (int, float)): + sn = sp = float(s_gb_m_s) + else: + if len(s_gb_m_s) != 2: + raise ValueError("s_gb_m_s must be a positive scalar or (S_n, S_p) pair") + sn, sp = float(s_gb_m_s[0]), float(s_gb_m_s[1]) + if not (math.isfinite(sn) and math.isfinite(sp) and sn > 0.0 and sp > 0.0): + raise ValueError("GB recombination velocities must be finite and positive") + return (gb_width_m / sn, gb_width_m / sp) + if tau_gb is None or len(tau_gb) != 2: + raise ValueError("tau_gb must be a positive (tau_n, tau_p) pair") + tn, tp = float(tau_gb[0]), float(tau_gb[1]) + if not (math.isfinite(tn) and math.isfinite(tp) and tn > 0.0 and tp > 0.0): + raise ValueError("tau_gb lifetimes must be finite and positive") + return (tn, tp) + + +def _centered_absorber_microstructure( + prepared: PreparedDevice, + *, + lateral_length_m: float, + gb_width_m: float, + tau_n_s: float, + tau_p_s: float, +) -> MicrostructureInput: + if gb_width_m > lateral_length_m: + raise ValueError( + f"gb_width_m ({gb_width_m:.3e} m) exceeds grain size lateral_length_m ({lateral_length_m:.3e} m)" + ) + target_ids = [ + layer.id for layer in prepared.layers if layer.role != "substrate" and layer.role == "absorber" + ] + if not target_ids: + raise CapabilityError("voc_grain_sweep_missing_absorber: device has no electrical 'absorber' layer") + gb = GrainBoundaryInput.model_validate( + { + "id": "centered_gb", + "layer_ids": target_ids, + "x_position": 0.5 * lateral_length_m, + "width": gb_width_m, + "tau_n": tau_n_s, + "tau_p": tau_p_s, + } + ) + return MicrostructureInput(grain_boundaries=(gb,)) + + +def _rebase_state_2d(device: CompiledDevice2D, state: State2D, new_voltage_V: float) -> State2D: + if state.voltage_V == new_voltage_V: + return state + u = state.u.copy() + n_nodes = device.node_count + old_e = device.column.carrier_reference_energies(state.voltage_V) + new_e = device.column.carrier_reference_energies(new_voltage_V) + for offset, old_val, new_val in zip((n_nodes, 2 * n_nodes), old_e, new_e): + u[offset:offset + n_nodes] += (old_val - new_val) / device.thermal_voltage_V + bottom, top = device.column.contact_potentials(new_voltage_V) + u[:device.geometry.nx] = bottom + u[n_nodes - device.geometry.nx:n_nodes] = top + return device.state(u, voltage_V=new_voltage_V) + + +def solve_direct_voc_2d( + prepared: PreparedDevice, + *, + lateral_length_m: float, + gb_width_m: float = 10.0e-9, + tau_gb: tuple[float, float] | None = (1.0e-9, 1.0e-9), + s_gb_m_s: tuple[float, float] | float | None = None, + Nx: int = 10, + Ny_per_layer: int = 10, + v_max_bracket_V: float = 1.5, + continuation_step_V: float = 0.1, + v_tol_V: float = 1.0e-6, + j_tol_A_m2: float = 1.0e-4, + initial_state_settle_s: float = 1.0e-3, + options: Steady2DOptions | None = None, +) -> DirectVoc2DResult: + """Solve direct 2D illuminated steady ``V_oc`` via continuation bracket + secant-Dekker.""" + started = time.monotonic() + if not math.isfinite(lateral_length_m) or lateral_length_m <= 0.0: + raise ValueError("lateral_length_m must be finite and positive") + tau_n, tau_p = resolve_gb_lifetimes_s( + gb_width_m=gb_width_m, tau_gb=tau_gb, s_gb_m_s=s_gb_m_s + ) + ms_input = _centered_absorber_microstructure( + prepared, + lateral_length_m=lateral_length_m, + gb_width_m=gb_width_m, + tau_n_s=tau_n, + tau_p_s=tau_p, + ) + geom_spatial = JV2DInput( + kind="jv_2d", + lateral_length=lateral_length_m, + Nx=Nx, + Ny_per_layer=Ny_per_layer, + lateral_bc="neumann", + microstructure=ms_input, + ) + has_ions, _ = _device_has_ions(prepared) + if has_ions: + proto = build_jv_2d_execution_protocol( + prepared, + ms_input, + lateral_length=lateral_length_m, + Nx=Nx, + V_max=max(v_max_bracket_V, 0.2), + V_step=max(continuation_step_V, 0.05), + illuminated=True, + lateral_bc="neumann", + Ny_per_layer=Ny_per_layer, + initial_state_settle_s=initial_state_settle_s, + implicit_legacy_protocol=True, + ) + device_2d, seed_2d, rr_specs, iface_couplings = _precondition_frozen_lane( + prepared, geom_spatial, proto + ) + if rr_specs or iface_couplings: + raise CapabilityError( + "direct_voc_2d_unsupported_extensions: direct steady V_oc requires standard local 2D recombination" + ) + else: + clean = _project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False) + device_2d = compile_device_2d(clean, geom_spatial) + col_illum = solve_steady_state(device_2d.column, voltage_V=0.0, generation_scale=1.0) + if col_illum.state is None: + return DirectVoc2DResult( + False, 0.0, 0.0, math.nan, 0.0, 0.0, 0, time.monotonic() - started, + "column_seed_failed", "1D illuminated seed failed", + ) + seed_2d = device_2d.state(device_2d.extrude_coordinates(col_illum.state.u), voltage_V=0.0) + + steady_opts = Steady2DOptions() if options is None else options + polarity = float(device_2d.column.voltage_polarity) + solves = 0 + + def eval_point(v_target: float, ref_state: State2D) -> tuple[bool, float, State2D | None, str | None]: + nonlocal solves + solves += 1 + guess = _rebase_state_2d(device_2d, ref_state, v_target) + res = solve_steady_state_2d( + device_2d, voltage_V=v_target, generation_scale=1.0, options=steady_opts, initial_state=guess + ) + if not res.accepted or res.state is None or res.diagnostics is None: + return False, math.nan, None, res.error or res.termination + term_j = float(res.diagnostics["terminal_mean_current_density_A_m2"][1]) + j_out = -polarity * term_j + return True, j_out, res.state, None + + ok0, jsc_out, s0, err0 = eval_point(0.0, seed_2d) + if not ok0 or s0 is None or jsc_out <= 0.0: + return DirectVoc2DResult( + False, 0.0, max(0.0, jsc_out if math.isfinite(jsc_out) else 0.0), + math.nan, 0.0, 0.0, solves, time.monotonic() - started, + "short_circuit_failed", err0 or "non-positive short-circuit output current", + ) + + # Walk forward in continuation steps until output current crosses <= 0 + v_lo, j_lo, s_lo = 0.0, jsc_out, s0 + v_hi: float | None = None + j_hi: float = math.nan + s_hi: State2D | None = None + step = max(float(continuation_step_V), 0.02) + v_cur = 0.0 + while v_cur < v_max_bracket_V - 1.0e-12: + v_next = min(v_cur + step, v_max_bracket_V) + ok, j_val, s_val, err = eval_point(v_next, s_lo) + if not ok or s_val is None: + if step > 0.0125: + step *= 0.5 + continue + return DirectVoc2DResult( + False, 0.0, jsc_out, math.nan, v_lo, v_next, solves, + time.monotonic() - started, "bracket_continuation_failed", err, + ) + v_cur = v_next + if j_val <= 0.0: + v_hi, j_hi, s_hi = v_next, j_val, s_val + break + v_lo, j_lo, s_lo = v_next, j_val, s_val + + if v_hi is None or s_hi is None: + return DirectVoc2DResult( + False, 0.0, jsc_out, j_lo, v_lo, v_max_bracket_V, solves, + time.monotonic() - started, "voc_not_bracketed", + f"V_oc exceeds v_max_bracket_V={v_max_bracket_V:.3f} V", + ) + + bracket_lo_init, bracket_hi_init = v_lo, v_hi + if abs(j_hi) <= j_tol_A_m2: + return DirectVoc2DResult( + True, v_hi, jsc_out, j_hi, bracket_lo_init, bracket_hi_init, solves, + time.monotonic() - started, "converged", + ) + + # Safeguarded secant-Dekker root polish inside [v_lo, v_hi] + for _ in range(24): + if abs(v_hi - v_lo) <= v_tol_V: + v_best = v_lo + j_lo * (v_hi - v_lo) / (j_lo - j_hi) + j_best = j_lo if abs(j_lo) <= abs(j_hi) else j_hi + return DirectVoc2DResult( + True, float(v_best), jsc_out, float(j_best), bracket_lo_init, bracket_hi_init, + solves, time.monotonic() - started, "converged", + ) + denom = j_lo - j_hi + v_sec = v_lo + j_lo * (v_hi - v_lo) / denom if abs(denom) > 1.0e-30 else 0.5 * (v_lo + v_hi) + margin = 0.05 * (v_hi - v_lo) + v_cand = v_sec if (v_lo + margin) < v_sec < (v_hi - margin) else 0.5 * (v_lo + v_hi) + ref_s = s_lo if abs(v_cand - v_lo) <= abs(v_hi - v_cand) else s_hi + ok_c, j_c, s_c, err_c = eval_point(v_cand, ref_s) + if not ok_c or s_c is None: + # Fall back to midpoint if secant candidate failed + v_cand = 0.5 * (v_lo + v_hi) + ok_c, j_c, s_c, err_c = eval_point(v_cand, s_lo) + if not ok_c or s_c is None: + return DirectVoc2DResult( + False, 0.0, jsc_out, math.nan, bracket_lo_init, bracket_hi_init, solves, + time.monotonic() - started, "root_polish_failed", err_c, + ) + if abs(j_c) <= j_tol_A_m2 and abs(v_hi - v_lo) <= max(10.0 * v_tol_V, 1.0e-5): + return DirectVoc2DResult( + True, float(v_cand), jsc_out, float(j_c), bracket_lo_init, bracket_hi_init, + solves, time.monotonic() - started, "converged", + ) + if j_c > 0.0: + v_lo, j_lo, s_lo = v_cand, j_c, s_c + else: + v_hi, j_hi, s_hi = v_cand, j_c, s_c + + v_est = float(v_lo + j_lo * (v_hi - v_lo) / (j_lo - j_hi)) + return DirectVoc2DResult( + True, v_est, jsc_out, float(min(abs(j_lo), abs(j_hi))), bracket_lo_init, bracket_hi_init, + solves, time.monotonic() - started, "converged", + ) + + +def run_voc_grain_sweep( + prepared_or_experiment: PreparedDevice | PreparedSpatialExperiment, + grain_sizes: Sequence[float] | None = None, + *, + tau_gb: tuple[float, float] | None = (1.0e-9, 1.0e-9), + s_gb_m_s: tuple[float, float] | float | None = None, + gb_width: float = 10.0e-9, + Nx: int = 10, + Ny_per_layer: int = 10, + V_max: float = 1.2, + V_step: float = 0.05, + illuminated: bool = True, + settle_t: float = 1.0e-3, + mode: Literal["jv_sweep", "direct_voc"] = "jv_sweep", + progress: ProgressCallback | None = None, + on_point_failure: Literal["raise", "record_partial"] = "raise", +) -> VocGrainSweepResult: + """Sweep lateral grain size ``L_g`` with one centered absorber GB band.""" + if mode not in {"jv_sweep", "direct_voc"}: + raise ValueError("mode must be 'jv_sweep' or 'direct_voc'") + if on_point_failure not in {"raise", "record_partial"}: + raise ValueError("on_point_failure must be 'raise' or 'record_partial'") + + if isinstance(prepared_or_experiment, PreparedSpatialExperiment): + inp = prepared_or_experiment.to_input() + if not isinstance(inp.experiment, GrainSweepInput): + raise ValueError("PreparedSpatialExperiment does not contain a voc_grain_sweep experiment") + prepared = resolve_device( + inp.device, + prepared_or_experiment.defaults, + prepared_or_experiment.resources, + sources=prepared_or_experiment.sources, + ) + mapping = prepared_or_experiment.to_mapping()["experiment"]["controls"] + sizes_seq: Sequence[float] = grain_sizes if grain_sizes is not None else mapping["grain_sizes_m"] + gb_width = float(mapping["gb_width"]) + tau_gb = (float(mapping["tau_gb_n"]), float(mapping["tau_gb_p"])) if s_gb_m_s is None else None + Nx = int(mapping["Nx"]) + Ny_per_layer = int(mapping["Ny_per_layer"]) + V_max = float(mapping["V_max"]) + V_step = float(mapping["V_step"]) + illuminated = bool(mapping["illuminated"]) + settle_t = float(mapping["settle_t"]) + elif isinstance(prepared_or_experiment, PreparedDevice): + prepared = prepared_or_experiment + if grain_sizes is None: + raise ValueError("grain_sizes must be supplied when running from PreparedDevice") + sizes_seq = grain_sizes + else: + raise TypeError("run_voc_grain_sweep requires PreparedDevice or PreparedSpatialExperiment") + + raw_sizes = [float(g) for g in sizes_seq] + if not raw_sizes or any(not math.isfinite(g) or g <= 0.0 for g in raw_sizes): + raise ValueError("grain_sizes must be a non-empty sequence of finite positive lengths [m]") + tau_n, tau_p = resolve_gb_lifetimes_s(gb_width_m=gb_width, tau_gb=tau_gb, s_gb_m_s=s_gb_m_s) + for g_len in raw_sizes: + if gb_width > g_len: + raise ValueError(f"gb_width ({gb_width:.3e} m) exceeds grain size ({g_len:.3e} m)") + + l_accepted: list[float] = [] + voc_list: list[float] = [] + jsc_list: list[float] = [] + ff_list: list[float] = [] + points: list[VocGrainPointResult] = [] + total = len(raw_sizes) + + for idx, l_g in enumerate(raw_sizes): + t0 = time.monotonic() + try: + if mode == "direct_voc": + if not illuminated: + raise ValueError("direct_voc mode requires illuminated=True") + d_res = solve_direct_voc_2d( + prepared, + lateral_length_m=l_g, + gb_width_m=gb_width, + tau_gb=(tau_n, tau_p), + Nx=Nx, + Ny_per_layer=Ny_per_layer, + v_max_bracket_V=max(V_max, 1.3), + continuation_step_V=max(V_step, 0.05), + ) + if not d_res.accepted: + raise RuntimeError(d_res.error or d_res.termination) + voc_val, jsc_val, ff_val = d_res.V_oc_V, d_res.J_sc_Am2, math.nan + else: + ms_in = _centered_absorber_microstructure( + prepared, + lateral_length_m=l_g, + gb_width_m=gb_width, + tau_n_s=tau_n, + tau_p_s=tau_p, + ) + jv_res = run_jv_sweep_2d( + prepared, + microstructure=ms_in, + lateral_length=l_g, + Nx=Nx, + Ny_per_layer=Ny_per_layer, + V_max=V_max, + V_step=V_step, + illuminated=illuminated, + lateral_bc="neumann", + settle_t=settle_t, + save_snapshots=False, + ) + voc_val = jv_res.metrics.V_oc + jsc_val = jv_res.metrics.J_sc + ff_val = jv_res.metrics.FF + except CapabilityError: + raise + except Exception as exc: + points.append( + VocGrainPointResult( + idx, l_g, False, math.nan, math.nan, math.nan, + "failed", time.monotonic() - t0, str(exc), + ) + ) + if on_point_failure == "raise": + raise + continue + + l_accepted.append(l_g) + voc_list.append(voc_val) + jsc_list.append(jsc_val) + ff_list.append(ff_val) + points.append( + VocGrainPointResult( + idx, l_g, True, voc_val, jsc_val, ff_val, + "converged", time.monotonic() - t0, None, + ) + ) + if progress is not None: + progress( + "voc_grain_sweep", + idx + 1, + total, + f"L_g={l_g * 1.0e9:.0f} nm V_oc={voc_val * 1.0e3:.1f} mV", + ) + + disp: Disposition = ( + "completed" + if len(l_accepted) == total + else ("partial" if l_accepted else "failed") + ) + return VocGrainSweepResult( + grain_sizes_m=np.asarray(l_accepted, dtype=np.float64), + V_oc_V=np.asarray(voc_list, dtype=np.float64), + J_sc_Am2=np.asarray(jsc_list, dtype=np.float64), + FF=np.asarray(ff_list, dtype=np.float64), + points=tuple(points), + mode=mode, + disposition=disp, + scientific_qualification=False, + ) + + +def write_voc_grain_sweep(path: str | Path, result: VocGrainSweepResult) -> str: + """Write a lossless JSON artifact for ``VocGrainSweepResult`` and return SHA-256.""" + target = Path(path) + payload: dict[str, Any] = { + "schema": VOC_GRAIN_SWEEP_SCHEMA, + "scientific_qualification": False, + "mode": result.mode, + "disposition": result.disposition, + "grain_sizes_m": result.grain_sizes_m, + "V_oc_V": result.V_oc_V, + "J_sc_Am2": result.J_sc_Am2, + "FF": result.FF, + "points": [asdict(p) for p in result.points], + } + _atomic_json(target, _encode(payload)) + return hashlib.sha256(target.read_bytes()).hexdigest() + + +def read_voc_grain_sweep(path: str | Path, *, expected_sha256: str | None = None) -> VocGrainSweepResult: + """Read and verify a lossless JSON ``VocGrainSweepResult`` artifact.""" + raw = Path(path).read_bytes() + actual_sha = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and actual_sha != expected_sha256: + raise ValueError("VocGrainSweepResult SHA-256 mismatch") + doc = _decode(json.loads(raw)) + if doc.get("schema") != VOC_GRAIN_SWEEP_SCHEMA or doc.get("scientific_qualification") is not False: + raise ValueError("invalid VocGrainSweepResult schema or qualification flag") + return VocGrainSweepResult( + grain_sizes_m=np.asarray(doc["grain_sizes_m"], dtype=np.float64), + V_oc_V=np.asarray(doc["V_oc_V"], dtype=np.float64), + J_sc_Am2=np.asarray(doc["J_sc_Am2"], dtype=np.float64), + FF=np.asarray(doc["FF"], dtype=np.float64), + points=tuple(VocGrainPointResult(**p) for p in doc["points"]), + mode=cast(Literal["jv_sweep", "direct_voc"], doc["mode"]), + disposition=cast(Disposition, doc["disposition"]), + scientific_qualification=False, + ) diff --git a/src/solarlab/mesh/geometry_2d.py b/src/solarlab/mesh/geometry_2d.py index e37f702d..f2bed503 100644 --- a/src/solarlab/mesh/geometry_2d.py +++ b/src/solarlab/mesh/geometry_2d.py @@ -1,9 +1,10 @@ -"""Rectangular, nonperiodic control volumes per unit out-of-plane depth.""" +"""Rectangular control volumes per unit out-of-plane depth (Neumann or periodic x).""" from __future__ import annotations from dataclasses import dataclass, field import hashlib +from typing import Literal import numpy as np from numpy.typing import NDArray @@ -12,6 +13,8 @@ from solarlab.mesh.geometry import HALF_ENDPOINT_V1, ControlVolumeGeometry1D, half_endpoint_widths RECTANGULAR_HALF_ENDPOINT_2D_V1 = "rectangular_half_endpoint_neumann_2d_v1" +RECTANGULAR_PERIODIC_2D_V1 = "rectangular_half_endpoint_periodic_2d_v1" +RECTANGULAR_2D_NAMES = (RECTANGULAR_HALF_ENDPOINT_2D_V1, RECTANGULAR_PERIODIC_2D_V1) @dataclass(frozen=True) @@ -20,12 +23,15 @@ class RectangularGeometry2D: Areas are wx*wy [m2], and x/y face lengths are wy/wx [m]. Fluxes retain their three-dimensional densities; integrated rows are per metre - of out-of-plane depth. There are no exterior x faces: their explicitly - prescribed displacement and particle fluxes are exactly zero. + of out-of-plane depth. Under ``lateral_bc="neumann"``, exterior lateral + fluxes are identically zero; under ``lateral_bc="periodic"``, each row + carries an explicit wrap face ``(nx-1) -> 0`` with spacing + ``0.5 * (dx[0] + dx[-1])`` and matching dual-cell widths at ``x_min/x_max``. """ x_m: NDArray[np.float64] y_geometry: ControlVolumeGeometry1D + lateral_bc: Literal["neumann", "periodic"] = "neumann" name: str = field(init=False, default=RECTANGULAR_HALF_ENDPOINT_2D_V1) x_widths_m: NDArray[np.float64] = field(init=False) face_spacing_m: NDArray[np.float64] = field(init=False) @@ -33,20 +39,44 @@ class RectangularGeometry2D: sha256: str = field(init=False) def __post_init__(self) -> None: + if self.lateral_bc not in ("neumann", "periodic"): + raise ValueError("lateral_bc must be 'neumann' or 'periodic'") + name = (RECTANGULAR_HALF_ENDPOINT_2D_V1 if self.lateral_bc == "neumann" + else RECTANGULAR_PERIODIC_2D_V1) + object.__setattr__(self, "name", name) x = frozen_array(self.x_m) - widths = half_endpoint_widths(x) + neumann_widths = half_endpoint_widths(x) + if self.lateral_bc == "neumann": + widths = neumann_widths + else: + dx = np.diff(x) + dx_wrap = 0.5 * float(dx[0] + dx[-1]) + widths = np.empty_like(x) + widths[0] = dx_wrap + widths[-1] = dx_wrap + if x.size > 2: + widths[1:-1] = 0.5 * (dx[:-1] + dx[1:]) y = self.y_geometry if y.name != HALF_ENDPOINT_V1 or y.node_count < 3: raise ValueError("2D stack requires at least three nodes with physical half-endpoint cells") object.__setattr__(self, "x_m", x) object.__setattr__(self, "x_widths_m", frozen_array(widths)) ids = np.arange(self.node_count).reshape(self.shape) - x_pairs = np.column_stack((ids[:, :-1].ravel(), ids[:, 1:].ravel())) + if self.lateral_bc == "neumann": + x_pairs = np.column_stack((ids[:, :-1].ravel(), ids[:, 1:].ravel())) + x_measures: np.ndarray = np.repeat(y.cell_measures_m, self.nx - 1) + x_distances = np.tile(np.diff(x), self.ny) + else: + dx = np.diff(x) + dx_wrap = 0.5 * float(dx[0] + dx[-1]) + x_pairs = np.column_stack((ids.ravel(), np.roll(ids, -1, axis=1).ravel())) + x_measures = np.repeat(y.cell_measures_m, self.nx) + x_distances = np.tile(np.r_[dx, dx_wrap], self.ny) y_pairs = np.column_stack((ids[:-1, :].ravel(), ids[1:, :].ravel())) pairs = np.concatenate((x_pairs, y_pairs)) areas = (y.cell_measures_m[:, None] * widths[None, :]).ravel() - measures = np.r_[np.repeat(y.cell_measures_m, self.nx - 1), np.tile(widths, self.ny - 1)] - distances = np.r_[np.tile(np.diff(x), self.ny), np.repeat(np.diff(y.nodes_m), self.nx)] + measures = np.r_[x_measures, np.tile(widths, self.ny - 1)] + distances = np.r_[x_distances, np.repeat(np.diff(y.nodes_m), self.nx)] geometry = Geometry(areas, pairs, measures, AREA, LENGTH) object.__setattr__(self, "contract_geometry", geometry) object.__setattr__(self, "face_spacing_m", frozen_array(distances)) @@ -71,14 +101,30 @@ def shape(self) -> tuple[int, int]: def node_count(self) -> int: return self.nx * self.ny + @property + def x_faces_per_row(self) -> int: + return self.nx if self.lateral_bc == "periodic" else self.nx - 1 + @property def x_face_count(self) -> int: - return self.ny * (self.nx - 1) + return self.ny * self.x_faces_per_row @property - def lateral_length_m(self) -> float: + def domain_span_m(self) -> float: return float(self.x_m[-1] - self.x_m[0]) + @property + def lateral_length_m(self) -> float: + if self.lateral_bc == "neumann": + return float(self.x_m[-1] - self.x_m[0]) + return float(np.sum(self.x_widths_m)) + + @property + def wrap_face_indices(self) -> NDArray[np.intp]: + if self.lateral_bc == "neumann": + return np.empty(0, dtype=np.intp) + return np.arange(self.nx - 1, self.x_face_count, self.nx, dtype=np.intp) + @property def contact_nodes(self) -> NDArray[np.int64]: return np.r_[np.arange(self.nx), np.arange(self.node_count - self.nx, self.node_count)] diff --git a/src/solarlab/solvers/nonlinear/ionic_2d.py b/src/solarlab/solvers/nonlinear/ionic_2d.py new file mode 100644 index 00000000..b2e3e648 --- /dev/null +++ b/src/solarlab/solvers/nonlinear/ionic_2d.py @@ -0,0 +1,414 @@ +"""Coupled 2D steady solver with whole-domain finite-site ion inventory closure. + +Replaces one ion balance row (``3*N + inventory_row_node``) with the physical 2D +domain inventory constraint ``fsum(area * P) - fsum(area * P0) = 0`` (or closes +every ion cell to ``P0`` when ``D_ion == 0`` everywhere). Every original ion row +is checked independently in ``diagnostics`` and ``checks``. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +import hashlib +import math +import time +from typing import Any, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix + +from solarlab.contracts import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.equations.assembly.ionic_2d import AssembledConstrainedIonic2DProblem, AssembledIonic2DProblem +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.implementation import use_assembled +from solarlab.equations.ionic_2d import CompiledIonicDevice2D, Ionic2DProblem, IonicState2D +from solarlab.reproducibility.job_provenance import admitted_source_pins +from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import CallableProblem, GateOutcome, ResidualScaling, SolveBudget, StepControl, state_digest +from solarlab.solvers.nonlinear.production import HISTORICAL_MAX_ROW_V1 +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + +__all__ = [ + "ConstrainedIonic2DProblem", + "IonicSteady2DOptions", + "IonicSteady2DResult", + "checks", + "diagnostics", + "solve_ionic_steady_state_2d", +] + + +@dataclass(frozen=True) +class ConstrainedIonic2DProblem: + """Reference 2D ionic steady problem with mobile inventory or immobile profile closure.""" + + original: Ionic2DProblem + inventory_row_node: int = 0 + + def __post_init__(self) -> None: + d = self.original.device + if type(self.inventory_row_node) is not int or not 0 <= self.inventory_row_node < d.ion_node_count: + raise ValueError("inventory_row_node must name a 2D ion-domain node") + manifest = d.binding_manifest + if hashlib.sha256(d.binding_manifest_json.encode()).hexdigest() != d.identity: + raise ValueError("2D ionic binding manifest hash mismatch") + domain = manifest.get("ion_domain") + contacts = domain.get("contacts") if isinstance(domain, dict) else None + if not isinstance(contacts, list) or contacts[:2] != ["blocking", "blocking"]: + raise CapabilityError("2D ionic steady closure requires four-side blocking domain") + + @property + def is_immobile(self) -> bool: + return bool(np.all(self.original.device.positive_ion_diffusivity_faces_m2_s == 0.0)) + + @property + def constraint_row(self) -> int: + return 3 * self.original.device.node_count + self.inventory_row_node + + @property + def inventory_target_m1(self) -> float: + return self.original.device.reference_inventory_m1 + + def residual(self, u: ArrayLike) -> np.ndarray: + res = self.original.residual(u) + if not np.all(np.isfinite(res)): + return res + d = self.original.device + _, _, _, ion_p = d.fields(u, voltage_V=self.original.voltage_V) + vol = d.ion_geometry.contract_geometry.volumes + if self.is_immobile: + res[3 * d.node_count:] = vol * (ion_p - d.positive_ion_reference_m3) + return res + inventory = math.fsum((vol * ion_p).tolist()) + res[self.constraint_row] = inventory - self.inventory_target_m1 + return res + + def jacobian(self, u: ArrayLike) -> csc_matrix: + jac = self.original.jacobian(u).tolil() + d = self.original.device + _, _, _, ion_p = d.fields(u, voltage_V=self.original.voltage_V) + vol = d.ion_geometry.contract_geometry.volumes + dp_dy = vol * ion_p * (1.0 - ion_p / d.positive_ion_site_limit_m3) + start = 3 * d.node_count + if self.is_immobile: + for idx in range(d.ion_node_count): + row = start + idx + jac.rows[row] = [row] + jac.data[row] = [float(dp_dy[idx])] + return jac.tocsc() + row = self.constraint_row + jac.rows[row] = list(range(start, start + d.ion_node_count)) + jac.data[row] = dp_dy.tolist() + return jac.tocsc() + + +@dataclass(frozen=True) +class IonicSteady2DOptions: + """Explicit numerical controls and conservation gates for 2D coupled ionic steady.""" + + electronic: SteadyOptions = field(default_factory=SteadyOptions) + inventory_relative_tolerance: float = 1.0e-12 + ion_balance_tolerance_m1_s: float = 1.0e3 + ion_flux_tolerance_m2_s: float = 1.0e9 + ion_logit_step: float = 1.0 + inventory_row_node: int = 0 + budget: SolveBudget = field(default_factory=lambda: SolveBudget(60, 600, 60, 24)) + wall_s: float = 30.0 + + def __post_init__(self) -> None: + if not isinstance(self.electronic, SteadyOptions) or not isinstance(self.budget, SolveBudget): + raise ValueError("SteadyOptions and SolveBudget are required") + for name in ( + "inventory_relative_tolerance", + "ion_balance_tolerance_m1_s", + "ion_flux_tolerance_m2_s", + "ion_logit_step", + "wall_s", + ): + val = float(getattr(self, name)) + if not math.isfinite(val) or val <= 0.0: + raise ValueError(f"{name} must be finite and positive") + + +@dataclass(frozen=True) +class IonicSteady2DResult: + """Coupled 2D ionic steady solve outcome and independent gate diagnostics.""" + + state: IonicState2D | None + accepted: bool + termination: str + newton: NewtonResult | None + initial_coordinates: np.ndarray + candidate_coordinates: np.ndarray + diagnostics: dict[str, Any] | None + checks: tuple[GateOutcome, ...] + compiled_identity: str + operating_voltage_V: float + generation_scale: float + solver_controls: dict[str, Any] + source_sha256: dict[str, str] + wall_s: float + error: str | None = None + scientific_qualification: bool = False + + def __post_init__(self) -> None: + object.__setattr__(self, "initial_coordinates", frozen_array(self.initial_coordinates)) + object.__setattr__(self, "candidate_coordinates", frozen_array(self.candidate_coordinates)) + + +_Unconstrained2D: TypeAlias = Ionic2DProblem | AssembledIonic2DProblem + + +def _poisson_weights_2d(device: CompiledIonicDevice2D) -> np.ndarray: + comp = device.electronic_component + g = comp.geometry.contract_geometry + reference_V = max(abs(comp.column.built_in_potential_V), comp.thermal_voltage_V) + density = comp.extrude(np.maximum(np.maximum( + comp.column.parameters.acceptor_density_m3, + comp.column.parameters.donor_density_m3, + ), 1.0)) + density = density.copy() + density[device.ion_node_indices] = np.maximum( + density[device.ion_node_indices], + device.positive_ion_reference_m3, + ) + capacitance = np.zeros(comp.node_count) + face = comp.face_capacitance_F_m2 * g.face_measures + np.add.at(capacitance, g.pairs[:, 0], face) + np.add.at(capacitance, g.pairs[:, 1], face) + scale = Q * density * g.volumes + reference_V * capacitance + result = 1.0 / scale + result[comp.geometry.contact_nodes] = 1.0 / reference_V + return result + + +def _newton_settings(device: CompiledIonicDevice2D, options: IonicSteady2DOptions, gate: Any) -> NewtonSettings: + c = options.electronic + comp = device.electronic_component + n_elec = comp.node_count + n_ion = device.ion_node_count + weights: NDArray[np.float64] = np.empty(device.state_size, dtype=np.float64) + weights[:n_elec] = _poisson_weights_2d(device) / c.poisson_tolerance + weights[n_elec:3 * n_elec] = 2.0 * n_elec * Q / ( + comp.geometry.lateral_length_m * c.continuity_tolerance_A_m2 + ) + weights[n_elec:3 * n_elec].reshape(2, n_elec)[comp.fixed_carrier_mask] = 1.0 / c.contact_log_tolerance + if np.all(device.positive_ion_diffusivity_faces_m2_s == 0.0): + weights[3 * n_elec:] = 1.0 / (device.reference_inventory_m1 * options.inventory_relative_tolerance / n_ion) + else: + weights[3 * n_elec:] = 1.0 / options.ion_balance_tolerance_m1_s + weights[3 * n_elec + options.inventory_row_node] = 1.0 / ( + device.reference_inventory_m1 * options.inventory_relative_tolerance + ) + steps = np.r_[ + np.full(n_elec, c.potential_step_V), + np.full(2 * n_elec, c.quasi_fermi_step), + np.full(n_ion, options.ion_logit_step), + ] + return NewtonSettings(ResidualScaling(weights), 1.0, StepControl(steps), options.budget, (gate,), False) + + +def diagnostics(problem: _Unconstrained2D, u: np.ndarray, options: IonicSteady2DOptions) -> dict[str, Any]: + d = problem.device + comp = d.electronic_component + n_elec = comp.node_count + raw_res = problem.residual(u) + phi, n, p, ion_p = d.fields(u, voltage_V=problem.voltage_V) + if not (np.all(np.isfinite(raw_res)) and np.all(np.isfinite(n)) and np.all(np.isfinite(p)) and np.all(np.isfinite(ion_p))): + raise ValueError("2D ionic diagnostic fields or original residual are non-finite") + poisson_norm = float(np.max(np.abs(raw_res[:n_elec] * _poisson_weights_2d(d)))) + carrier_rows = raw_res[n_elec:3 * n_elec].reshape(2, n_elec).copy() + contact_logs = carrier_rows[comp.fixed_carrier_mask].copy() + carrier_rows[comp.fixed_carrier_mask] = 0.0 + width = comp.geometry.lateral_length_m + carrier_bound = Q * float(np.sum(np.abs(carrier_rows))) / width + + ion_rows = raw_res[3 * n_elec:] + ion_eval = problem.ion_flux_evaluation(u) + inventory = math.fsum((d.ion_geometry.contract_geometry.volumes * ion_p).tolist()) + target = d.reference_inventory_m1 + inv_rel_err = abs(inventory - target) / max(abs(target), 1.0e-30) + max_site_frac = float(np.max(ion_p / d.positive_ion_site_limit_m3)) + + return { + "original_residual": raw_res, + "poisson_normalized_max": poisson_norm, + "contact_log_max": float(np.max(np.abs(contact_logs), initial=0.0)), + "carrier_balance_bound_A_m2": carrier_bound, + "ion_balance_max_m1_s": float(np.max(np.abs(ion_rows))), + "ion_flux_max_m2_s": float(np.max(np.abs(ion_eval.flux), initial=0.0)), + "domain_inventory_m1": inventory, + "reference_inventory_m1": target, + "inventory_relative_error": inv_rel_err, + "max_site_fraction": max_site_frac, + "minimum_electron_density_m3": float(np.min(n)), + "minimum_hole_density_m3": float(np.min(p)), + "minimum_ion_density_m3": float(np.min(ion_p)), + "finite_positive_fields": bool( + np.all(np.isfinite(phi)) + and np.all(n > 0.0) + and np.all(p > 0.0) + and np.all(ion_p > 0.0) + and np.all(ion_p < d.positive_ion_site_limit_m3) + ), + } + + +def checks(values: dict[str, Any], options: IonicSteady2DOptions) -> tuple[GateOutcome, ...]: + c = options.electronic + limits = { + "poisson_normalized_max": c.poisson_tolerance, + "contact_log_max": c.contact_log_tolerance, + "carrier_balance_bound_A_m2": c.continuity_tolerance_A_m2, + "ion_balance_max_m1_s": options.ion_balance_tolerance_m1_s, + "ion_flux_max_m2_s": options.ion_flux_tolerance_m2_s, + "inventory_relative_error": options.inventory_relative_tolerance, + } + outcomes = [ + GateOutcome(name, math.isfinite(values[name]) and values[name] <= limit, float(values[name]), limit) + for name, limit in limits.items() + ] + ok_fields = bool(values["finite_positive_fields"]) + outcomes.append(GateOutcome("finite_positive_fields", ok_fields, 0.0 if ok_fields else math.inf, 0.0)) + return tuple(outcomes) + + +def solve_ionic_steady_state_2d( + device: CompiledIonicDevice2D, + *, + voltage_V: float, + generation_scale: float, + options: IonicSteady2DOptions | None = None, + initial_state: IonicState2D | None = None, +) -> IonicSteady2DResult: + """Solve coupled 2D steady state with exact 2D ion inventory conservation.""" + started = time.monotonic() + if not isinstance(device, CompiledIonicDevice2D): + raise TypeError("CompiledIonicDevice2D is required") + controls = IonicSteady2DOptions() if options is None else options + if controls.electronic.convergence_policy != HISTORICAL_MAX_ROW_V1: + from dataclasses import replace as dc_replace + controls = dc_replace( + controls, + electronic=dc_replace(controls.electronic, convergence_policy=HISTORICAL_MAX_ROW_V1), + ) + + immobile = bool(np.all(device.positive_ion_diffusivity_faces_m2_s == 0.0)) + unconstrained: _Unconstrained2D + if use_assembled() and not immobile: + unconstrained = AssembledIonic2DProblem(device, voltage_V, generation_scale) + constrained: Any = AssembledConstrainedIonic2DProblem(unconstrained, controls.inventory_row_node) + else: + unconstrained = Ionic2DProblem(device, voltage_V, generation_scale) + constrained = ConstrainedIonic2DProblem(unconstrained, controls.inventory_row_node) + + comp = device.electronic_component + if initial_state is None: + u_elec = comp.extrude_coordinates( + np.r_[comp.column.reference_potential_V, np.zeros(2 * comp.geometry.ny)] + ) + phi = u_elec[:comp.node_count] + bottom, top = comp.column.contact_potentials(voltage_V) + phi[:comp.geometry.nx], phi[-comp.geometry.nx:] = bottom, top + for offset, ref, mask in zip( + (comp.node_count, 2 * comp.node_count), + comp.reference_potentials(voltage_V), + comp.fixed_carrier_mask, + ): + u_elec[offset:offset + comp.node_count][mask] = (ref[mask] - phi[mask]) / comp.thermal_voltage_V + u0 = np.r_[u_elec, np.zeros(device.ion_node_count)] + else: + if not isinstance(initial_state, IonicState2D) or initial_state.device_sha256 != device.identity: + raise ValueError("initial_state must belong to the same CompiledIonicDevice2D") + u0 = np.array(initial_state.u, copy=True) + # Rebase contact potentials & quasi-Fermi shifts if voltage changed + if initial_state.voltage_V != voltage_V: + n_elec = comp.node_count + old_e = comp.column.carrier_reference_energies(initial_state.voltage_V) + new_e = comp.column.carrier_reference_energies(voltage_V) + for offset, old_v, new_v in zip((n_elec, 2 * n_elec), old_e, new_e): + u0[offset:offset + n_elec] += comp.extrude((old_v - new_v) / comp.thermal_voltage_V) + bottom, top = comp.column.contact_potentials(voltage_V) + u0[:comp.geometry.nx] = bottom + u0[n_elec - comp.geometry.nx:n_elec] = top + + def gate_fn(candidate_u: np.ndarray) -> GateOutcome: + if time.monotonic() - started > controls.wall_s: + return GateOutcome("wall_budget", False, time.monotonic() - started, controls.wall_s) + try: + diag = diagnostics(unconstrained, candidate_u, controls) + gate_list = checks(diag, controls) + ok = all(g.passed for g in gate_list) + worst = max((g.value / max(g.limit, 1e-30) for g in gate_list if g.limit > 0), default=0.0) + return GateOutcome("ionic_steady_2d_gates", ok, worst, 1.0) + except (ValueError, FloatingPointError): + return GateOutcome("ionic_steady_2d_gates", False, math.inf, 1.0) + + settings = _newton_settings(device, controls, gate_fn) + problem = CallableProblem(constrained.residual, constrained.jacobian) + pins = admitted_source_pins() + try: + newton = solve_newton(problem, u0, settings) + except Exception as exc: + return IonicSteady2DResult( + state=None, + accepted=False, + termination="exception", + newton=None, + initial_coordinates=u0, + candidate_coordinates=u0, + diagnostics=None, + checks=(), + compiled_identity=device.identity, + operating_voltage_V=voltage_V, + generation_scale=generation_scale, + solver_controls={"options": asdict(controls), "initial_sha256": state_digest(u0)}, + source_sha256=pins, + wall_s=time.monotonic() - started, + error=str(exc), + ) + + cand = newton.state + try: + diag = diagnostics(unconstrained, cand, controls) + gate_outcomes = checks(diag, controls) + except (ValueError, FloatingPointError) as exc: + return IonicSteady2DResult( + state=None, + accepted=False, + termination=newton.termination, + newton=newton, + initial_coordinates=u0, + candidate_coordinates=cand, + diagnostics=None, + checks=(), + compiled_identity=device.identity, + operating_voltage_V=voltage_V, + generation_scale=generation_scale, + solver_controls={"options": asdict(controls), "initial_sha256": state_digest(u0)}, + source_sha256=pins, + wall_s=time.monotonic() - started, + error=str(exc), + ) + + accepted = bool(newton.accepted and all(g.passed for g in gate_outcomes)) + state = device.state(cand, voltage_V=voltage_V) if accepted else None + return IonicSteady2DResult( + state=state, + accepted=accepted, + termination=newton.termination if accepted else (newton.termination if not newton.accepted else "gate_rejected"), + newton=newton, + initial_coordinates=u0, + candidate_coordinates=cand, + diagnostics=diag, + checks=gate_outcomes, + compiled_identity=device.identity, + operating_voltage_V=voltage_V, + generation_scale=generation_scale, + solver_controls={"options": asdict(controls), "initial_sha256": state_digest(u0)}, + source_sha256=pins, + wall_s=time.monotonic() - started, + error=None if accepted else "ionic steady 2D did not satisfy all acceptance gates", + ) diff --git a/src/solarlab/solvers/nonlinear/steady_2d.py b/src/solarlab/solvers/nonlinear/steady_2d.py index acc21ca0..2866f608 100644 --- a/src/solarlab/solvers/nonlinear/steady_2d.py +++ b/src/solarlab/solvers/nonlinear/steady_2d.py @@ -22,7 +22,7 @@ from solarlab.equations.assembly.two_dimensional import AssembledDC2DProblem from solarlab.equations.dc_2d import CompiledDevice2D, DC2DProblem, State2D from solarlab.equations.implementation import use_assembled -from solarlab.mesh.geometry_2d import RECTANGULAR_HALF_ENDPOINT_2D_V1 +from solarlab.mesh.geometry_2d import RECTANGULAR_2D_NAMES from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton from solarlab.solvers.nonlinear.problem import CallableProblem, GateOutcome, ResidualScaling, StepControl, state_digest from solarlab.solvers.nonlinear.production import HISTORICAL_MAX_ROW_V1, POISSON_CONTACT_BALANCE_V1 @@ -56,8 +56,8 @@ def _problem(device: CompiledDevice2D, voltage_V: float, generation_scale: float def scope(device: CompiledDevice2D) -> None: if not isinstance(device, CompiledDevice2D): raise ValueError("an actual fully compiled classical 2D device is required") - if device.geometry.name != RECTANGULAR_HALF_ENDPOINT_2D_V1: - raise ValueError("2D steady requires physical half-endpoint Neumann geometry") + if device.geometry.name not in RECTANGULAR_2D_NAMES: + raise ValueError("2D steady requires physical half-endpoint Neumann or periodic geometry") if ((device.column.field_transport is not None and device.field_transport is None) or device.column.recombination.explicit_defects is not None or device.column.additional_recombination is not None): raise ValueError("2D steady supports constant mobility and lifetime SRH") @@ -160,12 +160,26 @@ def diagnostics(problem: _Problem2D, u: np.ndarray, options: Steady2DOptions) -> "terminal_mean_current_density_A_m2": terminals / width, "cross_section_terminal_spread_A_m2": float(np.ptp(integrated)) / width, "face_current_density_A_m2": current, - "lateral_current_density_A_m2": current[:g.x_face_count].reshape(g.ny, g.nx - 1), + "lateral_current_density_A_m2": current[:g.x_face_count].reshape(g.ny, g.x_faces_per_row), "stack_current_density_A_m2": current[g.x_face_count:].reshape(g.ny - 1, g.nx), "carrier_face_particle_flux_m2_s": np.stack((fluxes.electron.flux, fluxes.hole.flux)), "face_displacement_C_m2": problem.displacement(u), - "lateral_boundary_particle_flux_m2_s": np.zeros((2, g.ny, 2)), - "lateral_boundary_displacement_C_m2": np.zeros((g.ny, 2)), + "lateral_boundary_particle_flux_m2_s": ( + np.zeros((2, g.ny, 2)) + if g.lateral_bc == "neumann" + else np.stack(( + np.column_stack((fluxes.electron.flux[g.wrap_face_indices], fluxes.electron.flux[g.wrap_face_indices])), + np.column_stack((fluxes.hole.flux[g.wrap_face_indices], fluxes.hole.flux[g.wrap_face_indices])), + )) + ), + "lateral_boundary_displacement_C_m2": ( + np.zeros((g.ny, 2)) + if g.lateral_bc == "neumann" + else np.column_stack(( + problem.displacement(u)[g.wrap_face_indices], + problem.displacement(u)[g.wrap_face_indices], + )) + ), "finite_positive_fields": bool(np.all(n > 0.0) and np.all(p > 0.0) and np.all(np.isfinite(phi))), "minimum_electron_density_m3": float(np.min(n)), "minimum_hole_density_m3": float(np.min(p)), "generation_current_limit_per_depth_A_m": d.generation_limit_A_m * problem.generation_scale, diff --git a/src/solarlab/solvers/time/backward_euler_2d.py b/src/solarlab/solvers/time/backward_euler_2d.py new file mode 100644 index 00000000..fe921283 --- /dev/null +++ b/src/solarlab/solvers/time/backward_euler_2d.py @@ -0,0 +1,510 @@ +"""Conservative 2D Backward Euler stepper and Gauss-Maxwell port accounting (ion-free/frozen). + +Solves ``F(u_n; V_n, g_n) - (S(u_n) - S(u_{n-1})) / dt = 0`` on the unified +:class:`AssembledStorage2D` preallocated sparse graph (``M = -S_u``, +``J_BE = J + M / dt``). Carrier-only steady current readers explicitly refuse +active mobile-ion states so incomplete terminal currents can never be read out +silently. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field +import math +import time +from typing import Any, TypeAlias, cast + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix, diags +from scipy.sparse.linalg import spsolve + +from solarlab.contracts import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.equations.assembly.ionic_2d import AssembledStorage2D +from solarlab.equations.assembly.two_dimensional import ELECTRON, HOLE, POTENTIAL, SIDES +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dc_2d import CompiledDevice2D, DC2DProblem, State2D +from solarlab.equations.ionic_2d import ( + IonicState2D, RadiativeReabsorptionSpec2D, TwoSidedInterfaceSRHCoupling2D, +) +from solarlab.mesh.geometry_2d import RECTANGULAR_2D_NAMES +from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import CallableProblem, GateOutcome, ResidualScaling, SolveBudget, StepControl +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + +__all__ = [ + "BackwardEuler2DOptions", + "BackwardEuler2DRunResult", + "BackwardEuler2DStep", + "BackwardEuler2DStepAccounting", + "BackwardEuler2DStepResult", + "compute_carrier_only_terminal_current_2d", + "run_backward_euler_2d", + "step_accounting_2d", + "step_backward_euler_2d", +] + +Vector: TypeAlias = NDArray[np.float64] + + +def compute_carrier_only_terminal_current_2d( + device: CompiledDevice2D, + state: Any, + *, + generation_scale: float = 0.0, + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = (), + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = (), +) -> Vector: + """Carrier-only 2D terminal current density [A/m^2]; refuses mobile-ion states.""" + if isinstance(state, IonicState2D) or getattr(state, "positive_ion_density_m3", None) is not None: + raise CapabilityError( + "carrier_only_current_refuses_mobile_ion_2d: use ionic_step_accounting_2d or " + "evaluate_mobile_ion_current_components_2d for mobile-ion states" + ) + if getattr(state, "P_ion", None) is not None: + raise CapabilityError( + "carrier_only_current_refuses_mobile_ion_2d: snapshot carries P_ion; use complete 2D ion+displacement current" + ) + if not isinstance(state, State2D) or state.device_sha256 != device.identity: + raise ValueError("State2D bound to this exact CompiledDevice2D is required") + if not radiative_reabsorption and not interface_srh_couplings: + problem = DC2DProblem(device, state.voltage_V, generation_scale) + return problem.terminal_current_density_A_m2(state.u) + storage_prob = AssembledStorage2D( + device, + state.voltage_V, + generation_scale, + radiative_reabsorption=radiative_reabsorption, + interface_srh_couplings=interface_srh_couplings, + ) + sys_eval = storage_prob.evaluate(state.u, derivatives=False) + if not sys_eval.admissible: + raise ValueError("State2D is outside the admissible domain") + assembler = storage_prob.binding.assembler + g = device.geometry + sides = g.contact_nodes.reshape(2, g.nx) + ports: list[Vector] = [] + for block, carrier_code in ((ELECTRON, "n"), (HOLE, "p")): + rows: list[Vector] = [] + for (side_name, port_id), nodes in zip(SIDES, sides): + ch = device.column.channel(carrier_code, side_name) + if ch.kind == "fixed_reservoir": + rows.append(assembler.reaction_flux(sys_eval, block, port_id)) + else: + dc_prob = DC2DProblem(device, state.voltage_V, generation_scale) + exch, _ = dc_prob._contact_exchange(np.asarray(state.u, dtype=np.float64), ch, nodes) + rows.append(exch) + ports.append(np.stack(rows)) + return np.sum((-Q * ports[0] + Q * ports[1]) * g.x_widths_m[None, :], axis=1) / g.lateral_length_m + + +@dataclass(frozen=True) +class BackwardEuler2DStep: + """One conservative 2D Backward Euler nonlinear algebraic problem.""" + + current: AssembledStorage2D + previous: AssembledStorage2D + previous_u: Vector + dt_s: float + + def __post_init__(self) -> None: + if not math.isfinite(self.dt_s) or self.dt_s <= 0.0: + raise ValueError("dt_s must be finite and positive") + if self.current.binding.identity != self.previous.binding.identity: + raise ValueError("current and previous 2D problems must share one bound system") + object.__setattr__(self, "previous_u", frozen_array(self.previous_u)) + + def residual(self, u: ArrayLike) -> Vector: + res = self.current.residual(u) + if not np.all(np.isfinite(res)): + return res + try: + delta_s = self.current.storage_increment(u, self.previous, self.previous_u) + except FloatingPointError: + return np.full_like(res, np.nan) + return res - delta_s / self.dt_s + + def jacobian(self, u: ArrayLike) -> csc_matrix: + jac = self.current.jacobian(u) + mass = self.current.mass_matrix(u) + return cast(csc_matrix, (jac + mass / self.dt_s).tocsc()) + + +@dataclass(frozen=True) +class BackwardEuler2DOptions: + """Explicit numerical controls for 2D conservative Backward Euler.""" + + electronic: SteadyOptions = field( + default_factory=lambda: SteadyOptions(continuity_tolerance_A_m2=1.0e-5) + ) + budget: SolveBudget = field(default_factory=lambda: SolveBudget(60, 600, 65, 24)) + max_bisect: int = 8 + wall_s: float = 60.0 + radiative_reabsorption: tuple[RadiativeReabsorptionSpec2D, ...] = () + interface_srh_couplings: tuple[TwoSidedInterfaceSRHCoupling2D, ...] = () + + def __post_init__(self) -> None: + if not isinstance(self.electronic, SteadyOptions) or not isinstance(self.budget, SolveBudget): + raise ValueError("SteadyOptions and SolveBudget are required") + if type(self.max_bisect) is not int or self.max_bisect < 0: + raise ValueError("max_bisect must be a non-negative integer") + if not math.isfinite(self.wall_s) or self.wall_s <= 0.0: + raise ValueError("wall_s must be finite and positive") + + +@dataclass(frozen=True) +class BackwardEuler2DStepAccounting: + """Conservative BE interval terminal & cross-section total Maxwell current [A/m^2].""" + + dt_s: float + terminal_conduction_A_m2: Vector + terminal_displacement_A_m2: Vector + terminal_total_A_m2: Vector + cross_section_total_A_m2: Vector + max_total_current_spread_A_m2: float + + +def step_accounting_2d( + current: AssembledStorage2D, + u_new: ArrayLike, + previous: AssembledStorage2D, + u_old: ArrayLike, + dt_s: float, +) -> BackwardEuler2DStepAccounting: + """Compute conservative BE interval conduction + displacement port current.""" + d = current.device + g = d.geometry + width = g.lateral_length_m + sys_new = current.evaluate(u_new, derivatives=False) + sys_old = previous.evaluate(u_old, derivatives=False) + if not sys_new.admissible or not sys_old.admissible: + raise ValueError("2D BE step accounting requires admissible states") + + assembler = current.binding.assembler + delta_s_phys = current.physical_increment(u_new, previous, u_old) + storage_rate = delta_s_phys / dt_s + + # Port carrier particle fluxes along +y at y_min and y_max + sides = g.contact_nodes.reshape(2, g.nx) + particle_ports: list[Vector] = [] + for block, carrier_code in ((ELECTRON, "n"), (HOLE, "p")): + rows: list[Vector] = [] + for (side_name, port_id), nodes in zip(SIDES, sides): + ch = d.column.channel(carrier_code, side_name) + if ch.kind == "fixed_reservoir": + rows.append(assembler.reaction_flux(sys_new, block, port_id, storage_rate=storage_rate)) + else: + prob = DC2DProblem(d, current.voltage_V, current.generation_scale) + exch, _ = prob._contact_exchange(np.asarray(u_new, dtype=float), ch, nodes) + rows.append(exch) + particle_ports.append(np.stack(rows)) + j_cond_ports = np.sum((-Q * particle_ports[0] + Q * particle_ports[1]) * g.x_widths_m[None, :], axis=1) / width + + # Port electric displacement D_y along +y closing Gauss boundary cells + d_port_new = np.stack([assembler.reaction_flux(sys_new, POTENTIAL, port_id) for _, port_id in SIDES]) + d_port_old = np.stack([assembler.reaction_flux(sys_old, POTENTIAL, port_id) for _, port_id in SIDES]) + j_disp_ports = np.sum(((d_port_new - d_port_old) / dt_s) * g.x_widths_m[None, :], axis=1) / width + j_tot_ports = j_cond_ports + j_disp_ports + + # Interior horizontal cross-sections + state_new = assembler.state(u_new, current.inputs) + state_old = assembler.state(u_old, previous.inputs) + assert state_new is not None and state_old is not None + c_flux = current.binding.dc.transport.fluxes(state_new) + j_cond_y = (-Q * c_flux.electron.flux[g.x_face_count:] + Q * c_flux.hole.flux[g.x_face_count:]).reshape( + g.ny - 1, g.nx + ) + phi_new, phi_old = state_new.field("potential_V"), state_old.field("potential_V") + left, right = g.contract_geometry.pairs[g.x_face_count:].T + cap_y = d.face_capacitance_F_m2[g.x_face_count:] + d_y_new = (-cap_y * (phi_new[right] - phi_new[left])).reshape(g.ny - 1, g.nx) + d_y_old = (-cap_y * (phi_old[right] - phi_old[left])).reshape(g.ny - 1, g.nx) + j_tot_sections = np.sum((j_cond_y + (d_y_new - d_y_old) / dt_s) * g.x_widths_m[None, :], axis=1) / width + all_levels = np.r_[j_tot_ports[:1], j_tot_sections, j_tot_ports[1:]] + + return BackwardEuler2DStepAccounting( + dt_s=dt_s, + terminal_conduction_A_m2=frozen_array(j_cond_ports), + terminal_displacement_A_m2=frozen_array(j_disp_ports), + terminal_total_A_m2=frozen_array(j_tot_ports), + cross_section_total_A_m2=frozen_array(j_tot_sections), + max_total_current_spread_A_m2=float(np.ptp(all_levels)), + ) + + +@dataclass(frozen=True) +class BackwardEuler2DStepResult: + state: State2D | None + accepted: bool + termination: str + dt_s: float + newton: NewtonResult | None + accounting: BackwardEuler2DStepAccounting | None + wall_s: float + error: str | None = None + + +@dataclass(frozen=True) +class BackwardEuler2DRunResult: + times_s: Vector + states: tuple[State2D, ...] + accountings: tuple[BackwardEuler2DStepAccounting, ...] + accepted: bool + termination: str + attempted_steps: int + accepted_steps: int + rejected_steps: int + bisections: int + wall_s: float + error: str | None = None + scientific_qualification: bool = False + total_newton_iterations: int = 0 + + +def _poisson_weights(device: CompiledDevice2D) -> Vector: + g = device.geometry.contract_geometry + reference_V = max(abs(device.column.built_in_potential_V), device.thermal_voltage_V) + density = device.extrude(np.maximum(np.maximum( + device.column.parameters.acceptor_density_m3, + device.column.parameters.donor_density_m3, + ), 1.0)) + capacitance = np.zeros(device.node_count) + face = device.face_capacitance_F_m2 * g.face_measures + np.add.at(capacitance, g.pairs[:, 0], face) + np.add.at(capacitance, g.pairs[:, 1], face) + scale = Q * density * g.volumes + reference_V * capacitance + result = 1.0 / scale + result[device.geometry.contact_nodes] = 1.0 / reference_V + return result + + +def _rebase_electronic_u(device: CompiledDevice2D, u_old: Vector, old_V: float, new_V: float) -> Vector: + u_guess = np.array(u_old, copy=True) + if old_V == new_V: + return u_guess + n_nodes = device.node_count + old_e = device.column.carrier_reference_energies(old_V) + new_e = device.column.carrier_reference_energies(new_V) + for offset, old_val, new_val in zip((n_nodes, 2 * n_nodes), old_e, new_e): + u_guess[offset:offset + n_nodes] += (old_val - new_val) / device.thermal_voltage_V + resistance = 1.0 / device.column.poisson.face_capacitance_F_m2 + profile = np.r_[0.0, np.cumsum(resistance)] + profile /= profile[-1] + change = -device.column.voltage_polarity * (new_V - old_V) + before = u_guess[:n_nodes].copy() + u_guess[:n_nodes] += device.extrude(change * profile) + bottom, top = device.column.contact_potentials(new_V) + u_guess[:device.geometry.nx] = bottom + u_guess[n_nodes - device.geometry.nx:n_nodes] = top + shift = (u_guess[:n_nodes] - before) / device.thermal_voltage_V + u_guess[n_nodes:2 * n_nodes] -= shift + u_guess[2 * n_nodes:3 * n_nodes] -= shift + return u_guess + + +def _generation_inventory_seed_2d( + device: CompiledDevice2D, + step_prob: BackwardEuler2DStep, + u_base: Vector, + previous_state: State2D, + *, + dt_s: float, + voltage_V: float, + generation_scale: float, +) -> Vector: + n_nodes = device.node_count + try: + _, n_cur, p_cur = device.fields(u_base, voltage_V=voltage_V) + res_c = step_prob.residual(u_base)[n_nodes:3 * n_nodes] + if np.all(np.isfinite(res_c)) and np.all(n_cur > 0.0) and np.all(p_cur > 0.0): + inv_d = np.r_[1.0 / n_cur, -1.0 / p_cur] + mat = step_prob.jacobian(u_base)[n_nodes:3 * n_nodes, n_nodes:3 * n_nodes] @ diags(inv_d) + inc = np.asarray(spsolve(mat.tocsc(), -res_c), dtype=float) + trial_n, trial_p = n_cur + inc[:n_nodes], p_cur + inc[n_nodes:] + if np.all(np.isfinite(trial_n)) and np.all(np.isfinite(trial_p)) and np.all(trial_n > 0.0) and np.all(trial_p > 0.0): + u_lin = np.array(u_base, copy=True) + for offset, dens, trial, delta, sign in ( + (n_nodes, n_cur, trial_n, inc[:n_nodes], 1.0), + (2 * n_nodes, p_cur, trial_p, inc[n_nodes:], -1.0), + ): + with np.errstate(over="ignore", divide="ignore"): + chg = np.log1p(delta / dens) + bad = ~np.isfinite(chg) + chg[bad] = np.log(trial[bad]) - np.log(dens[bad]) + u_lin[offset:offset + n_nodes] += sign * chg + if np.all(np.isfinite(u_lin)): + return u_lin + except Exception: + pass + u_seed = np.array(u_base, copy=True) + if generation_scale <= 0.0: + return u_seed + increment = dt_s * generation_scale * device.generation_source_m3_s + fixed = device.fixed_carrier_mask + for species, (density_2d, offset, sign) in enumerate(( + (previous_state.electron_density_m3, n_nodes, 1.0), + (previous_state.hole_density_m3, 2 * n_nodes, -1.0), + )): + density = density_2d.ravel() + addition = np.where(~fixed[species], increment, 0.0) + u_seed[offset:offset + n_nodes] += sign * np.log1p(addition / np.maximum(density, 1.0e-300)) + return u_seed + + +def step_backward_euler_2d( + device: CompiledDevice2D, + previous_state: State2D, + *, + dt_s: float, + voltage_V: float, + generation_scale: float, + previous_generation_scale: float | None = None, + options: BackwardEuler2DOptions | None = None, +) -> BackwardEuler2DStepResult: + """Advance one conservative 2D Backward Euler step.""" + started = time.monotonic() + if device.geometry.name not in RECTANGULAR_2D_NAMES: + raise ValueError("2D BE requires Neumann or periodic half-endpoint geometry") + if previous_state.device_sha256 != device.identity: + raise ValueError("previous_state must match CompiledDevice2D identity") + controls = BackwardEuler2DOptions() if options is None else options + prev_g = generation_scale if previous_generation_scale is None else previous_generation_scale + prev_prob = AssembledStorage2D( + device, + previous_state.voltage_V, + prev_g, + radiative_reabsorption=controls.radiative_reabsorption, + interface_srh_couplings=controls.interface_srh_couplings, + ) + curr_prob = AssembledStorage2D( + device, + voltage_V, + generation_scale, + radiative_reabsorption=controls.radiative_reabsorption, + interface_srh_couplings=controls.interface_srh_couplings, + ) + step_prob = BackwardEuler2DStep(curr_prob, prev_prob, previous_state.u, dt_s) + + c = controls.electronic + n_nodes = device.node_count + weights = np.full(3 * n_nodes, 2.0 * n_nodes * Q / (device.geometry.lateral_length_m * c.continuity_tolerance_A_m2)) + weights[:n_nodes] = _poisson_weights(device) / c.poisson_tolerance + weights[n_nodes:].reshape(2, n_nodes)[device.fixed_carrier_mask] = 1.0 / c.contact_log_tolerance + steps = np.r_[np.full(n_nodes, c.potential_step_V), np.full(2 * n_nodes, c.quasi_fermi_step)] + + def gate_fn(cand_u: Vector) -> GateOutcome: + if time.monotonic() - started > controls.wall_s: + return GateOutcome("wall_budget", False, time.monotonic() - started, controls.wall_s) + res = step_prob.residual(cand_u) + if not np.all(np.isfinite(res)): + return GateOutcome("finite_be_residual", False, math.inf, 1.0) + scaled = float(np.max(np.abs(res * weights))) + return GateOutcome("be_2d_scaled_max", scaled <= 1.0, scaled, 1.0) + + settings = NewtonSettings(ResidualScaling(weights), 1.0, StepControl(steps), controls.budget, (gate_fn,), False) + u_rebased = _rebase_electronic_u(device, previous_state.u, previous_state.voltage_V, voltage_V) + u_guess = ( + _generation_inventory_seed_2d( + device, step_prob, u_rebased, previous_state, + dt_s=dt_s, voltage_V=voltage_V, generation_scale=generation_scale, + ) + if generation_scale > prev_g + else u_rebased + ) + prob = CallableProblem(step_prob.residual, step_prob.jacobian) + try: + newton = solve_newton(prob, u_guess, settings) + if not newton.accepted and generation_scale <= prev_g: + u_alt = _generation_inventory_seed_2d( + device, step_prob, u_rebased, previous_state, + dt_s=dt_s, voltage_V=voltage_V, generation_scale=generation_scale, + ) + newton_alt = solve_newton(prob, u_alt, settings) + if newton_alt.accepted: + newton = newton_alt + except Exception as exc: + return BackwardEuler2DStepResult(None, False, "exception", dt_s, None, None, time.monotonic() - started, str(exc)) + if not newton.accepted: + return BackwardEuler2DStepResult( + None, False, newton.termination, dt_s, newton, None, time.monotonic() - started, + "2D Backward Euler step did not converge", + ) + state = device.state(newton.state, voltage_V=voltage_V) + acct = step_accounting_2d(curr_prob, newton.state, prev_prob, previous_state.u, dt_s) + return BackwardEuler2DStepResult(state, True, "converged", dt_s, newton, acct, time.monotonic() - started) + + +def run_backward_euler_2d( + device: CompiledDevice2D, + initial_state: State2D, + time_grid_s: ArrayLike, + *, + voltage_fn: Callable[[float], float], + generation_fn: Callable[[float], float], + options: BackwardEuler2DOptions | None = None, +) -> BackwardEuler2DRunResult: + """Advance across ``time_grid_s`` with bounded step-bisection recovery.""" + started = time.monotonic() + controls = BackwardEuler2DOptions() if options is None else options + grid = np.asarray(time_grid_s, dtype=float) + if grid.ndim != 1 or grid.size < 2 or not np.all(np.isfinite(grid)) or np.any(np.diff(grid) <= 0.0): + raise ValueError("time_grid_s must be 1D, finite, and strictly increasing") + + times = [float(grid[0])] + states = [initial_state] + accountings: list[BackwardEuler2DStepAccounting] = [] + attempted = accepted = rejected = bisections = total_newton = 0 + curr_state = initial_state + prev_g = float(generation_fn(float(grid[0]))) + + for seg_idx in range(grid.size - 1): + t_cur = float(grid[seg_idx]) + t_target = float(grid[seg_idx + 1]) + dt = t_target - t_cur + depth = 0 + while t_cur < t_target - 1.0e-15 * max(1.0, abs(t_target)): + if time.monotonic() - started > controls.wall_s: + return BackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), False, "wall_budget_exceeded", + attempted, accepted, rejected, bisections, time.monotonic() - started, + "2D BE wall budget exceeded", total_newton_iterations=total_newton, + ) + dt_try = min(dt, t_target - t_cur) + t_next = t_cur + dt_try + v_next = float(voltage_fn(t_next)) + g_next = float(generation_fn(t_next)) + attempted += 1 + res = step_backward_euler_2d( + device, curr_state, dt_s=dt_try, voltage_V=v_next, + generation_scale=g_next, previous_generation_scale=prev_g, options=controls, + ) + if res.newton is not None: + total_newton += len(res.newton.iterations) + if res.accepted and res.state is not None and res.accounting is not None: + accepted += 1 + curr_state = res.state + prev_g = g_next + t_cur = t_next + times.append(t_cur) + states.append(curr_state) + accountings.append(res.accounting) + else: + rejected += 1 + if depth >= controls.max_bisect: + return BackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), False, res.termination, + attempted, accepted, rejected, bisections, time.monotonic() - started, + res.error or "2D BE step bisection budget exhausted", + total_newton_iterations=total_newton, + ) + depth += 1 + bisections += 1 + dt *= 0.5 + + return BackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), True, "completed", + attempted, accepted, rejected, bisections, time.monotonic() - started, + total_newton_iterations=total_newton, + ) diff --git a/src/solarlab/solvers/time/ionic_backward_euler_2d.py b/src/solarlab/solvers/time/ionic_backward_euler_2d.py new file mode 100644 index 00000000..e15ff35b --- /dev/null +++ b/src/solarlab/solvers/time/ionic_backward_euler_2d.py @@ -0,0 +1,781 @@ +"""Conservative 2D single-mobile-ion Backward Euler stepper and port total current. + +Solves ``F(u_n; V_n, g_n) - (S(u_n) - S(u_{n-1})) / dt = 0`` on the unified +:class:`AssembledIonic2DProblem` preallocated sparse graph (``M = -S_u``, +``J_BE = J + M / dt``) with cancellation-free ``expm1`` carrier storage +increments and ``finite_site_secant_2d_m3`` ion storage increments. + +Provides BOTH: +1. :func:`ionic_step_accounting_2d`: conservative BE interval Maxwell port & + cross-section current (``J_n + J_p + J_ion + (D_new - D_old)/dt``). +2. :func:`evaluate_mobile_ion_current_components_2d` / + :func:`compute_mobile_ion_current_components_2d`: instantaneous semidiscrete + differentiated-Poisson Maxwell current decomposition with explicit + ``applied_voltage_rate_V_s`` (true ``dV/dt`` during ramps and ``0`` at dwell + endpoints). +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field +import math +import time +from typing import TypeAlias, cast + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix, diags +from scipy.sparse.linalg import spsolve + +from solarlab.contracts import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M +from solarlab.equations.assembly.ionic_2d import AssembledIonic2DProblem +from solarlab.equations.ionic_2d import ( + CompiledIonicDevice2D, IonicState2D, MobileIonDiagnostics2D, + assess_mobile_ion_terminal_2d, positive_ion_fluxes_2d, +) +from solarlab.physics.contacts import junction_polarity +from solarlab.solvers.nonlinear.ionic_2d import _poisson_weights_2d +from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import CallableProblem, GateOutcome, ResidualScaling, SolveBudget, StepControl +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + +__all__ = [ + "IonicBackwardEuler2DOptions", + "IonicBackwardEuler2DRunResult", + "IonicBackwardEuler2DStep", + "IonicBackwardEuler2DStepAccounting", + "IonicBackwardEuler2DStepResult", + "MobileIonCurrentComponents2D", + "compute_mobile_ion_current_components_2d", + "evaluate_mobile_ion_current_components_2d", + "ionic_step_accounting_2d", + "run_ionic_backward_euler_2d", + "step_ionic_backward_euler_2d", +] + +Vector: TypeAlias = NDArray[np.float64] + + +def _read_only(values: ArrayLike) -> Vector: + arr = np.asarray(values, dtype=float).copy() + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True, slots=True) +class MobileIonCurrentComponents2D: + """Instantaneous 2D vertical Maxwell current decomposition [A/m^2].""" + + electron_y_A_m2: Vector + hole_y_A_m2: Vector + positive_ion_y_A_m2: Vector + displacement_y_A_m2: Vector + total_y_A_m2: Vector + lateral_average_electron_A_m2: Vector + lateral_average_hole_A_m2: Vector + lateral_average_positive_ion_A_m2: Vector + lateral_average_displacement_A_m2: Vector + lateral_average_total_A_m2: Vector + terminal_electron_A_m2: float + terminal_hole_A_m2: float + terminal_positive_ion_A_m2: float + terminal_displacement_A_m2: float + terminal_total_A_m2: float + max_face_spread_A_m2: float + max_relative_face_spread: float + applied_voltage_rate_V_s: float + + +def _terminal_decomposition_is_roundoff_consistent(total: float, components: tuple[float, ...]) -> bool: + comp_sum = sum(components) + scale = max(abs(float(total)), sum(abs(float(v)) for v in components), float(np.finfo(float).tiny)) + return bool(abs(float(total) - comp_sum) <= 64.0 * float(np.finfo(float).eps) * scale) + + +def _solve_poisson_rate_2d( + device: CompiledIonicDevice2D, + charge_rate_C_m3: Vector, + *, + phi_bottom_rate_V_s: float, + phi_top_rate_V_s: float, +) -> Vector: + """Solve linear differentiated 2D Gauss system ``div(eps grad(dphi/dt)) = -drho/dt``.""" + comp = device.electronic_component + g = comp.geometry + cg = g.contract_geometry + count = comp.node_count + left, right = cg.pairs[:, 0], cg.pairs[:, 1] + cap_w = comp.face_capacitance_F_m2 * cg.face_measures + + contact_mask: NDArray[np.bool_] = np.zeros(count, dtype=np.bool_) + contact_nodes = g.contact_nodes.astype(np.intp) + contact_mask[contact_nodes] = True + + r_chunks = [left, left, right, right] + c_chunks = [left, right, left, right] + # Standard discrete Laplacian -div(D) = sum_{faces} cap*(phi_node - phi_nbr) + v_chunks = [cap_w, -cap_w, -cap_w, cap_w] + all_r = np.concatenate(r_chunks) + all_c = np.concatenate(c_chunks) + all_v = np.concatenate(v_chunks) + keep = ~contact_mask[all_r] + + mat = csc_matrix( + ( + np.concatenate((all_v[keep], np.ones(contact_nodes.size, dtype=float))), + ( + np.concatenate((all_r[keep], contact_nodes)), + np.concatenate((all_c[keep], contact_nodes)), + ), + ), + shape=(count, count), + ) + rhs = cg.volumes * charge_rate_C_m3.ravel() + rhs[:g.nx] = phi_bottom_rate_V_s + rhs[-g.nx:] = phi_top_rate_V_s + solved = np.asarray(spsolve(mat, rhs), dtype=float) + return solved.reshape(g.shape) + + +def compute_mobile_ion_current_components_2d( + device: CompiledIonicDevice2D, + state: IonicState2D, + *, + generation_scale: float = 0.0, + applied_voltage_rate_V_s: float = 0.0, +) -> MobileIonCurrentComponents2D: + """Evaluate instantaneous semidiscrete 2D Maxwell current components from an ``IonicState2D``.""" + if not isinstance(device, CompiledIonicDevice2D) or not isinstance(state, IonicState2D): + raise TypeError("CompiledIonicDevice2D and IonicState2D are required") + if state.device_sha256 != device.identity: + raise ValueError("IonicState2D does not match CompiledIonicDevice2D identity") + voltage_rate = float(applied_voltage_rate_V_s) + if not math.isfinite(voltage_rate): + raise ValueError("applied_voltage_rate_V_s must be finite") + + problem = AssembledIonic2DProblem(device, state.voltage_V, generation_scale) + system = problem.evaluate(state.u, derivatives=False) + if not system.admissible: + raise ValueError("IonicState2D is outside the admissible domain") + + comp = device.electronic_component + g = comp.geometry + ny, nx = g.shape + count = comp.node_count + elec_vol = g.contract_geometry.volumes + + # Semidiscrete continuity rates: area * dn/dt = balance_n (zero on ohmic Dirichlet contact rows) + dn_dt = (system.balance[count:2 * count] / elec_vol).copy() + dp_dt = (system.balance[2 * count:3 * count] / elec_vol).copy() + dn_dt[comp.fixed_carrier_mask[0]] = 0.0 + dp_dt[comp.fixed_carrier_mask[1]] = 0.0 + + ion_vol = device.ion_geometry.contract_geometry.volumes + dp_ion_domain_dt = system.balance[3 * count:] / ion_vol + dp_ion_elec: Vector = np.zeros(count, dtype=np.float64) + dp_ion_elec[device.ion_node_indices] = dp_ion_domain_dt * device.ion_charge_weight_ratio + + charge_rate = Q * (dp_dt - dn_dt + dp_ion_elec) + polarity = float(junction_polarity(comp.column.built_in_potential_V)) + phi_rate = _solve_poisson_rate_2d( + device, + charge_rate, + phi_bottom_rate_V_s=0.0, + phi_top_rate_V_s=-polarity * voltage_rate, + ) + + dy = np.diff(g.y_geometry.nodes_m)[:, None] + field_rate_y = -(phi_rate[1:, :] - phi_rate[:-1, :]) / dy + eps_r = comp.relative_permittivity_y + eps_face_y = (2.0 * eps_r[:-1] * eps_r[1:] / (eps_r[:-1] + eps_r[1:]))[:, None] + displacement_y = VACUUM_PERMITTIVITY_F_M * eps_face_y * field_rate_y + + c_fluxes = problem.carrier_fluxes(state.u) + electron_y = c_fluxes.electron_current()[g.x_face_count:].reshape(ny - 1, nx) + hole_y = c_fluxes.hole_current()[g.x_face_count:].reshape(ny - 1, nx) + + ion_eval = problem.ion_flux_evaluation(state.u) + ion_g = device.ion_geometry + ion_y_domain = Q * ion_eval.flux[ion_g.x_face_count:].reshape(ion_g.ny - 1, nx) + positive_ion_y: Vector = np.zeros((ny - 1, nx), dtype=np.float64) + row_start = int(device.ion_row_indices[0]) + positive_ion_y[row_start:row_start + ion_g.ny - 1, :] = ion_y_domain + + total_y = electron_y + hole_y + positive_ion_y + displacement_y + if not all(np.all(np.isfinite(arr)) for arr in (electron_y, hole_y, positive_ion_y, displacement_y, total_y)): + raise ValueError("2D mobile-ion current decomposition produced non-finite values") + + widths = g.x_widths_m + domain_w = g.lateral_length_m + avg_e = (electron_y @ widths) / domain_w + avg_h = (hole_y @ widths) / domain_w + avg_ion = (positive_ion_y @ widths) / domain_w + avg_disp = (displacement_y @ widths) / domain_w + avg_tot = (total_y @ widths) / domain_w + + term_idx = -1 + term_comps = ( + float(avg_e[term_idx]), + float(avg_h[term_idx]), + float(avg_ion[term_idx]), + float(avg_disp[term_idx]), + ) + term_tot = float(avg_tot[term_idx]) + if not _terminal_decomposition_is_roundoff_consistent(term_tot, term_comps): + raise RuntimeError("2D mobile-ion terminal current decomposition is inconsistent") + + spread = float(np.ptp(avg_tot)) + scale = max(float(np.max(np.abs(avg_tot))), 1.0e-30) + + return MobileIonCurrentComponents2D( + electron_y_A_m2=_read_only(electron_y), + hole_y_A_m2=_read_only(hole_y), + positive_ion_y_A_m2=_read_only(positive_ion_y), + displacement_y_A_m2=_read_only(displacement_y), + total_y_A_m2=_read_only(total_y), + lateral_average_electron_A_m2=_read_only(avg_e), + lateral_average_hole_A_m2=_read_only(avg_h), + lateral_average_positive_ion_A_m2=_read_only(avg_ion), + lateral_average_displacement_A_m2=_read_only(avg_disp), + lateral_average_total_A_m2=_read_only(avg_tot), + terminal_electron_A_m2=term_comps[0], + terminal_hole_A_m2=term_comps[1], + terminal_positive_ion_A_m2=term_comps[2], + terminal_displacement_A_m2=term_comps[3], + terminal_total_A_m2=term_tot, + max_face_spread_A_m2=spread, + max_relative_face_spread=spread / scale, + applied_voltage_rate_V_s=voltage_rate, + ) + + +def evaluate_mobile_ion_current_components_2d( + device: CompiledIonicDevice2D, + phi_2d: ArrayLike, + Jy_n_2d: ArrayLike, + Jy_p_2d: ArrayLike, + P_ion_2d: ArrayLike, + state_derivative_3block: ArrayLike, + *, + applied_voltage_rate_V_s: float = 0.0, +) -> MobileIonCurrentComponents2D: + """Evaluate 2D Maxwell current components from explicit snapshot arrays & 3-block density RHS.""" + comp = device.electronic_component + g = comp.geometry + ny, nx = g.shape + voltage_rate = float(applied_voltage_rate_V_s) + if not math.isfinite(voltage_rate): + raise ValueError("applied_voltage_rate_V_s must be finite") + + phi = np.asarray(phi_2d, dtype=float) + jy_n = np.asarray(Jy_n_2d, dtype=float) + jy_p = np.asarray(Jy_p_2d, dtype=float) + p_ion = np.asarray(P_ion_2d, dtype=float) + deriv = np.asarray(state_derivative_3block, dtype=float) + if phi.shape != (ny, nx) or p_ion.shape != (ny, nx): + raise ValueError("phi_2d and P_ion_2d must have shape (Ny, Nx)") + if jy_n.shape != (ny - 1, nx) or jy_p.shape != (ny - 1, nx): + raise ValueError("Jy_n_2d and Jy_p_2d must have shape (Ny - 1, Nx)") + if deriv.shape != (3 * ny * nx,) or not np.all(np.isfinite(deriv)): + raise ValueError("state_derivative_3block must be finite with shape (3 * Ny * Nx,)") + + dn = deriv[:ny * nx] + dp = deriv[ny * nx:2 * ny * nx] + d_pion = deriv[2 * ny * nx:] + charge_rate = Q * (dp - dn + d_pion) + polarity = float(junction_polarity(comp.column.built_in_potential_V)) + phi_rate = _solve_poisson_rate_2d( + device, + charge_rate, + phi_bottom_rate_V_s=0.0, + phi_top_rate_V_s=-polarity * voltage_rate, + ) + dy = np.diff(g.y_geometry.nodes_m)[:, None] + field_rate_y = -(phi_rate[1:, :] - phi_rate[:-1, :]) / dy + eps_r = comp.relative_permittivity_y + eps_face_y = (2.0 * eps_r[:-1] * eps_r[1:] / (eps_r[:-1] + eps_r[1:]))[:, None] + displacement_y = VACUUM_PERMITTIVITY_F_M * eps_face_y * field_rate_y + + from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1 + ion_flux = positive_ion_fluxes_2d( + g.x_m, + g.y_geometry.nodes_m, + phi, + p_ion, + device.full_grid_ion_diffusivity_m2_s(), + comp.thermal_voltage_V, + device.full_grid_ion_site_limit_m3(), + steric_diffusion_only=(device.steric_model == DIFFUSION_ONLY_STERIC_V1), + ) + positive_ion_y = Q * ion_flux.y + total_y = jy_n + jy_p + positive_ion_y + displacement_y + + widths = g.x_widths_m + domain_w = g.lateral_length_m + avg_e = (jy_n @ widths) / domain_w + avg_h = (jy_p @ widths) / domain_w + avg_ion = (positive_ion_y @ widths) / domain_w + avg_disp = (displacement_y @ widths) / domain_w + avg_tot = (total_y @ widths) / domain_w + term_comps = (float(avg_e[-1]), float(avg_h[-1]), float(avg_ion[-1]), float(avg_disp[-1])) + term_tot = float(avg_tot[-1]) + if not _terminal_decomposition_is_roundoff_consistent(term_tot, term_comps): + raise RuntimeError("2D mobile-ion terminal current decomposition is inconsistent") + spread = float(np.ptp(avg_tot)) + scale = max(float(np.max(np.abs(avg_tot))), 1.0e-30) + + return MobileIonCurrentComponents2D( + electron_y_A_m2=_read_only(jy_n), + hole_y_A_m2=_read_only(jy_p), + positive_ion_y_A_m2=_read_only(positive_ion_y), + displacement_y_A_m2=_read_only(displacement_y), + total_y_A_m2=_read_only(total_y), + lateral_average_electron_A_m2=_read_only(avg_e), + lateral_average_hole_A_m2=_read_only(avg_h), + lateral_average_positive_ion_A_m2=_read_only(avg_ion), + lateral_average_displacement_A_m2=_read_only(avg_disp), + lateral_average_total_A_m2=_read_only(avg_tot), + terminal_electron_A_m2=term_comps[0], + terminal_hole_A_m2=term_comps[1], + terminal_positive_ion_A_m2=term_comps[2], + terminal_displacement_A_m2=term_comps[3], + terminal_total_A_m2=term_tot, + max_face_spread_A_m2=spread, + max_relative_face_spread=spread / scale, + applied_voltage_rate_V_s=voltage_rate, + ) + + +@dataclass(frozen=True) +class IonicBackwardEuler2DStep: + """One conservative 2D single-mobile-ion Backward Euler nonlinear algebraic problem.""" + + current: AssembledIonic2DProblem + previous: AssembledIonic2DProblem + previous_u: Vector + dt_s: float + + def __post_init__(self) -> None: + if not math.isfinite(self.dt_s) or self.dt_s <= 0.0: + raise ValueError("dt_s must be finite and positive") + if self.current.binding.identity != self.previous.binding.identity: + raise ValueError("current and previous 2D ionic problems must share one bound system") + object.__setattr__(self, "previous_u", frozen_array(self.previous_u)) + + def residual(self, u: ArrayLike) -> Vector: + res = self.current.residual(u) + if not np.all(np.isfinite(res)): + return res + try: + delta_s = self.current.storage_increment(u, self.previous, self.previous_u) + except FloatingPointError: + return np.full_like(res, np.nan) + return res - delta_s / self.dt_s + + def jacobian(self, u: ArrayLike) -> csc_matrix: + jac = self.current.jacobian(u) + mass = self.current.mass_matrix(u) + return cast(csc_matrix, (jac + mass / self.dt_s).tocsc()) + + +@dataclass(frozen=True) +class IonicBackwardEuler2DOptions: + """Explicit numerical controls and conservation gates for 2D mobile-ion BE.""" + + electronic: SteadyOptions = field( + default_factory=lambda: SteadyOptions(continuity_tolerance_A_m2=1.0e-5) + ) + ion_inventory_rtol: float = 1.0e-12 + ion_step_rtol: float = 1.0e-13 + ion_logit_step: float = 1.0 + budget: SolveBudget = field(default_factory=lambda: SolveBudget(65, 650, 70, 24)) + max_bisect: int = 8 + wall_s: float = 90.0 + + def __post_init__(self) -> None: + if not isinstance(self.electronic, SteadyOptions) or not isinstance(self.budget, SolveBudget): + raise ValueError("SteadyOptions and SolveBudget are required") + if type(self.max_bisect) is not int or self.max_bisect < 0: + raise ValueError("max_bisect must be a non-negative integer") + for name in ("ion_inventory_rtol", "ion_step_rtol", "ion_logit_step", "wall_s"): + val = float(getattr(self, name)) + if not math.isfinite(val) or val <= 0.0: + raise ValueError(f"{name} must be finite and positive") + + +@dataclass(frozen=True) +class IonicBackwardEuler2DStepAccounting: + """Conservative BE interval Maxwell port & cross-section total current [A/m^2].""" + + dt_s: float + terminal_carrier_A_m2: Vector + terminal_ion_A_m2: Vector + terminal_displacement_A_m2: Vector + terminal_total_A_m2: Vector + cross_section_carrier_A_m2: Vector + cross_section_ion_A_m2: Vector + cross_section_displacement_A_m2: Vector + cross_section_total_A_m2: Vector + max_total_current_spread_A_m2: float + ion_inventory_m1: float + relative_ion_inventory_step_drift: float + + +def ionic_step_accounting_2d( + current: AssembledIonic2DProblem, + u_new: ArrayLike, + previous: AssembledIonic2DProblem, + u_old: ArrayLike, + dt_s: float, +) -> IonicBackwardEuler2DStepAccounting: + """Compute conservative BE interval carrier + ion + displacement Maxwell current.""" + d = current.device + comp = d.electronic_component + g = comp.geometry + width = g.lateral_length_m + + delta_s_phys = current.physical_increment(u_new, previous, u_old) + storage_rate = delta_s_phys / dt_s + + electron_port, hole_port = current.contact_particle_fluxes(u_new, storage_rate=storage_rate) + j_carrier_ports = np.sum((-Q * electron_port + Q * hole_port) * g.x_widths_m[None, :], axis=1) / width + # Exterior electrodes block ions; if ion domain reaches y_min/y_max, reaction_flux on ion is 0 + j_ion_ports: Vector = np.zeros(2, dtype=float) + + d_port_new = current.contact_displacement_C_m2(u_new) + d_port_old = previous.contact_displacement_C_m2(u_old) + j_disp_ports = np.sum(((d_port_new - d_port_old) / dt_s) * g.x_widths_m[None, :], axis=1) / width + j_tot_ports = j_carrier_ports + j_ion_ports + j_disp_ports + + c_flux = current.carrier_fluxes(u_new) + j_carrier_y = (-Q * c_flux.electron.flux[g.x_face_count:] + Q * c_flux.hole.flux[g.x_face_count:]).reshape( + g.ny - 1, g.nx + ) + ion_eval = current.ion_flux_evaluation(u_new) + ion_g = d.ion_geometry + j_ion_y: Vector = np.zeros((g.ny - 1, g.nx), dtype=np.float64) + row0 = int(d.ion_row_indices[0]) + j_ion_y[row0:row0 + ion_g.ny - 1, :] = Q * ion_eval.flux[ion_g.x_face_count:].reshape(ion_g.ny - 1, g.nx) + + phi_new, _, _, ion_p_new = d.fields(u_new, voltage_V=current.voltage_V) + phi_old, _, _, ion_p_old = d.fields(u_old, voltage_V=previous.voltage_V) + left, right = g.contract_geometry.pairs[g.x_face_count:].T + cap_y = comp.face_capacitance_F_m2[g.x_face_count:] + d_y_new = (-cap_y * (phi_new[right] - phi_new[left])).reshape(g.ny - 1, g.nx) + d_y_old = (-cap_y * (phi_old[right] - phi_old[left])).reshape(g.ny - 1, g.nx) + j_disp_y = (d_y_new - d_y_old) / dt_s + + sec_carrier = np.sum(j_carrier_y * g.x_widths_m[None, :], axis=1) / width + sec_ion = np.sum(j_ion_y * g.x_widths_m[None, :], axis=1) / width + sec_disp = np.sum(j_disp_y * g.x_widths_m[None, :], axis=1) / width + sec_tot = sec_carrier + sec_ion + sec_disp + all_levels = np.r_[j_tot_ports[:1], sec_tot, j_tot_ports[1:]] + + ion_vol = ion_g.contract_geometry.volumes + inv_new = math.fsum((ion_vol * ion_p_new).tolist()) + inv_old = math.fsum((ion_vol * ion_p_old).tolist()) + step_drift = abs(inv_new - inv_old) / max(abs(inv_old), 1.0e-30) + + return IonicBackwardEuler2DStepAccounting( + dt_s=dt_s, + terminal_carrier_A_m2=frozen_array(j_carrier_ports), + terminal_ion_A_m2=frozen_array(j_ion_ports), + terminal_displacement_A_m2=frozen_array(j_disp_ports), + terminal_total_A_m2=frozen_array(j_tot_ports), + cross_section_carrier_A_m2=frozen_array(sec_carrier), + cross_section_ion_A_m2=frozen_array(sec_ion), + cross_section_displacement_A_m2=frozen_array(sec_disp), + cross_section_total_A_m2=frozen_array(sec_tot), + max_total_current_spread_A_m2=float(np.ptp(all_levels)), + ion_inventory_m1=inv_new, + relative_ion_inventory_step_drift=step_drift, + ) + + +@dataclass(frozen=True) +class IonicBackwardEuler2DStepResult: + state: IonicState2D | None + accepted: bool + termination: str + dt_s: float + newton: NewtonResult | None + accounting: IonicBackwardEuler2DStepAccounting | None + wall_s: float + error: str | None = None + + +@dataclass(frozen=True) +class IonicBackwardEuler2DRunResult: + times_s: Vector + states: tuple[IonicState2D, ...] + accountings: tuple[IonicBackwardEuler2DStepAccounting, ...] + ion_diagnostics: MobileIonDiagnostics2D + accepted: bool + termination: str + attempted_steps: int + accepted_steps: int + rejected_steps: int + bisections: int + wall_s: float + error: str | None = None + scientific_qualification: bool = False + total_newton_iterations: int = 0 + + +def _rebase_ionic_u(device: CompiledIonicDevice2D, u_old: Vector, old_V: float, new_V: float) -> Vector: + u_guess = np.array(u_old, copy=True) + if old_V == new_V: + return u_guess + comp = device.electronic_component + n_elec = comp.node_count + old_e = comp.column.carrier_reference_energies(old_V) + new_e = comp.column.carrier_reference_energies(new_V) + for offset, old_val, new_val in zip((n_elec, 2 * n_elec), old_e, new_e): + u_guess[offset:offset + n_elec] += (old_val - new_val) / comp.thermal_voltage_V + resistance = 1.0 / comp.column.poisson.face_capacitance_F_m2 + profile = np.r_[0.0, np.cumsum(resistance)] + profile /= profile[-1] + change = -comp.column.voltage_polarity * (new_V - old_V) + before = u_guess[:n_elec].copy() + u_guess[:n_elec] += comp.extrude(change * profile) + bottom, top = comp.column.contact_potentials(new_V) + u_guess[:comp.geometry.nx] = bottom + u_guess[n_elec - comp.geometry.nx:n_elec] = top + shift = (u_guess[:n_elec] - before) / comp.thermal_voltage_V + u_guess[n_elec:2 * n_elec] -= shift + u_guess[2 * n_elec:3 * n_elec] -= shift + return u_guess + + +def _generation_inventory_ionic_seed_2d( + device: CompiledIonicDevice2D, + step_prob: IonicBackwardEuler2DStep, + u_base: Vector, + previous_state: IonicState2D, + *, + dt_s: float, + voltage_V: float, + generation_scale: float, +) -> Vector: + comp = device.electronic_component + n_elec = comp.node_count + try: + _, n_cur, p_cur, _ = device.fields(u_base, voltage_V=voltage_V) + res_c = step_prob.residual(u_base)[n_elec:3 * n_elec] + if np.all(np.isfinite(res_c)) and np.all(n_cur > 0.0) and np.all(p_cur > 0.0): + inv_d = np.r_[1.0 / n_cur, -1.0 / p_cur] + mat = step_prob.jacobian(u_base)[n_elec:3 * n_elec, n_elec:3 * n_elec] @ diags(inv_d) + inc = np.asarray(spsolve(mat.tocsc(), -res_c), dtype=float) + trial_n, trial_p = n_cur + inc[:n_elec], p_cur + inc[n_elec:] + if np.all(np.isfinite(trial_n)) and np.all(np.isfinite(trial_p)) and np.all(trial_n > 0.0) and np.all(trial_p > 0.0): + u_lin = np.array(u_base, copy=True) + for offset, dens, trial, delta, sign in ( + (n_elec, n_cur, trial_n, inc[:n_elec], 1.0), + (2 * n_elec, p_cur, trial_p, inc[n_elec:], -1.0), + ): + with np.errstate(over="ignore", divide="ignore"): + chg = np.log1p(delta / dens) + bad = ~np.isfinite(chg) + chg[bad] = np.log(trial[bad]) - np.log(dens[bad]) + u_lin[offset:offset + n_elec] += sign * chg + if np.all(np.isfinite(u_lin)): + return u_lin + except Exception: + pass + u_seed = np.array(u_base, copy=True) + if generation_scale <= 0.0: + return u_seed + increment = dt_s * generation_scale * comp.generation_source_m3_s + fixed = comp.fixed_carrier_mask + elec_state = previous_state.electronic_state + for species, (density_2d, offset, sign) in enumerate(( + (elec_state.electron_density_m3, n_elec, 1.0), + (elec_state.hole_density_m3, 2 * n_elec, -1.0), + )): + density = density_2d.ravel() + addition = np.where(~fixed[species], increment, 0.0) + u_seed[offset:offset + n_elec] += sign * np.log1p(addition / np.maximum(density, 1.0e-300)) + return u_seed + + +def step_ionic_backward_euler_2d( + device: CompiledIonicDevice2D, + previous_state: IonicState2D, + *, + dt_s: float, + voltage_V: float, + generation_scale: float, + previous_generation_scale: float | None = None, + options: IonicBackwardEuler2DOptions | None = None, +) -> IonicBackwardEuler2DStepResult: + """Advance one conservative 2D single-mobile-ion Backward Euler step.""" + started = time.monotonic() + if previous_state.device_sha256 != device.identity: + raise ValueError("previous_state must match CompiledIonicDevice2D identity") + controls = IonicBackwardEuler2DOptions() if options is None else options + prev_g = generation_scale if previous_generation_scale is None else previous_generation_scale + prev_prob = AssembledIonic2DProblem(device, previous_state.voltage_V, prev_g) + curr_prob = AssembledIonic2DProblem(device, voltage_V, generation_scale) + step_prob = IonicBackwardEuler2DStep(curr_prob, prev_prob, previous_state.u, dt_s) + + c = controls.electronic + comp = device.electronic_component + n_elec = comp.node_count + n_ion = device.ion_node_count + weights: Vector = np.empty(device.state_size, dtype=float) + weights[:n_elec] = _poisson_weights_2d(device) / c.poisson_tolerance + weights[n_elec:3 * n_elec] = 2.0 * n_elec * Q / ( + comp.geometry.lateral_length_m * c.continuity_tolerance_A_m2 + ) + weights[n_elec:3 * n_elec].reshape(2, n_elec)[comp.fixed_carrier_mask] = 1.0 / c.contact_log_tolerance + # Tight per-row ion balance scaling guarantees dt * sum(|R_ion|) <= ion_step_rtol * I_ion + ion_row_tol = max(device.reference_inventory_m1 * controls.ion_step_rtol / (n_ion * dt_s), 1.0e-30) + weights[3 * n_elec:] = 1.0 / ion_row_tol + steps = np.r_[ + np.full(n_elec, c.potential_step_V), + np.full(2 * n_elec, c.quasi_fermi_step), + np.full(n_ion, controls.ion_logit_step), + ] + + def gate_fn(cand_u: Vector) -> GateOutcome: + if time.monotonic() - started > controls.wall_s: + return GateOutcome("wall_budget", False, time.monotonic() - started, controls.wall_s) + res = step_prob.residual(cand_u) + if not np.all(np.isfinite(res)): + return GateOutcome("finite_ionic_be_residual", False, math.inf, 1.0) + scaled = float(np.max(np.abs(res * weights))) + return GateOutcome("ionic_be_2d_scaled_max", scaled <= 1.0, scaled, 1.0) + + settings = NewtonSettings(ResidualScaling(weights), 1.0, StepControl(steps), controls.budget, (gate_fn,), False) + u_rebased = _rebase_ionic_u(device, previous_state.u, previous_state.voltage_V, voltage_V) + u_guess = ( + _generation_inventory_ionic_seed_2d( + device, step_prob, u_rebased, previous_state, + dt_s=dt_s, voltage_V=voltage_V, generation_scale=generation_scale, + ) + if generation_scale > prev_g + else u_rebased + ) + prob = CallableProblem(step_prob.residual, step_prob.jacobian) + try: + newton = solve_newton(prob, u_guess, settings) + if not newton.accepted and generation_scale <= prev_g: + u_alt = _generation_inventory_ionic_seed_2d( + device, step_prob, u_rebased, previous_state, + dt_s=dt_s, voltage_V=voltage_V, generation_scale=generation_scale, + ) + newton_alt = solve_newton(prob, u_alt, settings) + if newton_alt.accepted: + newton = newton_alt + except Exception as exc: + return IonicBackwardEuler2DStepResult( + None, False, "exception", dt_s, None, None, time.monotonic() - started, str(exc) + ) + if not newton.accepted: + return IonicBackwardEuler2DStepResult( + None, False, newton.termination, dt_s, newton, None, time.monotonic() - started, + "2D mobile-ion Backward Euler step did not converge", + ) + state = device.state(newton.state, voltage_V=voltage_V) + acct = ionic_step_accounting_2d(curr_prob, newton.state, prev_prob, previous_state.u, dt_s) + if acct.relative_ion_inventory_step_drift > controls.ion_inventory_rtol: + return IonicBackwardEuler2DStepResult( + None, False, "inventory_drift_exceeded", dt_s, newton, acct, time.monotonic() - started, + f"step ion inventory drift {acct.relative_ion_inventory_step_drift:.3e} exceeded {controls.ion_inventory_rtol:.3e}", + ) + return IonicBackwardEuler2DStepResult(state, True, "converged", dt_s, newton, acct, time.monotonic() - started) + + +def run_ionic_backward_euler_2d( + device: CompiledIonicDevice2D, + initial_state: IonicState2D, + time_grid_s: ArrayLike, + *, + voltage_fn: Callable[[float], float], + generation_fn: Callable[[float], float], + options: IonicBackwardEuler2DOptions | None = None, +) -> IonicBackwardEuler2DRunResult: + """Advance 2D single-mobile-ion transient across ``time_grid_s`` with bisection recovery.""" + started = time.monotonic() + controls = IonicBackwardEuler2DOptions() if options is None else options + grid = np.asarray(time_grid_s, dtype=float) + if grid.ndim != 1 or grid.size < 2 or not np.all(np.isfinite(grid)) or np.any(np.diff(grid) <= 0.0): + raise ValueError("time_grid_s must be 1D, finite, and strictly increasing") + + times = [float(grid[0])] + states = [initial_state] + accountings: list[IonicBackwardEuler2DStepAccounting] = [] + attempted = accepted = rejected = bisections = total_newton = 0 + curr_state = initial_state + prev_g = float(generation_fn(float(grid[0]))) + + def make_diag(final_state: IonicState2D) -> MobileIonDiagnostics2D: + return assess_mobile_ion_terminal_2d( + device.ion_geometry.x_m, + device.ion_geometry.y_geometry.nodes_m, + initial_state.positive_ion_density_m3, + final_state.positive_ion_density_m3, + device.positive_ion_site_limit_m3.reshape(device.ion_geometry.shape), + terminal_electron_density=final_state.electronic_state.electron_density_m3, + terminal_hole_density=final_state.electronic_state.hole_density_m3, + inventory_rtol=controls.ion_inventory_rtol, + control_volume_areas_m2=device.ion_geometry.contract_geometry.volumes.reshape(device.ion_geometry.shape), + ) + + for seg_idx in range(grid.size - 1): + t_cur = float(grid[seg_idx]) + t_target = float(grid[seg_idx + 1]) + dt = t_target - t_cur + depth = 0 + while t_cur < t_target - 1.0e-15 * max(1.0, abs(t_target)): + if time.monotonic() - started > controls.wall_s: + return IonicBackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), make_diag(curr_state), + False, "wall_budget_exceeded", attempted, accepted, rejected, bisections, + time.monotonic() - started, "2D mobile-ion BE wall budget exceeded", + total_newton_iterations=total_newton, + ) + dt_try = min(dt, t_target - t_cur) + t_next = t_cur + dt_try + v_next = float(voltage_fn(t_next)) + g_next = float(generation_fn(t_next)) + attempted += 1 + res = step_ionic_backward_euler_2d( + device, curr_state, dt_s=dt_try, voltage_V=v_next, + generation_scale=g_next, previous_generation_scale=prev_g, options=controls, + ) + if res.newton is not None: + total_newton += len(res.newton.iterations) + if res.accepted and res.state is not None and res.accounting is not None: + accepted += 1 + curr_state = res.state + prev_g = g_next + t_cur = t_next + times.append(t_cur) + states.append(curr_state) + accountings.append(res.accounting) + else: + rejected += 1 + if depth >= controls.max_bisect: + return IonicBackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), make_diag(curr_state), + False, res.termination, attempted, accepted, rejected, bisections, + time.monotonic() - started, res.error or "2D mobile-ion BE bisection budget exhausted", + total_newton_iterations=total_newton, + ) + depth += 1 + bisections += 1 + dt *= 0.5 + + diag = make_diag(curr_state) + ok = diag.passed + return IonicBackwardEuler2DRunResult( + frozen_array(times), tuple(states), tuple(accountings), diag, + ok, "completed" if ok else "terminal_gate_failed", + attempted, accepted, rejected, bisections, time.monotonic() - started, + None if ok else ("; ".join(diag.violations) or "terminal mobile-ion gate failed"), + total_newton_iterations=total_newton, + ) diff --git a/tests/integration/test_contacts_2d.py b/tests/integration/test_contacts_2d.py index 3f482c0e..9300401a 100644 --- a/tests/integration/test_contacts_2d.py +++ b/tests/integration/test_contacts_2d.py @@ -303,7 +303,7 @@ def no_solve(problem, initial, settings, **kwargs): np.testing.assert_array_equal(u[offset:offset+N][mask], (reference[mask] - u[:N][mask]) / mixed.thermal_voltage_V) -@pytest.mark.parametrize("extra", [{"lateral_bc": "periodic"}, {"ion_dynamics": "single_mobile"}, +@pytest.mark.parametrize("extra", [{"lateral_bc": None}, {"ion_dynamics": "single_mobile"}, {"interface_srh": "two_sided_cross_node"}]) def test_unbound_contact_combinations_remain_refused(prepared, extra): spatial = spatial_input().editing_data() diff --git a/tests/integration/test_dc_2d.py b/tests/integration/test_dc_2d.py index 86255711..b1d709c0 100644 --- a/tests/integration/test_dc_2d.py +++ b/tests/integration/test_dc_2d.py @@ -207,7 +207,7 @@ def test_width_changes_integrated_current_but_not_uniform_density(prepared: Prep assert wide.identity != device.identity and wide.geometry.sha256 != device.geometry.sha256 -@pytest.mark.parametrize("field,value", [("lateral_bc", "periodic"), ("lateral_length", None), ("Ny_per_layer", 1), ("settle_t", 1e-6)]) +@pytest.mark.parametrize("field,value", [("lateral_bc", None), ("lateral_length", None), ("Ny_per_layer", 1), ("settle_t", 1e-6)]) def test_unbound_spatial_modes_are_rejected(prepared: PreparedDevice, field: str, value: Any) -> None: data = example.spatial_input().editing_data() data[field] = value diff --git a/tests/integration/test_ionic_transient_and_experiments_2d.py b/tests/integration/test_ionic_transient_and_experiments_2d.py new file mode 100644 index 00000000..b73c96f7 --- /dev/null +++ b/tests/integration/test_ionic_transient_and_experiments_2d.py @@ -0,0 +1,699 @@ +"""Integration, conservation, live legacy-parity, and 4-axis refinement tests for P06-02 and P06-03.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from examples.research_1d.ionic_multilayer import prepare_confined_ion_device +from examples.research_1d.steady import load_device +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from perovskite_sim.twod.experiments.jv_sweep_2d import ( + run_jv_sweep_2d as legacy_run_jv_sweep_2d, +) +from perovskite_sim.twod.experiments.voc_grain_sweep import ( + run_voc_grain_sweep as legacy_run_voc_grain_sweep, +) +from perovskite_sim.twod.interface_recombination_2d import ( + TwoSidedInterfaceSRHCoupling2D as LegacyInterfaceCoupling2D, + evaluate_two_sided_interface_srh_2d as legacy_eval_interface_srh_2d, +) +from perovskite_sim.twod.ion_migration_2d import ( + positive_ion_fluxes_2d as legacy_positive_ion_fluxes_2d, +) +from perovskite_sim.twod.microstructure import GrainBoundary as LegacyGrainBoundary, Microstructure as LegacyMicrostructure +from perovskite_sim.twod.mobile_ion_current_2d import ( + evaluate_mobile_ion_current_components_2d as legacy_eval_mobile_ion_current_2d, +) +from perovskite_sim.twod.radiative_reabsorption_2d import ( + recompute_g_with_rad_2d as legacy_recompute_g_with_rad_2d, +) +from perovskite_sim.twod.snapshot import SpatialSnapshot2D as LegacySnapshot2D +from perovskite_sim.twod.solver_2d import ( + build_material_arrays_2d as legacy_build_material_arrays_2d, +) +from perovskite_sim.twod.grid_2d import build_grid_2d as legacy_build_grid_2d +from perovskite_sim.discretization.grid import Layer as LegacyGridLayer +from perovskite_sim.models.device import electrical_layers as legacy_electrical_layers +from solarlab.device.compile_ionic_2d import compile_ionic_device_2d +from solarlab.device.inputs import GrainBoundaryInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.ionic_2d import ( + TwoSidedInterfaceSRHCoupling2D, + evaluate_two_sided_interface_srh_2d, + positive_ion_fluxes_2d, + recompute_g_with_rad_2d, +) +from solarlab.experiments.two_dimensional.inputs import JV2DInput, MicrostructureInput +from solarlab.experiments.two_dimensional.jv_protocol_2d import ( + DynamicJVPairProtocol2D, + ImplicitProtocolError, + ProtocolMismatchError, +) +from solarlab.experiments.two_dimensional.jv_sweep_2d import ( + build_jv_2d_execution_protocol, + read_jv_2d_result, + run_dynamic_jv_pair_2d, + run_jv_sweep_2d, + write_jv_2d_result, +) +from solarlab.experiments.two_dimensional.refinement_2d import ( + RefinementBaseline2D, + read_refinement_report_2d, + run_four_axis_refinement_2d, + write_refinement_report_2d, +) +from solarlab.experiments.two_dimensional.voc_grain_sweep import ( + read_voc_grain_sweep, + run_voc_grain_sweep, + write_voc_grain_sweep, +) +from solarlab.solvers.nonlinear.ionic_2d import solve_ionic_steady_state_2d +from solarlab.solvers.time.ionic_backward_euler_2d import ( + compute_mobile_ion_current_components_2d, + evaluate_mobile_ion_current_components_2d, + run_ionic_backward_euler_2d, +) + +_LEGACY_MAT_KEYS = ( + "eps_r", "mu_n", "mu_p", "D_ion", "P_lim", "P0", "E_a_ion", + "ni", "tau_n", "tau_p", "n1", "p1", "B_rad", "C_n", "C_p", + "alpha", "N_A", "N_D", "chi", "Eg", "Nc300", "Nv300", "v_th", +) + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> Any: + with threadpool_limits(limits=1): + yield + + +def _to_legacy_stack(prepared: PreparedDevice) -> DeviceStack: + mapping = prepared.to_mapping() + settings = mapping["settings"] + layers = [] + for lyr in prepared.layers: + params = dict(lyr.parameters) + mp = MaterialParams(**{k: params[k] for k in _LEGACY_MAT_KEYS if k in params}) + layers.append(LayerSpec(name=lyr.id, thickness=lyr.thickness, params=mp, role=lyr.role)) + return DeviceStack( + layers=tuple(layers), + V_bi=float(settings.get("V_bi", 1.1)), + Phi=float(settings["Phi"]), + T=float(settings["T"]), + mode=str(settings.get("mode", "full")), + ion_steric_diffusion_only=bool(settings.get("ion_steric_diffusion_only", False)), + built_in_potential_mode=str(settings.get("built_in_potential_mode", "work_function")), + dos_band_potentials=bool(settings.get("dos_band_potentials", False)), + ) + + +def test_ionic_be_2d_transient_ramp_dwell_maxwell_current_and_1d_parity() -> None: + """P06-02 (1)-(4): 2D mobile-ion BE conservation, Maxwell port current, and 1D lateral parity.""" + prep_ion = prepare_confined_ion_device() + abs_ids = [lyr.id for lyr in prep_ion.layers if lyr.role == "absorber"] + + # 1. Laterally uniform 2D Neumann transient BE has zero lateral spread across columns + uni_sp = JV2DInput( + kind="jv_2d", + lateral_length=2.0e-7, + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="single_mobile", + ) + uni_dev = compile_ionic_device_2d( + prep_ion, uni_sp, ion_domain_layer=abs_ids[0], ion_domain_endpoints=("blocking", "blocking") + ) + uni_eq = solve_ionic_steady_state_2d(uni_dev, voltage_V=0.0, generation_scale=0.0) + assert uni_eq.accepted and uni_eq.state is not None + + t_ramp = np.linspace(0.0, 2.0e-6, 5, dtype=np.float64) + dv_dt = 0.4 / 2.0e-6 + uni_run = run_ionic_backward_euler_2d( + uni_dev, + uni_eq.state, + t_ramp, + voltage_fn=lambda t: dv_dt * t, + generation_fn=lambda _t: 0.0, + ) + assert uni_run.accepted + assert uni_run.ion_diagnostics.passed + assert uni_run.ion_diagnostics.relative_inventory_drift <= 1.0e-12 + end_u = uni_run.states[-1] + rel_spread = np.ptp(end_u.positive_ion_density_m3, axis=1) / np.max(end_u.positive_ion_density_m3, axis=1) + assert float(np.max(rel_spread)) <= 1.0e-13 + + # 2. Centered-GB 2D ramp (dV/dt != 0) + dwell (dV/dt == 0) Maxwell current & conservation + ms = MicrostructureInput( + grain_boundaries=( + GrainBoundaryInput.model_validate( + { + "id": "gb_mid", + "layer_ids": abs_ids, + "x_position": 1.0e-7, + "width": 2.0e-8, + "tau_n": 1.0e-9, + "tau_p": 1.0e-9, + } + ), + ) + ) + gb_sp = JV2DInput( + kind="jv_2d", + lateral_length=2.0e-7, + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=ms, + ion_dynamics="single_mobile", + ) + gb_dev = compile_ionic_device_2d( + prep_ion, gb_sp, ion_domain_layer=abs_ids[0], ion_domain_endpoints=("blocking", "blocking") + ) + gb_eq = solve_ionic_steady_state_2d(gb_dev, voltage_V=0.0, generation_scale=0.0) + assert gb_eq.accepted and gb_eq.state is not None + + ramp_run = run_ionic_backward_euler_2d( + gb_dev, + gb_eq.state, + t_ramp, + voltage_fn=lambda t: dv_dt * t, + generation_fn=lambda t: 0.0 if t <= 0.0 else 1.0, + ) + assert ramp_run.accepted + assert ramp_run.ion_diagnostics.passed + assert ramp_run.ion_diagnostics.relative_inventory_drift <= 1.0e-12 + assert ramp_run.ion_diagnostics.terminal_min_density_m3 > 0.0 + assert ramp_run.ion_diagnostics.terminal_max_site_fraction < 1.0 + for acct in ramp_run.accountings: + assert acct.max_total_current_spread_A_m2 < 1.0e-3 + assert abs(float(acct.terminal_displacement_A_m2[1])) > 0.0 + + ramp_state = ramp_run.states[-1] + curr_ramp = compute_mobile_ion_current_components_2d( + gb_dev, ramp_state, generation_scale=1.0, applied_voltage_rate_V_s=dv_dt + ) + curr_zero_rate = compute_mobile_ion_current_components_2d( + gb_dev, ramp_state, generation_scale=1.0, applied_voltage_rate_V_s=0.0 + ) + assert curr_ramp.max_relative_face_spread < 1.0e-4 + assert abs(curr_ramp.terminal_displacement_A_m2 - curr_zero_rate.terminal_displacement_A_m2) > 1.0 + assert curr_ramp.terminal_total_A_m2 == pytest.approx( + curr_ramp.terminal_electron_A_m2 + + curr_ramp.terminal_hole_A_m2 + + curr_ramp.terminal_positive_ion_A_m2 + + curr_ramp.terminal_displacement_A_m2, + rel=1.0e-14, + ) + + # Settle dwell at fixed V = 0.4 V -> displacement current decays toward zero + dwell_run = run_ionic_backward_euler_2d( + gb_dev, + ramp_state, + np.geomspace(1.0e-7, 1.0e-2, 8) - 1.0e-7, + voltage_fn=lambda _t: 0.4, + generation_fn=lambda _t: 1.0, + ) + assert dwell_run.accepted + assert dwell_run.ion_diagnostics.passed + assert dwell_run.ion_diagnostics.relative_inventory_drift <= 1.0e-12 + + +def test_live_legacy_operator_and_protocol_parity_2d() -> None: + """P06-02 (5): Direct operator & canonical protocol parity against perovskite_sim.twod.*.""" + rng = np.random.default_rng(20261112) + x = np.linspace(0.0, 2.4e-7, 4) + y = np.array([0.0, 4.0e-8, 8.0e-8, 2.0e-7, 3.2e-7, 3.6e-7, 4.0e-7], dtype=float) + ny, nx = y.size, x.size + phi = np.linspace(0.9, 0.1, ny)[:, None] + 0.015 * np.cos(np.linspace(0.0, np.pi, nx))[None, :] + p_ion = np.zeros((ny, nx), dtype=float) + p_ion[2:5, :] = 1.5e24 * (1.0 + 0.1 * rng.uniform(-1.0, 1.0, size=(3, nx))) + d_ion = np.zeros((ny, nx), dtype=float) + d_ion[2:5, :] = 1.0e-16 + p_lim = np.full((ny, nx), 1.0e25, dtype=float) + + for diff_only in (False, True): + f_new = positive_ion_fluxes_2d( + x, y, phi, p_ion, d_ion, 0.02585, p_lim, steric_diffusion_only=diff_only + ) + f_leg = legacy_positive_ion_fluxes_2d( + x, y, phi, p_ion, d_ion, 0.02585, p_lim, steric_diffusion_only=diff_only + ) + np.testing.assert_allclose(f_new.x, f_leg.x, rtol=1.0e-14, atol=1.0e-6) + np.testing.assert_allclose(f_new.y, f_leg.y, rtol=1.0e-14, atol=1.0e-6) + + # Instantaneous Maxwell current decomposition parity (dV/dt = 0 and dV/dt = 250 V/s) + prep_ion_op = prepare_confined_ion_device() + abs_ids_op = [lyr.id for lyr in prep_ion_op.layers if lyr.role == "absorber"] + op_sp = JV2DInput( + kind="jv_2d", + lateral_length=2.4e-7, + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="single_mobile", + ) + op_dev = compile_ionic_device_2d( + prep_ion_op, op_sp, ion_domain_layer=abs_ids_op[0], ion_domain_endpoints=("blocking", "blocking") + ) + op_eq = solve_ionic_steady_state_2d(op_dev, voltage_V=0.0, generation_scale=0.0) + assert op_eq.accepted and op_eq.state is not None + stack_op = _to_legacy_stack(prep_ion_op) + leg_layers = [LegacyGridLayer(thickness=lyr.thickness, N=4) for lyr in legacy_electrical_layers(stack_op)] + leg_grid = legacy_build_grid_2d(leg_layers, Nx=3, lateral_length=2.4e-7) + leg_mat = legacy_build_material_arrays_2d( + leg_grid, stack_op, LegacyMicrostructure(), lateral_bc="neumann", ion_dynamics="single_mobile" + ) + ny_op, nx_op = op_dev.electronic_component.geometry.shape + phi_op = op_eq.state.electronic_state.potential_V + pion_op = op_dev.full_grid_ion_density(op_eq.state.positive_ion_density_m3) + jy_n_zero = np.zeros((ny_op - 1, nx_op), dtype=float) + jy_p_zero = np.zeros((ny_op - 1, nx_op), dtype=float) + jx_zero = np.zeros((ny_op, nx_op - 1), dtype=float) + n_snap = op_eq.state.electronic_state.electron_density_m3.copy() + p_snap = op_eq.state.electronic_state.hole_density_m3.copy() + n_snap[0, :], n_snap[-1, :] = leg_mat.n_eq_left, leg_mat.n_eq_right + p_snap[0, :], p_snap[-1, :] = leg_mat.p_eq_left, leg_mat.p_eq_right + leg_snap = LegacySnapshot2D( + V=0.0, + x=leg_grid.x, + y=leg_grid.y, + phi=phi_op, + n=n_snap, + p=p_snap, + Jx_n=jx_zero, + Jy_n=jy_n_zero, + Jx_p=jx_zero, + Jy_p=jy_p_zero, + P_ion=pion_op, + ) + zero_3b = np.zeros(3 * op_dev.node_count, dtype=float) + for rate in (0.0, 250.0): + c_new = evaluate_mobile_ion_current_components_2d( + op_dev, phi_op, jy_n_zero, jy_p_zero, pion_op, zero_3b, applied_voltage_rate_V_s=rate + ) + c_leg = legacy_eval_mobile_ion_current_2d( + leg_snap, zero_3b, leg_mat, applied_voltage_rate_V_s=rate + ) + np.testing.assert_allclose(c_new.total_y_A_m2, c_leg.total_y_A_m2, rtol=1.0e-13, atol=1.0e-12) + assert c_new.terminal_total_A_m2 == pytest.approx(c_leg.terminal_total_A_m2, rel=1.0e-13, abs=1.0e-12) + assert c_new.terminal_displacement_A_m2 == pytest.approx( + c_leg.terminal_displacement_A_m2, rel=1.0e-13, abs=1.0e-12 + ) + c_eq = compute_mobile_ion_current_components_2d( + op_dev, op_eq.state, generation_scale=0.0, applied_voltage_rate_V_s=0.0 + ) + assert abs(c_eq.terminal_total_A_m2) <= 1.0e-12 + + n = np.exp(np.linspace(48.0, 52.0, ny))[:, None] * (1.0 + 0.05 * np.sin(np.arange(nx))[None, :]) + p = np.exp(np.linspace(52.0, 47.0, ny))[:, None] * (1.0 + 0.04 * np.cos(np.arange(nx))[None, :]) + g_opt = np.full((ny, nx), 1.0e27) + + # Two-sided cross-node interface SRH parity + srh_kwargs = { + "interface_index": 0, + "interface_row": 2, + "left_sample_row": 1, + "right_sample_row": 3, + "electron_capture_velocity_m_s": 12.0, + "hole_capture_velocity_m_s": 8.0, + "n1_m3": 1.0e15, + "p1_m3": 2.0e15, + "pair_a_equilibrium_product_m6": 1.0e30, + "pair_b_equilibrium_product_m6": 1.5e30, + } + c_srh_new = (TwoSidedInterfaceSRHCoupling2D(**srh_kwargs),) + c_srh_leg = (LegacyInterfaceCoupling2D(**srh_kwargs),) + rep_new = evaluate_two_sided_interface_srh_2d(n, p, y, c_srh_new) + rep_leg = legacy_eval_interface_srh_2d(n, p, y, c_srh_leg) + np.testing.assert_allclose(rep_new.volumetric_sink_m3_s, rep_leg.volumetric_sink_m3_s, rtol=1.0e-14) + np.testing.assert_allclose(rep_new.total_surface_rate_m2_s, rep_leg.total_surface_rate_m2_s, rtol=1.0e-14) + + # Bounded radiative reabsorption parity + b_rad = np.zeros((ny, nx), dtype=float) + b_rad[2:5, :] = 5.0e-17 + ni_sq_arr = np.full((ny, nx), 1.0e22, dtype=float) + area_abs = (y[4] - y[2]) * (x[-1] - x[0]) + g_rr_new = recompute_g_with_rad_2d( + G_optical=g_opt, + n=n, + p=p, + B_rad=b_rad, + ni_sq=ni_sq_arr, + x=x, + y=y, + absorber_y_ranges=((2, 5),), + absorber_p_esc=(0.15,), + absorber_areas=(area_abs,), + ) + g_rr_leg = legacy_recompute_g_with_rad_2d( + G_optical=g_opt, + n=n, + p=p, + B_rad=b_rad, + ni_sq=ni_sq_arr, + x=x, + y=y, + absorber_y_ranges=((2, 5),), + absorber_p_esc=(0.15,), + absorber_areas=(area_abs,), + ) + np.testing.assert_allclose(g_rr_new, g_rr_leg, rtol=1.0e-14) + + # Canonical JV2DProtocol JSON & SHA-256 hash parity + from perovskite_sim.twod.experiments.jv_sweep_2d import ( + build_jv_2d_execution_protocol as legacy_build_exec_proto, + ) + ms_proto_new = MicrostructureInput( + grain_boundaries=( + GrainBoundaryInput.model_validate( + { + "id": "gb_p", + "layer_ids": abs_ids_op, + "x_position": 1.2e-7, + "width": 2.0e-8, + "tau_n": 1.0e-9, + "tau_p": 2.0e-9, + } + ), + ) + ) + ms_proto_leg = LegacyMicrostructure( + grain_boundaries=( + LegacyGrainBoundary(x_position=1.2e-7, width=2.0e-8, tau_n=1.0e-9, tau_p=2.0e-9), + ) + ) + proto_kw: dict[str, Any] = { + "lateral_length": 2.4e-7, + "Nx": 3, + "Ny_per_layer": 4, + "V_max": 1.05, + "V_step": 0.35, + "illuminated": True, + "lateral_bc": "neumann", + "settle_t": 1.0e-4, + "ion_dynamics": "single_mobile", + "interface_srh": "off", + "initial_state_settle_s": 1.0e-4, + } + p_new = build_jv_2d_execution_protocol(prep_ion_op, ms_proto_new, **proto_kw) + p_leg = legacy_build_exec_proto(stack_op, ms_proto_leg, **proto_kw) + assert p_new.canonical_json() == p_leg.canonical_json() + assert p_new.protocol_hash == p_leg.protocol_hash + + +def test_live_legacy_experiment_parity_and_protocol_gates_2d() -> None: + """P06-02 (5): Live parity of run_voc_grain_sweep & mobile-ion run_jv_sweep_2d vs perovskite_sim.""" + prep = load_device() + stack = _to_legacy_stack(prep) + + # 1. voc_grain_sweep jv_sweep parity & s_gb_m_s equivalence + res_new = run_voc_grain_sweep( + prep, [2.0e-7, 8.0e-7], tau_gb=(1.0e-9, 1.0e-9), gb_width=1.0e-8, + Nx=3, Ny_per_layer=4, V_max=1.14, V_step=0.38, settle_t=1.0e-4, mode="jv_sweep", + ) + res_leg = legacy_run_voc_grain_sweep( + stack, [2.0e-7, 8.0e-7], tau_gb=(1.0e-9, 1.0e-9), gb_width=1.0e-8, + Nx=3, Ny_per_layer=4, V_max=1.14, V_step=0.38, settle_t=1.0e-4, + ) + np.testing.assert_allclose(res_new.V_oc_V, res_leg.V_oc_V, atol=1.0e-3) + np.testing.assert_allclose(res_new.J_sc_Am2, res_leg.J_sc_Am2, rtol=1.0e-4) + assert res_new.V_oc_V[1] > res_new.V_oc_V[0] + assert res_new.scientific_qualification is False + + # Velocity parametrization s_gb = width / tau_gb reproduces identical Voc + res_vel = run_voc_grain_sweep( + prep, [2.0e-7], tau_gb=None, s_gb_m_s=10.0, gb_width=1.0e-8, + Nx=3, Ny_per_layer=4, V_max=1.14, V_step=0.38, settle_t=1.0e-4, mode="jv_sweep", + ) + assert res_vel.V_oc_V[0] == pytest.approx(res_new.V_oc_V[0], abs=1.0e-12) + + # Direct steady Voc mode matches J_sc and preserves grain-size Voc ordering + res_direct = run_voc_grain_sweep( + prep, [2.0e-7, 8.0e-7], tau_gb=(1.0e-9, 1.0e-9), gb_width=1.0e-8, + Nx=3, Ny_per_layer=4, V_max=1.3, V_step=0.2, mode="direct_voc", + ) + np.testing.assert_allclose(res_direct.J_sc_Am2, res_new.J_sc_Am2, rtol=1.0e-5) + assert res_direct.V_oc_V[1] > res_direct.V_oc_V[0] + assert np.all(np.isnan(res_direct.FF)) + + # 2. Mobile-ion research_strict run_jv_sweep_2d parity + protocol enforcement + prep_ion = prepare_confined_ion_device() + stack_ion = _to_legacy_stack(prep_ion) + abs_ids = [lyr.id for lyr in prep_ion.layers if lyr.role == "absorber"] + ms_new = MicrostructureInput( + grain_boundaries=( + GrainBoundaryInput.model_validate( + { + "id": "gb0", + "layer_ids": abs_ids, + "x_position": 1.0e-7, + "width": 2.0e-8, + "tau_n": 1.0e-9, + "tau_p": 1.0e-9, + } + ), + ) + ) + ms_leg = LegacyMicrostructure( + grain_boundaries=( + LegacyGrainBoundary(x_position=1.0e-7, width=2.0e-8, tau_n=1.0e-9, tau_p=1.0e-9), + ) + ) + kw: dict[str, Any] = { + "lateral_length": 2.0e-7, + "Nx": 3, + "Ny_per_layer": 4, + "V_max": 1.05, + "V_step": 0.35, + "illuminated": True, + "lateral_bc": "neumann", + "settle_t": 1.0e-4, + "initial_state_settle_s": 1.0e-4, + "ion_dynamics": "single_mobile", + "interface_srh": "off", + "save_snapshots": False, + } + + with pytest.raises(ImplicitProtocolError): + run_jv_sweep_2d(prep_ion, microstructure=ms_new, protocol_mode="research_strict", **kw) + + proto_mob = build_jv_2d_execution_protocol(prep_ion, ms_new, **kw) + with pytest.raises(ProtocolMismatchError): + run_jv_sweep_2d( + prep_ion, + microstructure=ms_new, + jv_2d_protocol=proto_mob, + protocol_mode="research_strict", + **(kw | {"settle_t": 2.0e-4}), + ) + + mob_new = run_jv_sweep_2d( + prep_ion, microstructure=ms_new, jv_2d_protocol=proto_mob, protocol_mode="research_strict", **kw + ) + from perovskite_sim.twod.experiments.jv_protocol_2d import JV2DProtocol as LegacyJV2DProtocol + leg_proto = LegacyJV2DProtocol.from_json(proto_mob.canonical_json()) + mob_leg = legacy_run_jv_sweep_2d( + stack_ion, + ms_leg, + jv_2d_protocol=leg_proto, + protocol_mode="research_strict", + **kw, + ) + assert mob_new.disposition == "completed" + assert all(d.passed and d.relative_inventory_drift <= 1.0e-12 for d in mob_new.ion_diagnostics) + assert mob_new.metrics.V_oc == pytest.approx(mob_leg.metrics.V_oc, abs=5.0e-3) + assert mob_new.metrics.J_sc == pytest.approx(mob_leg.metrics.J_sc, rel=2.0e-3) + + +def test_dynamic_jv_pair_partial_disposition_and_artifact_roundtrip_2d(tmp_path: Path) -> None: + """P06-02: Continuous dynamic forward/reverse scan, partial failure recording, and lossless I/O.""" + prep_ion = prepare_confined_ion_device() + abs_ids = [lyr.id for lyr in prep_ion.layers if lyr.role == "absorber"] + ms = MicrostructureInput( + grain_boundaries=( + GrainBoundaryInput.model_validate( + { + "id": "gb_dyn", + "layer_ids": abs_ids, + "x_position": 1.0e-7, + "width": 2.0e-8, + "tau_n": 1.0e-9, + "tau_p": 1.0e-9, + } + ), + ) + ) + base_proto = build_jv_2d_execution_protocol( + prep_ion, + ms, + lateral_length=2.0e-7, + Nx=3, + Ny_per_layer=4, + V_max=1.05, + V_step=0.35, + illuminated=True, + lateral_bc="neumann", + settle_t=1.0e-4, + initial_state_settle_s=1.0e-4, + ion_dynamics="single_mobile", + ) + pair_proto = DynamicJVPairProtocol2D( + temperature_K=base_proto.temperature_K, + illuminated=True, + precondition_voltage_V=0.0, + precondition_hold_s=1.0e-4, + forward_voltages_V=(0.0, 0.35, 0.7, 1.05), + turnaround_hold_s=1.0e-3, + reverse_voltages_V=(1.05, 0.7, 0.35, 0.0), + step_mode="linear_ramp", + dwell_or_step_time_s=1.0e-3, + state_topology="single_positive_mobile_ion", + lateral_bc="neumann", + carrier_boundary_condition="ohmic", + interface_srh="off", + x_coordinates_m=base_proto.x_coordinates_m, + y_coordinates_m=base_proto.y_coordinates_m, + grain_boundaries=base_proto.grain_boundaries, + substeps_per_point=4, + ) + pair_res = run_dynamic_jv_pair_2d(prep_ion, pair_proto, microstructure=ms) + assert pair_res.disposition == "completed" + assert pair_res.scientific_qualification is False + assert pair_res.preconditioned_state_sha256 != pair_res.turnaround_state_sha256 + assert pair_res.hysteresis_voc_delta_V is not None + assert all(d.passed for d in pair_res.forward.ion_diagnostics) + assert all(d.passed for d in pair_res.reverse.ion_diagnostics) + assert any(abs(c.terminal_displacement_A_m2) > 0.0 for c in pair_res.forward.current_components[1:]) + + # Partial failure recording vs raise when extreme forward voltage jump exceeds zero-bisection step + prep_std = load_device() + partial_res = run_jv_sweep_2d( + prep_std, + lateral_length=2.0e-7, + Nx=2, + Ny_per_layer=3, + V_max=15.0, + V_step=7.5, + illuminated=False, + settle_t=1.0e-2, + max_bisect=0, + max_nfev_per_solve=25, + save_snapshots=False, + on_point_failure="record_partial", + ) + assert partial_res.disposition in {"partial", "completed"} + assert len(partial_res.attempts) >= 1 + + # Lossless artifact round-trip in tmp_path + jv_path = tmp_path / "jv_2d_forward.json" + sha_jv = write_jv_2d_result(jv_path, pair_res.forward) + loaded_jv = read_jv_2d_result(jv_path, expected_sha256=sha_jv) + np.testing.assert_array_equal(loaded_jv.V, pair_res.forward.V) + np.testing.assert_array_equal(loaded_jv.J, pair_res.forward.J) + assert loaded_jv.scientific_qualification is False + with pytest.raises(ValueError, match="SHA-256"): + read_jv_2d_result(jv_path, expected_sha256="0" * 64) + + voc_res = run_voc_grain_sweep( + prep_std, [2.0e-7, 6.0e-7], Nx=2, Ny_per_layer=3, V_max=1.3, V_step=0.25, mode="direct_voc" + ) + voc_path = tmp_path / "voc_grain_direct.json" + sha_voc = write_voc_grain_sweep(voc_path, voc_res) + loaded_voc = read_voc_grain_sweep(voc_path, expected_sha256=sha_voc) + np.testing.assert_array_equal(loaded_voc.grain_sizes_m, voc_res.grain_sizes_m) + np.testing.assert_array_equal(loaded_voc.V_oc_V, voc_res.V_oc_V) + assert np.all(np.isnan(loaded_voc.FF)) + + +def test_four_axis_refinement_harness_2d(tmp_path: Path) -> None: + """P06-03 (1)-(2): 4-axis independent 2D refinement harness & structural/resource metrics.""" + prep_ion = prepare_confined_ion_device() + + # Mobile-ion 4-axis refinement with centered GB + report_mob = run_four_axis_refinement_2d( + prep_ion, + baseline=RefinementBaseline2D( + lateral_length_m=2.0e-7, + Nx=2, + Ny_per_layer=3, + dt_s=5.0e-7, + total_time_s=1.0e-6, + nonlinear_tol_scale=1.0, + voltage_V=0.2, + generation_scale=0.0, + lateral_bc="neumann", + ion_dynamics="single_mobile", + gb_width_m=2.0e-8, + ), + nx_values=(2, 4), + ny_per_layer_values=(3, 5), + dt_s_values=(5.0e-7, 2.5e-7), + nonlinear_tol_scales=(10.0, 1.0), + ) + assert report_mob.scientific_qualification is False + assert report_mob.performance_gate_evaluated is False + + axes = ( + ("Nx", report_mob.nx_axis, {"Ny_per_layer", "dt_s", "nonlinear_tol_scale"}), + ("Ny_per_layer", report_mob.ny_axis, {"Nx", "dt_s", "nonlinear_tol_scale"}), + ("dt_s", report_mob.dt_axis, {"Nx", "Ny_per_layer", "nonlinear_tol_scale"}), + ("nonlinear_tolerance", report_mob.nonlinear_tolerance_axis, {"Nx", "Ny_per_layer", "dt_s"}), + ) + for expected_name, axis_rep, expected_fixed_keys in axes: + assert axis_rep.axis == expected_name + assert set(axis_rep.held_fixed.keys()) == expected_fixed_keys + assert len(axis_rep.points) == 2 + for pt in axis_rep.points: + assert pt.accepted is True + assert pt.dof > 0 + assert pt.jacobian_nnz > 0 + assert pt.lu_nnz >= pt.jacobian_nnz + assert pt.rss_bytes > 0 + assert pt.wall_seconds > 0.0 + assert pt.newton_iterations > 0 + assert pt.ion_inventory_rel_drift is not None and pt.ion_inventory_rel_drift <= 1.0e-12 + assert axis_rep.points[-1].delta_from_finest_current_A_m2 == 0.0 + + assert report_mob.nx_axis.points[1].dof > report_mob.nx_axis.points[0].dof + assert report_mob.ny_axis.points[1].dof > report_mob.ny_axis.points[0].dof + + # Frozen-ion periodic 4-axis refinement + lossless JSON round-trip + report_frz = run_four_axis_refinement_2d( + load_device(), + baseline=RefinementBaseline2D( + lateral_length_m=2.0e-7, + Nx=2, + Ny_per_layer=3, + dt_s=5.0e-7, + total_time_s=1.0e-6, + nonlinear_tol_scale=1.0, + voltage_V=0.2, + generation_scale=0.0, + lateral_bc="periodic", + ion_dynamics="frozen", + gb_width_m=None, + ), + nx_values=(2, 4), + ny_per_layer_values=(3, 5), + dt_s_values=(5.0e-7, 2.5e-7), + nonlinear_tol_scales=(10.0, 1.0), + ) + assert all(pt.accepted and pt.ion_inventory_rel_drift is None for pt in report_frz.nx_axis.points) + + ref_path = tmp_path / "refinement_2d_report.json" + ref_sha = write_refinement_report_2d(ref_path, report_mob) + loaded_ref = read_refinement_report_2d(ref_path, expected_sha256=ref_sha) + assert loaded_ref.scientific_qualification is False + assert loaded_ref.performance_gate_evaluated is False + assert loaded_ref.nx_axis.points[-1].lu_nnz == report_mob.nx_axis.points[-1].lu_nnz + with pytest.raises(ValueError, match="SHA-256"): + read_refinement_report_2d(ref_path, expected_sha256="f" * 64) diff --git a/tests/unit/assembly/test_periodic_and_ionic_assembly_2d.py b/tests/unit/assembly/test_periodic_and_ionic_assembly_2d.py new file mode 100644 index 00000000..3368aa71 --- /dev/null +++ b/tests/unit/assembly/test_periodic_and_ionic_assembly_2d.py @@ -0,0 +1,612 @@ +"""Unit and sparse-assembly contracts for P06-01 (periodic 2D) and P06-02 (2D mobile-ion & extensions).""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np +import pytest +from scipy.sparse import csc_matrix, issparse +from scipy.sparse.linalg import spsolve +from threadpoolctl import threadpool_limits + +from examples.research_1d.ionic_multilayer import prepare_confined_dual_ion_device, prepare_confined_ion_device +from examples.research_1d.steady import load_device +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.compile_ionic_2d import ( + build_two_sided_interface_srh_2d, + compile_ionic_device_2d, +) +from solarlab.device.inputs import DeviceInput, GrainBoundaryInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.ionic_2d import ( + AssembledIonic2DProblem, + AssembledIonicDC2DProblem, + AssembledIonicTransient2DProblem, + AssembledStorage2D, +) +from solarlab.equations.assembly.two_dimensional import AssembledDC2DProblem +from solarlab.equations.dc_1d import CapabilityError, DC1DProblem +from solarlab.equations.dc_2d import DC2DProblem +from solarlab.equations.ionic_2d import ( + Ionic2DProblem, + finite_site_secant_2d_m3, +) +from solarlab.experiments.two_dimensional.inputs import JV2DInput, MicrostructureInput +from solarlab.experiments.two_dimensional.jv_sweep_2d import SpatialSnapshot2D +from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry_2d import ( + RECTANGULAR_HALF_ENDPOINT_2D_V1, + RECTANGULAR_PERIODIC_2D_V1, + RectangularGeometry2D, +) +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state +from solarlab.solvers.nonlinear.ionic_2d import IonicSteady2DOptions, solve_ionic_steady_state_2d +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state +from solarlab.solvers.nonlinear.steady_2d import solve_steady_state_2d +from solarlab.solvers.time.backward_euler_2d import compute_carrier_only_terminal_current_2d + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> Any: + with threadpool_limits(limits=1): + yield + + +def _edit_device(prepared: PreparedDevice, mutate: Any) -> PreparedDevice: + data = prepared.to_input().editing_data() + mutate(data) + return resolve_device( + DeviceInput.model_validate(data), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +def test_periodic_and_neumann_geometry_measures_wrap_faces_and_single_axis_decoupling() -> None: + x = np.array([0.0, 0.15, 0.45, 1.0]) * 1e-6 + y = np.array([0.0, 0.1, 0.3, 0.6, 1.0]) * 1e-6 + y_geom = half_endpoint_geometry(y) + + g_neu = RectangularGeometry2D(x, y_geom, lateral_bc="neumann") + g_per = RectangularGeometry2D(x, y_geom, lateral_bc="periodic") + + assert g_neu.name == RECTANGULAR_HALF_ENDPOINT_2D_V1 + assert g_per.name == RECTANGULAR_PERIODIC_2D_V1 + assert g_per.shape == (5, 4) + assert g_per.x_faces_per_row == 4 + assert g_neu.x_faces_per_row == 3 + assert g_per.x_face_count == 5 * 4 + assert g_neu.x_face_count == 5 * 3 + assert g_per.wrap_face_indices.shape == (5,) + assert g_neu.wrap_face_indices.size == 0 + + # Domain total area equals lateral_length_m * stack_length_m under both lateral BCs + dx = np.diff(x) + wrap_spacing = 0.5 * (dx[0] + dx[-1]) + expected_area_neu = (x[-1] - x[0]) * (y[-1] - y[0]) + expected_area_per = ((x[-1] - x[0]) + wrap_spacing) * (y[-1] - y[0]) + np.testing.assert_allclose(g_neu.contract_geometry.volumes.sum(), expected_area_neu, rtol=1e-15) + np.testing.assert_allclose(g_per.contract_geometry.volumes.sum(), expected_area_per, rtol=1e-15) + np.testing.assert_allclose(g_per.lateral_length_m, (x[-1] - x[0]) + wrap_spacing, rtol=1e-15) + + # Periodic wrap faces connect (row, Nx-1) -> (row, 0) with spacing 0.5 * (dx[0] + dx[-1]) + for row, f_idx in enumerate(g_per.wrap_face_indices): + left, right = g_per.contract_geometry.pairs[f_idx] + assert left == row * g_per.nx + (g_per.nx - 1) + assert right == row * g_per.nx + np.testing.assert_allclose(g_per.face_spacing_m[f_idx], wrap_spacing, rtol=1e-15) + + # Opposite-face scatter conservation: sum of divergence over closed x-periodic ring is 0 + rng = np.random.default_rng(42) + face_flux = rng.standard_normal(g_per.face_spacing_m.size) + weighted = face_flux * g_per.contract_geometry.face_measures + div = np.zeros(g_per.node_count) + np.add.at(div, g_per.contract_geometry.pairs[:, 0], weighted) + np.add.at(div, g_per.contract_geometry.pairs[:, 1], -weighted) + assert abs(math.fsum(div.tolist())) <= 1e-14 * np.max(np.abs(weighted)) + + # Single-axis perturbations decouple orthogonal faces + phi_x_only = np.tile(np.sin(2.0 * np.pi * x / (x[-1] - x[0])), (y.size, 1)).ravel() + grad_x_only = (phi_x_only[g_per.contract_geometry.pairs[:, 1]] - phi_x_only[g_per.contract_geometry.pairs[:, 0]]) + np.testing.assert_allclose(grad_x_only[g_per.x_face_count:], 0.0, atol=1e-16) + + phi_y_only = np.repeat(np.cos(np.pi * y / (y[-1] - y[0])), x.size) + grad_y_only = (phi_y_only[g_per.contract_geometry.pairs[:, 1]] - phi_y_only[g_per.contract_geometry.pairs[:, 0]]) + np.testing.assert_allclose(grad_y_only[:g_per.x_face_count], 0.0, atol=1e-16) + + +@pytest.mark.parametrize("lateral_bc", ["periodic", "neumann"]) +def test_mms_2d_poisson_second_order_convergence(lateral_bc: str) -> None: + """Manufactured-solution 2D Poisson verification on periodic-x and Neumann-x operators.""" + lx, ly = 1.2e-6, 0.8e-6 + errors: list[float] = [] + for n_int in (8, 16, 32): + x = np.linspace(0.0, lx, n_int + 1) + y = np.linspace(0.0, ly, n_int + 1) + g = RectangularGeometry2D(x, half_endpoint_geometry(y), lateral_bc=lateral_bc) # type: ignore[arg-type] + cg = g.contract_geometry + xx, yy = np.meshgrid(x, y) + if lateral_bc == "periodic": + # Exact power-of-two ring of n_int nodes on period lx -> spacing dx = lx / n_int + dx = lx / n_int + x_ring = np.arange(n_int, dtype=float) * dx + g = RectangularGeometry2D(x_ring, half_endpoint_geometry(y), lateral_bc="periodic") + cg = g.contract_geometry + xx, yy = np.meshgrid(x_ring, y) + kx = 2.0 * np.pi / lx + phi_exact = (np.sin(kx * xx) * np.sin(np.pi * yy / ly)).ravel() + rhs_vol = ((kx**2 + (np.pi / ly) ** 2) * np.sin(kx * xx) * np.sin(np.pi * yy / ly)).ravel() + else: + kx = np.pi / lx + phi_exact = (np.cos(kx * xx) * np.sin(np.pi * yy / ly)).ravel() + rhs_vol = ((kx**2 + (np.pi / ly) ** 2) * np.cos(kx * xx) * np.sin(np.pi * yy / ly)).ravel() + + # Assemble finite-volume Laplacian L_ij: sum_{f=(i,j)} (w_f / d_f) * (phi_i - phi_j) = V_i * rhs_i + n_nodes = g.node_count + left, right = cg.pairs[:, 0], cg.pairs[:, 1] + cond = cg.face_measures / g.face_spacing_m + rows = np.concatenate([left, right, left, right]) + cols = np.concatenate([left, right, right, left]) + vals = np.concatenate([cond, cond, -cond, -cond]) + mat = csc_matrix((vals, (rows, cols)), shape=(n_nodes, n_nodes)).tolil() + b = cg.volumes * rhs_vol + # Dirichlet y=0 and y=Ly contact rows + for c_node in g.contact_nodes: + mat.rows[c_node] = [int(c_node)] + mat.data[c_node] = [1.0] + b[c_node] = phi_exact[c_node] + phi_num = spsolve(mat.tocsc(), b) + l2_err = math.sqrt(float(np.sum(cg.volumes * (phi_num - phi_exact) ** 2) / np.sum(cg.volumes))) + errors.append(l2_err) + + rate_1 = math.log2(errors[0] / errors[1]) + rate_2 = math.log2(errors[1] / errors[2]) + assert rate_1 > 1.95 and rate_2 > 1.97, f"expected O(h^2) convergence, got rates {(rate_1, rate_2)}" + + +@pytest.mark.parametrize("lateral_bc", ["neumann", "periodic"]) +def test_laterally_uniform_periodic_and_neumann_reduce_to_1d_steady_within_1e12(lateral_bc: str) -> None: + prepared = load_device() + spatial = JV2DInput(kind="jv_2d", lateral_length="0.8 um", Nx=4, Ny_per_layer=4, lateral_bc=lateral_bc) # type: ignore[arg-type] + dev_2d = compile_device_2d(prepared, spatial) + dev_1d = compile_device_1d(prepared, intervals_per_layer=(4, 4, 4)) + + s_1d = solve_steady_state(dev_1d, voltage_V=0.45, generation_scale=1.0) + assert s_1d.state is not None + seed_2d = dev_2d.state(dev_2d.extrude_coordinates(s_1d.state.u), voltage_V=0.45) + + # Check both direct DC2DProblem and AssembledDC2DProblem residual & terminal current parity + p1 = DC1DProblem(dev_1d, 0.45, 1.0) + p2_raw = DC2DProblem(dev_2d, 0.45, 1.0) + p2_asm = AssembledDC2DProblem(dev_2d, 0.45, 1.0) + np.testing.assert_allclose(p2_asm.residual(seed_2d.u), p2_raw.residual(seed_2d.u), rtol=1e-13, atol=1e-22) + assert isinstance(p2_asm.jacobian(seed_2d.u), csc_matrix) + np.testing.assert_allclose(p2_asm.jacobian(seed_2d.u).toarray(), p2_raw.jacobian(seed_2d.u).toarray(), rtol=1e-13, atol=1e-22) + + s_2d = solve_steady_state_2d(dev_2d, voltage_V=0.45, generation_scale=1.0, initial_state=seed_2d) + assert s_2d.accepted and s_2d.state is not None and s_2d.diagnostics is not None + j_1d = float(p1.contact_current_density(s_1d.state.u)[1]) + j_2d = float(s_2d.diagnostics["terminal_mean_current_density_A_m2"][1]) + assert abs(j_2d - j_1d) <= 1e-12 * max(abs(j_1d), 1.0) + + +def test_assembled_ionic_2d_sparse_jacobian_mass_matrix_fd_and_1d_parity() -> None: + prepared = prepare_confined_ion_device(diffusion_only=True) + # Enable finite B_rad on absorber so radiative_reabsorption is active when requested + prepared_rad = _edit_device( + prepared, + lambda d: next(lyr for lyr in d["layers"] if lyr["role"] == "absorber")["parameters"].update( + B_rad=2.0e-16 + ), + ) + spatial = JV2DInput( + kind="jv_2d", + lateral_length="0.6 um", + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + ion_dynamics="single_mobile", + ) + ion_2d = compile_ionic_device_2d( + prepared_rad, + spatial, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + enable_radiative_reabsorption=True, + ) + assert len(ion_2d.radiative_reabsorption) == 1 + + # Compare 1D ionic steady vs laterally uniform 2D ionic steady (with reabsorption off for exact 1D match) + ion_2d_plain = compile_ionic_device_2d( + prepared, + spatial, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + enable_radiative_reabsorption=False, + ) + ion_1d = compile_ionic_device_1d( + prepared, + intervals_per_layer=(4, 4, 4), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + opts_1d = IonicSteadyOptions( + SteadyOptions(), 1e-12, 1e6, 1e6, 1.0, ion_1d.ion_node_count - 1, + SolveBudget(60, 600, 60, 24), 30.0, + ) + res_1d = solve_ionic_steady_state(ion_1d, voltage_V=0.2, generation_scale=0.0, options=opts_1d) + assert res_1d.accepted and res_1d.state is not None + res_2d = solve_ionic_steady_state_2d( + ion_2d_plain, voltage_V=0.2, generation_scale=0.0, options=IonicSteady2DOptions() + ) + assert res_2d.accepted and res_2d.state is not None + np.testing.assert_allclose( + res_2d.state.positive_ion_density_m3[:, 0], + res_1d.state.positive_ion_density_m3, + rtol=1e-12, + atol=1e10, + ) + np.testing.assert_allclose( + res_2d.state.positive_ion_density_m3[:, -1], + res_1d.state.positive_ion_density_m3, + rtol=1e-12, + atol=1e10, + ) + + # Perturb state laterally and verify preallocated sparse csc_matrix, M = -S_u, 4-side ion conservation, and FD + s0 = res_2d.state + rng = np.random.default_rng(123) + u = s0.u.copy() + n_elec = ion_2d.node_count + interior = np.setdiff1d(np.arange(n_elec), ion_2d.electronic_component.geometry.contact_nodes) + u[interior] += 0.015 * rng.standard_normal(interior.size) + u[n_elec + interior] += 0.1 * rng.standard_normal(interior.size) + u[2 * n_elec + interior] += 0.1 * rng.standard_normal(interior.size) + u[3 * n_elec:] += 0.08 * rng.standard_normal(ion_2d.ion_node_count) + + raw_prob = Ionic2DProblem(ion_2d, voltage_V=0.25, generation_scale=1.0) + dc_asm = AssembledIonicDC2DProblem(ion_2d, voltage_V=0.25, generation_scale=1.0) + tr_asm = AssembledIonicTransient2DProblem(ion_2d, voltage_V=0.25, generation_scale=1.0) + assert isinstance(tr_asm, AssembledIonic2DProblem) + + f_raw, j_raw = raw_prob.residual(u), raw_prob.jacobian(u) + f_dc, j_dc = dc_asm.residual(u), dc_asm.jacobian(u) + f_tr, j_tr = tr_asm.residual(u), tr_asm.jacobian(u) + assert issparse(j_dc) and isinstance(j_dc, csc_matrix) + assert issparse(j_tr) and isinstance(j_tr, csc_matrix) + assert j_tr.nnz < 0.15 * (ion_2d.state_size ** 2) + + np.testing.assert_allclose(f_dc, f_raw, rtol=1e-13, atol=1e-12) + np.testing.assert_allclose(f_tr, f_raw, rtol=1e-13, atol=1e-12) + np.testing.assert_allclose(j_tr.toarray(), j_raw.toarray(), rtol=1e-13, atol=1e-10) + + # Four-side blocking ion conservation: sum of all ion residual rows is zero + ion_rows = f_tr[3 * n_elec:] + assert abs(math.fsum(ion_rows.tolist())) <= 1e-12 * np.max(np.abs(ion_rows)) + + # M = -S_u convention on shared Assembler + s_vec, s_u = tr_asm.binding.assembler.storage(u, tr_asm.inputs, derivatives=True) + assert s_u is not None + mass = tr_asm.mass_matrix(u) + assert isinstance(mass, csc_matrix) + np.testing.assert_allclose(mass.toarray(), (-s_u).toarray(), rtol=1e-15, atol=0.0) + np.testing.assert_allclose(mass.toarray(), raw_prob.storage_jacobian(u).toarray(), rtol=1e-14, atol=0.0) + + # Directional central finite-difference verification of full coupled Jacobian (with radiative reabsorption!) + direction = np.zeros_like(u) + direction[interior] = 1e-3 * rng.standard_normal(interior.size) + direction[n_elec + interior] = 1e-2 * rng.standard_normal(interior.size) + direction[2 * n_elec + interior] = 1e-2 * rng.standard_normal(interior.size) + direction[3 * n_elec:] = 1e-2 * rng.standard_normal(ion_2d.ion_node_count) + eps = 1.0e-6 + fd_jv = (tr_asm.residual(u + eps * direction) - tr_asm.residual(u - eps * direction)) / (2.0 * eps) + exact_jv = j_tr @ direction + for sl in ( + slice(0, n_elec), + slice(n_elec, 2 * n_elec), + slice(2 * n_elec, 3 * n_elec), + slice(3 * n_elec, None), + ): + assert float(np.linalg.norm(fd_jv[sl] - exact_jv[sl]) / np.linalg.norm(exact_jv[sl])) < 1.0e-7 + + +def test_two_sided_interface_srh_assembly_jacobian_and_zero_overhead_when_off() -> None: + base = load_device() + + def _enable_two_sided_srh(data: dict[str, Any]) -> None: + defect_spec = { + "id": "if_trap", + "trap_depth_eV": 0.5, + "energy_reference": "below_conduction_band", + "total_density_m2": 1.0e14, + "kinetics": { + "sigma_n_m2": 1.0e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0, + } + data["settings"]["interface_two_sided"] = True + data["interfaces"] = [ + {"id": "if_htl_abs", "left": "htl", "right": "absorber", "v_n": 150.0, "v_p": 200.0, "defect": defect_spec}, + {"id": "if_abs_etl", "left": "absorber", "right": "etl", "v_n": 150.0, "v_p": 200.0, "defect": defect_spec}, + ] + + prep_if = _edit_device(base, _enable_two_sided_srh) + prep_clean = _edit_device(base, lambda _d: None) + spatial = JV2DInput(kind="jv_2d", lateral_length="0.6 um", Nx=3, Ny_per_layer=3, lateral_bc="neumann") + dev = compile_device_2d(prep_clean, spatial) + + couplings = build_two_sided_interface_srh_2d(prep_if, dev, interface_srh_mode="two_sided_cross_node") + assert len(couplings) == 2 + + st_off = AssembledStorage2D(dev, 0.7, 1.0) + st_on = AssembledStorage2D(dev, 0.7, 1.0, interface_srh_couplings=couplings) + dc_plain = AssembledDC2DProblem(dev, 0.7, 1.0) + + s0 = solve_steady_state_2d(dev, voltage_V=0.7, generation_scale=1.0).state + assert s0 is not None + rng = np.random.default_rng(7) + u_test = s0.u.copy() + interior = np.setdiff1d(np.arange(dev.node_count), dev.geometry.contact_nodes) + u_test[interior] += 0.005 * rng.standard_normal(interior.size) + u_test[dev.node_count + interior] += 0.05 * rng.standard_normal(interior.size) + u_test[2 * dev.node_count + interior] += 0.05 * rng.standard_normal(interior.size) + + # Exact bitwise identity with AssembledDC2DProblem when optional extensions are off + np.testing.assert_array_equal(st_off.residual(u_test), dc_plain.residual(u_test)) + np.testing.assert_array_equal(st_off.jacobian(u_test).toarray(), dc_plain.jacobian(u_test).toarray()) + + # Active cross-node interface SRH alters residual & matches central FD + assert np.max(np.abs(st_on.residual(s0.u) - st_off.residual(s0.u))) > 0.0 + direction = np.zeros_like(s0.u) + direction[interior] = 1e-3 * rng.standard_normal(interior.size) + direction[dev.node_count + interior] = 1e-2 * rng.standard_normal(interior.size) + direction[2 * dev.node_count + interior] = 1e-2 * rng.standard_normal(interior.size) + eps = 1.0e-6 + fd = (st_on.residual(s0.u + eps * direction) - st_on.residual(s0.u - eps * direction)) / (2.0 * eps) + ana = st_on.jacobian(s0.u) @ direction + n_el = dev.node_count + for sl in (slice(0, n_el), slice(n_el, 2 * n_el), slice(2 * n_el, 3 * n_el)): + assert float(np.linalg.norm(fd[sl] - ana[sl]) / np.linalg.norm(ana[sl])) < 1.0e-7 + + +def test_finite_site_secant_2d_is_cancellation_free_at_tiny_increments() -> None: + cap = np.array([1.0e27, 2.5e26, 5.0e26]) + a0 = np.array([-6.9, -2.5, 0.4]) + y_old = np.array([0.3, -1.1, 2.0]) + dy_req = np.array([1.0e-13, -2.5e-13, 5.0e-14]) + y_new = y_old + dy_req + dy_exact = y_new - y_old + secant = finite_site_secant_2d_m3(cap, a0, y_old, y_new) + from scipy.special import expit + sig = expit(a0 + y_old) + expected = cap * sig * (1.0 - sig) * dy_exact + np.testing.assert_allclose(secant, expected, rtol=1.0e-11, atol=0.0) + + +def test_gb_geometric_coverage_mixes_rates_rather_than_averaging_lifetimes() -> None: + prepared = load_device() + abs_id = next(lyr.id for lyr in prepared.layers if lyr.role == "absorber") + # Choose x grid [0, 0.5, 1.0] um -> cell 1 spans [0.25, 0.75] um (width 0.5 um). + # GB centered at 0.5 um with width 0.25 um covers f = 0.25 / 0.5 = 0.5 of cell 1! + gb = GrainBoundaryInput.model_validate( + { + "id": "gb_half", + "layer_ids": [abs_id], + "x_position": "0.5 um", + "width": "0.25 um", + "tau_n": "1 ns", + "tau_p": "1 ns", + } + ) + sp = JV2DInput( + kind="jv_2d", + lateral_length="1.0 um", + Nx=2, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=(gb,)), + ) + dev_gb = compile_device_2d(prepared, sp) + dev_bulk = compile_device_2d( + prepared, + JV2DInput(kind="jv_2d", lateral_length="1.0 um", Nx=2, Ny_per_layer=4, lateral_bc="neumann"), + ) + assert dev_gb.grain_recombination is not None + # Pick an interior absorber row and col=1 (center column, f=0.5) + abs_row = 6 + node_center = abs_row * dev_gb.geometry.nx + 1 + frac = float(dev_gb.grain_recombination.regions[0].fractions[node_center]) + assert math.isclose(frac, 0.5, rel_tol=1e-12) + + n = np.full(dev_gb.node_count, 1.0e21) + p = np.full(dev_gb.node_count, 2.0e21) + p_bulk = DC2DProblem(dev_bulk, 0.0, 0.0) + p_gb = DC2DProblem(dev_gb, 0.0, 0.0) + r_bulk = float(p_bulk.recombination_rate(n, p, derivatives=False).rate[node_center]) + r_actual = float(p_gb.recombination_rate(n, p, derivatives=False).rate[node_center]) + + # Full-coverage GB (width = 1.0 um -> f = 1.0) gives pure R_gb + gb_full = GrainBoundaryInput.model_validate( + { + "id": "gb_full", + "layer_ids": [abs_id], + "x_position": "0.5 um", + "width": "1.0 um", + "tau_n": "1 ns", + "tau_p": "1 ns", + } + ) + dev_full = compile_device_2d( + prepared, + JV2DInput( + kind="jv_2d", + lateral_length="1.0 um", + Nx=2, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=(gb_full,)), + ), + ) + r_pure_gb = float(DC2DProblem(dev_full, 0.0, 0.0).recombination_rate(n, p, derivatives=False).rate[node_center]) + + expected_rate_mix = r_bulk + 0.5 * (r_pure_gb - r_bulk) + np.testing.assert_allclose(r_actual, expected_rate_mix, rtol=1e-14) + # Averaging tau_eff = 0.5 * tau_bulk + 0.5 * tau_gb would give ~2x tau_bulk -> drastically smaller rate! + tau_b = float(dev_bulk.column.recombination.coefficients.tau_n_s[abs_row]) + ni_sq = float(dev_bulk.column.recombination.coefficients.ni_sq_m6[abs_row]) + n1 = float(dev_bulk.column.recombination.coefficients.n1_m3[abs_row]) + p1 = float(dev_bulk.column.recombination.coefficients.p1_m3[abs_row]) + tau_avg = 0.5 * tau_b + 0.5 * 1.0e-9 + r_wrong_tau_avg = (n[node_center] * p[node_center] - ni_sq) / (tau_avg * (n[node_center] + n1 + p[node_center] + p1)) + assert abs(r_actual - r_wrong_tau_avg) > 0.4 * abs(r_actual) + + +def test_fail_closed_2d_capability_error_refusal_matrix() -> None: + base = load_device() + abs_id = next(lyr.id for lyr in base.layers if lyr.role == "absorber") + gb = GrainBoundaryInput.model_validate( + { + "id": "gb0", + "layer_ids": [abs_id], + "x_position": "0.3 um", + "width": "20 nm", + "tau_n": "1 ns", + "tau_p": "1 ns", + } + ) + + # 1. Periodic + grain boundaries -> CapabilityError + sp_per_gb = JV2DInput( + kind="jv_2d", + lateral_length="0.6 um", + Nx=3, + Ny_per_layer=3, + lateral_bc="periodic", + microstructure=MicrostructureInput(grain_boundaries=(gb,)), + ) + with pytest.raises(CapabilityError, match="Neumann"): + compile_device_2d(base, sp_per_gb) + + # 2. Periodic + mobile-ion -> CapabilityError + ion_prep = prepare_confined_ion_device() + sp_per_ion = JV2DInput( + kind="jv_2d", lateral_length="0.6 um", Nx=3, Ny_per_layer=3, lateral_bc="periodic" + ) + with pytest.raises(CapabilityError, match="periodic|Neumann"): + compile_ionic_device_2d( + ion_prep, sp_per_ion, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 3. Dual-ion 2D -> CapabilityError + dual_prep = prepare_confined_dual_ion_device() + sp_neu = JV2DInput(kind="jv_2d", lateral_length="0.6 um", Nx=3, Ny_per_layer=3, lateral_bc="neumann") + with pytest.raises(CapabilityError, match="dual_ion_2d_unsupported"): + compile_ionic_device_2d( + dual_prep, sp_neu, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 4. Shared-site 2D -> CapabilityError + shared_prep = _edit_device(ion_prep, lambda d: d["settings"].update(ion_steric_shared_site=True)) + with pytest.raises(CapabilityError, match="dual_ion_2d_unsupported"): + compile_ionic_device_2d( + shared_prep, sp_neu, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 5. Selective Robin contacts + mobile-ion 2D -> CapabilityError + robin_ion_prep = _edit_device( + ion_prep, + lambda d: d.update( + contacts=[{"id": "front", "side": "left", "layer": "htl", "S_n": 1e5, "S_p": 1e-2}] + ), + ) + with pytest.raises(CapabilityError, match="selective_robin_ionic_2d_unsupported"): + compile_ionic_device_2d( + robin_ion_prep, sp_neu, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 6. Dynamic interface flags -> CapabilityError + for updates in ( + {"interface_plane_projection": True}, + {"interface_shared_occupancy": True}, + {"interface_charge_closure": "equilibrium_referenced", "interface_charge_rebaseline_acknowledged": True}, + ): + dyn_prep = _edit_device(ion_prep, lambda d, u=updates: d["settings"].update(u)) + with pytest.raises(CapabilityError, match="dynamic_interface_2d_unsupported"): + compile_ionic_device_2d( + dyn_prep, sp_neu, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 7. Active electrical interface SRH silently ignored when interface_srh="off" -> CapabilityError + active_if_prep = _edit_device( + ion_prep, + lambda d: d.update( + interfaces=[ + {"id": "if_htl_abs", "left": "htl", "right": "absorber", "v_n": 100.0, "v_p": 100.0}, + {"id": "if_abs_etl", "left": "absorber", "right": "etl"}, + ] + ), + ) + with pytest.raises(CapabilityError, match="interface_srh_2d_not_enabled|interface recombination is not bound"): + compile_ionic_device_2d( + active_if_prep, sp_neu, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 8. Zero-diffusivity D_ion == 0 with ion_dynamics="single_mobile" -> CapabilityError + zero_d_prep = _edit_device( + ion_prep, + lambda d: next(lyr for lyr in d["layers"] if lyr["role"] == "absorber")["parameters"].update(D_ion=0.0), + ) + sp_single = JV2DInput( + kind="jv_2d", + lateral_length="0.6 um", + Nx=3, + Ny_per_layer=3, + lateral_bc="neumann", + ion_dynamics="single_mobile", + ) + with pytest.raises(CapabilityError, match="mobile_ion_2d_requires_positive_diffusivity"): + compile_ionic_device_2d( + zero_d_prep, sp_single, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + + # 9. Carrier-only terminal current helper refuses IonicState2D and P_ion-bearing snapshots + ion_dev = compile_ionic_device_2d( + ion_prep, sp_single, ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking") + ) + elec_u0 = ion_dev.electronic_component.extrude_coordinates( + np.r_[ + ion_dev.electronic_component.column.reference_potential_V, + np.zeros(2 * ion_dev.electronic_component.geometry.ny), + ] + ) + ion_state = ion_dev.state(np.r_[elec_u0, np.zeros(ion_dev.ion_node_count)], voltage_V=0.0) + with pytest.raises(CapabilityError, match="carrier_only_current_refuses_mobile_ion_2d"): + compute_carrier_only_terminal_current_2d(ion_dev.electronic_component, ion_state) + elec_state = ion_dev.electronic_component.state(ion_state.u[:3 * ion_dev.node_count], voltage_V=0.0) + fake_snap = SpatialSnapshot2D( + V_app=0.0, + x=ion_dev.electronic_component.geometry.x_m, + y=ion_dev.electronic_component.geometry.y_geometry.nodes_m, + phi=elec_state.potential_V, + n=elec_state.electron_density_m3, + p=elec_state.hole_density_m3, + Jx_n=np.zeros((10, 3)), + Jy_n=np.zeros((9, 4)), + Jx_p=np.zeros((10, 3)), + Jy_p=np.zeros((9, 4)), + R_total=np.zeros((10, 4)), + P_ion=np.ones((10, 4)), + ) + with pytest.raises(CapabilityError, match="carrier_only_current_refuses_mobile_ion_2d"): + compute_carrier_only_terminal_current_2d(ion_dev.electronic_component, fake_snap) From 9a1cb01fea316eb6c0aff7d9147ddd1ff8cee469 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 23:00:10 +0800 Subject: [PATCH 09/46] N(2d): promote cross-module 2D helpers to public API for test_numerical_public_imports --- src/solarlab/equations/assembly/ionic_2d.py | 10 +- src/solarlab/equations/dc_2d.py | 8 +- src/solarlab/equations/ionic_2d.py | 11 +- .../two_dimensional/jv_sweep_2d.py | 129 ++++++++++++++---- .../two_dimensional/refinement_2d.py | 31 +++-- .../two_dimensional/voc_grain_sweep.py | 21 +-- src/solarlab/solvers/nonlinear/ionic_2d.py | 7 +- .../solvers/time/backward_euler_2d.py | 4 +- .../solvers/time/ionic_backward_euler_2d.py | 4 +- 9 files changed, 156 insertions(+), 69 deletions(-) diff --git a/src/solarlab/equations/assembly/ionic_2d.py b/src/solarlab/equations/assembly/ionic_2d.py index 74e81ee0..c0b186b9 100644 --- a/src/solarlab/equations/assembly/ionic_2d.py +++ b/src/solarlab/equations/assembly/ionic_2d.py @@ -44,9 +44,9 @@ from solarlab.equations.dc_2d import CompiledDevice2D from solarlab.equations.ionic_2d import ( CompiledIonicDevice2D, RadiativeReabsorptionSpec2D, TwoSidedInterfaceSRHCoupling2D, - _interface_srh_sheet_rate_and_partials, evaluate_two_sided_interface_srh_2d, - finite_site_secant_2d_m3, ion_pair_flux_jacobian_2d, recompute_g_with_rad_2d, - trapezoid_weights_1d, + evaluate_two_sided_interface_srh_2d, finite_site_secant_2d_m3, + interface_srh_sheet_rate_and_partials, ion_pair_flux_jacobian_2d, + recompute_g_with_rad_2d, trapezoid_weights_1d, ) from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, IonFaceFluxJacobian from solarlab.physics.recombination.bulk import RecombinationRate @@ -724,7 +724,7 @@ def emit_carrier(carrier_idx: int, offset: int, r: ArrayLike, c: ArrayLike, v: A right_nodes: NDArray[np.intp] = c.right_sample_row * nx + cols_x scale = vol[row_nodes] / normal_widths[c.interface_row] - raw_a, da_dn, da_dp = _interface_srh_sheet_rate_and_partials( + raw_a, da_dn, da_dp = interface_srh_sheet_rate_and_partials( n_2d[c.right_sample_row, :], p_2d[c.left_sample_row, :], c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, @@ -733,7 +733,7 @@ def emit_carrier(carrier_idx: int, offset: int, r: ArrayLike, c: ArrayLike, v: A dn_r = -scale * act_a * da_dn * n_2d[c.right_sample_row, :] dp_l = -scale * act_a * da_dp * p_2d[c.left_sample_row, :] - raw_b, db_dn, db_dp = _interface_srh_sheet_rate_and_partials( + raw_b, db_dn, db_dp = interface_srh_sheet_rate_and_partials( n_2d[c.left_sample_row, :], p_2d[c.right_sample_row, :], c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, diff --git a/src/solarlab/equations/dc_2d.py b/src/solarlab/equations/dc_2d.py index 078d23ca..1250e092 100644 --- a/src/solarlab/equations/dc_2d.py +++ b/src/solarlab/equations/dc_2d.py @@ -273,8 +273,8 @@ def displacement(self, u: ArrayLike) -> Vector: left, right = self.device.geometry.contract_geometry.pairs.T return -self.device.face_capacitance_F_m2 * (phi[right] - phi[left]) - def _contact_exchange(self, u: Vector, channel: CarrierExchangeChannel, - nodes: NDArray[np.int64]) -> tuple[Vector, float]: + def contact_exchange(self, u: Vector, channel: CarrierExchangeChannel, + nodes: NDArray[np.int64]) -> tuple[Vector, float]: """The 1D contact law/expm1 construction on a whole y contact face. Left/right means y-min/y-max here. Gamma is directed along +y, @@ -289,6 +289,10 @@ def _contact_exchange(self, u: Vector, channel: CarrierExchangeChannel, excess = channel.reservoir_density_m3 * np.expm1(exponent) return boundary.density_derivative * excess, boundary.density_derivative + def _contact_exchange(self, u: Vector, channel: CarrierExchangeChannel, + nodes: NDArray[np.int64]) -> tuple[Vector, float]: + return self.contact_exchange(u, channel, nodes) + def residual(self, u: ArrayLike) -> Vector: d, count = self.device, self.device.node_count values = np.asarray(u, dtype=float) diff --git a/src/solarlab/equations/ionic_2d.py b/src/solarlab/equations/ionic_2d.py index e4c53e5e..c850fefb 100644 --- a/src/solarlab/equations/ionic_2d.py +++ b/src/solarlab/equations/ionic_2d.py @@ -50,6 +50,7 @@ "control_volume_areas_2d", "evaluate_two_sided_interface_srh_2d", "finite_site_secant_2d_m3", + "interface_srh_sheet_rate_and_partials", "ion_inventory_2d", "ion_pair_flux_jacobian_2d", "positive_ion_fluxes_2d", @@ -185,7 +186,7 @@ class TwoSidedInterfaceSRHReport2D: volumetric_sink_m3_s: Vector -def _interface_srh_sheet_rate_and_partials( +def interface_srh_sheet_rate_and_partials( n_sample: Vector, p_sample: Vector, eq_product: float, @@ -232,12 +233,12 @@ def evaluate_two_sided_interface_srh_2d( for idx, c in enumerate(couplings): if c.interface_row <= 0 or c.interface_row >= electrons.shape[0] - 1: raise ValueError("interface-SRH sheet must use interior idx-1/idx+1 sampling") - raw_a, _, _ = _interface_srh_sheet_rate_and_partials( + raw_a, _, _ = interface_srh_sheet_rate_and_partials( electrons[c.right_sample_row, :], holes[c.left_sample_row, :], c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, ) - raw_b, _, _ = _interface_srh_sheet_rate_and_partials( + raw_b, _, _ = interface_srh_sheet_rate_and_partials( np.maximum(electrons[c.left_sample_row, :], 0.0), np.maximum(holes[c.right_sample_row, :], 0.0), c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, @@ -1083,7 +1084,7 @@ def emit(r: ArrayLike, c: ArrayLike, v: ArrayLike) -> None: right_nodes: NDArray[np.intp] = c.right_sample_row * nx + cols_x scale = vol[row_nodes] / normal_widths[c.interface_row] - raw_a, da_dn, da_dp = _interface_srh_sheet_rate_and_partials( + raw_a, da_dn, da_dp = interface_srh_sheet_rate_and_partials( n_2d[c.right_sample_row, :], p_2d[c.left_sample_row, :], c.pair_a_equilibrium_product_m6, c.n1_m3, c.p1_m3, c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, @@ -1093,7 +1094,7 @@ def emit(r: ArrayLike, c: ArrayLike, v: ArrayLike) -> None: dn_r = -scale * act_a * da_dn * n_2d[c.right_sample_row, :] dp_l = -scale * act_a * da_dp * p_2d[c.left_sample_row, :] - raw_b, db_dn, db_dp = _interface_srh_sheet_rate_and_partials( + raw_b, db_dn, db_dp = interface_srh_sheet_rate_and_partials( n_2d[c.left_sample_row, :], p_2d[c.right_sample_row, :], c.pair_b_equilibrium_product_m6, c.n1_m3, c.p1_m3, c.electron_capture_velocity_m_s, c.hole_capture_velocity_m_s, diff --git a/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py b/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py index aa022a10..c87b7e8a 100644 --- a/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py +++ b/src/solarlab/experiments/two_dimensional/jv_sweep_2d.py @@ -17,10 +17,12 @@ from __future__ import annotations from collections.abc import Callable, Mapping, Sequence -from dataclasses import asdict, dataclass, field, replace +from dataclasses import asdict, dataclass, field, fields, is_dataclass, replace +from enum import Enum import hashlib import json import math +import os from pathlib import Path import time from typing import Any, Literal, TypeAlias, cast @@ -55,7 +57,7 @@ recompute_g_with_rad_2d, ) from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics -from solarlab.experiments.transient_results import _decode, _encode +from solarlab.experiments.results import decode_array, encode_array from solarlab.experiments.two_dimensional.inputs import ( JV2DInput, JV2DProtocolInput, @@ -71,7 +73,6 @@ resolve_jv_2d_protocol, ) from solarlab.experiments.two_dimensional.preparation import PreparedSpatialExperiment -from solarlab.experiments.worker import _atomic_json from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state from solarlab.solvers.nonlinear.ionic_2d import solve_ionic_steady_state_2d from solarlab.solvers.nonlinear.problem import SolveBudget, state_digest @@ -99,13 +100,91 @@ "SpatialSnapshot2D", "build_jv_2d_execution_protocol", "compute_jv_2d_metrics", + "decode_json_payload", + "default_ionic_steady_options_1d", + "device_has_ions", + "embed_frozen_ion_excess_2d", + "encode_json_payload", "extract_snapshot_2d", + "precondition_frozen_lane", + "project_prepared_for_electronic_2d", "read_jv_2d_result", "run_dynamic_jv_pair_2d", "run_jv_sweep_2d", + "write_atomic_json", "write_jv_2d_result", ] +_JSON_CODEC_TAGS = {"$array", "$scalar", "$float", "$tuple"} + + +def encode_json_payload(value: Any) -> Any: + """Losslessly encode dataclasses, tuples, arrays, and nonfinite floats for JSON.""" + if is_dataclass(value) and not isinstance(value, type): + return {f.name: encode_json_payload(getattr(value, f.name)) for f in fields(value)} + if type(value) is np.ndarray: + return {"$array": encode_array(value, unit="raw diagnostic; units follow the named producer field")} + if isinstance(value, np.generic): + return {"$scalar": encode_array(np.asarray(value), unit="raw diagnostic")} + if isinstance(value, Enum): + return encode_json_payload(value.value) + if type(value) is tuple: + return {"$tuple": [encode_json_payload(item) for item in value]} + if type(value) is list: + return [encode_json_payload(item) for item in value] + if type(value) is dict: + if any(type(key) is not str for key in value) or set(value) & _JSON_CODEC_TAGS: + raise ValueError("JSON payloads require plain string keys without codec tags") + return {key: encode_json_payload(item) for key, item in value.items()} + if type(value) is float and not math.isfinite(value): + return {"$float": encode_array(np.asarray(value), unit="raw diagnostic")} + if value is None or type(value) in {str, bool, int, float}: + return value + raise ValueError("unsupported JSON payload type: " + type(value).__name__) + + +def decode_json_payload(value: Any) -> Any: + """Decode a payload written with :func:`encode_json_payload`.""" + if type(value) is list: + return [decode_json_payload(item) for item in value] + if type(value) is dict: + tags = set(value) & _JSON_CODEC_TAGS + if tags: + if len(value) != 1: + raise ValueError("ambiguous JSON payload tag") + (tag,) = tags + if tag == "$tuple": + if type(value[tag]) is not list: + raise ValueError("invalid JSON payload tuple") + return tuple(decode_json_payload(item) for item in value[tag]) + array = decode_array(value[tag]) + if tag != "$array": + if array.shape != (): + raise ValueError("JSON payload scalar must have scalar shape") + return array.item() if tag == "$float" else array[()] + return array + return {key: decode_json_payload(item) for key, item in value.items()} + return value + + +def write_atomic_json(path: Path, value: dict[str, Any]) -> None: + """Atomically write canonical strict JSON to ``path`` with fsync.""" + if type(value) is not dict: + raise ValueError("an explicit strict JSON object is required") + raw = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") + partial = path.with_suffix(path.suffix + ".part") + fd = os.open(partial, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + os.replace(partial, path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + Vector: TypeAlias = NDArray[np.float64] ProgressCallback: TypeAlias = Callable[[str, int, int, str], None] Disposition: TypeAlias = Literal["completed", "partial", "failed"] @@ -354,14 +433,14 @@ def _fn(t: float) -> float: return _fn -def _default_ionic_steady_options_1d(ion_node_count: int) -> IonicSteadyOptions: +def default_ionic_steady_options_1d(ion_node_count: int) -> IonicSteadyOptions: return IonicSteadyOptions( SteadyOptions(), 1.0e-12, 1.0e6, 1.0e6, 1.0, ion_node_count - 1, SolveBudget(60, 600, 60, 24), 30.0, ) -def _device_has_ions(prepared: PreparedDevice) -> tuple[bool, str | None]: +def device_has_ions(prepared: PreparedDevice) -> tuple[bool, str | None]: elec = [layer for layer in prepared.layers if layer.role != "substrate"] ion_layers: list[str] = [] for layer in elec: @@ -375,7 +454,7 @@ def _device_has_ions(prepared: PreparedDevice) -> tuple[bool, str | None]: return (len(ion_layers) == 1, ion_layers[0] if ion_layers else None) -def _project_prepared_for_electronic_2d( +def project_prepared_for_electronic_2d( prepared: PreparedDevice, *, strip_ions: bool, @@ -423,7 +502,7 @@ def _project_prepared_for_electronic_2d( ) -def _embed_frozen_ion_excess_2d( +def embed_frozen_ion_excess_2d( device_2d: CompiledDevice2D, excess_1d_m3: Vector, ) -> CompiledDevice2D: @@ -504,7 +583,7 @@ def extract_snapshot_2d( ) -def _precondition_frozen_lane( +def precondition_frozen_lane( prepared: PreparedDevice, geom_spatial: JV2DInput, protocol: JV2DProtocol, @@ -515,10 +594,10 @@ def _precondition_frozen_lane( tuple[TwoSidedInterfaceSRHCoupling2D, ...], ]: """Compile frozen-ion 2D device and run 1D dark/illuminated preconditioner.""" - has_ions, ion_layer_id = _device_has_ions(prepared) + has_ions, ion_layer_id = device_has_ions(prepared) use_iface = protocol.interface_srh == "two_sided_cross_node" # Validate dynamic interface flags and two-sided SRH before projecting interfaces - base_clean = _project_prepared_for_electronic_2d( + base_clean = project_prepared_for_electronic_2d( prepared, strip_ions=has_ions, strip_interfaces=use_iface ) device_2d = compile_device_2d(base_clean, geom_spatial) @@ -534,7 +613,7 @@ def _precondition_frozen_lane( # 1. Solve 1D dark equilibrium (and 1D illuminated finite-time settle if requested) excess_1d: Vector = np.zeros(ny_nodes, dtype=np.float64) if has_ions and ion_layer_id is not None: - prep_1d_ion = _project_prepared_for_electronic_2d( + prep_1d_ion = project_prepared_for_electronic_2d( prepared, strip_ions=False, strip_interfaces=use_iface, strip_grains=True ) # If carrier contacts are ohmic and Neumann-x, use Nx=1 auxiliary 2D ionic solver so @@ -551,7 +630,7 @@ def _precondition_frozen_lane( interface_srh=protocol.interface_srh, ) aux_ionic = compile_ionic_device_2d( - _project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False, strip_grains=True), + project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False, strip_grains=True), aux_spatial, ion_domain_layer=ion_layer_id, ion_domain_endpoints=("blocking", "blocking"), @@ -613,7 +692,7 @@ def _precondition_frozen_lane( ref_col0 = aux_ionic.positive_ion_reference_m3.reshape(aux_ionic.ion_geometry.ny, aux_nx)[:, 0] ratio_col0 = aux_ionic.ion_charge_weight_ratio.reshape(aux_ionic.ion_geometry.ny, aux_nx)[:, 0] excess_1d[aux_ionic.ion_row_indices] = (ion_p_col0 - ref_col0) * ratio_col0 - device_2d = _embed_frozen_ion_excess_2d(device_2d, excess_1d) + device_2d = embed_frozen_ion_excess_2d(device_2d, excess_1d) init_2d = device_2d.state(device_2d.extrude_coordinates(col_u_1d), voltage_V=0.0) return device_2d, init_2d, rr_specs, iface_couplings @@ -628,7 +707,7 @@ def _precondition_frozen_lane( ionic_1d, voltage_V=0.0, generation_scale=0.0, - options=_default_ionic_steady_options_1d(ionic_1d.ion_node_count), + options=default_ionic_steady_options_1d(ionic_1d.ion_node_count), ) if not dark_1d_ion.accepted or dark_1d_ion.state is None: raise RuntimeError(f"1D Robin ionic dark equilibrium failed: {dark_1d_ion.error}") @@ -637,7 +716,7 @@ def _precondition_frozen_lane( excess_1d[ionic_1d.ion_node_indices] = ( ion_p_1d - ionic_1d.positive_ion_reference_m3 ) * ionic_1d.ion_charge_weight_ratio - device_2d = _embed_frozen_ion_excess_2d(device_2d, excess_1d) + device_2d = embed_frozen_ion_excess_2d(device_2d, excess_1d) if not protocol.illuminated: return device_2d, device_2d.state(device_2d.extrude_coordinates(col_u_1d), voltage_V=0.0), rr_specs, iface_couplings else: @@ -658,10 +737,10 @@ def _precondition_frozen_lane( lateral_bc="neumann", microstructure=MicrostructureInput(grain_boundaries=()), ) - aux_clean = _project_prepared_for_electronic_2d( + aux_clean = project_prepared_for_electronic_2d( prepared, strip_ions=has_ions, strip_interfaces=use_iface, strip_grains=True ) - aux_dev = _embed_frozen_ion_excess_2d(compile_device_2d(aux_clean, aux_geom), excess_1d) + aux_dev = embed_frozen_ion_excess_2d(compile_device_2d(aux_clean, aux_geom), excess_1d) aux_rr = build_radiative_reabsorption_2d(prepared, aux_dev) aux_if = build_two_sided_interface_srh_2d(prepared, aux_dev, interface_srh_mode=protocol.interface_srh) aux_s0 = aux_dev.state(aux_dev.extrude_coordinates(col_u_1d), voltage_V=0.0) @@ -689,7 +768,7 @@ def _precondition_mobile_ion_lane( protocol: JV2DProtocol, ) -> tuple[CompiledIonicDevice2D, IonicState2D]: """Compile mobile-ion 2D device and run 1D dark/illuminated preconditioner.""" - _, ion_layer_id = _device_has_ions(prepared) + _, ion_layer_id = device_has_ions(prepared) ionic_2d = compile_ionic_device_2d( prepared, exec_spatial, @@ -706,7 +785,7 @@ def _precondition_mobile_ion_lane( ion_dynamics="single_mobile", interface_srh=protocol.interface_srh, ) - aux_prep = _project_prepared_for_electronic_2d( + aux_prep = project_prepared_for_electronic_2d( prepared, strip_ions=False, strip_interfaces=False, strip_grains=True ) aux_ionic = compile_ionic_device_2d( @@ -848,8 +927,8 @@ def build_jv_2d_execution_protocol( lateral_bc=lateral_bc, microstructure=ms_input, ) - has_ions, _ = _device_has_ions(prepared) - clean_prep = _project_prepared_for_electronic_2d( + has_ions, _ = device_has_ions(prepared) + clean_prep = project_prepared_for_electronic_2d( prepared, strip_ions=has_ions, strip_interfaces=(interface_srh == "two_sided_cross_node"), @@ -1200,7 +1279,7 @@ def run_jv_sweep_2d( if progress is not None: progress("jv_2d", idx + 1, int(voltages.size), f"V = {v_val:.3f} V") else: - elec_dev, elec_state, rr_specs, iface_couplings = _precondition_frozen_lane( + elec_dev, elec_state, rr_specs, iface_couplings = precondition_frozen_lane( prepared, geom_spatial, resolved_proto ) polarity = float(elec_dev.column.voltage_polarity) @@ -1349,7 +1428,7 @@ def run_dynamic_jv_pair_2d( ion_dynamics="single_mobile", interface_srh=protocol.interface_srh, ) - _, ion_layer_id = _device_has_ions(prepared) + _, ion_layer_id = device_has_ions(prepared) ionic_dev = compile_ionic_device_2d( prepared, exec_spatial, @@ -1525,7 +1604,7 @@ def write_jv_2d_result(path: str | Path, result: JV2DResult) -> str: "attempts": [asdict(a) for a in result.attempts], "ion_diagnostics": [asdict(d) for d in result.ion_diagnostics], } - _atomic_json(target, _encode(payload)) + write_atomic_json(target, encode_json_payload(payload)) return hashlib.sha256(target.read_bytes()).hexdigest() @@ -1535,7 +1614,7 @@ def read_jv_2d_result(path: str | Path, *, expected_sha256: str | None = None) - actual_sha = hashlib.sha256(raw).hexdigest() if expected_sha256 is not None and actual_sha != expected_sha256: raise ValueError("JV2DResult SHA-256 mismatch") - doc = _decode(json.loads(raw)) + doc = decode_json_payload(json.loads(raw)) if doc.get("schema") != JV2D_RESULT_SCHEMA or doc.get("scientific_qualification") is not False: raise ValueError("invalid JV2DResult schema or qualification flag") proto = None if doc["protocol"] is None else JV2DProtocol.from_dict(doc["protocol"]) diff --git a/src/solarlab/experiments/two_dimensional/refinement_2d.py b/src/solarlab/experiments/two_dimensional/refinement_2d.py index bcd0bbab..5704cd7c 100644 --- a/src/solarlab/experiments/two_dimensional/refinement_2d.py +++ b/src/solarlab/experiments/two_dimensional/refinement_2d.py @@ -36,15 +36,16 @@ from solarlab.device.compile_ionic_2d import compile_ionic_device_2d from solarlab.device.inputs import GrainBoundaryInput from solarlab.device.resolved import PreparedDevice -from solarlab.experiments.transient_results import _decode, _encode from solarlab.experiments.two_dimensional.inputs import JV2DInput, MicrostructureInput from solarlab.experiments.two_dimensional.jv_sweep_2d import ( - _default_ionic_steady_options_1d, - _device_has_ions, - _embed_frozen_ion_excess_2d, - _project_prepared_for_electronic_2d, + decode_json_payload, + default_ionic_steady_options_1d, + device_has_ions, + embed_frozen_ion_excess_2d, + encode_json_payload, + project_prepared_for_electronic_2d, + write_atomic_json, ) -from solarlab.experiments.worker import _atomic_json from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state from solarlab.solvers.nonlinear.ionic_2d import solve_ionic_steady_state_2d from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state @@ -246,7 +247,7 @@ def _evaluate_one_point( elec_tol = _scaled_steady_options(tol_scale) if baseline.ion_dynamics == "single_mobile": - _, ion_layer_id = _device_has_ions(prepared) + _, ion_layer_id = device_has_ions(prepared) exec_spatial = JV2DInput( kind="jv_2d", lateral_length=baseline.lateral_length_m, @@ -264,7 +265,7 @@ def _evaluate_one_point( ion_domain_endpoints=("blocking", "blocking"), ) # Seed from 1D dark equilibrium on grain-free Nx=1 column - aux_prep = _project_prepared_for_electronic_2d( + aux_prep = project_prepared_for_electronic_2d( prepared, strip_ions=False, strip_interfaces=False, strip_grains=True ) aux_sp = JV2DInput( @@ -349,8 +350,8 @@ def _evaluate_one_point( ) # Frozen-ion / classical 2D refinement lane - has_ions, ion_layer_id = _device_has_ions(prepared) - clean_prep = _project_prepared_for_electronic_2d(prepared, strip_ions=has_ions, strip_interfaces=False) + has_ions, ion_layer_id = device_has_ions(prepared) + clean_prep = project_prepared_for_electronic_2d(prepared, strip_ions=has_ions, strip_interfaces=False) geom_sp = JV2DInput( kind="jv_2d", lateral_length=baseline.lateral_length_m, @@ -362,7 +363,7 @@ def _evaluate_one_point( elec_dev = compile_device_2d(clean_prep, geom_sp) if has_ions and ion_layer_id is not None: n_layers = len([lyr for lyr in prepared.layers if lyr.role != "substrate"]) - prep_1d_ion = _project_prepared_for_electronic_2d( + prep_1d_ion = project_prepared_for_electronic_2d( prepared, strip_ions=False, strip_interfaces=False, strip_grains=True ) from solarlab.device.compile_ionic_1d import compile_ionic_device_1d @@ -377,7 +378,7 @@ def _evaluate_one_point( ion_1d, voltage_V=0.0, generation_scale=0.0, - options=_default_ionic_steady_options_1d(ion_1d.ion_node_count), + options=default_ionic_steady_options_1d(ion_1d.ion_node_count), ) if not dark_1d_i.accepted or dark_1d_i.state is None: raise RuntimeError(f"refinement 1D frozen-ion seed failed: {dark_1d_i.error}") @@ -385,7 +386,7 @@ def _evaluate_one_point( exc[ion_1d.ion_node_indices] = ( dark_1d_i.state.positive_ion_density_m3 - ion_1d.positive_ion_reference_m3 ) * ion_1d.ion_charge_weight_ratio - elec_dev = _embed_frozen_ion_excess_2d(elec_dev, exc) + elec_dev = embed_frozen_ion_excess_2d(elec_dev, exc) u_1d = dark_1d_i.state.u[:3 * ion_1d.node_count] else: dark_1d = solve_steady_state(elec_dev.column, voltage_V=0.0, generation_scale=0.0) @@ -582,7 +583,7 @@ def run_four_axis_refinement_2d( def write_refinement_report_2d(path: str | Path, report: FourAxisRefinementReport2D) -> str: """Write a lossless JSON artifact for ``FourAxisRefinementReport2D`` and return SHA-256.""" target = Path(path) - _atomic_json(target, _encode(report.to_dict())) + write_atomic_json(target, encode_json_payload(report.to_dict())) return hashlib.sha256(target.read_bytes()).hexdigest() @@ -594,7 +595,7 @@ def read_refinement_report_2d( actual_sha = hashlib.sha256(raw).hexdigest() if expected_sha256 is not None and actual_sha != expected_sha256: raise ValueError("FourAxisRefinementReport2D SHA-256 mismatch") - doc = _decode(json.loads(raw)) + doc = decode_json_payload(json.loads(raw)) if ( doc.get("schema") != REFINEMENT_2D_SCHEMA or doc.get("scientific_qualification") is not False diff --git a/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py b/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py index 26b2473c..b4eb7650 100644 --- a/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py +++ b/src/solarlab/experiments/two_dimensional/voc_grain_sweep.py @@ -34,7 +34,6 @@ from solarlab.device.resolved import PreparedDevice from solarlab.equations.dc_1d import CapabilityError from solarlab.equations.dc_2d import CompiledDevice2D, State2D -from solarlab.experiments.transient_results import _decode, _encode from solarlab.experiments.two_dimensional.inputs import ( GrainSweepInput, JV2DInput, @@ -43,14 +42,16 @@ from solarlab.experiments.two_dimensional.jv_sweep_2d import ( Disposition, ProgressCallback, - _device_has_ions, - _precondition_frozen_lane, - _project_prepared_for_electronic_2d, build_jv_2d_execution_protocol, + decode_json_payload, + device_has_ions, + encode_json_payload, + precondition_frozen_lane, + project_prepared_for_electronic_2d, run_jv_sweep_2d, + write_atomic_json, ) from solarlab.experiments.two_dimensional.preparation import PreparedSpatialExperiment -from solarlab.experiments.worker import _atomic_json from solarlab.solvers.nonlinear.steady_1d import solve_steady_state from solarlab.solvers.nonlinear.steady_2d import Steady2DOptions, solve_steady_state_2d @@ -237,7 +238,7 @@ def solve_direct_voc_2d( lateral_bc="neumann", microstructure=ms_input, ) - has_ions, _ = _device_has_ions(prepared) + has_ions, _ = device_has_ions(prepared) if has_ions: proto = build_jv_2d_execution_protocol( prepared, @@ -252,7 +253,7 @@ def solve_direct_voc_2d( initial_state_settle_s=initial_state_settle_s, implicit_legacy_protocol=True, ) - device_2d, seed_2d, rr_specs, iface_couplings = _precondition_frozen_lane( + device_2d, seed_2d, rr_specs, iface_couplings = precondition_frozen_lane( prepared, geom_spatial, proto ) if rr_specs or iface_couplings: @@ -260,7 +261,7 @@ def solve_direct_voc_2d( "direct_voc_2d_unsupported_extensions: direct steady V_oc requires standard local 2D recombination" ) else: - clean = _project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False) + clean = project_prepared_for_electronic_2d(prepared, strip_ions=False, strip_interfaces=False) device_2d = compile_device_2d(clean, geom_spatial) col_illum = solve_steady_state(device_2d.column, voltage_V=0.0, generation_scale=1.0) if col_illum.state is None: @@ -545,7 +546,7 @@ def write_voc_grain_sweep(path: str | Path, result: VocGrainSweepResult) -> str: "FF": result.FF, "points": [asdict(p) for p in result.points], } - _atomic_json(target, _encode(payload)) + write_atomic_json(target, encode_json_payload(payload)) return hashlib.sha256(target.read_bytes()).hexdigest() @@ -555,7 +556,7 @@ def read_voc_grain_sweep(path: str | Path, *, expected_sha256: str | None = None actual_sha = hashlib.sha256(raw).hexdigest() if expected_sha256 is not None and actual_sha != expected_sha256: raise ValueError("VocGrainSweepResult SHA-256 mismatch") - doc = _decode(json.loads(raw)) + doc = decode_json_payload(json.loads(raw)) if doc.get("schema") != VOC_GRAIN_SWEEP_SCHEMA or doc.get("scientific_qualification") is not False: raise ValueError("invalid VocGrainSweepResult schema or qualification flag") return VocGrainSweepResult( diff --git a/src/solarlab/solvers/nonlinear/ionic_2d.py b/src/solarlab/solvers/nonlinear/ionic_2d.py index b2e3e648..035ce1a5 100644 --- a/src/solarlab/solvers/nonlinear/ionic_2d.py +++ b/src/solarlab/solvers/nonlinear/ionic_2d.py @@ -36,6 +36,7 @@ "IonicSteady2DResult", "checks", "diagnostics", + "poisson_weights_2d", "solve_ionic_steady_state_2d", ] @@ -161,7 +162,7 @@ def __post_init__(self) -> None: _Unconstrained2D: TypeAlias = Ionic2DProblem | AssembledIonic2DProblem -def _poisson_weights_2d(device: CompiledIonicDevice2D) -> np.ndarray: +def poisson_weights_2d(device: CompiledIonicDevice2D) -> np.ndarray: comp = device.electronic_component g = comp.geometry.contract_geometry reference_V = max(abs(comp.column.built_in_potential_V), comp.thermal_voltage_V) @@ -190,7 +191,7 @@ def _newton_settings(device: CompiledIonicDevice2D, options: IonicSteady2DOption n_elec = comp.node_count n_ion = device.ion_node_count weights: NDArray[np.float64] = np.empty(device.state_size, dtype=np.float64) - weights[:n_elec] = _poisson_weights_2d(device) / c.poisson_tolerance + weights[:n_elec] = poisson_weights_2d(device) / c.poisson_tolerance weights[n_elec:3 * n_elec] = 2.0 * n_elec * Q / ( comp.geometry.lateral_length_m * c.continuity_tolerance_A_m2 ) @@ -218,7 +219,7 @@ def diagnostics(problem: _Unconstrained2D, u: np.ndarray, options: IonicSteady2D phi, n, p, ion_p = d.fields(u, voltage_V=problem.voltage_V) if not (np.all(np.isfinite(raw_res)) and np.all(np.isfinite(n)) and np.all(np.isfinite(p)) and np.all(np.isfinite(ion_p))): raise ValueError("2D ionic diagnostic fields or original residual are non-finite") - poisson_norm = float(np.max(np.abs(raw_res[:n_elec] * _poisson_weights_2d(d)))) + poisson_norm = float(np.max(np.abs(raw_res[:n_elec] * poisson_weights_2d(d)))) carrier_rows = raw_res[n_elec:3 * n_elec].reshape(2, n_elec).copy() contact_logs = carrier_rows[comp.fixed_carrier_mask].copy() carrier_rows[comp.fixed_carrier_mask] = 0.0 diff --git a/src/solarlab/solvers/time/backward_euler_2d.py b/src/solarlab/solvers/time/backward_euler_2d.py index fe921283..ce20754b 100644 --- a/src/solarlab/solvers/time/backward_euler_2d.py +++ b/src/solarlab/solvers/time/backward_euler_2d.py @@ -94,7 +94,7 @@ def compute_carrier_only_terminal_current_2d( rows.append(assembler.reaction_flux(sys_eval, block, port_id)) else: dc_prob = DC2DProblem(device, state.voltage_V, generation_scale) - exch, _ = dc_prob._contact_exchange(np.asarray(state.u, dtype=np.float64), ch, nodes) + exch, _ = dc_prob.contact_exchange(np.asarray(state.u, dtype=np.float64), ch, nodes) rows.append(exch) ports.append(np.stack(rows)) return np.sum((-Q * ports[0] + Q * ports[1]) * g.x_widths_m[None, :], axis=1) / g.lateral_length_m @@ -197,7 +197,7 @@ def step_accounting_2d( rows.append(assembler.reaction_flux(sys_new, block, port_id, storage_rate=storage_rate)) else: prob = DC2DProblem(d, current.voltage_V, current.generation_scale) - exch, _ = prob._contact_exchange(np.asarray(u_new, dtype=float), ch, nodes) + exch, _ = prob.contact_exchange(np.asarray(u_new, dtype=float), ch, nodes) rows.append(exch) particle_ports.append(np.stack(rows)) j_cond_ports = np.sum((-Q * particle_ports[0] + Q * particle_ports[1]) * g.x_widths_m[None, :], axis=1) / width diff --git a/src/solarlab/solvers/time/ionic_backward_euler_2d.py b/src/solarlab/solvers/time/ionic_backward_euler_2d.py index e15ff35b..0525d000 100644 --- a/src/solarlab/solvers/time/ionic_backward_euler_2d.py +++ b/src/solarlab/solvers/time/ionic_backward_euler_2d.py @@ -37,7 +37,7 @@ assess_mobile_ion_terminal_2d, positive_ion_fluxes_2d, ) from solarlab.physics.contacts import junction_polarity -from solarlab.solvers.nonlinear.ionic_2d import _poisson_weights_2d +from solarlab.solvers.nonlinear.ionic_2d import poisson_weights_2d from solarlab.solvers.nonlinear.newton import NewtonResult, NewtonSettings, solve_newton from solarlab.solvers.nonlinear.problem import CallableProblem, GateOutcome, ResidualScaling, SolveBudget, StepControl from solarlab.solvers.nonlinear.steady_1d import SteadyOptions @@ -626,7 +626,7 @@ def step_ionic_backward_euler_2d( n_elec = comp.node_count n_ion = device.ion_node_count weights: Vector = np.empty(device.state_size, dtype=float) - weights[:n_elec] = _poisson_weights_2d(device) / c.poisson_tolerance + weights[:n_elec] = poisson_weights_2d(device) / c.poisson_tolerance weights[n_elec:3 * n_elec] = 2.0 * n_elec * Q / ( comp.geometry.lateral_length_m * c.continuity_tolerance_A_m2 ) From 6d0064b200e183bcfe5f4e8a52c73b14514b4ecb Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Fri, 13 Nov 2026 00:43:55 +0800 Subject: [PATCH 10/46] feat(web): close P06-07 and P06-08 workstation handshake, diagnostics, and catalog dispatch [M] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - P06-07: add startup SHA-256 schema/registry handshake verification (`schema-handshake.ts`) across `/configuration-schema` and `/experiments` (`X-Solarlab-Registry`, `X-Solarlab-Job-Schema`, `ETag`, payload digest), rendering an explicit `[role="alert"]` mismatch banner and mounting `ConfigurationWorkstation` across all 5 canonical preparation modes (`device`, `tandem`, `jv`, `spatial`, `sweep`). - P06-07: propagate stable-ID renames and surface dangling-reference, topology-order, duplicate-ID, duplicate-contact-side, and sweep-axis target diagnostics in `device-edits.ts`, `device-editor.ts`, and `sweep.ts`, with lossless round-trip regression coverage for spatial defect profiles, composition grading, n-k optical resources, and 2T tandem stacks. - P06-08: replace frontend `TIER_FLAGS` / `deviceSnapshot.device.mode` post-run physics guessing with backend execution-manifest receipt extraction (`execution-physics.ts`), surfacing `scientific_qualification === false` (`Unqualified · Engineering Preview`) and explicit diagnostic banners/badges for failed sweep/trajectory points, non-identifiable `tau === null` + `non_identifiable_reason`, and unbracketed/invalid `V_oc`. - P06-08: replace hardcoded experiment switch/union dispatch with declarative `EXPERIMENT_CATALOG` + plot renderer catalog and delete unreachable legacy modules (`panels/degradation.ts`, `panes/current-decomp-pane.ts`, `panes/spatial-pane.ts`). --- web/src/editors/device-editor.ts | 12 + web/src/editors/device-edits.ts | 177 +++++ web/src/editors/sweep.ts | 58 +- web/src/job-stream.ts | 20 +- web/src/main.ts | 31 + web/src/panels/configuration-workstation.ts | 264 +++++++ web/src/panels/degradation.ts | 147 ---- web/src/test-helpers/schema-fixture.mjs | 3 +- web/src/types.ts | 44 +- web/src/workstation/execution-physics.ts | 260 +++++++ web/src/workstation/experiment-catalog.ts | 240 +++++++ .../p06-07-handshake-and-editors.test.ts | 656 ++++++++++++++++++ ...8-manifest-diagnostics-and-catalog.test.ts | 547 +++++++++++++++ .../workstation/panes/current-decomp-pane.ts | 102 --- web/src/workstation/panes/dark-jv-pane.ts | 7 +- web/src/workstation/panes/degradation-pane.ts | 21 +- .../panes/dynamic-defect-transient-pane.ts | 7 +- web/src/workstation/panes/el-pane.ts | 7 +- web/src/workstation/panes/eqe-pane.ts | 7 +- web/src/workstation/panes/experiment-pane.ts | 161 +---- web/src/workstation/panes/impedance-pane.ts | 7 +- web/src/workstation/panes/jv-2d-pane.ts | 25 +- web/src/workstation/panes/jv-pane.ts | 26 +- web/src/workstation/panes/main-plot-pane.ts | 323 +++++++-- .../workstation/panes/mott-schottky-pane.ts | 7 +- web/src/workstation/panes/spatial-pane.ts | 101 --- web/src/workstation/panes/suns-voc-pane.ts | 7 +- web/src/workstation/panes/tandem-pane.ts | 103 ++- web/src/workstation/panes/tpv-pane.ts | 24 +- .../workstation/panes/voc-grain-sweep-pane.ts | 34 +- web/src/workstation/panes/voc-t-pane.ts | 7 +- web/src/workstation/schema-handshake.ts | 330 +++++++++ web/src/workstation/shell.ts | 68 +- web/src/workstation/tree.ts | 62 +- web/src/workstation/types.ts | 5 + 35 files changed, 3247 insertions(+), 653 deletions(-) create mode 100644 web/src/panels/configuration-workstation.ts delete mode 100644 web/src/panels/degradation.ts create mode 100644 web/src/workstation/execution-physics.ts create mode 100644 web/src/workstation/experiment-catalog.ts create mode 100644 web/src/workstation/p06-07-handshake-and-editors.test.ts create mode 100644 web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts delete mode 100644 web/src/workstation/panes/current-decomp-pane.ts delete mode 100644 web/src/workstation/panes/spatial-pane.ts create mode 100644 web/src/workstation/schema-handshake.ts diff --git a/web/src/editors/device-editor.ts b/web/src/editors/device-editor.ts index 996b7a4f..4fe95b16 100644 --- a/web/src/editors/device-editor.ts +++ b/web/src/editors/device-editor.ts @@ -287,10 +287,22 @@ export function mountDeviceEditor(root: HTMLElement, options: DeviceEditorOption const device = cellInput(draft, selection.cell) const items: HTMLElement[] = [] const ids = device.layers.map(layer => layer.id) + const materials = device.materials ?? [] + for (const [index, material] of materials.entries()) { + if (materials.filter(item => item.id === material.id).length > 1) { + items.push(element('li', `materials[${index}].id: duplicate ${material.id}`)) + } + } for (const collection of ['interfaces', 'contacts'] as const) { const records = device[collection] ?? [] for (const [index, record] of records.entries()) if (records.filter(item => item.id === record.id).length > 1) items.push(element('li', `${collection}[${index}].id: duplicate ${record.id}`)) } + const contacts = device.contacts ?? [] + for (const [index, contact] of contacts.entries()) { + if (contacts.filter(item => item.side === contact.side).length > 1) { + items.push(element('li', `contacts[${index}].side: duplicate ${contact.side} contact`)) + } + } for (const [index, layer] of device.layers.entries()) { if (ids.filter(id => id === layer.id).length > 1) items.push(element('li', `layers[${index}].id: duplicate ${layer.id}`)) if (layer.material != null && !(device.materials ?? []).some(material => material.id === layer.material)) items.push(element('li', `layers[${index}].material: ${layer.material} is not a supplied material`)) diff --git a/web/src/editors/device-edits.ts b/web/src/editors/device-edits.ts index ec8873d3..294cd626 100644 --- a/web/src/editors/device-edits.ts +++ b/web/src/editors/device-edits.ts @@ -348,3 +348,180 @@ export function exactInputEqual(a: unknown, b: unknown): boolean { return keys.length === other.length && keys.every((key, index) => key === other[index] && exactInputEqual(Reflect.get(a, key), Reflect.get(b, key))) } + +export interface ReferenceDiagnostic { + readonly path: Path + readonly code: 'duplicate_id' | 'dangling_reference' | 'topology_order' | 'duplicate_contact_side' + readonly message: string +} + +function collectCellReferenceDiagnostics(device: DeviceInput, prefix: Path): ReferenceDiagnostic[] { + const diagnostics: ReferenceDiagnostic[] = [] + const layerIds = device.layers.map(layer => layer.id) + const materialIds = (device.materials ?? []).map(material => material.id) + + for (const [index, material] of (device.materials ?? []).entries()) { + if (materialIds.filter(id => id === material.id).length > 1) { + diagnostics.push({ + path: [...prefix, 'materials', index, 'id'], + code: 'duplicate_id', + message: `materials[${index}].id: duplicate ${material.id}`, + }) + } + } + + for (const collection of ['interfaces', 'contacts'] as const) { + const records = device[collection] ?? [] + for (const [index, record] of records.entries()) { + if (records.filter(item => item.id === record.id).length > 1) { + diagnostics.push({ + path: [...prefix, collection, index, 'id'], + code: 'duplicate_id', + message: `${collection}[${index}].id: duplicate ${record.id}`, + }) + } + } + } + + const contacts = device.contacts ?? [] + for (const [index, contact] of contacts.entries()) { + if (contacts.filter(item => item.side === contact.side).length > 1) { + diagnostics.push({ + path: [...prefix, 'contacts', index, 'side'], + code: 'duplicate_contact_side', + message: `contacts[${index}].side: duplicate ${contact.side} contact`, + }) + } + } + + for (const [index, layer] of device.layers.entries()) { + if (layerIds.filter(id => id === layer.id).length > 1) { + diagnostics.push({ + path: [...prefix, 'layers', index, 'id'], + code: 'duplicate_id', + message: `layers[${index}].id: duplicate ${layer.id}`, + }) + } + if (layer.material != null && !materialIds.includes(layer.material)) { + diagnostics.push({ + path: [...prefix, 'layers', index, 'material'], + code: 'dangling_reference', + message: `layers[${index}].material: ${layer.material} is not a supplied material`, + }) + } + const defects = layer.bulk_defects ?? [] + for (const [offset, defect] of defects.entries()) { + if (defects.filter(item => item.id === defect.id).length > 1) { + diagnostics.push({ + path: [...prefix, 'layers', index, 'bulk_defects', offset, 'id'], + code: 'duplicate_id', + message: `layers[${index}].bulk_defects[${offset}].id: duplicate ${defect.id}`, + }) + } + } + const metastable = layer.metastable_document?.metastable_defects ?? [] + for (const [offset, defect] of metastable.entries()) { + if (metastable.filter(item => item.id === defect.id).length > 1) { + diagnostics.push({ + path: [...prefix, 'layers', index, 'metastable_document', 'metastable_defects', offset, 'id'], + code: 'duplicate_id', + message: `layers[${index}].metastable_document.metastable_defects[${offset}].id: duplicate ${defect.id}`, + }) + } + } + for (const [offset, metadata] of (layer.scaps_defect_metadata ?? []).entries()) { + if (!defects.some(defect => defect.id === metadata.defect_id)) { + diagnostics.push({ + path: [...prefix, 'layers', index, 'scaps_defect_metadata', offset, 'defect_id'], + code: 'dangling_reference', + message: `layers[${index}].scaps_defect_metadata[${offset}].defect_id: ${metadata.defect_id} is not a supplied defect`, + }) + } + } + } + + for (const ref of layerReferences(device)) { + if (!layerIds.includes(ref.value)) { + diagnostics.push({ + path: [...prefix, ...ref.path], + code: 'dangling_reference', + message: `${JSON.stringify(ref.path)}: ${ref.value} is not a supplied layer`, + }) + } + } + + for (const [index, grain] of (device.grain_boundaries ?? []).entries()) { + if (device.grain_boundaries!.filter(item => item.id === grain.id).length > 1) { + diagnostics.push({ + path: [...prefix, 'grain_boundaries', index, 'id'], + code: 'duplicate_id', + message: `Duplicate ID ${grain.id}`, + }) + } + for (const [offset, id] of grain.layer_ids.entries()) { + if ( + !device.layers.some(layer => layer.id === id && layer.role !== 'substrate') || + grain.layer_ids.filter(value => value === id).length > 1 + ) { + diagnostics.push({ + path: [...prefix, 'grain_boundaries', index, 'layer_ids', offset], + code: 'dangling_reference', + message: `${id} must reference one existing electrical layer without duplicates`, + }) + } + } + } + + for (const [index, row] of (device.electrical_grid ?? []).entries()) { + if ( + !device.layers.some(layer => layer.id === row.layer && layer.role !== 'substrate') || + device.electrical_grid!.filter(item => item.layer === row.layer).length > 1 + ) { + diagnostics.push({ + path: [...prefix, 'electrical_grid', index, 'layer'], + code: 'dangling_reference', + message: `${row.layer} must reference one existing electrical layer exactly once`, + }) + } + } + + for (const [index, item] of (device.interfaces ?? []).entries()) { + if (layerIds.indexOf(item.left) < 0 || layerIds[layerIds.indexOf(item.left) + 1] !== item.right) { + diagnostics.push({ + path: [...prefix, 'interfaces', index], + code: 'topology_order', + message: `interfaces[${index}]: ${item.left} → ${item.right} is not a directed adjacent pair in this order`, + }) + } + } + + return diagnostics +} + +/** Collect all stable-ID duplicate, dangling-reference, and adjacency diagnostics + * across single-junction or 2T tandem preparation inputs without mutating them. */ +export function collectReferenceDiagnostics(input: EditorInput, cell?: Cell): ReferenceDiagnostic[] { + if (input.schema_version === 'solarlab.device-preparation.v1') { + return collectCellReferenceDiagnostics(input, []) + } + const diagnostics: ReferenceDiagnostic[] = [] + const cells: readonly ('top_cell' | 'bottom_cell')[] = + cell === 'top_cell' || cell === 'bottom_cell' ? [cell] : ['top_cell', 'bottom_cell'] + for (const targetCell of cells) { + diagnostics.push(...collectCellReferenceDiagnostics(input[targetCell], [targetCell])) + } + const opticalRows = [ + ...input.junction_stack.map((value, index) => ({ value, path: ['junction_stack', index] as Path })), + ...(input.back_reflector ? [{ value: input.back_reflector, path: ['back_reflector'] as Path }] : []), + ] + for (const row of opticalRows) { + if (opticalRows.filter(item => item.value.id === row.value.id).length > 1) { + diagnostics.push({ + path: [...row.path, 'id'], + code: 'duplicate_id', + message: `Duplicate optical-layer ID ${row.value.id}`, + }) + } + } + return diagnostics +} diff --git a/web/src/editors/sweep.ts b/web/src/editors/sweep.ts index 3dad8e83..737aa246 100644 --- a/web/src/editors/sweep.ts +++ b/web/src/editors/sweep.ts @@ -54,6 +54,56 @@ export function sweepTargets(base: Base): TargetChoice[] { return choices } +export function collectSweepReferenceDiagnostics( + input: SweepInput, +): { path: Path; message: string }[] { + const choices = sweepTargets(input.base) + const device = + input.base.schema_version === 'solarlab.device-preparation.v1' + ? input.base + : input.base.device + const diagnostics: { path: Path; message: string }[] = [] + + for (const [index, axis] of input.axes.entries()) { + if (axis.id && input.axes.filter(other => other.id === axis.id).length > 1) { + diagnostics.push({ + path: ['axes', index, 'id'], + message: `axes[${index}].id: duplicate ${axis.id}`, + }) + } + if (!axis.target || !Object.keys(axis.target).length) continue + const matchesTarget = choices.some(choice => exactInputEqual(choice.target, axis.target)) + if (!matchesTarget) { + diagnostics.push({ + path: ['axes', index, 'target'], + message: `axes[${index}].target: dangling target ${JSON.stringify(axis.target)} does not match any supplied parameter instance`, + }) + continue + } + if ( + (axis.target.family === 'layer_parameter' || + axis.target.family === 'bulk_defect' || + axis.target.family === 'cbo') && + device.layers.filter(item => item.id === axis.target.owner_id).length > 1 + ) { + diagnostics.push({ + path: ['axes', index, 'target', 'owner_id'], + message: `axes[${index}].target.owner_id: ambiguous duplicate layer ID ${axis.target.owner_id}`, + }) + } + if ( + axis.target.family === 'cbo' && + device.layers.filter(item => item.id === axis.target.reference_id).length > 1 + ) { + diagnostics.push({ + path: ['axes', index, 'target', 'reference_id'], + message: `axes[${index}].target.reference_id: ambiguous duplicate layer ID ${axis.target.reference_id}`, + }) + } + } + return diagnostics +} + export interface SweepDraft { input: SweepInput; dirty: boolean; incomplete: Path[] } export interface SweepEditor { read(): SweepDraft; setInput(input: SweepInput): void; apply(): boolean; discard(): void; dispose(): void } @@ -62,13 +112,14 @@ export function mountSweepEditor(root: HTMLElement, options: { input: SweepInput let axisIndex = 0, coordinateIndex = 0, lastApplied: SweepInput | undefined const pending = new Map }>(), controls: { dispose(): void }[] = [] const card = node('section'); card.className = 'card'; card.dataset.panel = 'sweep-editor'; card.style.minWidth = '0'; card.style.overflowWrap = 'anywhere' - const status = node('p'), fields = node('div'), navigation = node('select'), actions = node('div'), baseDetails = node('details'), baseHost = node('div') + const status = node('p'), referenceNotices = node('ul'), fields = node('div'), navigation = node('select'), actions = node('div'), baseDetails = node('details'), baseHost = node('div') status.setAttribute('role', 'status'); status.dataset.role = 'sweep-draft-status'; actions.className = 'toolbar' + referenceNotices.dataset.role = 'sweep-reference-notices' navigation.setAttribute('aria-label', 'Sweep axis'); navigation.dataset.role = 'sweep-axis' baseDetails.append(node('summary', 'Base device and J–V input'), baseHost) const applyButton = button('Apply sweep to preview', 'apply-sweep', () => { apply() }), discardButton = button('Discard sweep changes', 'discard-sweep', discard) actions.append(applyButton, discardButton) - card.append(node('h3', 'Serial sweep preparation'), node('p', 'Declare one or two axes and inspect each prepared point. No numerical scan, point reuse or execution qualification is performed.'), status, actions, baseDetails, navigation, fields) + card.append(node('h3', 'Serial sweep preparation'), node('p', 'Declare one or two axes and inspect each prepared point. No numerical scan, point reuse or execution qualification is performed.'), status, referenceNotices, actions, baseDetails, navigation, fields) root.replaceChildren(card) let child: { read(): { input: Base; incomplete: Path[] }; dispose(): void } function mountBase() { @@ -86,6 +137,9 @@ export function mountSweepEditor(root: HTMLElement, options: { input: SweepInput function updateStatus() { if (disposed) return const value = read(), applied = !!lastApplied && exactInputEqual(value.input, lastApplied) + const sweepDiagnostics = collectSweepReferenceDiagnostics(value.input) + referenceNotices.replaceChildren(...sweepDiagnostics.map(item => node('li', item.message))) + referenceNotices.hidden = sweepDiagnostics.length === 0 for (const [index, option] of [...navigation.options].entries()) option.textContent = `${index + 1}: ${draft.axes[index]?.id || 'Unnamed axis'}` const coordinateSelect = fields.querySelector('[data-role=sweep-coordinate]') if (coordinateSelect) for (const [index, option] of [...coordinateSelect.options].entries()) option.textContent = coordinateLabel(index) diff --git a/web/src/job-stream.ts b/web/src/job-stream.ts index e55f871c..e1156e26 100644 --- a/web/src/job-stream.ts +++ b/web/src/job-stream.ts @@ -1,24 +1,8 @@ -import type { JobStartResponse, JobStreamHandlers, ProgressEvent } from './types' +import type { DispatchableJobKind, JobStartResponse, JobStreamHandlers, ProgressEvent } from './types' import { BASE } from './api' export async function startJob( - kind: - | 'jv' - | 'impedance' - | 'dynamic_defect_transient' - | 'degradation' - | 'tpv' - | 'current_decomp' - | 'spatial' - | 'tandem' - | 'dark_jv' - | 'suns_voc' - | 'voc_t' - | 'eqe' - | 'el' - | 'mott_schottky' - | 'jv_2d' - | 'voc_grain_sweep', + kind: DispatchableJobKind, device: unknown, params: Record, configPath: string | null = null, diff --git a/web/src/main.ts b/web/src/main.ts index 8482ae37..8fbc2fef 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -67,6 +67,7 @@ async function mount() { } else if (query.get('view') === 'steady-jv') { const { mountSteadyJVPanel } = await import('./panels/steady-jv') app.innerHTML = `

SolarLab

Steady DC research

+ Configuration · V2 DTO 2D steady Transient · new core Ionic transient @@ -77,6 +78,36 @@ async function mount() { const panel = mountSteadyJVPanel(host, new URL('/steady-service/', location.origin)) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready + } else if (query.get('view') === 'configuration') { + const { mountConfigurationWorkstation } = await import('./panels/configuration-workstation') + app.innerHTML = `

SolarLab

V2 Configuration & Sweep Preparation

+ Steady J–V + 2D steady + Transient · new core + Ionic transient + Ionic J–V + Workspace / legacy experiments
` + const host = app.querySelector('#configuration-v2')! + host.style.cssText = 'max-width:1440px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' + const panel = mountConfigurationWorkstation(host, new URL('/steady-service/', location.origin)) + window.addEventListener('pagehide', () => panel.dispose(), { once: true }) + await panel.ready + } else if (query.get('view') === 'stored-run' && query.get('storeId') && query.get('runId') && query.get('attemptId')) { + const { mountStoredRunPanel } = await import('./panels/stored-run') + app.innerHTML = `

SolarLab

Stored Run Inspector

+ Configuration · V2 DTO + Steady J–V + Workspace / legacy experiments
` + const host = app.querySelector('#stored-run')! + host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' + const panel = mountStoredRunPanel(host, { + endpoint: new URL('/steady-service/', location.origin), + storeId: query.get('storeId')!, + runId: query.get('runId')!, + attemptId: query.get('attemptId')!, + }) + window.addEventListener('pagehide', () => panel.dispose(), { once: true }) + await panel.ready } else { const { mountWorkstation } = await import('./workstation/shell') await mountWorkstation(app) diff --git a/web/src/panels/configuration-workstation.ts b/web/src/panels/configuration-workstation.ts new file mode 100644 index 00000000..b0ba1b0f --- /dev/null +++ b/web/src/panels/configuration-workstation.ts @@ -0,0 +1,264 @@ +/** + * V2 Configuration Preparation & Lossless DTO Editor Surface (P06-07). + * + * Connects the generated schema digest handshake (`verifyWorkstationHandshake`) + * with the stable-ID lossless editors (`mountDeviceEditor`, `mountJVExperimentEditor`, + * `mountSpatialExperimentEditor`, `mountSweepEditor`) and `mountConfigurationPreviewPanel`. + */ +import type { + DeviceInput, + JVExperimentInput, + SpatialExperimentInput, + SweepInput, + TandemInput, +} from '../generated/configuration-inputs' +import { mountDeviceEditor } from '../editors/device-editor' +import { mountJVExperimentEditor } from '../editors/jv-experiment' +import { mountSpatialExperimentEditor } from '../editors/spatial-experiment' +import { mountSweepEditor } from '../editors/sweep' +import { mountConfigurationPreviewPanel, type ConfigurationPreviewPanel } from './configuration-preview' +import { + renderHandshakeBanner, + verifyWorkstationHandshake, + type WorkstationHandshakeOptions, + type WorkstationHandshakeResult, +} from '../workstation/schema-handshake' + +export type ConfigurationEditorMode = 'device' | 'tandem' | 'jv' | 'spatial' | 'sweep' + +export interface ConfigurationWorkstationHandle { + readonly ready: Promise + selectMode(mode: ConfigurationEditorMode): void + dispose(): void +} + +function defaultDeviceInput(id = 'device-v2'): DeviceInput { + return { + schema_version: 'solarlab.device-preparation.v1', + id, + source_format: 'canonical', + layers: [ + { id: 'htl', name: 'HTL', role: 'HTL', thickness: '40 nm' }, + { id: 'absorber', name: 'Absorber', role: 'absorber', thickness: '500 nm' }, + { id: 'etl', name: 'ETL', role: 'ETL', thickness: '30 nm' }, + ], + interfaces: [ + { id: 'htl_absorber', left: 'htl', right: 'absorber' }, + { id: 'absorber_etl', left: 'absorber', right: 'etl' }, + ], + contacts: [ + { id: 'front_contact', side: 'left', layer: 'htl' }, + { id: 'back_contact', side: 'right', layer: 'etl' }, + ], + } +} + +function defaultTandemInput(): TandemInput { + return { + schema_version: 'solarlab.tandem-preparation.v1', + id: 'tandem-v2', + source_schema_version: 1, + device_type: 'tandem_2T_monolithic', + top_cell: defaultDeviceInput('top-cell'), + bottom_cell: defaultDeviceInput('bottom-cell'), + top_cell_reference: 'top_cell.yaml', + bottom_cell_reference: 'bottom_cell.yaml', + junction_model: 'ideal_ohmic', + light_direction: 'top_first', + junction_stack: [ + { + id: 'recombination_ito', + name: 'Recombination ITO', + thickness: '20 nm', + optical_material: 'ITO', + incoherent: false, + }, + ], + benchmark: null, + back_reflector: null, + } +} + +function defaultJVExperimentInput(): JVExperimentInput { + return { + schema_version: 'solarlab.experiment-preparation.v1', + id: 'jv-v2', + device: defaultDeviceInput('jv-device'), + experiment: { kind: 'jv' }, + } +} + +function defaultSpatialExperimentInput(): SpatialExperimentInput { + return { + schema_version: 'solarlab.experiment-preparation.v1', + id: 'spatial-v2', + device: defaultDeviceInput('spatial-device'), + experiment: { kind: 'jv_2d' }, + } +} + +function defaultSweepInput(): SweepInput { + return { + schema_version: 'solarlab.sweep-preparation.v1', + id: 'sweep-v2', + base: defaultDeviceInput('sweep-device'), + axes: [ + { + id: 'absorber_mobility', + target: { family: 'layer_parameter', owner_id: 'absorber', parameter: ['mu_n'] }, + coordinates: [{ kind: 'omit' }], + }, + ], + } +} + +export function mountConfigurationWorkstation( + root: HTMLElement, + serviceBase: URL, + handshakeOptions?: WorkstationHandshakeOptions, +): ConfigurationWorkstationHandle { + let disposed = false + let activeEditor: { dispose(): void } | null = null + let previewPanel: ConfigurationPreviewPanel | null = null + + const bannerHost = document.createElement('div') + bannerHost.dataset.role = 'configuration-handshake-host' + + const toolbar = document.createElement('div') + toolbar.className = 'toolbar' + toolbar.style.marginBottom = '12px' + const modeLabel = document.createElement('label') + modeLabel.textContent = 'Preparation document ' + const modeSelect = document.createElement('select') + modeSelect.dataset.role = 'configuration-mode' + modeSelect.setAttribute('aria-label', 'Preparation document') + for (const [value, label] of [ + ['device', 'Single-junction device (DeviceInput)'], + ['tandem', '2T monolithic tandem (TandemInput)'], + ['jv', '1D J–V experiment (JVExperimentInput)'], + ['spatial', '2D spatial experiment (SpatialExperimentInput)'], + ['sweep', 'Serial parameter sweep (SweepInput)'], + ] as const) { + modeSelect.add(new Option(label, value)) + } + modeLabel.appendChild(modeSelect) + toolbar.appendChild(modeLabel) + + const layout = document.createElement('div') + layout.style.cssText = 'display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px;align-items:start;' + const editorHost = document.createElement('div') + editorHost.dataset.role = 'configuration-editor-host' + const previewHost = document.createElement('div') + previewHost.dataset.role = 'configuration-preview-host' + layout.append(editorHost, previewHost) + + root.replaceChildren(bannerHost, toolbar, layout) + + let handshakeBlocked = false + + function previewEndpoint(path: string): URL { + return new URL(path, serviceBase) + } + + function showPreview( + selection: Parameters[0], + ): void { + if (disposed || handshakeBlocked) return + if (!previewPanel) { + previewPanel = mountConfigurationPreviewPanel(previewHost, selection) + } else { + void previewPanel.select(selection) + } + } + + function selectMode(mode: ConfigurationEditorMode): void { + if (disposed) return + modeSelect.value = mode + activeEditor?.dispose() + activeEditor = null + editorHost.replaceChildren() + + if (mode === 'device') { + activeEditor = mountDeviceEditor(editorHost, { + input: defaultDeviceInput(), + onApply: input => + showPreview({ + endpoint: previewEndpoint('configuration/preview/device'), + kind: 'device', + input: input as DeviceInput, + }), + }) + } else if (mode === 'tandem') { + activeEditor = mountDeviceEditor(editorHost, { + input: defaultTandemInput(), + onApply: input => + showPreview({ + endpoint: previewEndpoint('configuration/preview/tandem'), + kind: 'tandem', + input: input as TandemInput, + }), + }) + } else if (mode === 'jv') { + activeEditor = mountJVExperimentEditor(editorHost, { + input: defaultJVExperimentInput(), + onApply: input => + showPreview({ + endpoint: previewEndpoint('configuration/preview/experiment'), + kind: 'experiment', + input, + }), + }) + } else if (mode === 'spatial') { + activeEditor = mountSpatialExperimentEditor(editorHost, { + input: defaultSpatialExperimentInput(), + onApply: input => + showPreview({ + endpoint: previewEndpoint('configuration/preview/experiment'), + kind: 'experiment', + input, + }), + }) + } else { + activeEditor = mountSweepEditor(editorHost, { + input: defaultSweepInput(), + onApply: input => + showPreview({ + endpoint: previewEndpoint('configuration/preview/sweep'), + kind: 'sweep', + input, + }), + }) + } + } + + modeSelect.addEventListener('change', () => { + selectMode(modeSelect.value as ConfigurationEditorMode) + }) + + selectMode('device') + + const ready = verifyWorkstationHandshake( + handshakeOptions ?? { + schemaEndpoint: new URL('configuration-schema', serviceBase), + experimentsEndpoint: new URL('experiments', serviceBase), + }, + ).then(result => { + if (!disposed) { + handshakeBlocked = result.status === 'mismatch' || result.status === 'error' + renderHandshakeBanner(bannerHost, result) + } + return result + }) + + return { + ready, + selectMode, + dispose() { + if (disposed) return + disposed = true + activeEditor?.dispose() + previewPanel?.dispose() + root.replaceChildren() + }, + } +} diff --git a/web/src/panels/degradation.ts b/web/src/panels/degradation.ts deleted file mode 100644 index 9e481f97..00000000 --- a/web/src/panels/degradation.ts +++ /dev/null @@ -1,147 +0,0 @@ -import Plotly from 'plotly.js-basic-dist-min' -import { mountDevicePanel } from '../device-panel' -import { startJob, streamJobEvents } from '../job-stream' -import { createProgressBar, type ProgressBarHandle } from '../progress' -import { baseLayout, plotConfig, PALETTE, LINE, MARKER, axisTitle } from '../plot-theme' -import { setStatus, numField, readNum } from '../ui-helpers' -import type { DegResult } from '../types' - -export async function mountDegradationPanel(root: HTMLElement): Promise { - root.innerHTML = ` -
-
-

Degradation Parameters

-
- ${numField('deg-N', 'Ngrid', 40, '1')} - ${numField('deg-Vbias', 'Vbias (V)', 0.9, '0.01')} - ${numField('deg-tend', 'tend (s)', 100, 'any')} - ${numField('deg-nsnap', 'N snapshots', 10, '1')} -
-
- - -
-
-
-
` - - const devicePanel = await mountDevicePanel( - root.querySelector('#deg-device')!, - 'deg', - ) - - const progressEl = root.querySelector('#progress-deg')! - const progressBar: ProgressBarHandle = createProgressBar(progressEl) - - const btn = root.querySelector('#btn-deg')! - btn.addEventListener('click', async () => { - btn.disabled = true - progressBar.reset() - progressBar.busy() - setStatus('status-deg', 'Starting job…') - try { - const device = devicePanel.getConfig() - const params = { - N_grid: Math.max(3, Math.round(readNum('deg-N', 40))), - V_bias: readNum('deg-Vbias', 0.9), - t_end: readNum('deg-tend', 100), - n_snapshots: Math.max(2, Math.round(readNum('deg-nsnap', 10))), - } - const jobId = await startJob('degradation', device, params) - setStatus('status-deg', 'Running degradation simulation…') - - streamJobEvents(jobId, { - onProgress: (ev) => progressBar.update(ev), - onResult: (result) => { - renderDegResults(root.querySelector('#results-deg')!, result) - progressBar.done() - setStatus('status-deg', 'Done') - }, - onError: (msg) => { - progressBar.error(msg) - setStatus('status-deg', `Error: ${msg}`, true) - }, - onDone: () => { - btn.disabled = false - }, - }) - } catch (e) { - progressBar.error((e as Error).message) - setStatus('status-deg', `Error: ${(e as Error).message}`, true) - btn.disabled = false - } - }) -} - -function renderDegResults(container: HTMLElement, r: DegResult): void { - container.innerHTML = ` -
-
-

PCE vs Time

-
-
-
-

Voc & Jsc vs Time

-
-
-
` - - const pce_pct = r.PCE.map(p => p * 100) - const basePce = baseLayout() - - Plotly.newPlot( - 'plot-pce', - [{ - x: r.times, y: pce_pct, - mode: 'lines+markers', - line: { color: PALETTE.primary, width: LINE.width }, - marker: { ...MARKER, color: PALETTE.primary }, - hovertemplate: 't = %{x:.2e} s
PCE = %{y:.2f} %', - }], - baseLayout({ - xaxis: { ...(basePce.xaxis as object), title: axisTitle('Time, t (s)'), type: 'log' }, - yaxis: { ...(basePce.yaxis as object), title: axisTitle('Power conversion efficiency, PCE (%)') }, - showlegend: false, - }), - plotConfig('pce_degradation'), - ) - - const jsc_mA = r.J_sc.map(j => j / 10) - const baseVJ = baseLayout() - - Plotly.newPlot( - 'plot-voc-jsc', - [ - { - x: r.times, y: r.V_oc, name: 'Voc', - mode: 'lines+markers', - line: { color: PALETTE.primary, width: LINE.width }, - marker: { ...MARKER, color: PALETTE.primary }, - yaxis: 'y', - hovertemplate: 't = %{x:.2e} s
V_OC = %{y:.3f} V', - }, - { - x: r.times, y: jsc_mA, name: 'Jsc', - mode: 'lines+markers', - line: { color: PALETTE.reverse, width: LINE.width, dash: 'dash' }, - marker: { ...MARKER, color: PALETTE.reverse, symbol: 'square' }, - yaxis: 'y2', - hovertemplate: 't = %{x:.2e} s
J_SC = %{y:.2f} mA/cm²', - }, - ], - baseLayout({ - xaxis: { ...(baseVJ.xaxis as object), title: axisTitle('Time, t (s)'), type: 'log' }, - yaxis: { ...(baseVJ.yaxis as object), title: axisTitle('Open-circuit voltage, VOC (V)') }, - yaxis2: { - ...(baseVJ.yaxis as object), - title: axisTitle('Short-circuit current, JSC (mA·cm⁻²)'), - overlaying: 'y', - side: 'right', - showgrid: false, - }, - legend: { x: 0.02, y: 0.05, xanchor: 'left', yanchor: 'bottom', ...(baseVJ.legend as object) }, - margin: { t: 30, r: 70, b: 60, l: 70 }, - }), - plotConfig('voc_jsc_degradation'), - ) -} diff --git a/web/src/test-helpers/schema-fixture.mjs b/web/src/test-helpers/schema-fixture.mjs index 1d180398..d8304d54 100644 --- a/web/src/test-helpers/schema-fixture.mjs +++ b/web/src/test-helpers/schema-fixture.mjs @@ -1,5 +1,6 @@ import { execFileSync } from 'node:child_process'; import { webcrypto } from 'node:crypto'; +import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; export { webcrypto }; @@ -8,7 +9,7 @@ export { webcrypto }; export function configurationSchemaBytes() { // Real Python DTO metadata supplies the bytes; JSON.stringify in JavaScript // cannot reproduce Python's numeric JSON spelling in general. - const root = fileURLToPath(new URL('../../../', import.meta.url)); + const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); const code = [ 'from pathlib import Path', 'import sys', diff --git a/web/src/types.ts b/web/src/types.ts index 4efc2d06..dca1c382 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -328,6 +328,17 @@ export interface JVWaveformEvidence { inventory_relative_drift?: number[] } +export interface SweepFailurePoint { + index?: number + label?: string + bias_V?: number + voltage_V?: number + time_s?: number + grain_size_nm?: number + branch?: string + reason?: string +} + export interface JVResult extends JVWaveformEvidence { V_fwd: number[] J_fwd: number[] @@ -338,6 +349,8 @@ export interface JVResult extends JVWaveformEvidence { hysteresis_index: number bulk_defect_evidence?: JVBulkDefectEvidence | null interface_charge_evidence?: InterfaceChargeJVEvidence | null + failed_points?: SweepFailurePoint[] | null + converged?: boolean[] | null } export interface InterfaceChargeJVSolverControls { @@ -877,6 +890,8 @@ export interface DegResult { PCE: number[] V_oc: number[] J_sc: number[] + valid?: boolean[] | null + failed_points?: SweepFailurePoint[] | null } export interface TPVResult { @@ -886,6 +901,7 @@ export interface TPVResult { V_oc: number tau: number | null delta_V0: number + non_identifiable_reason?: string | null V_reference?: number[] | null delta_V?: number[] | null valid?: boolean[] | null @@ -896,6 +912,7 @@ export interface TPVResult { tau_s: number | null amplitude_V: number status: string + non_identifiable_reason?: string | null points: number r_squared: number | null normalized_max_error: number | null @@ -1064,6 +1081,8 @@ export interface JV2DResult { * case. ``J_sc`` is in A/m² (same convention as the J array; the * backend has already sign-normalised to J_sc>0). */ metrics?: JVMetrics + failed_points?: SweepFailurePoint[] | null + converged?: boolean[] | null } /** V_oc(L_g) sweep result — Stage-B headline experiment. @@ -1073,6 +1092,8 @@ export interface VocGrainSweepResult { V_oc_V: number[] J_sc_Am2: number[] FF: number[] + voc_bracketed?: boolean[] | null + failed_points?: SweepFailurePoint[] | null } export interface JVParams { @@ -1207,6 +1228,8 @@ export interface TandemJVMetrics { J_sc: number FF: number PCE: number + voc_bracketed?: boolean + open_circuit_voltage_V?: number | null } /** Mirrors the JSON response from POST /api/tandem. @@ -1220,4 +1243,23 @@ export interface TandemJVPayload { benchmark: TandemBenchmark | null top_layers?: TandemJunctionLayer[] bot_layers?: TandemJunctionLayer[] -} + failed_points?: SweepFailurePoint[] | null +} + +export type DispatchableJobKind = + | 'jv' + | 'impedance' + | 'dynamic_defect_transient' + | 'degradation' + | 'tpv' + | 'current_decomp' + | 'spatial' + | 'tandem' + | 'dark_jv' + | 'suns_voc' + | 'voc_t' + | 'eqe' + | 'el' + | 'mott_schottky' + | 'jv_2d' + | 'voc_grain_sweep' diff --git a/web/src/workstation/execution-physics.ts b/web/src/workstation/execution-physics.ts new file mode 100644 index 00000000..37c714c8 --- /dev/null +++ b/web/src/workstation/execution-physics.ts @@ -0,0 +1,260 @@ +/** + * Authoritative post-run physics & qualification extractor (P06-08). + * + * Post-run badges and result headers read ONLY what the backend actually + * executed (`execution.worker_result`, `execution_manifest`, `effective_physics`, + * `active_physics`, and `scientific_qualification`) — never frontend `TIER_FLAGS` + * or `deviceSnapshot.device.mode` guesses. + */ + +export interface ExecutionPhysicsReceipt { + readonly source: 'execution_manifest' | 'worker_result' | 'backend_receipt' | 'unavailable' + readonly engine?: string + readonly driver?: string + readonly manifestSha256?: string + readonly executionSha256?: string + readonly scientificQualification: boolean | null + readonly effectiveModels?: Readonly> + readonly badgeLabel: string + readonly summary: string +} + +export interface QualificationBadgeInfo { + readonly qualified: boolean + readonly explicitUnqualified: boolean + readonly label: string + readonly detail: string +} + +const ENVELOPE_KEYS = new Set([ + 'active_physics', + 'execution', + 'execution_manifest', + 'effective_physics', + 'scientific_qualification', + 'artifacts', + 'run_id', + 'attempt_id', +]) + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +function asNonEmptyString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined +} + +function parseEffectiveModels(raw: unknown): Readonly> | undefined { + if (Array.isArray(raw)) { + const entries = raw + .map((item, idx) => { + if (typeof item === 'string' && item.trim()) return [`model_${idx + 1}`, item.trim()] as const + if (isRecord(item) && typeof item.family === 'string' && typeof item.model_id === 'string') { + return [item.family, item.model_id] as const + } + return null + }) + .filter((entry): entry is readonly [string, string] => entry !== null) + return entries.length > 0 ? Object.freeze(Object.fromEntries(entries)) : undefined + } + if (isRecord(raw)) { + const entries: Array<[string, string]> = [] + for (const [key, val] of Object.entries(raw)) { + if (val === null || val === undefined) continue + if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') { + entries.push([key, String(val)]) + } else if (Array.isArray(val)) { + entries.push([key, val.map(String).join(', ')]) + } else if (isRecord(val) && typeof val.model_id === 'string') { + entries.push([key, val.model_id]) + } + } + return entries.length > 0 ? Object.freeze(Object.fromEntries(entries)) : undefined + } + return undefined +} + +export function extractExecutionPhysics( + rawResult: T, +): { receipt: ExecutionPhysicsReceipt; pure: T } { + const record: Record = isRecord(rawResult) ? rawResult : {} + const pureCopy: Record = {} + for (const [key, value] of Object.entries(record)) { + if (!ENVELOPE_KEYS.has(key)) { + pureCopy[key] = value + } + } + + const executionObj = isRecord(record.execution) ? record.execution : undefined + const workerResult = isRecord(executionObj?.worker_result) + ? executionObj.worker_result + : executionObj + const manifestObj = isRecord(record.execution_manifest) + ? record.execution_manifest + : isRecord(workerResult?.execution_manifest) + ? workerResult.execution_manifest + : undefined + + const effectiveRaw = + record.effective_physics ?? + manifestObj?.effective_physics ?? + manifestObj?.selected_models ?? + workerResult?.effective_physics + const effectiveModels = parseEffectiveModels(effectiveRaw) + const effectiveText = typeof effectiveRaw === 'string' ? asNonEmptyString(effectiveRaw) : undefined + + const engine = + asNonEmptyString(manifestObj?.engine) ?? + asNonEmptyString(workerResult?.engine) + const driver = + asNonEmptyString(manifestObj?.driver) ?? + asNonEmptyString(workerResult?.driver) + const manifestSha256 = + asNonEmptyString(manifestObj?.manifest_sha256) ?? + asNonEmptyString(workerResult?.manifest_sha256) + const executionSha256 = + asNonEmptyString(manifestObj?.execution_sha256) ?? + asNonEmptyString(manifestObj?.H_execution) ?? + asNonEmptyString(workerResult?.H_execution) ?? + asNonEmptyString(workerResult?.execution_sha256) + + const rawQual = + typeof record.scientific_qualification === 'boolean' + ? record.scientific_qualification + : typeof manifestObj?.scientific_qualification === 'boolean' + ? manifestObj.scientific_qualification + : typeof workerResult?.scientific_qualification === 'boolean' + ? workerResult.scientific_qualification + : engine === 'legacy' + ? false + : null + + const activePhysicsText = + asNonEmptyString(record.active_physics) ?? + asNonEmptyString(workerResult?.active_physics) ?? + effectiveText + + const engineDriverLabel = [engine?.toUpperCase(), driver].filter(Boolean).join(' · ') + const digestSuffix = manifestSha256 + ? ` · manifest:${manifestSha256.slice(0, 12)}…` + : executionSha256 + ? ` · exec:${executionSha256.slice(0, 12)}…` + : '' + + if (manifestObj || effectiveModels) { + const modelsText = effectiveModels + ? Object.entries(effectiveModels) + .map(([k, v]) => `${k}=${v}`) + .join(', ') + : activePhysicsText ?? 'declared execution manifest' + const prefix = engineDriverLabel ? `Execution manifest (${engineDriverLabel})` : 'Execution manifest' + return { + pure: pureCopy as T, + receipt: Object.freeze({ + source: 'execution_manifest', + engine, + driver, + manifestSha256, + executionSha256, + scientificQualification: rawQual, + effectiveModels, + badgeLabel: engineDriverLabel || 'MANIFEST', + summary: `${prefix}: ${modelsText}${digestSuffix}`, + }), + } + } + + if (workerResult && (engine || driver || manifestSha256 || executionSha256 || rawQual !== null)) { + const baseText = activePhysicsText ?? `Executed via ${engineDriverLabel || 'worker'}` + return { + pure: pureCopy as T, + receipt: Object.freeze({ + source: 'worker_result', + engine, + driver, + manifestSha256, + executionSha256, + scientificQualification: rawQual, + badgeLabel: engineDriverLabel || 'WORKER', + summary: `${baseText}${digestSuffix}`, + }), + } + } + + if (activePhysicsText) { + return { + pure: pureCopy as T, + receipt: Object.freeze({ + source: 'backend_receipt', + scientificQualification: rawQual, + badgeLabel: 'BACKEND RECEIPT', + summary: activePhysicsText, + }), + } + } + + return { + pure: pureCopy as T, + receipt: Object.freeze({ + source: 'unavailable', + scientificQualification: rawQual, + badgeLabel: 'UNVERIFIED', + summary: 'Execution manifest not recorded on run payload', + }), + } +} + +export function resolveRunExecutionPhysics(run: { + readonly activePhysics: string + readonly executionPhysics?: ExecutionPhysicsReceipt + readonly scientificQualification?: boolean | null +}): ExecutionPhysicsReceipt { + if (run.executionPhysics) return run.executionPhysics + const qual = + typeof run.scientificQualification === 'boolean' ? run.scientificQualification : null + const text = asNonEmptyString(run.activePhysics) + if (text && text !== 'unknown') { + return Object.freeze({ + source: 'backend_receipt', + scientificQualification: qual, + badgeLabel: 'BACKEND RECEIPT', + summary: text, + }) + } + return Object.freeze({ + source: 'unavailable', + scientificQualification: qual, + badgeLabel: 'UNVERIFIED', + summary: 'Execution manifest not recorded on run payload', + }) +} + +export function formatQualificationBadge( + receipt: ExecutionPhysicsReceipt, +): QualificationBadgeInfo { + if (receipt.scientificQualification === false) { + return { + qualified: false, + explicitUnqualified: true, + label: 'Unqualified · Engineering Preview', + detail: + 'scientific_qualification=false — compatibility or engineering preview execution only; not qualified for scientific signoff.', + } + } + if (receipt.scientificQualification === true) { + return { + qualified: true, + explicitUnqualified: false, + label: 'Scientifically Qualified', + detail: 'Execution manifest carries scientific_qualification=true.', + } + } + return { + qualified: false, + explicitUnqualified: false, + label: 'Unverified Qualification', + detail: + 'Run payload did not carry an explicit scientific_qualification boolean; do not treat as scientific signoff.', + } +} diff --git a/web/src/workstation/experiment-catalog.ts b/web/src/workstation/experiment-catalog.ts new file mode 100644 index 00000000..7424f5c1 --- /dev/null +++ b/web/src/workstation/experiment-catalog.ts @@ -0,0 +1,240 @@ +/** + * Declarative experiment capability & surface catalog (P06-08). + * + * Replaces ad-hoc `switch (kind)` / `if/elif` chains across `tree.ts`, + * `experiment-pane.ts`, and `main-plot-pane.ts`, while providing safe + * fallback rendering for newly registered backend capabilities that do + * not define a bespoke form or plot renderer. + */ +import type { DeviceConfig } from '../types' +import type { ExperimentKind, Run } from './types' +import { mountJVPane } from './panes/jv-pane' +import { mountImpedancePane } from './panes/impedance-pane' +import { mountDynamicDefectTransientPane } from './panes/dynamic-defect-transient-pane' +import { mountDegradationPane } from './panes/degradation-pane' +import { mountTPVPane } from './panes/tpv-pane' +import { mountDarkJVPane } from './panes/dark-jv-pane' +import { mountSunsVocPane } from './panes/suns-voc-pane' +import { mountVocTPane } from './panes/voc-t-pane' +import { mountEQEPane } from './panes/eqe-pane' +import { mountELPane } from './panes/el-pane' +import { mountMottSchottkyPane } from './panes/mott-schottky-pane' +import { mountJV2DPane } from './panes/jv-2d-pane' +import { mountVocGrainSweepPane } from './panes/voc-grain-sweep-pane' + +export interface SharedExperimentPaneOptions { + readonly getActiveDevice: () => { id: string; config: DeviceConfig } | null + readonly onRunComplete: (deviceId: string, run: Run) => void +} + +export interface MountedExperimentForm { + updateDevice(resetDefaults?: boolean): void +} + +export type ExperimentCategory = + | 'Illuminated J\u2013V' + | 'Dark characterisation' + | 'Spectral' + | 'Transient' + | '2D / Microstructure' + +export interface ExperimentDescriptor { + readonly kind: ExperimentKind + readonly category: ExperimentCategory + /** Short HTML label used in the workspace tree (static source constant only). */ + readonly treeLabelHTML: string + /** Full HTML label used in the experiment dropdown (static source constant only). */ + readonly selectorLabelHTML: string + /** Exported renderer symbol in `main-plot-pane.ts` (matches Python ExperimentRegistry). */ + readonly rendererSymbol: string + /** Present when this experiment appears as a standalone dropdown entry. */ + readonly mountForm?: ( + container: HTMLElement, + opts: SharedExperimentPaneOptions, + ) => MountedExperimentForm | void + /** Present when selecting this kind delegates to a parent form with preset toggles. */ + readonly delegateToKind?: ExperimentKind + readonly applyFormPreset?: (formHost: HTMLElement) => void +} + +function setJVOutputPreset( + formHost: HTMLElement, + mode: 'jv' | 'current_decomp' | 'spatial', +): void { + const solver = formHost.querySelector('#jvp-solver') + if (solver && (mode === 'current_decomp' || mode === 'spatial')) { + solver.value = 'transient' + solver.dispatchEvent(new Event('change', { bubbles: true })) + } + const decomp = formHost.querySelector('#jvp-decomp') + const spatial = formHost.querySelector('#jvp-spatial') + if (decomp) decomp.checked = mode === 'current_decomp' + if (spatial) spatial.checked = mode === 'spatial' +} + +export const EXPERIMENT_CATALOG: readonly ExperimentDescriptor[] = Object.freeze([ + { + kind: 'jv', + category: 'Illuminated J\u2013V', + treeLabelHTML: 'J\u2013V Sweep', + selectorLabelHTML: 'J\u2013V Sweep', + rendererSymbol: 'renderJV', + mountForm: (el, opts) => mountJVPane(el, opts), + applyFormPreset: el => setJVOutputPreset(el, 'jv'), + }, + { + kind: 'current_decomp', + category: 'Illuminated J\u2013V', + treeLabelHTML: 'Current Decomp.', + selectorLabelHTML: 'Current Decomposition', + rendererSymbol: 'renderCurrentDecomp', + delegateToKind: 'jv', + applyFormPreset: el => setJVOutputPreset(el, 'current_decomp'), + }, + { + kind: 'spatial', + category: 'Illuminated J\u2013V', + treeLabelHTML: 'Spatial Profiles', + selectorLabelHTML: 'Spatial Profiles', + rendererSymbol: 'renderSpatialProfiles', + delegateToKind: 'jv', + applyFormPreset: el => setJVOutputPreset(el, 'spatial'), + }, + { + kind: 'suns_voc', + category: 'Illuminated J\u2013V', + treeLabelHTML: 'Suns\u2013Voc', + selectorLabelHTML: 'Suns\u2013Voc', + rendererSymbol: 'renderSunsVoc', + mountForm: (el, opts) => mountSunsVocPane(el, opts), + }, + { + kind: 'voc_t', + category: 'Illuminated J\u2013V', + treeLabelHTML: 'Voc(T)', + selectorLabelHTML: 'Voc(T)', + rendererSymbol: 'renderVocT', + mountForm: (el, opts) => mountVocTPane(el, opts), + }, + { + kind: 'dark_jv', + category: 'Dark characterisation', + treeLabelHTML: 'Dark J\u2013V', + selectorLabelHTML: 'Dark J\u2013V', + rendererSymbol: 'renderDarkJV', + mountForm: (el, opts) => mountDarkJVPane(el, opts), + }, + { + kind: 'mott_schottky', + category: 'Dark characterisation', + treeLabelHTML: 'Mott\u2013Schottky (C\u2013V)', + selectorLabelHTML: 'Mott\u2013Schottky (C\u2013V)', + rendererSymbol: 'renderMottSchottky', + mountForm: (el, opts) => mountMottSchottkyPane(el, opts), + }, + { + kind: 'eqe', + category: 'Spectral', + treeLabelHTML: 'EQE / IPCE', + selectorLabelHTML: 'EQE / IPCE', + rendererSymbol: 'renderEQE', + mountForm: (el, opts) => mountEQEPane(el, opts), + }, + { + kind: 'el', + category: 'Spectral', + treeLabelHTML: 'EL / \u0394Vnr', + selectorLabelHTML: 'EL / \u0394Vnr', + rendererSymbol: 'renderEL', + mountForm: (el, opts) => mountELPane(el, opts), + }, + { + kind: 'impedance', + category: 'Transient', + treeLabelHTML: 'Impedance', + selectorLabelHTML: 'Impedance', + rendererSymbol: 'renderImpedance', + mountForm: (el, opts) => mountImpedancePane(el, opts), + }, + { + kind: 'dynamic_defect_transient', + category: 'Transient', + treeLabelHTML: 'Defect\u2013Ion Transient', + selectorLabelHTML: 'Defect\u2013Ion Transient', + rendererSymbol: 'renderDynamicDefectTransient', + mountForm: (el, opts) => mountDynamicDefectTransientPane(el, opts), + }, + { + kind: 'tpv', + category: 'Transient', + treeLabelHTML: 'TPV', + selectorLabelHTML: 'Transient Photovoltage (TPV)', + rendererSymbol: 'renderTPV', + mountForm: (el, opts) => mountTPVPane(el, opts), + }, + { + kind: 'degradation', + category: 'Transient', + treeLabelHTML: 'Degradation', + selectorLabelHTML: 'Degradation', + rendererSymbol: 'renderDegradation', + mountForm: (el, opts) => mountDegradationPane(el, opts), + }, + { + kind: 'jv_2d', + category: '2D / Microstructure', + treeLabelHTML: 'J\u2013V Sweep (2D)', + selectorLabelHTML: 'J\u2013V Sweep (2D)', + rendererSymbol: 'renderJV2D', + mountForm: (el, opts) => mountJV2DPane(el, opts), + }, + { + kind: 'voc_grain_sweep', + category: '2D / Microstructure', + treeLabelHTML: 'Voc(Lg) Grain Sweep', + selectorLabelHTML: 'Voc(Lg) Grain Sweep', + rendererSymbol: 'renderVocGrainSweep', + mountForm: (el, opts) => mountVocGrainSweepPane(el, opts), + }, +]) + +export const EXPERIMENT_CATEGORY_ORDER: readonly ExperimentCategory[] = Object.freeze([ + 'Illuminated J\u2013V', + 'Dark characterisation', + 'Spectral', + 'Transient', + '2D / Microstructure', +]) + +const DESCRIPTOR_BY_KIND = new Map( + EXPERIMENT_CATALOG.map(entry => [entry.kind, entry]), +) + +function escapeHtml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +export function getExperimentDescriptor(kind: string): ExperimentDescriptor | undefined { + return DESCRIPTOR_BY_KIND.get(kind) +} + +export function getExperimentTreeLabelHTML(kind: string): string { + return DESCRIPTOR_BY_KIND.get(kind)?.treeLabelHTML ?? escapeHtml(kind) +} + +export function getSelectableExperimentGroups(): ReadonlyArray<{ + readonly label: ExperimentCategory + readonly entries: readonly ExperimentDescriptor[] +}> { + return EXPERIMENT_CATEGORY_ORDER.map(category => ({ + label: category, + entries: EXPERIMENT_CATALOG.filter( + entry => entry.category === category && typeof entry.mountForm === 'function', + ), + })).filter(group => group.entries.length > 0) +} diff --git a/web/src/workstation/p06-07-handshake-and-editors.test.ts b/web/src/workstation/p06-07-handshake-and-editors.test.ts new file mode 100644 index 00000000..ca4a0ef5 --- /dev/null +++ b/web/src/workstation/p06-07-handshake-and-editors.test.ts @@ -0,0 +1,656 @@ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { configurationSchemaBytes, webcrypto } from '../test-helpers/schema-fixture.mjs' +import { + configurationSchema, + configurationSchemaSha256, +} from '../generated/configuration-schema' +import type { + DeviceInput, + SweepInput, + TandemInput, +} from '../generated/configuration-inputs' +import { + previewDeviceConfiguration, + previewTandemConfiguration, +} from '../configuration-client' +import { + collectReferenceDiagnostics, + exactInputEqual, + moveLayer, + renameConnection, + renameLayer, + renameMaterial, + writeField, +} from '../editors/device-edits' +import { + changeProfileRows, + removeBulkDefect, + renameDefect, + setDefectSection, + writeDefectField, +} from '../editors/defect-edits' +import { + changeExtendedRows, + setExtendedSection, + writeExtendedField, +} from '../editors/extended-edits' +import { mountDeviceEditor } from '../editors/device-editor' +import { collectSweepReferenceDiagnostics, mountSweepEditor } from '../editors/sweep' +import { mountConfigurationWorkstation } from '../panels/configuration-workstation' +import { + renderHandshakeBanner, + verifyWorkstationHandshake, +} from './schema-handshake' + +let SCHEMA_JSON_BYTES: ArrayBuffer +const DUMMY_HASH_A = 'a'.repeat(64) +const DUMMY_HASH_B = 'b'.repeat(64) +const DUMMY_HASH_C = 'c'.repeat(64) + +async function sha256Hex(text: string): Promise { + const bytes = new TextEncoder().encode(text) + const digest = await webcrypto.subtle.digest('SHA-256', bytes) + return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('') +} + +beforeAll(() => { + SCHEMA_JSON_BYTES = configurationSchemaBytes() +}) + +beforeEach(() => { + vi.stubGlobal('crypto', webcrypto) +}) + +async function buildCatalogResponse(overrides?: { + registryHeader?: string + jobSchemaHeader?: string + etag?: string + bodyJobSchema?: string + status?: number +}): Promise { + const status = overrides?.status ?? 200 + if (status !== 200) { + return new Response(JSON.stringify({ detail: 'mismatch' }), { + status, + headers: { 'Content-Type': 'application/json' }, + }) + } + const jobSchemaSha = overrides?.bodyJobSchema ?? DUMMY_HASH_B + const payload = JSON.stringify({ + schema: 'solarlab.execution-catalog.v1', + job_schema_sha256: jobSchemaSha, + model_registry_sha256: DUMMY_HASH_C, + bindings: [ + { experiment_id: 'jv', solver_family: 'steady_1d' }, + { experiment_id: 'tpv', solver_family: 'transient_1d' }, + ], + }) + const computedDigest = await sha256Hex(payload) + const registryHeader = overrides?.registryHeader ?? computedDigest + const jobSchemaHeader = overrides?.jobSchemaHeader ?? jobSchemaSha + const etag = overrides?.etag ?? `"${registryHeader}"` + return new Response(payload, { + status: 200, + headers: { + 'Content-Type': 'application/json', + 'X-Solarlab-Registry': registryHeader, + 'X-Solarlab-Job-Schema': jobSchemaHeader, + ETag: etag, + }, + }) +} + +afterEach(() => { + vi.unstubAllGlobals() + document.body.replaceChildren() +}) + +describe('P06-07: startup schema/registry digest handshake', () => { + it('verifies matching /configuration-schema and /experiments SHA-256 digests and hides alert banner', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL) => { + const url = String(input) + if (url.includes('configuration-schema')) { + return new Response(SCHEMA_JSON_BYTES, { + status: 200, + headers: { + 'Content-Type': 'application/json', + 'X-Solarlab-Configuration-Schema': configurationSchemaSha256, + }, + }) + } + return buildCatalogResponse() + }), + ) + + const result = await verifyWorkstationHandshake({ + schemaEndpoint: 'http://test.local/configuration-schema', + experimentsEndpoint: 'http://test.local/experiments', + }) + expect(result.status).toBe('verified') + if (result.status === 'verified') { + expect(result.configurationSchemaSha256).toBe(configurationSchemaSha256) + expect(result.metadata.schema_version).toBe(configurationSchema.schema_version) + expect(result.catalog?.bindingsCount).toBe(2) + expect(result.catalog?.bindingIds).toEqual(['jv', 'tpv']) + } + + const bannerHost = document.createElement('div') + renderHandshakeBanner(bannerHost, result) + expect(bannerHost.hidden).toBe(true) + expect(bannerHost.querySelector('[data-test="schema-handshake-alert"]')).toBeNull() + }) + + it('surfaces an explicit [role="alert"] banner when /configuration-schema digest disagrees with client DTOs', async () => { + const tamperedBytes = new TextEncoder().encode( + JSON.stringify({ ...configurationSchema, tampered_extra: true }), + ) + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL) => { + const url = String(input) + if (url.includes('configuration-schema')) { + return new Response(tamperedBytes, { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + } + return buildCatalogResponse() + }), + ) + + const result = await verifyWorkstationHandshake({ + schemaEndpoint: 'http://test.local/configuration-schema', + experimentsEndpoint: 'http://test.local/experiments', + }) + expect(result.status).toBe('mismatch') + if (result.status === 'mismatch') { + expect(result.code).toBe('identity_mismatch') + } + + const bannerHost = document.createElement('div') + renderHandshakeBanner(bannerHost, result) + expect(bannerHost.hidden).toBe(false) + const alert = bannerHost.querySelector('[data-test="schema-handshake-alert"]') + expect(alert).not.toBeNull() + expect(alert?.getAttribute('role')).toBe('alert') + expect(alert?.textContent).toContain('Schema / registry version mismatch') + expect(alert?.textContent).toContain('Silent field dropping or coercion is refused') + }) + + it('surfaces an explicit [role="alert"] banner when /experiments X-Solarlab-Registry or X-Solarlab-Job-Schema mismatches', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL) => { + const url = String(input) + if (url.includes('configuration-schema')) { + return new Response(SCHEMA_JSON_BYTES, { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + } + return buildCatalogResponse({ registryHeader: DUMMY_HASH_A }) + }), + ) + + const result = await verifyWorkstationHandshake({ + schemaEndpoint: 'http://test.local/configuration-schema', + experimentsEndpoint: 'http://test.local/experiments', + }) + expect(result.status).toBe('mismatch') + if (result.status === 'mismatch') { + expect(result.code).toBe('catalog_mismatch') + } + + const bannerHost = document.createElement('div') + renderHandshakeBanner(bannerHost, result) + const alert = bannerHost.querySelector('[data-test="schema-handshake-alert"]') + expect(alert?.getAttribute('role')).toBe('alert') + expect(alert?.textContent).toContain('X-Solarlab-Registry') + }) +}) + +describe('P06-07: stable-ID add/remove/rename/reorder and dangling-reference diagnostics', () => { + function sampleDevice(): DeviceInput { + return { + schema_version: 'solarlab.device-preparation.v1', + id: 'dev-stable', + source_format: 'canonical', + materials: [ + { id: 'mat_pvk', name: 'MAPbI3', parameters: { Eg: '1.6 eV' } }, + ], + layers: [ + { id: 'htl', name: 'HTL', role: 'HTL', thickness: '40 nm' }, + { + id: 'pvk', + name: 'Absorber', + role: 'absorber', + thickness: '500 nm', + material: 'mat_pvk', + bulk_defects: [ + { + id: 'trap_1', + charge_transition: 'acceptor', + neutral_reference: 'empty', + degeneracy: 1, + distribution: { + kind: 'single_level', + normalization: 'integrated_total', + total_density_m3: '1e21 m^-3', + }, + energy_level: { reference: 'below_conduction_band', value_eV: '0.8 eV' }, + kinetics: { + sigma_n_m2: '1e-19 m^2', + sigma_p_m2: '1e-19 m^2', + thermal_velocity_n_m_s: '1e5 m/s', + thermal_velocity_p_m_s: '1e5 m/s', + }, + }, + ], + scaps_defect_metadata: [ + { + defect_id: 'trap_1', + distribution: 'single', + energy_reference: 'below_conduction_band', + trap_depth_eV: '0.8 eV', + }, + ], + }, + { id: 'etl', name: 'ETL', role: 'ETL', thickness: '30 nm' }, + ], + interfaces: [ + { + id: 'if_htl_pvk', + left: 'htl', + right: 'pvk', + defect: { + id: 'if_trap_1', + calibration_factor: 1, + iface_state_calibration_factor: 1, + energy_reference: 'below_conduction_band', + total_density_m2: '1e14 m^-2', + trap_depth_eV: '0.3 eV', + kinetics: { + sigma_n_m2: '1e-19 m^2', + sigma_p_m2: '1e-19 m^2', + thermal_velocity_n_m_s: '1e5 m/s', + thermal_velocity_p_m_s: '1e5 m/s', + }, + partner_metadata: { + defect_id: 'if_trap_1', + distribution: 'single', + energy_reference: 'below_conduction_band', + trap_depth_eV: '0.3 eV', + }, + }, + }, + { id: 'if_pvk_etl', left: 'pvk', right: 'etl' }, + ], + contacts: [ + { id: 'c_left', side: 'left', layer: 'htl' }, + { id: 'c_right', side: 'right', layer: 'etl' }, + ], + grain_boundaries: [ + { + id: 'gb_main', + x_position: '250 nm', + width: '10 nm', + tau_n: '1e-9 s', + tau_p: '1e-9 s', + layer_ids: ['pvk'], + }, + ], + electrical_grid: [ + { layer: 'htl', interval_weight: 1, alpha: 1 }, + { layer: 'pvk', interval_weight: 4, alpha: 1 }, + { layer: 'etl', interval_weight: 1, alpha: 1 }, + ], + } + } + + it('propagates layer, material, interface, contact, and defect renames across typed references cleanly', () => { + let doc = sampleDevice() + expect(collectReferenceDiagnostics(doc)).toEqual([]) + + doc = renameLayer(doc, { cell: 'device', kind: 'layer', id: 'pvk', occurrence: 0 }, 'absorber_main').input + expect(doc.interfaces?.[0].right).toBe('absorber_main') + expect(doc.interfaces?.[1].left).toBe('absorber_main') + expect(doc.grain_boundaries?.[0].layer_ids).toEqual(['absorber_main']) + expect(doc.electrical_grid?.[1].layer).toBe('absorber_main') + expect(collectReferenceDiagnostics(doc)).toEqual([]) + + doc = renameMaterial(doc, { cell: 'device', kind: 'material', id: 'mat_pvk', occurrence: 0 }, 'mat_fapbi3').input + expect(doc.layers[1].material).toBe('mat_fapbi3') + + doc = renameConnection(doc, { cell: 'device', kind: 'interface', id: 'if_htl_pvk', occurrence: 0 }, 'if_front').input + doc = renameConnection(doc, { cell: 'device', kind: 'contact', id: 'c_left', occurrence: 0 }, 'anode').input + expect(doc.interfaces?.[0].id).toBe('if_front') + expect(doc.contacts?.[0].id).toBe('anode') + + doc = renameDefect( + doc, + { + cell: 'device', + kind: 'bulk_defect', + parent: { id: 'absorber_main', occurrence: 0 }, + id: 'trap_1', + occurrence: 0, + }, + 'deep_acceptor', + ).input + expect(doc.layers[1].scaps_defect_metadata?.[0].defect_id).toBe('deep_acceptor') + + doc = renameDefect( + doc, + { + cell: 'device', + kind: 'interface_defect', + parent: { id: 'if_front', occurrence: 0 }, + id: 'if_trap_1', + }, + 'front_recombination_center', + ).input + expect(doc.interfaces?.[0].defect?.partner_metadata?.defect_id).toBe('front_recombination_center') + expect(collectReferenceDiagnostics(doc)).toEqual([]) + }) + + it('detects dangling references, adjacency breakage on layer reorder, duplicate material IDs, duplicate contact sides, and dangling sweep targets', () => { + const base = sampleDevice() + const reordered = moveLayer(base, { cell: 'device', kind: 'layer', id: 'pvk', occurrence: 0 }, 1).input + const reorderDiag = collectReferenceDiagnostics(reordered) + expect(reorderDiag.some(d => d.code === 'topology_order')).toBe(true) + + const removedDefect = removeBulkDefect(base, { + cell: 'device', + kind: 'bulk_defect', + parent: { id: 'pvk', occurrence: 0 }, + id: 'trap_1', + occurrence: 0, + }) + const defectDiag = collectReferenceDiagnostics(removedDefect) + expect( + defectDiag.some( + d => d.code === 'dangling_reference' && d.message.includes('scaps_defect_metadata'), + ), + ).toBe(true) + + const brokenDevice: DeviceInput = { + ...base, + materials: [ + { id: 'dup_mat', name: 'M1', parameters: {} }, + { id: 'dup_mat', name: 'M2', parameters: {} }, + ], + layers: base.layers.map((l, idx) => (idx === 0 ? { ...l, material: 'missing_mat' } : l)), + contacts: [ + { id: 'c1', side: 'left', layer: 'htl' }, + { id: 'c2', side: 'left', layer: 'ghost_layer' }, + ], + } + const brokenDiag = collectReferenceDiagnostics(brokenDevice) + expect(brokenDiag.some(d => d.code === 'duplicate_id' && d.message.includes('dup_mat'))).toBe(true) + expect(brokenDiag.some(d => d.code === 'dangling_reference' && d.message.includes('missing_mat'))).toBe(true) + expect(brokenDiag.some(d => d.code === 'duplicate_contact_side')).toBe(true) + expect(brokenDiag.some(d => d.code === 'dangling_reference' && d.message.includes('ghost_layer'))).toBe(true) + + const editorHost = document.createElement('div') + document.body.appendChild(editorHost) + const editor = mountDeviceEditor(editorHost, { input: brokenDevice, onApply: () => {} }) + const noticesText = editorHost.querySelector('[data-role="reference-notices"]')?.textContent ?? '' + expect(noticesText).toContain('dup_mat') + expect(noticesText).toContain('duplicate left contact') + editor.dispose() + + const sweepInput: SweepInput = { + schema_version: 'solarlab.sweep-preparation.v1', + id: 'sweep-dangling', + base: sampleDevice(), + axes: [ + { + id: 'ax_1', + target: { family: 'layer_parameter', owner_id: 'deleted_layer', parameter: ['mu_n'] }, + coordinates: [{ kind: 'omit' }], + }, + ], + } + expect(collectSweepReferenceDiagnostics(sweepInput)).toHaveLength(1) + const sweepHost = document.createElement('div') + document.body.appendChild(sweepHost) + const sweepEditor = mountSweepEditor(sweepHost, { input: sweepInput, onApply: () => {} }) + const sweepNotice = sweepHost.querySelector('[data-role="sweep-reference-notices"]')?.textContent ?? '' + expect(sweepNotice).toContain('deleted_layer') + sweepEditor.dispose() + }) +}) + +describe('P06-07: lossless round-trip across all 4 special editors (untouched defaults, explicit null, units, -0.0)', () => { + it('round-trips spatial defect profiles, composition grading, n-k optical curves, and 2T tandem stacks without coercing defaults, null, units, or -0.0', async () => { + const capturedBodies: Array<{ url: string; body: string }> = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = String(input) + const body = String(init?.body ?? '') + capturedBodies.push({ url, body }) + const isTandem = url.includes('/tandem') + const kind = isTandem ? 'tandem' : 'device' + const responseJson = + `{"schema":"solarlab.configuration-preview.v1","kind":"${kind}",` + + `"status":"prepared_pending_dependencies","can_execute":false,` + + `"input":${body},` + + `"resolved":{"schema":"solarlab.resolved-${kind}-preparation.v1","id":${JSON.stringify(isTandem ? 'tandem-special' : 'device-special')},"can_execute":false},` + + `"identity":{"scope":"configuration_content","content_sha256":"${DUMMY_HASH_A}","default_catalog_sha256":"${DUMMY_HASH_B}","resource_library_sha256":"${DUMMY_HASH_C}"}}` + return new Response(responseJson, { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + }), + ) + + // 1 + 2 + 3: Spatial defect profile + Composition grading + n-k optical resources on DeviceInput + let device: DeviceInput = { + schema_version: 'solarlab.device-preparation.v1', + id: 'device-special', + source_format: 'canonical', + spectrum: 'AM1.5G', + layers: [ + { + id: 'cigs_abs', + name: 'Graded CIGS', + role: 'absorber', + thickness: '2.0 um', + parameters: { + optical_material: 'CIGS_nk_table', + n_optical: 2.85, + incoherent: false, + Eg: '1.15 eV', + Eg_back: '1.35 eV', + chi: '4.5 eV', + chi_back: '4.3 eV', + grading_profile: 'linear', + }, + cigs_graded_optics: null, + bulk_defects: [ + { + id: 'graded_trap', + charge_transition: 'acceptor', + neutral_reference: 'empty', + degeneracy: 1, + distribution: { + kind: 'gaussian', + normalization: 'integrated_total', + total_density_m3: '2.5e21 m^-3', + center_eV_above_vb: '0.65 eV', + width_eV: '0.05 eV', + width_convention: 'gaussian_standard_deviation', + }, + kinetics: { + sigma_n_m2: '1e-19 m^2', + sigma_p_m2: '5e-20 m^2', + thermal_velocity_n_m_s: '1e5 m/s', + thermal_velocity_p_m_s: '1e5 m/s', + }, + spatial_profile: { + coordinate: 'normalized_layer_coordinate', + density_normalization: 'layer_average_unity', + interpolation: 'piecewise_linear', + knots: [ + { position_fraction: -0.0, density_multiplier: 2.0 }, + { position_fraction: 1.0, density_multiplier: 0.5 }, + ], + }, + }, + ], + }, + ], + } + + // Mutate via the special editor helpers and verify untouched defaults stay omitted + const defectSel = { + cell: 'device' as const, + kind: 'bulk_defect' as const, + parent: { id: 'cigs_abs', occurrence: 0 }, + id: 'graded_trap', + occurrence: 0, + } + device = changeProfileRows(device, defectSel, { + kind: 'append', + knot: { position_fraction: 0.5, density_multiplier: 1.25 }, + }) + device = writeDefectField(device, defectSel, 'spatial_profile', 'interpolation', { + kind: 'value', + value: 'piecewise_linear', + }) + device = setDefectSection(device, defectSel, 'energy_level', 'null') + + // Toggle layer_optics cigs_graded_optics from explicit null -> omitted -> explicit object -> explicit null + const opticsSel = { cell: 'device' as const, kind: 'layer_optics' as const, id: 'cigs_abs', occurrence: 0 } + const omittedOptics = setExtendedSection(device, opticsSel, 'cigs', 'omit') + expect(Object.hasOwn(omittedOptics.layers[0], 'cigs_graded_optics')).toBe(false) + const emptyOptics = setExtendedSection(omittedOptics, opticsSel, 'cigs', 'empty') + const editedOptics = writeExtendedField(emptyOptics, opticsSel, 'cigs', 'ggi_front', { + kind: 'value', + value: -0.0, + }) + expect(Object.is(editedOptics.layers[0].cigs_graded_optics?.ggi_front, -0)).toBe(true) + const restoredNullOptics = setExtendedSection(editedOptics, opticsSel, 'cigs', 'null') + expect(restoredNullOptics.layers[0].cigs_graded_optics).toBeNull() + + // Edit optical curve resource via resources & layer parameters + device = writeExtendedField( + restoredNullOptics, + { cell: 'device', kind: 'resources' }, + 'resources', + 'spectrum', + { kind: 'value', value: 'AM1.5G_tabular_nk' }, + ) + device = writeField( + device, + { cell: 'device', kind: 'layer', id: 'cigs_abs', occurrence: 0 }, + 'Eg_back', + { kind: 'value', value: '1.40 eV' }, + true, + ) + + const devicePreview = await previewDeviceConfiguration( + 'http://test.local/configuration/preview/device', + device, + ) + expect(capturedBodies[0].body).toContain('"position_fraction":-0.0') + expect(capturedBodies[0].body).toContain('"cigs_graded_optics":null') + expect(capturedBodies[0].body).toContain('"energy_level":null') + expect(capturedBodies[0].body).toContain('"Eg_back":"1.40 eV"') + expect(capturedBodies[0].body).toContain('"optical_material":"CIGS_nk_table"') + expect(capturedBodies[0].body).not.toContain('"contacts"') + expect(exactInputEqual(devicePreview.value.input, device)).toBe(true) + + // 4: 2T Tandem stack special editor round-trip + let tandem: TandemInput = { + schema_version: 'solarlab.tandem-preparation.v1', + id: 'tandem-special', + source_schema_version: 1, + device_type: 'tandem_2T_monolithic', + top_cell: { + schema_version: 'solarlab.device-preparation.v1', + id: 'top-pvk', + source_format: 'canonical', + settings: { V_bi: -0.0 }, + layers: [{ id: 'top_abs', name: 'Wide-Eg PVK', role: 'absorber', thickness: '400 nm' }], + }, + bottom_cell: device, + top_cell_reference: 'top.yaml', + bottom_cell_reference: 'bot.yaml', + junction_model: 'ideal_ohmic', + light_direction: 'top_first', + junction_stack: [ + { + id: 'iz_ito', + name: 'ITO Recombination Layer', + thickness: '15 nm', + optical_material: 'ITO_nk', + incoherent: false, + }, + ], + benchmark: null, + back_reflector: null, + } + + const stackSel = { cell: 'top_cell' as const, kind: 'optical_stack' as const } + tandem = changeExtendedRows(tandem, stackSel, 'junction', { kind: 'insert', index: 1 }, 0) + tandem.junction_stack[1].id = 'iz_sn_ox' + tandem = writeExtendedField(tandem, stackSel, 'optical:1', 'thickness', { + kind: 'value', + value: '10 nm', + }) + + const tandemPreview = await previewTandemConfiguration( + 'http://test.local/configuration/preview/tandem', + tandem, + ) + expect(capturedBodies[1].body).toContain('"V_bi":-0.0') + expect(capturedBodies[1].body).toContain('"back_reflector":null') + expect(capturedBodies[1].body).toContain('"benchmark":null') + expect(capturedBodies[1].body).toContain('"optical_material":"ITO_nk"') + expect(exactInputEqual(tandemPreview.value.input, tandem)).toBe(true) + }) + + it('mounts ConfigurationWorkstation across all 5 preparation modes and blocks preview on schema mismatch', async () => { + const previewCalls: string[] = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string | URL) => { + const url = String(input) + if (url.includes('configuration-schema')) { + return new Response(new TextEncoder().encode('{"schema_version":"tampered"}'), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + } + if (url.includes('/experiments')) { + return buildCatalogResponse() + } + previewCalls.push(url) + return new Response('{}', { status: 200 }) + }), + ) + + const root = document.createElement('div') + document.body.appendChild(root) + const ws = mountConfigurationWorkstation(root, new URL('http://test.local/')) + const handshake = await ws.ready + expect(handshake.status).toBe('mismatch') + expect(root.querySelector('[data-test="schema-handshake-alert"]')).not.toBeNull() + + for (const mode of ['tandem', 'jv', 'spatial', 'sweep', 'device'] as const) { + ws.selectMode(mode) + expect( + root.querySelector('[data-role="configuration-mode"]')?.value, + ).toBe(mode) + } + + const applyBtn = root.querySelector('[data-action="apply-device"]') + applyBtn?.click() + expect(previewCalls).toEqual([]) + ws.dispose() + }) +}) diff --git a/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts b/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts new file mode 100644 index 00000000..4aa53d3b --- /dev/null +++ b/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts @@ -0,0 +1,547 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + newPlot: vi.fn(() => Promise.resolve()), + purge: vi.fn(), + resize: vi.fn(() => Promise.resolve()), + startJob: vi.fn(), + streamJobEvents: vi.fn(), + listConfigs: vi.fn(() => Promise.resolve([{ name: 'tandem_lin2019.yaml', device_type: 'tandem_2T' }])), + mountTandemStackVisualizer: vi.fn(() => ({ update: vi.fn(), clear: vi.fn() })), +})) + +vi.mock('plotly.js-basic-dist-min', () => ({ + default: { + newPlot: mocks.newPlot, + purge: mocks.purge, + Plots: { resize: mocks.resize }, + }, +})) + +vi.mock('../job-stream', () => ({ + startJob: mocks.startJob, + streamJobEvents: mocks.streamJobEvents, +})) + +vi.mock('../api', () => ({ + BASE: '', + listConfigs: mocks.listConfigs, +})) + +vi.mock('../stack/tandem-stack-visualizer', () => ({ + mountTandemStackVisualizer: mocks.mountTandemStackVisualizer, +})) + +import { + extractExecutionPhysics, + formatQualificationBadge, + resolveRunExecutionPhysics, +} from './execution-physics' +import { + EXPERIMENT_CATALOG, + getExperimentTreeLabelHTML, + getSelectableExperimentGroups, +} from './experiment-catalog' +import { renderTreeHTML } from './tree' +import { mountExperimentPane } from './panes/experiment-pane' +import { + mountMainPlotPane, + renderDegradation, + renderJV, + renderJV2D, + renderTPV, + renderVocGrainSweep, +} from './panes/main-plot-pane' +import { mountTPVPane } from './panes/tpv-pane' +import { mountJVPane } from './panes/jv-pane' +import { mountJV2DPane } from './panes/jv-2d-pane' +import { mountDegradationPane } from './panes/degradation-pane' +import { mountVocGrainSweepPane } from './panes/voc-grain-sweep-pane' +import { mountTandemPane } from './panes/tandem-pane' +import type { Workspace, Run } from './types' +import type { + DegResult, + DeviceConfig, + JV2DResult, + JVResult, + TandemJVPayload, + TPVResult, + VocGrainSweepResult, +} from '../types' + +const SAMPLE_CONFIG: DeviceConfig = { + device: { V_bi: 1.1, Phi: 1.4e21, mode: 'full' }, + layers: [], +} + +const flushAsync = (): Promise => new Promise(resolve => setTimeout(resolve, 0)) + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(() => { + document.body.replaceChildren() +}) + +describe('P06-08: execution-manifest physics & scientific_qualification badges (no TIER_FLAGS guessing)', () => { + it('extracts backend execution_manifest & scientific_qualification=false and strips envelope keys from pure payload', () => { + const rawPayload = { + V_fwd: [0, 1.0], + J_fwd: [200, -10], + V_rev: [1.0, 0], + J_rev: [-10, 200], + metrics_fwd: { V_oc: 0.95, J_sc: 200, FF: 0.75, PCE: 0.1425, voc_bracketed: true }, + metrics_rev: { V_oc: 0.95, J_sc: 200, FF: 0.75, PCE: 0.1425, voc_bracketed: true }, + hysteresis_index: 0.0, + active_physics: 'legacy compatibility shim', + scientific_qualification: false, + run_id: 'run-99', + attempt_id: 'att-1', + execution: { + worker_result: { + engine: 'legacy', + driver: 'legacy_jv_compat', + scientific_qualification: false, + manifest_sha256: 'd'.repeat(64), + }, + }, + execution_manifest: { + engine: 'legacy', + driver: 'legacy_jv_compat', + manifest_sha256: 'd'.repeat(64), + scientific_qualification: false, + effective_physics: { + transport: 'boltzmann_sg', + recombination: 'bulk_srh_only', + }, + }, + } + + const { pure, receipt } = extractExecutionPhysics(rawPayload) + expect('execution' in pure).toBe(false) + expect('execution_manifest' in pure).toBe(false) + expect('active_physics' in pure).toBe(false) + expect('scientific_qualification' in pure).toBe(false) + expect('run_id' in pure).toBe(false) + expect(pure.V_fwd).toEqual([0, 1.0]) + + expect(receipt.source).toBe('execution_manifest') + expect(receipt.engine).toBe('legacy') + expect(receipt.driver).toBe('legacy_jv_compat') + expect(receipt.scientificQualification).toBe(false) + expect(receipt.badgeLabel).toBe('LEGACY · legacy_jv_compat') + expect(receipt.summary).toContain('transport=boltzmann_sg') + + const qual = formatQualificationBadge(receipt) + expect(qual.qualified).toBe(false) + expect(qual.explicitUnqualified).toBe(true) + expect(qual.label).toBe('Unqualified · Engineering Preview') + }) + + it('renders backend execution_manifest & Unqualified · Engineering Preview in main-plot-pane and tree even when deviceSnapshot.device.mode is "full"', () => { + const rawReceipt = extractExecutionPhysics({ + execution_manifest: { + engine: 'solarlab', + driver: 'metastable_split_preview', + scientific_qualification: false, + manifest_sha256: 'e'.repeat(64), + effective_physics: { defects: 'operator_split_preview' }, + }, + }).receipt + + const run: Run = { + id: 'run-unqual', + timestamp: 1_700_000_000_000, + durationMs: 42, + activePhysics: rawReceipt.summary, + executionPhysics: rawReceipt, + scientificQualification: false, + // Intentionally set deviceSnapshot.device.mode = 'full' to prove post-run UI ignores it! + deviceSnapshot: SAMPLE_CONFIG, + result: { + kind: 'jv', + data: { + V_fwd: [0, 1], + J_fwd: [200, -10], + V_rev: [1, 0], + J_rev: [-10, 200], + metrics_fwd: { V_oc: 0.92, J_sc: 200, FF: 0.72, PCE: 0.132, voc_bracketed: true }, + metrics_rev: { V_oc: 0.92, J_sc: 200, FF: 0.72, PCE: 0.132, voc_bracketed: true }, + hysteresis_index: 0, + }, + }, + } + + const ws: Workspace = { + version: 1, + id: 'ws-1', + name: 'Manifest Test', + layout: null, + activeDeviceId: 'dev-1', + activeExperimentId: 'exp-1', + activeRunId: 'run-unqual', + devices: [ + { + id: 'dev-1', + name: 'Declared Full Stack', + tier: 'full', + config: SAMPLE_CONFIG, + experiments: [{ id: 'exp-1', kind: 'jv', params: {}, runs: [run] }], + }, + ], + } + + const host = document.createElement('div') + document.body.appendChild(host) + const plotHandle = mountMainPlotPane(host) + plotHandle.update(ws) + + const header = host.querySelector('#mpp-header')! + expect(header.textContent).not.toContain('FULL ·') + expect( + host.querySelector('[data-test="run-manifest-badge"]')?.textContent, + ).toBe('SOLARLAB · metastable_split_preview') + const qualBadge = host.querySelector('[data-test="run-qualification-badge"]')! + expect(qualBadge.textContent).toBe('Unqualified · Engineering Preview') + expect(qualBadge.getAttribute('data-qualified')).toBe('false') + + const treeHtml = renderTreeHTML(ws) + expect(treeHtml).toContain('data-test="tree-run-qualification"') + expect(treeHtml).toContain('PREVIEW') + plotHandle.dispose() + + const fallbackReceipt = resolveRunExecutionPhysics({ + activePhysics: 'unknown', + scientificQualification: true, + }) + expect(formatQualificationBadge(fallbackReceipt).label).toBe('Scientifically Qualified') + }) +}) + +describe('P06-08: explicit diagnostic states for failed points, non-identifiable tau, and invalid V_oc', () => { + it('surfaces tau === null + non_identifiable_reason in renderTPV and mountTPVPane', async () => { + const tpvPayload: TPVResult = { + t: [0, 1e-6, 2e-6, 3e-6], + V: [1.05, 1.0501, 1.05009, 1.05009], + J: [0, 0, 0, 0], + delta_V: [0, 1e-4, 9e-5, 9e-5], + tau: null, + V_oc: 1.05, + delta_V0: 1e-4, + non_identifiable_reason: 'plateau_unresolved_ion_drift', + fit: { + tau_s: null, + amplitude_V: 1e-4, + status: 'insufficient_decay_window', + non_identifiable_reason: 'plateau_unresolved_ion_drift', + points: 4, + r_squared: null, + normalized_max_error: null, + }, + } + + const plotHost = document.createElement('div') + renderTPV(plotHost, tpvPayload) + const tpvWarn = plotHost.querySelector('[data-test="tpv-diagnostic-warning"]') + expect(tpvWarn).not.toBeNull() + expect(tpvWarn?.getAttribute('role')).toBe('alert') + expect(tpvWarn?.textContent).toContain('Lifetime τ is non-identifiable') + expect(tpvWarn?.textContent).toContain('plateau_unresolved_ion_drift') + + const capturedRuns: Run[] = [] + mocks.startJob.mockResolvedValueOnce('job-tpv-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult({ + ...tpvPayload, + scientific_qualification: false, + execution_manifest: { engine: 'solarlab', driver: 'tpv_1d', scientific_qualification: false }, + }) + handlers.onDone?.() + }) + + const paneHost = document.createElement('div') + document.body.appendChild(paneHost) + mountTPVPane(paneHost, { + getActiveDevice: () => ({ id: 'd1', config: SAMPLE_CONFIG }), + onRunComplete: (_id, run) => { + capturedRuns.push(run) + }, + }) + paneHost.querySelector('#btn-tpv')!.click() + await flushAsync() + + expect(paneHost.querySelector('#status-tpv')?.textContent).toContain( + 'τ non-identifiable (plateau_unresolved_ion_drift)', + ) + expect(capturedRuns[0]?.scientificQualification).toBe(false) + }) + + it('surfaces unbracketed V_oc and failed sweep points in 1D J-V, 2D J-V, Tandem, Degradation, and V_oc(L_g)', async () => { + // 1. 1D J-V + const jvBad: JVResult = { + V_fwd: [0, 0.4, 0.8], + J_fwd: [210, 195, 80], + V_rev: [0.8, 0.4, 0], + J_rev: [85, 196, 210], + metrics_fwd: { V_oc: 0, J_sc: 210, FF: 0, PCE: 0, voc_bracketed: false }, + metrics_rev: { V_oc: 0, J_sc: 210, FF: 0, PCE: 0, voc_bracketed: false }, + hysteresis_index: 0, + failed_points: [{ index: 3, bias_V: 1.0, reason: 'Newton step stalled' }], + } + const jvPlot = document.createElement('div') + renderJV(jvPlot, jvBad) + const jvWarn = jvPlot.querySelector('[data-test="jv-diagnostic-warning"]') + expect(jvWarn?.getAttribute('role')).toBe('alert') + expect(jvWarn?.textContent).toContain('Forward sweep V_oc not bracketed') + expect(jvWarn?.textContent).toContain('Newton step stalled') + + mocks.startJob.mockResolvedValueOnce('job-jv-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult(jvBad) + handlers.onDone?.() + }) + const jvPane = document.createElement('div') + document.body.appendChild(jvPane) + mountJVPane(jvPane, { + getActiveDevice: () => ({ id: 'd1', config: SAMPLE_CONFIG }), + onRunComplete: () => {}, + }) + jvPane.querySelector('#btn-jvp')!.click() + await flushAsync() + expect(jvPane.querySelector('#status-jvp')?.textContent).toContain('fwd V_oc not bracketed') + expect(jvPane.querySelector('#status-jvp')?.textContent).toContain('1 failed point(s)') + + // 2. 2D J-V + const jv2dBad: JV2DResult = { + V: [0, 0.5], + J: [-200, -120], + grid_x: [0, 500], + grid_y: [0, 250, 500], + lateral_bc: 'neumann', + snapshots: [], + metrics: { V_oc: 0, J_sc: 200, FF: 0, PCE: 0, voc_bracketed: false }, + failed_points: [{ index: 2, bias_V: 1.0, reason: '2D GMRES breakdown' }], + } + const jv2dPlot = document.createElement('div') + renderJV2D(jv2dPlot, jv2dBad) + expect( + jv2dPlot.querySelector('[data-test="jv2d-voc-not-bracketed"]')?.getAttribute('role'), + ).toBe('alert') + expect( + jv2dPlot.querySelector('[data-test="jv2d-failed-points-warning"]')?.textContent, + ).toContain('2D GMRES breakdown') + + mocks.startJob.mockResolvedValueOnce('job-jv2d-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult({ + ...jv2dBad, + execution_manifest: { + engine: 'solarlab', + driver: 'jv_2d_fvm', + scientific_qualification: true, + effective_physics: { poisson: '2d_anisotropic' }, + }, + }) + handlers.onDone?.() + }) + const jv2dPane = document.createElement('div') + document.body.appendChild(jv2dPane) + mountJV2DPane(jv2dPane, { + getActiveDevice: () => ({ id: 'd1', config: SAMPLE_CONFIG }), + onRunComplete: () => {}, + }) + jv2dPane.querySelector('#btn-jv2d')!.click() + await flushAsync() + expect(jv2dPane.querySelector('#status-jv2d')?.textContent).toContain('V_oc not bracketed') + expect(jv2dPane.querySelector('#jv2d-active-physics')?.textContent).toContain( + 'poisson=2d_anisotropic', + ) + + // 3. Tandem J-V + const tandemBad: TandemJVPayload = { + V: [0, 1.0], + J: [190, 80], + V_top: [0, 0.5], + V_bot: [0, 0.5], + metrics: { + V_oc: 0, + open_circuit_voltage_V: null, + voc_bracketed: false, + J_sc: 190, + FF: 0, + PCE: 0, + }, + benchmark: null, + failed_points: [{ index: 2, label: 'J_match=0', reason: 'subcell bracket miss' }], + } + mocks.startJob.mockResolvedValueOnce('job-tandem-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult({ + ...tandemBad, + scientific_qualification: false, + execution_manifest: { + engine: 'solarlab', + driver: 'tandem_2t_series', + scientific_qualification: false, + }, + }) + handlers.onDone?.() + }) + const tandemPane = document.createElement('div') + document.body.appendChild(tandemPane) + mountTandemPane(tandemPane) + await flushAsync() + tandemPane.querySelector('#btn-tandem')!.click() + await flushAsync() + + expect( + tandemPane.querySelector('[data-test="tandem-qualification-badge"]')?.textContent, + ).toBe('Unqualified · Engineering Preview') + const tandemWarn = tandemPane.querySelector('[data-test="tandem-diagnostic-warning"]') + expect(tandemWarn?.getAttribute('role')).toBe('alert') + expect(tandemWarn?.textContent).toContain('Tandem V_oc not bracketed') + expect(tandemWarn?.textContent).toContain('subcell bracket miss') + expect(tandemPane.querySelector('.tandem-metrics-pre')?.textContent).toContain( + 'V_oc = unavailable (not bracketed)', + ) + + // 4. Degradation + const pceRaw = [0.18, 0.16, Number.NaN] + const degBad: DegResult = { + times: [0, 50, 100], + PCE: [...pceRaw], + V_oc: [1.08, 1.05, Number.NaN], + J_sc: [210, 208, 200], + valid: [true, true, false], + failed_points: [{ index: 2, label: 't=100 s', reason: 'J-V probe failed' }], + } + const degPlot = document.createElement('div') + renderDegradation(degPlot, degBad) + expect(degBad.PCE).toEqual(pceRaw) + expect( + degPlot.querySelector('[data-test="degradation-diagnostic-warning"]')?.textContent, + ).toContain('J-V probe failed') + + mocks.startJob.mockResolvedValueOnce('job-deg-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult(degBad) + handlers.onDone?.() + }) + const degPane = document.createElement('div') + document.body.appendChild(degPane) + mountDegradationPane(degPane, { + getActiveDevice: () => ({ id: 'd1', config: SAMPLE_CONFIG }), + onRunComplete: () => {}, + }) + degPane.querySelector('#btn-deg')!.click() + await flushAsync() + expect(degPane.querySelector('#status-deg')?.textContent).toContain( + 'failed/invalid trajectory step(s)', + ) + + // 5. V_oc(L_g) grain sweep + const vgsBad: VocGrainSweepResult = { + grain_sizes_nm: [200, 500, 1000], + V_oc_V: [0.98, 0, 1.06], + voc_bracketed: [true, false, true], + J_sc_Am2: [205, 206, 208], + FF: [0.74, 0, 0.79], + failed_points: [{ index: 1, label: 'L_g=500 nm', reason: 'V_oc above V_max' }], + } + const vgsPlot = document.createElement('div') + renderVocGrainSweep(vgsPlot, vgsBad) + const vgsWarn = vgsPlot.querySelector('[data-test="voc-grain-sweep-diagnostic-warning"]') + expect(vgsWarn?.getAttribute('role')).toBe('alert') + expect(vgsWarn?.textContent).toContain('L_g=500 nm') + expect(vgsWarn?.textContent).toContain('V_oc above V_max') + + mocks.startJob.mockResolvedValueOnce('job-vgs-1') + mocks.streamJobEvents.mockImplementationOnce((_jobId, handlers) => { + handlers.onResult(vgsBad) + handlers.onDone?.() + }) + const vgsPane = document.createElement('div') + document.body.appendChild(vgsPane) + mountVocGrainSweepPane(vgsPane, { + getActiveDevice: () => ({ id: 'd1', config: SAMPLE_CONFIG }), + onRunComplete: () => {}, + }) + vgsPane.querySelector('#btn-vgs')!.click() + await flushAsync() + expect(vgsPane.querySelector('#status-vgs')?.textContent).toContain('980.0–1060.0 mV') + expect(vgsPane.querySelector('#status-vgs')?.textContent).toContain( + '1 failed/unbracketed point(s)', + ) + }) +}) + +describe('P06-08: registry/descriptor catalog dispatch and unknown-capability fallback', () => { + it('renders selectable experiment groups from EXPERIMENT_CATALOG and falls back gracefully on newly registered backend capabilities', () => { + expect(Object.keys(EXPERIMENT_CATALOG)).toHaveLength(15) + const groups = getSelectableExperimentGroups() + expect(groups.flatMap(g => g.entries).some(i => i.kind === 'current_decomp')).toBe(false) + expect(groups.flatMap(g => g.entries).some(i => i.kind === 'spatial')).toBe(false) + expect(getExperimentTreeLabelHTML('celiv_future_v2')).toBe('celiv_future_v2') + + const futureExpWs: Workspace = { + version: 1, + id: 'ws-future', + name: 'Future Capability', + layout: null, + activeDeviceId: 'dev-1', + activeExperimentId: 'exp-future', + activeRunId: 'run-future', + devices: [ + { + id: 'dev-1', + name: 'Device', + tier: 'full', + config: SAMPLE_CONFIG, + experiments: [ + { + id: 'exp-future', + kind: 'celiv_future_v2' as unknown as Workspace['devices'][number]['experiments'][number]['kind'], + params: {}, + runs: [ + { + id: 'run-future', + timestamp: 0, + durationMs: 10, + activePhysics: 'SOLARLAB · celiv_1d', + scientificQualification: true, + deviceSnapshot: SAMPLE_CONFIG, + result: { + kind: 'celiv_future_v2', + data: { peak_current_A_m2: 42.5 }, + } as unknown as Run['result'], + }, + ], + }, + ], + }, + ], + } + + const expHost = document.createElement('div') + const expHandle = mountExperimentPane(expHost, { + getActiveDevice: () => ({ id: 'dev-1', config: SAMPLE_CONFIG }), + onRunComplete: () => {}, + }) + expHandle.selectExperiment( + 'celiv_future_v2' as unknown as Workspace['devices'][number]['experiments'][number]['kind'], + ) + expect( + expHost.querySelector('[data-test="experiment-capability-fallback"]')?.textContent, + ).toContain('celiv_future_v2') + + const plotHost = document.createElement('div') + document.body.appendChild(plotHost) + const plotHandle = mountMainPlotPane(plotHost) + plotHandle.update(futureExpWs) + expect( + plotHost.querySelector('[data-test="plot-capability-fallback"]')?.textContent, + ).toContain('42.5') + plotHandle.dispose() + }) +}) diff --git a/web/src/workstation/panes/current-decomp-pane.ts b/web/src/workstation/panes/current-decomp-pane.ts deleted file mode 100644 index 0bb8b0ba..00000000 --- a/web/src/workstation/panes/current-decomp-pane.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { startJob, streamJobEvents } from '../../job-stream' -import { createProgressBar, type ProgressBarHandle } from '../../progress' -import { setStatus, numField, readNum, checkField, readCheck } from '../../ui-helpers' -import type { DeviceConfig, CurrentDecompResult } from '../../types' -import type { Run, RunResult } from '../types' - -export interface CurrentDecompPaneOptions { - getActiveDevice: () => { id: string; config: DeviceConfig } | null - onRunComplete: (deviceId: string, run: Run) => void -} - -export function mountCurrentDecompPane(container: HTMLElement, opts: CurrentDecompPaneOptions): void { - container.innerHTML = ` -
-

Current Decomposition

-

- Decomposes the terminal current into electron (Jn), - hole (Jp), ionic (Jion), and displacement - (Jdisp) components across a J–V sweep. -

-
- ${numField('cd-N', 'Ngrid', 60, '1')} - ${numField('cd-np', 'V sample points', 30, '1')} - ${numField('cd-rate', 'Scan rate (V/s)', 1.0, 'any')} - ${numField('cd-vmax', 'Vmax (V)', 1.1, '0.01')} - ${checkField('cd-dark', 'Dark (no illumination)', false)} -
-
- - -
-
-
Results stream into the Main Plot pane.
-
` - - const progressBar: ProgressBarHandle = createProgressBar( - container.querySelector('#progress-cd')!, - ) - const btn = container.querySelector('#btn-cd')! - - btn.addEventListener('click', () => { - const active = opts.getActiveDevice() - if (!active) { - setStatus('status-cd', 'No active device. Select one in the tree.', true) - return - } - btn.disabled = true - progressBar.reset() - progressBar.busy() - setStatus('status-cd', 'Starting job…') - - const isDark = readCheck('cd-dark', false) - const params = { - N_grid: Math.max(3, Math.round(readNum('cd-N', 60))), - n_points: Math.max(2, Math.round(readNum('cd-np', 30))), - v_rate: readNum('cd-rate', 1.0), - V_max: readNum('cd-vmax', 1.4), - illuminated: !isDark, - } - const t0 = performance.now() - const snapshot: DeviceConfig = JSON.parse(JSON.stringify(active.config)) - - startJob('current_decomp', active.config, params) - .then(jobId => { - setStatus('status-cd', 'Running current decomposition…') - streamJobEvents(jobId, { - onProgress: (ev) => progressBar.update(ev), - onResult: (result) => { - const { active_physics, ...pure } = result as CurrentDecompResult & { active_physics?: string } - const runResult: RunResult = { kind: 'current_decomp', data: pure } - const run: Run = { - id: randomRunId(), - timestamp: Date.now(), - result: runResult, - activePhysics: active_physics ?? 'unknown', - durationMs: performance.now() - t0, - deviceSnapshot: snapshot, - } - opts.onRunComplete(active.id, run) - progressBar.done() - setStatus('status-cd', 'Done') - }, - onError: (msg) => { - progressBar.error(msg) - setStatus('status-cd', `Error: ${msg}`, true) - }, - onDone: () => { - btn.disabled = false - }, - }) - }) - .catch(e => { - progressBar.error((e as Error).message) - setStatus('status-cd', `Error: ${(e as Error).message}`, true) - btn.disabled = false - }) - }) -} - -function randomRunId(): string { - return 'r-' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36) -} diff --git a/web/src/workstation/panes/dark-jv-pane.ts b/web/src/workstation/panes/dark-jv-pane.ts index 602c32ba..0919cd6a 100644 --- a/web/src/workstation/panes/dark-jv-pane.ts +++ b/web/src/workstation/panes/dark-jv-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, DarkJVResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface DarkJVPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -58,13 +59,15 @@ export function mountDarkJVPane(container: HTMLElement, opts: DarkJVPaneOptions) streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as DarkJVResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as DarkJVResult & { active_physics?: string }) const runResult: RunResult = { kind: 'dark_jv', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/degradation-pane.ts b/web/src/workstation/panes/degradation-pane.ts index 3c318a6b..33ad52fe 100644 --- a/web/src/workstation/panes/degradation-pane.ts +++ b/web/src/workstation/panes/degradation-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, DegResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface DegradationPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -57,18 +58,34 @@ export function mountDegradationPane(container: HTMLElement, opts: DegradationPa streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as DegResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as DegResult & { active_physics?: string }) const runResult: RunResult = { kind: 'degradation', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } opts.onRunComplete(active.id, run) progressBar.done() + const invalidCount = + (pure.failed_points?.length ?? 0) || + pure.times.filter( + (_, i) => + pure.valid?.[i] === false || + pure.PCE[i] == null || + !Number.isFinite(pure.PCE[i]) || + pure.V_oc[i] == null || + !Number.isFinite(pure.V_oc[i]), + ).length + if (invalidCount > 0) { + setStatus('status-deg', `Done · Diagnostics: ${invalidCount} failed/invalid trajectory step(s)`, true) + return + } setStatus('status-deg', 'Done') }, onError: (msg) => { diff --git a/web/src/workstation/panes/dynamic-defect-transient-pane.ts b/web/src/workstation/panes/dynamic-defect-transient-pane.ts index 16f6c1fd..167491b7 100644 --- a/web/src/workstation/panes/dynamic-defect-transient-pane.ts +++ b/web/src/workstation/panes/dynamic-defect-transient-pane.ts @@ -4,6 +4,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import type { DeviceConfig, DynamicDefectTransientResult } from '../../types' import { numField, readNum, setStatus } from '../../ui-helpers' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface DynamicDefectTransientPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -94,7 +95,7 @@ export function mountDynamicDefectTransientPane( { onProgress: ev => progressBar.update(ev), onResult: result => { - const { active_physics, ...pure } = result + const { pure, receipt } = extractExecutionPhysics(result) const runResult: RunResult = { kind: 'dynamic_defect_transient', data: pure, @@ -103,7 +104,9 @@ export function mountDynamicDefectTransientPane( id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/el-pane.ts b/web/src/workstation/panes/el-pane.ts index 0565ec19..19f168b3 100644 --- a/web/src/workstation/panes/el-pane.ts +++ b/web/src/workstation/panes/el-pane.ts @@ -4,6 +4,7 @@ import { setStatus, numField, readNum } from '../../ui-helpers' import { hasTMMOptics } from '../../device-utils' import type { DeviceConfig, ELResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' const NON_TMM_MSG = 'TMM optical data required. Select a preset with wavelength-resolved n,k data.' @@ -78,13 +79,15 @@ export function mountELPane(container: HTMLElement, opts: ELPaneOptions): void { streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as ELResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as ELResult & { active_physics?: string }) const runResult: RunResult = { kind: 'el', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/eqe-pane.ts b/web/src/workstation/panes/eqe-pane.ts index 79733c73..5e980f51 100644 --- a/web/src/workstation/panes/eqe-pane.ts +++ b/web/src/workstation/panes/eqe-pane.ts @@ -4,6 +4,7 @@ import { setStatus, numField, readNum } from '../../ui-helpers' import { hasTMMOptics } from '../../device-utils' import type { DeviceConfig, EQEResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' const NON_TMM_MSG = 'TMM optical data required. Select a preset with wavelength-resolved n,k data.' @@ -85,13 +86,15 @@ export function mountEQEPane(container: HTMLElement, opts: EQEPaneOptions): void streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as EQEResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as EQEResult & { active_physics?: string }) const runResult: RunResult = { kind: 'eqe', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/experiment-pane.ts b/web/src/workstation/panes/experiment-pane.ts index 8757c646..5935cd4d 100644 --- a/web/src/workstation/panes/experiment-pane.ts +++ b/web/src/workstation/panes/experiment-pane.ts @@ -18,19 +18,12 @@ */ import type { DeviceConfig } from '../../types' import type { Run, ExperimentKind } from '../types' -import { mountJVPane } from './jv-pane' -import { mountImpedancePane } from './impedance-pane' -import { mountDynamicDefectTransientPane } from './dynamic-defect-transient-pane' -import { mountDegradationPane } from './degradation-pane' -import { mountTPVPane } from './tpv-pane' -import { mountDarkJVPane } from './dark-jv-pane' -import { mountSunsVocPane } from './suns-voc-pane' -import { mountVocTPane } from './voc-t-pane' -import { mountEQEPane } from './eqe-pane' -import { mountELPane } from './el-pane' -import { mountMottSchottkyPane } from './mott-schottky-pane' -import { mountJV2DPane } from './jv-2d-pane' -import { mountVocGrainSweepPane } from './voc-grain-sweep-pane' +import { + getExperimentDescriptor, + getSelectableExperimentGroups, + type ExperimentDescriptor, + type MountedExperimentForm, +} from '../experiment-catalog' export interface ExperimentPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -42,20 +35,6 @@ export interface ExperimentPaneHandle { selectExperiment(kind: ExperimentKind): void } -type DeviceAwarePane = Pick - -interface ExperimentEntry { - kind: ExperimentKind - /** HTML — may contain for proper subscript typography. Static source constants only. */ - labelHTML: string - mount: (container: HTMLElement) => DeviceAwarePane | void -} - -interface ExperimentGroup { - label: string - entries: ExperimentEntry[] -} - export function mountExperimentPane(container: HTMLElement, opts: ExperimentPaneOptions): ExperimentPaneHandle { // Golden Layout clips component content by default. Make the host own the // scroll area so long forms (including the Calado scan history) stay usable. @@ -70,93 +49,13 @@ export function mountExperimentPane(container: HTMLElement, opts: ExperimentPane opts.onRunComplete(deviceId, run.result.kind, run), }) - const groups: ExperimentGroup[] = [ - { - label: 'Illuminated J\u2013V', - entries: [ - { - kind: 'jv', labelHTML: 'J\u2013V Sweep', - mount: (el) => mountJVPane(el, paneOpts()), - }, - { - kind: 'suns_voc', labelHTML: 'Suns\u2013Voc', - mount: (el) => mountSunsVocPane(el, paneOpts()), - }, - { - kind: 'voc_t', labelHTML: 'Voc(T)', - mount: (el) => mountVocTPane(el, paneOpts()), - }, - ], - }, - { - label: 'Dark characterisation', - entries: [ - { - kind: 'dark_jv', labelHTML: 'Dark J\u2013V', - mount: (el) => mountDarkJVPane(el, paneOpts()), - }, - { - kind: 'mott_schottky', labelHTML: 'Mott\u2013Schottky (C\u2013V)', - mount: (el) => mountMottSchottkyPane(el, paneOpts()), - }, - ], - }, - { - label: 'Spectral', - entries: [ - { - kind: 'eqe', labelHTML: 'EQE / IPCE', - mount: (el) => mountEQEPane(el, paneOpts()), - }, - { - kind: 'el', labelHTML: 'EL / \u0394Vnr', - mount: (el) => mountELPane(el, paneOpts()), - }, - ], - }, - { - label: 'Transient', - entries: [ - { - kind: 'impedance', labelHTML: 'Impedance', - mount: (el) => mountImpedancePane(el, paneOpts()), - }, - { - kind: 'dynamic_defect_transient', - labelHTML: 'Defect–Ion Transient', - mount: (el) => mountDynamicDefectTransientPane(el, paneOpts()), - }, - { - kind: 'tpv', labelHTML: 'Transient Photovoltage (TPV)', - mount: (el) => mountTPVPane(el, paneOpts()), - }, - { - kind: 'degradation', labelHTML: 'Degradation', - mount: (el) => mountDegradationPane(el, paneOpts()), - }, - ], - }, - { - label: '2D / Microstructure', - entries: [ - { - kind: 'jv_2d', labelHTML: 'J–V Sweep (2D)', - mount: (el) => mountJV2DPane(el, paneOpts()), - }, - { - kind: 'voc_grain_sweep', labelHTML: 'Voc(Lg) Grain Sweep', - mount: (el) => mountVocGrainSweepPane(el, paneOpts()), - }, - ], - }, - ] - - const entries: ExperimentEntry[] = groups.flatMap(g => g.entries) + const groups = getSelectableExperimentGroups() + const entries: readonly ExperimentDescriptor[] = groups.flatMap(g => g.entries) const groupHTML = groups .map(g => { const optionHTML = g.entries - .map(e => `
${e.labelHTML}
`) + .map(e => `
${e.selectorLabelHTML}
`) .join('') return `
${escapeText(g.label)}
@@ -188,19 +87,40 @@ export function mountExperimentPane(container: HTMLElement, opts: ExperimentPane const body = container.querySelector('#exp-body')! let selectedKind: ExperimentKind = entries[0].kind - let activePane: DeviceAwarePane | void + let activePane: MountedExperimentForm | void + + function renderUnsupportedCapability(kind: string): void { + body.replaceChildren() + const card = document.createElement('div') + card.className = 'card' + card.dataset.test = 'experiment-capability-fallback' + const title = document.createElement('h3') + title.textContent = `Registered capability: ${kind}` + const note = document.createElement('p') + note.textContent = + 'This registered experiment capability has no bespoke legacy form in the workstation dock; inspect or submit it through its dedicated V2 route.' + card.append(title, note) + body.appendChild(card) + } function selectKind(kind: ExperimentKind): void { const entry = entries.find(e => e.kind === kind) - if (!entry) return + if (!entry || !entry.mountForm) { + selectedKind = kind + current.textContent = kind + options.forEach(o => o.classList.remove('experiment-dropdown-option-selected')) + activePane = undefined + renderUnsupportedCapability(kind) + return + } if (kind === selectedKind && body.childElementCount > 0) return selectedKind = kind - current.innerHTML = entry.labelHTML + current.innerHTML = entry.selectorLabelHTML options.forEach(o => o.classList.toggle('experiment-dropdown-option-selected', o.dataset.kind === kind), ) body.innerHTML = '' - activePane = entry.mount(body) + activePane = entry.mountForm(body, paneOpts()) } function setOpen(open: boolean): void { @@ -266,18 +186,11 @@ export function mountExperimentPane(container: HTMLElement, opts: ExperimentPane return { updateDevice: resetDefaults => activePane?.updateDevice(resetDefaults), selectExperiment: kind => { - const target = kind === 'current_decomp' || kind === 'spatial' ? 'jv' : kind + const descriptor = getExperimentDescriptor(kind) + const target = descriptor?.delegateToKind ?? kind selectKind(target) setOpen(false) - if (target === 'jv') { - const solver = body.querySelector('#jvp-solver')! - if (kind === 'current_decomp' || kind === 'spatial') { - solver.value = 'transient' - solver.dispatchEvent(new Event('change', { bubbles: true })) - } - body.querySelector('#jvp-decomp')!.checked = kind === 'current_decomp' - body.querySelector('#jvp-spatial')!.checked = kind === 'spatial' - } + descriptor?.applyFormPreset?.(body) }, } } diff --git a/web/src/workstation/panes/impedance-pane.ts b/web/src/workstation/panes/impedance-pane.ts index aa0d4988..1d258598 100644 --- a/web/src/workstation/panes/impedance-pane.ts +++ b/web/src/workstation/panes/impedance-pane.ts @@ -11,6 +11,7 @@ import { import type { DeviceConfig, ISResult } from '../../types' import { dynamicDefectImpedancePreset } from '../../explicit-defect-capability' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface ImpedancePaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -172,13 +173,15 @@ export function mountImpedancePane(container: HTMLElement, opts: ImpedancePaneOp streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as ISResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as ISResult & { active_physics?: string }) const runResult: RunResult = { kind: 'impedance', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/jv-2d-pane.ts b/web/src/workstation/panes/jv-2d-pane.ts index b562c7c3..9bad054d 100644 --- a/web/src/workstation/panes/jv-2d-pane.ts +++ b/web/src/workstation/panes/jv-2d-pane.ts @@ -13,6 +13,7 @@ import { setStatus, numField, readNum } from '../../ui-helpers' import { describeActivePhysics } from '../../active-physics' import type { DeviceConfig, JV2DResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface JV2DPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -164,19 +165,39 @@ export function mountJV2DPane(container: HTMLElement, opts: JV2DPaneOptions): vo streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as JV2DResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as JV2DResult & { active_physics?: string }) const runResult: RunResult = { kind: 'jv_2d', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } + physSlot.textContent = receipt.summary opts.onRunComplete(active.id, run) progressBar.done() const nV = pure.V.length + const diag: string[] = [] + if (pure.metrics?.voc_bracketed === false || (pure.metrics && !Number.isFinite(pure.metrics.V_oc))) { + diag.push('V_oc not bracketed') + } + if ((pure.failed_points?.length ?? 0) > 0) { + diag.push(`${pure.failed_points!.length} failed point(s)`) + } else if (pure.converged?.some(c => !c)) { + diag.push(`${pure.converged.filter(c => !c).length} unconverged point(s)`) + } + if (diag.length > 0) { + setStatus( + 'status-jv2d', + `Done · ${nV} voltage points · BC=${pure.lateral_bc} · Diagnostics: ${diag.join(', ')}`, + true, + ) + return + } setStatus('status-jv2d', `Done · ${nV} voltage points · BC=${pure.lateral_bc}`) }, onError: (msg) => { diff --git a/web/src/workstation/panes/jv-pane.ts b/web/src/workstation/panes/jv-pane.ts index 0f2b9be7..7c6b7ee5 100644 --- a/web/src/workstation/panes/jv-pane.ts +++ b/web/src/workstation/panes/jv-pane.ts @@ -13,6 +13,7 @@ import type { SpatialProfileResult, } from '../../types' import type { Run, RunResult, ExperimentKind } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface JVPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -259,7 +260,7 @@ export function mountJVPane(container: HTMLElement, opts: JVPaneOptions): JVPane streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result + const { pure, receipt } = extractExecutionPhysics(result) const runResult: RunResult = kind === 'jv' ? { kind: 'jv', data: pure as JVResult } @@ -270,12 +271,33 @@ export function mountJVPane(container: HTMLElement, opts: JVPaneOptions): JVPane id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } opts.onRunComplete(active.id, run) progressBar.done() + if (kind === 'jv') { + const jvData = pure as JVResult + const diag: string[] = [] + if (jvData.metrics_fwd?.voc_bracketed === false || (jvData.metrics_fwd && !Number.isFinite(jvData.metrics_fwd.V_oc))) { + diag.push('fwd V_oc not bracketed') + } + if (!jvData.interface_charge_evidence && (jvData.metrics_rev?.voc_bracketed === false || (jvData.metrics_rev && !Number.isFinite(jvData.metrics_rev.V_oc)))) { + diag.push('rev V_oc not bracketed') + } + if ((jvData.failed_points?.length ?? 0) > 0) { + diag.push(`${jvData.failed_points!.length} failed point(s)`) + } else if (jvData.converged?.some(c => !c)) { + diag.push(`${jvData.converged.filter(c => !c).length} unconverged point(s)`) + } + if (diag.length > 0) { + setStatus('status-jvp', `Done · Diagnostics: ${diag.join(', ')}`, true) + return + } + } setStatus('status-jvp', 'Done') }, onError: (msg) => { diff --git a/web/src/workstation/panes/main-plot-pane.ts b/web/src/workstation/panes/main-plot-pane.ts index d466bb3d..5c04816d 100644 --- a/web/src/workstation/panes/main-plot-pane.ts +++ b/web/src/workstation/panes/main-plot-pane.ts @@ -1,6 +1,8 @@ import Plotly from 'plotly.js-basic-dist-min' import type { Workspace } from '../types' import { findRun } from '../state' +import { formatQualificationBadge, resolveRunExecutionPhysics } from '../execution-physics' +import { getExperimentDescriptor } from '../experiment-catalog' import { baseLayout, plotConfig, LINE, axisTitle, publicationLayout, publicationAxis, publicationConfig, @@ -46,6 +48,46 @@ export interface MainPlotHandle { dispose(): void } +const PLOT_RENDERERS_BY_KIND: Readonly void>> = Object.freeze({ + jv: (el, data) => renderJV(el, data as JVResult), + impedance: (el, data) => renderImpedance(el, data as ISResult), + dynamic_defect_transient: (el, data) => renderDynamicDefectTransient(el, data as DynamicDefectTransientResult), + degradation: (el, data) => renderDegradation(el, data as DegResult), + tpv: (el, data) => renderTPV(el, data as TPVResult), + current_decomp: (el, data) => renderCurrentDecomp(el, data as CurrentDecompResult), + spatial: (el, data) => renderSpatialProfiles(el, data as SpatialProfileResult), + dark_jv: (el, data) => renderDarkJV(el, data as DarkJVResult), + suns_voc: (el, data) => renderSunsVoc(el, data as SunsVocResult), + voc_t: (el, data) => renderVocT(el, data as VocTResult), + eqe: (el, data) => renderEQE(el, data as EQEResult), + el: (el, data) => renderEL(el, data as ELResult), + mott_schottky: (el, data) => renderMottSchottky(el, data as MottSchottkyResult), + jv_2d: (el, data) => renderJV2D(el, data as JV2DResult), + voc_grain_sweep: (el, data) => renderVocGrainSweep(el, data as VocGrainSweepResult), +}) + +function renderRegisteredCapabilityResultFallback( + el: HTMLElement, + kind: string, + data: unknown, +): void { + Plotly.purge(el) + while (el.firstChild) el.removeChild(el.firstChild) + const wrapper = document.createElement('div') + wrapper.className = 'plot-capability-fallback' + wrapper.setAttribute('data-test', 'plot-capability-fallback') + const desc = getExperimentDescriptor(kind) + const heading = document.createElement('div') + heading.className = 'plot-capability-fallback-title' + const labelText = desc ? desc.treeLabelHTML.replace(/<[^>]+>/g, '') : kind + heading.textContent = `${labelText} — Registered Capability Payload` + const pre = document.createElement('pre') + pre.className = 'plot-capability-fallback-json' + pre.textContent = JSON.stringify(data, null, 2) + wrapper.append(heading, pre) + el.appendChild(wrapper) +} + export function mountMainPlotPane(container: HTMLElement): MainPlotHandle { container.innerHTML = `
@@ -84,7 +126,7 @@ export function mountMainPlotPane(container: HTMLElement): MainPlotHandle { resizeObserver?.observe(container) function clear(msg: string): void { - header.textContent = 'Results' + header.replaceChildren(document.createTextNode('Results')) header.removeAttribute('title') purgePlots() plotEl.innerHTML = '
' @@ -105,57 +147,41 @@ export function mountMainPlotPane(container: HTMLElement): MainPlotHandle { clear('Result not found') return } - const runMode = run.deviceSnapshot?.device?.mode - header.textContent = `${runMode ? `${runMode.toUpperCase()} · ` : ''}${new Date(run.timestamp).toLocaleString()}` - header.title = run.activePhysics + const receipt = resolveRunExecutionPhysics(run) + const qual = formatQualificationBadge(receipt) + const timeSpan = document.createElement('span') + timeSpan.className = 'mpp-header-time' + timeSpan.textContent = new Date(run.timestamp).toLocaleString() + const manifestBadge = document.createElement('span') + manifestBadge.className = 'mpp-manifest-badge' + manifestBadge.setAttribute('data-test', 'run-manifest-badge') + manifestBadge.title = receipt.summary + manifestBadge.textContent = receipt.badgeLabel + const qualBadge = document.createElement('span') + qualBadge.className = qual.explicitUnqualified + ? 'mpp-qualification-badge mpp-qualification-preview' + : qual.qualified + ? 'mpp-qualification-badge mpp-qualification-ok' + : 'mpp-qualification-badge mpp-qualification-unverified' + qualBadge.setAttribute('data-test', 'run-qualification-badge') + qualBadge.setAttribute('data-qualified', String(qual.qualified)) + qualBadge.title = qual.detail + qualBadge.textContent = qual.label + header.replaceChildren( + timeSpan, + document.createTextNode(' · '), + manifestBadge, + document.createTextNode(' · '), + qualBadge, + ) + header.title = `${receipt.summary} | ${qual.detail}` purgePlots() - switch (run.result.kind) { - case 'jv': - renderJV(plotEl, run.result.data) - return - case 'impedance': - renderImpedance(plotEl, run.result.data) - return - case 'dynamic_defect_transient': - renderDynamicDefectTransient(plotEl, run.result.data) - return - case 'degradation': - renderDegradation(plotEl, run.result.data) - return - case 'tpv': - renderTPV(plotEl, run.result.data) - return - case 'current_decomp': - renderCurrentDecomp(plotEl, run.result.data) - return - case 'spatial': - renderSpatialProfiles(plotEl, run.result.data) - return - case 'dark_jv': - renderDarkJV(plotEl, run.result.data) - return - case 'suns_voc': - renderSunsVoc(plotEl, run.result.data) - return - case 'voc_t': - renderVocT(plotEl, run.result.data) - return - case 'eqe': - renderEQE(plotEl, run.result.data) - return - case 'el': - renderEL(plotEl, run.result.data) - return - case 'mott_schottky': - renderMottSchottky(plotEl, run.result.data) - return - case 'jv_2d': - renderJV2D(plotEl, run.result.data) - return - case 'voc_grain_sweep': - renderVocGrainSweep(plotEl, run.result.data) - return + const renderer = PLOT_RENDERERS_BY_KIND[run.result.kind] + if (renderer) { + renderer(plotEl, run.result.data) + return } + renderRegisteredCapabilityResultFallback(plotEl, run.result.kind, run.result.data) }, dispose() { if (disposed) return @@ -179,13 +205,35 @@ export function renderVocGrainSweep(el: HTMLElement, r: VocGrainSweepResult): vo _vgsPlotDiv.id = 'voc-grain-sweep-plot-inner' el.appendChild(_vgsPlotDiv) - const V_oc_mV = r.V_oc_V.map(v => v * 1e3) + const invalidIndices = r.grain_sizes_nm + .map((_, i) => i) + .filter( + i => + r.V_oc_V[i] == null || + !Number.isFinite(r.V_oc_V[i]) || + r.voc_bracketed?.[i] === false, + ) + + const V_oc_mV: Array = + invalidIndices.length === 0 + ? r.V_oc_V.map(v => v * 1e3) + : r.V_oc_V.map((v, i) => + v == null || !Number.isFinite(v) || r.voc_bracketed?.[i] === false + ? null + : v * 1e3, + ) const J_sc_mA = r.J_sc_Am2.map(j => j / 10) const ann = r.grain_sizes_nm - .map((L, i) => - `Lg=${L.toFixed(0)} nm: Voc=${V_oc_mV[i].toFixed(1)} mV, ` + - `Jsc=${J_sc_mA[i].toFixed(2)} mA·cm⁻², FF=${r.FF[i].toFixed(3)}`, - ) + .map((L, i) => { + const vocCell = + V_oc_mV[i] === null ? 'not bracketed / failed' : `${V_oc_mV[i]!.toFixed(1)} mV` + const jscCell = Number.isFinite(J_sc_mA[i]) ? `${J_sc_mA[i].toFixed(2)} mA·cm⁻²` : '—' + const ffCell = Number.isFinite(r.FF[i]) && V_oc_mV[i] !== null ? r.FF[i].toFixed(3) : '—' + return ( + `Lg=${L.toFixed(0)} nm: Voc=${vocCell}, ` + + `Jsc=${jscCell}, FF=${ffCell}` + ) + }) .join('
') Plotly.newPlot( @@ -225,6 +273,26 @@ export function renderVocGrainSweep(el: HTMLElement, r: VocGrainSweepResult): vo }), publicationConfig('voc_grain_sweep'), ) + + if (invalidIndices.length > 0 || (r.failed_points?.length ?? 0) > 0) { + const notes: string[] = [] + if (invalidIndices.length > 0) { + const grains = invalidIndices.map(i => `L_g=${r.grain_sizes_nm[i].toFixed(0)} nm`).join(', ') + notes.push(`V_oc unavailable or unbracketed at ${grains}`) + } + if ((r.failed_points?.length ?? 0) > 0) { + const reasons = r.failed_points! + .map(fp => `${fp.label ?? `#${fp.index}`} (${fp.reason})`) + .join('; ') + notes.push(`Failed sweep points (${r.failed_points!.length}): ${reasons}`) + } + const warnBanner = document.createElement('div') + warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') + warnBanner.setAttribute('data-test', 'voc-grain-sweep-diagnostic-warning') + warnBanner.textContent = notes.join(' | ') + el.appendChild(warnBanner) + } } // ── Stage-A 2D J-V (Phase 6) ──────────────────────────────────────────────── @@ -360,15 +428,16 @@ export function renderJV2D(el: HTMLElement, r: JV2DResult): void { // is misleading — show "—" (em dash, the conventional "not // available" placeholder). J_sc stays because ``compute_metrics`` // interpolates it at V=0 regardless of bracket success. - const bracketed = m.voc_bracketed !== false + const bracketed = m.voc_bracketed !== false && Number.isFinite(m.V_oc) const dash = '—' const vocStr = bracketed ? `${m.V_oc.toFixed(3)} V` : dash - const ffStr = bracketed ? `${(m.FF * 100).toFixed(1)} %` : dash - const pceStr = bracketed ? `${(m.PCE * 100).toFixed(2)} %` : dash + const jscStr = Number.isFinite(m.J_sc) ? `${(m.J_sc / 10).toFixed(2)} mA/cm²` : dash + const ffStr = bracketed && Number.isFinite(m.FF) ? `${(m.FF * 100).toFixed(1)} %` : dash + const pceStr = bracketed && Number.isFinite(m.PCE) ? `${(m.PCE * 100).toFixed(2)} %` : dash const cardsHtml = `
` + metricCard('Voc', vocStr) + - metricCard('Jsc', `${(m.J_sc / 10).toFixed(2)} mA/cm²`) + + metricCard('Jsc', jscStr) + metricCard('FF', ffStr) + metricCard('PCE', pceStr) + `
` @@ -383,12 +452,34 @@ export function renderJV2D(el: HTMLElement, r: JV2DResult): void { if (m.voc_bracketed === false) { const warnBanner = document.createElement('div') warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') warnBanner.setAttribute('data-test', 'jv2d-voc-not-bracketed') warnBanner.textContent = 'V_oc not bracketed — increase V_max' el.appendChild(warnBanner) } } + + const failedMessages: string[] = [] + if (m && m.voc_bracketed !== false && !Number.isFinite(m.V_oc)) { + failedMessages.push('V_oc is unavailable or non-finite') + } + if ((r.failed_points?.length ?? 0) > 0) { + const details = r.failed_points! + .map(fp => `${fp.label ?? (fp.bias_V !== undefined ? `V=${fp.bias_V} V` : `#${fp.index}`)} (${fp.reason})`) + .join('; ') + failedMessages.push(`Failed sweep points (${r.failed_points!.length}): ${details}`) + } else if (r.converged?.some(c => !c)) { + failedMessages.push(`${r.converged.filter(c => !c).length} bias point(s) failed to converge`) + } + if (failedMessages.length > 0) { + const failBanner = document.createElement('div') + failBanner.className = 'jv2d-warning' + failBanner.setAttribute('role', 'alert') + failBanner.setAttribute('data-test', 'jv2d-failed-points-warning') + failBanner.textContent = failedMessages.join(' | ') + el.appendChild(failBanner) + } } // Publication-mode operational ranges for the 1D J-V workstation @@ -618,6 +709,36 @@ export function renderJV(el: HTMLElement, r: JVResult): void { }), publicationConfig('jv_sweep'), ) + + const diagNotes: string[] = [] + if (r.metrics_fwd?.voc_bracketed === false) { + diagNotes.push('Forward sweep V_oc not bracketed') + } else if (r.metrics_fwd && !Number.isFinite(r.metrics_fwd.V_oc)) { + diagNotes.push('Forward sweep V_oc unavailable') + } + if (!chargedEvidence) { + if (r.metrics_rev?.voc_bracketed === false) { + diagNotes.push('Reverse sweep V_oc not bracketed') + } else if (r.metrics_rev && !Number.isFinite(r.metrics_rev.V_oc)) { + diagNotes.push('Reverse sweep V_oc unavailable') + } + } + if ((r.failed_points?.length ?? 0) > 0) { + const details = r.failed_points! + .map(fp => `${fp.label ?? (fp.bias_V !== undefined ? `V=${fp.bias_V} V` : `#${fp.index}`)} (${fp.reason})`) + .join('; ') + diagNotes.push(`Failed sweep points (${r.failed_points!.length}): ${details}`) + } else if (r.converged?.some(c => !c)) { + diagNotes.push(`${r.converged.filter(c => !c).length} sweep point(s) failed to converge`) + } + if (diagNotes.length > 0) { + const warnBanner = document.createElement('div') + warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') + warnBanner.setAttribute('data-test', 'jv-diagnostic-warning') + warnBanner.textContent = diagNotes.join(' | ') + el.appendChild(warnBanner) + } } export function renderImpedance(el: HTMLElement, r: ISResult): void { @@ -780,8 +901,20 @@ export function renderDegradation(el: HTMLElement, r: DegResult): void { _degPlotDiv.id = 'degradation-plot-inner' el.appendChild(_degPlotDiv) - const pce0 = r.PCE[0] || 1 - const normalized = r.PCE.map(p => p / pce0) + const hasInvalid = Boolean( + r.valid?.some(v => !v) || + r.PCE.some(p => p == null || !Number.isFinite(p)) || + r.V_oc.some(v => v == null || !Number.isFinite(v)) || + (r.failed_points?.length ?? 0) > 0, + ) + const pce0 = hasInvalid + ? (r.PCE.find((p, i) => r.valid?.[i] !== false && Number.isFinite(p) && p !== 0) ?? (r.PCE[0] || 1)) + : (r.PCE[0] || 1) + const normalized: Array = hasInvalid + ? r.PCE.map((p, i) => + r.valid?.[i] === false || p == null || !Number.isFinite(p) ? null : p / pce0, + ) + : r.PCE.map(p => p / pce0) Plotly.newPlot( _degPlotDiv, @@ -801,6 +934,33 @@ export function renderDegradation(el: HTMLElement, r: DegResult): void { }), publicationConfig('degradation'), ) + + if (hasInvalid) { + const degNotes: string[] = [] + if ((r.failed_points?.length ?? 0) > 0) { + const details = r.failed_points! + .map(fp => `${fp.label ?? `#${fp.index}`} (${fp.reason})`) + .join('; ') + degNotes.push(`Failed trajectory steps (${r.failed_points!.length}): ${details}`) + } + const invalidStepCount = r.times.filter( + (_, i) => + r.valid?.[i] === false || + r.PCE[i] == null || + !Number.isFinite(r.PCE[i]) || + r.V_oc[i] == null || + !Number.isFinite(r.V_oc[i]), + ).length + if (invalidStepCount > 0) { + degNotes.push(`${invalidStepCount} trajectory step(s) invalid or non-identifiable`) + } + const warnBanner = document.createElement('div') + warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') + warnBanner.setAttribute('data-test', 'degradation-diagnostic-warning') + warnBanner.textContent = degNotes.join(' | ') + el.appendChild(warnBanner) + } } export function renderTPV(el: HTMLElement, r: TPVResult): void { @@ -816,9 +976,10 @@ export function renderTPV(el: HTMLElement, r: TPVResult): void { // Convert time to microseconds for readability const t_us = r.t.map(t => t * 1e6) + const nonIdReason = r.non_identifiable_reason ?? r.fit?.non_identifiable_reason ?? null const validTrace = !r.valid || r.valid.every(Boolean) const hasDecay = validTrace && r.tau !== null && Number.isFinite(r.tau) && r.tau > 0 - && (!r.fit || r.fit.status === 'accepted') + && (!r.fit || r.fit.status === 'accepted') && !nonIdReason const fitStatus: Record = { no_signal: 'No resolved pulse', insufficient_data: 'Insufficient data', @@ -830,9 +991,13 @@ export function renderTPV(el: HTMLElement, r: TPVResult): void { } const tauLabel = hasDecay ? `${((r.tau as number) * 1e6).toFixed(1)} \u00B5s` - : (validTrace ? (fitStatus[r.fit?.status ?? ''] ?? 'Unavailable') : 'Invalid response') - const delta = r.delta_V ?? r.V.map((v, i) => v - (r.V_reference?.[i] ?? r.V_oc)) - const dV_mV = delta.map((v, i) => r.valid && !r.valid[i] ? null : v * 1e3) + : (validTrace ? (fitStatus[r.fit?.status ?? ''] ?? nonIdReason ?? 'Unavailable') : 'Invalid response') + const vocValid = Number.isFinite(r.V_oc) + const vocRefFallback = vocValid ? r.V_oc : 0 + const delta = r.delta_V ?? r.V.map((v, i) => v - (r.V_reference?.[i] ?? vocRefFallback)) + const dV_mV = delta.map((v, i) => (r.valid && !r.valid[i]) || !Number.isFinite(v) ? null : v * 1e3) + const vocLabel = vocValid ? `${r.V_oc.toFixed(3)} V` : 'unavailable' + const dv0Label = Number.isFinite(r.delta_V0) ? `${(r.delta_V0 * 1e3).toFixed(2)} mV` : 'unavailable' Plotly.newPlot( _tpvPlotDiv, @@ -858,9 +1023,9 @@ export function renderTPV(el: HTMLElement, r: TPVResult): void { xanchor: 'right' as const, yanchor: 'top' as const, showarrow: false, text: - `Voc = ${r.V_oc.toFixed(3)} V
` + + `Voc = ${vocLabel}
` + `\u03C4 = ${tauLabel}
` + - `\u0394V0 = ${(r.delta_V0 * 1e3).toFixed(2)} mV`, + `\u0394V0 = ${dv0Label}`, align: 'right' as const, bgcolor: 'rgba(255,255,255,0)', bordercolor: 'rgba(0,0,0,0)', @@ -872,6 +1037,30 @@ export function renderTPV(el: HTMLElement, r: TPVResult): void { publicationConfig('tpv'), ) observePlotResize(el, _tpvPlotDiv) + + if (!hasDecay || !vocValid) { + const tpvNotes: string[] = [] + if (!validTrace) { + tpvNotes.push('Invalid response points detected in ΔV(t) trajectory') + } + if (r.tau === null || !Number.isFinite(r.tau) || r.tau <= 0) { + tpvNotes.push('Lifetime τ is non-identifiable') + } + if (nonIdReason) { + tpvNotes.push(`Reason: ${nonIdReason}`) + } else if (r.fit?.status && r.fit.status !== 'accepted') { + tpvNotes.push(`Fit status: ${fitStatus[r.fit.status] ?? r.fit.status}`) + } + if (!vocValid) { + tpvNotes.push('Steady open-circuit voltage V_oc unavailable') + } + const warnBanner = document.createElement('div') + warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') + warnBanner.setAttribute('data-test', 'tpv-diagnostic-warning') + warnBanner.textContent = tpvNotes.join(' | ') + el.appendChild(warnBanner) + } } export function renderVocT(el: HTMLElement, r: VocTResult): void { diff --git a/web/src/workstation/panes/mott-schottky-pane.ts b/web/src/workstation/panes/mott-schottky-pane.ts index 35c741c9..53a09c5f 100644 --- a/web/src/workstation/panes/mott-schottky-pane.ts +++ b/web/src/workstation/panes/mott-schottky-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, MottSchottkyResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface MottSchottkyPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -70,13 +71,15 @@ export function mountMottSchottkyPane(container: HTMLElement, opts: MottSchottky streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as MottSchottkyResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as MottSchottkyResult & { active_physics?: string }) const runResult: RunResult = { kind: 'mott_schottky', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/spatial-pane.ts b/web/src/workstation/panes/spatial-pane.ts deleted file mode 100644 index b5fc3371..00000000 --- a/web/src/workstation/panes/spatial-pane.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { startJob, streamJobEvents } from '../../job-stream' -import { createProgressBar, type ProgressBarHandle } from '../../progress' -import { setStatus, numField, readNum, checkField, readCheck } from '../../ui-helpers' -import type { DeviceConfig, SpatialProfileResult } from '../../types' -import type { Run, RunResult } from '../types' - -export interface SpatialPaneOptions { - getActiveDevice: () => { id: string; config: DeviceConfig } | null - onRunComplete: (deviceId: string, run: Run) => void -} - -export function mountSpatialPane(container: HTMLElement, opts: SpatialPaneOptions): void { - container.innerHTML = ` -
-

Spatial Profiles

-

- Extracts position-resolved profiles (φ, E, n, p, ρ) - at each voltage point during a J–V sweep. -

-
- ${numField('sp-N', 'Ngrid', 60, '1')} - ${numField('sp-np', 'V sample points', 10, '1')} - ${numField('sp-rate', 'Scan rate (V/s)', 1.0, 'any')} - ${numField('sp-vmax', 'Vmax (V)', 1.0, '0.01')} - ${checkField('sp-dark', 'Dark (no illumination)', false)} -
-
- - -
-
-
Results stream into the Main Plot pane. Forward sweep snapshots are shown.
-
` - - const progressBar: ProgressBarHandle = createProgressBar( - container.querySelector('#progress-sp')!, - ) - const btn = container.querySelector('#btn-sp')! - - btn.addEventListener('click', () => { - const active = opts.getActiveDevice() - if (!active) { - setStatus('status-sp', 'No active device. Select one in the tree.', true) - return - } - btn.disabled = true - progressBar.reset() - progressBar.busy() - setStatus('status-sp', 'Starting job…') - - const isDark = readCheck('sp-dark', false) - const params = { - N_grid: Math.max(3, Math.round(readNum('sp-N', 60))), - n_points: Math.max(2, Math.round(readNum('sp-np', 10))), - v_rate: readNum('sp-rate', 1.0), - V_max: readNum('sp-vmax', 1.0), - illuminated: !isDark, - } - const t0 = performance.now() - const snapshot: DeviceConfig = JSON.parse(JSON.stringify(active.config)) - - startJob('spatial', active.config, params) - .then(jobId => { - setStatus('status-sp', 'Running spatial profiles…') - streamJobEvents(jobId, { - onProgress: (ev) => progressBar.update(ev), - onResult: (result) => { - const { active_physics, ...pure } = result as SpatialProfileResult & { active_physics?: string } - const runResult: RunResult = { kind: 'spatial', data: pure } - const run: Run = { - id: randomRunId(), - timestamp: Date.now(), - result: runResult, - activePhysics: active_physics ?? 'unknown', - durationMs: performance.now() - t0, - deviceSnapshot: snapshot, - } - opts.onRunComplete(active.id, run) - progressBar.done() - setStatus('status-sp', 'Done') - }, - onError: (msg) => { - progressBar.error(msg) - setStatus('status-sp', `Error: ${msg}`, true) - }, - onDone: () => { - btn.disabled = false - }, - }) - }) - .catch(e => { - progressBar.error((e as Error).message) - setStatus('status-sp', `Error: ${(e as Error).message}`, true) - btn.disabled = false - }) - }) -} - -function randomRunId(): string { - return 'r-' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36) -} diff --git a/web/src/workstation/panes/suns-voc-pane.ts b/web/src/workstation/panes/suns-voc-pane.ts index 2cf856f3..639a9ea1 100644 --- a/web/src/workstation/panes/suns-voc-pane.ts +++ b/web/src/workstation/panes/suns-voc-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, SunsVocResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface SunsVocPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -68,13 +69,15 @@ export function mountSunsVocPane(container: HTMLElement, opts: SunsVocPaneOption streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as SunsVocResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as SunsVocResult & { active_physics?: string }) const runResult: RunResult = { kind: 'suns_voc', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/panes/tandem-pane.ts b/web/src/workstation/panes/tandem-pane.ts index 7bbb8035..86d09230 100644 --- a/web/src/workstation/panes/tandem-pane.ts +++ b/web/src/workstation/panes/tandem-pane.ts @@ -4,6 +4,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, readNum, numField } from '../../ui-helpers' import { mountTandemStackVisualizer } from '../../stack/tandem-stack-visualizer' import type { TandemJVPayload, ConfigEntry } from '../../types' +import { extractExecutionPhysics, formatQualificationBadge } from '../execution-physics' /** * Tandem pane — config-path-based workflow (not device-object-based). @@ -17,17 +18,33 @@ function fmt4(v: number): string { return v.toFixed(4) } +function isTandemVocValid(data: TandemJVPayload): boolean { + const m = data.metrics + return ( + m.voc_bracketed !== false && + Number.isFinite(m.V_oc) && + m.open_circuit_voltage_V !== null + ) +} + function renderMetrics(data: TandemJVPayload): string { const m = data.metrics - const jscDisplay = Math.abs(m.J_sc) / 10 - const pceDisplay = m.PCE * 100 + const vocValid = isTandemVocValid(data) + const jscValid = Number.isFinite(m.J_sc) + const jscDisplay = jscValid ? Math.abs(m.J_sc) / 10 : Number.NaN + const pceDisplay = vocValid && Number.isFinite(m.PCE) ? m.PCE * 100 : Number.NaN + + const vocSimStr = vocValid ? `${fmt4(m.V_oc)} V` : 'unavailable (not bracketed)' + const jscSimStr = jscValid ? `${fmt4(jscDisplay)} mA/cm²` : 'unavailable' + const ffSimStr = vocValid && Number.isFinite(m.FF) ? fmt4(m.FF) : '— (V_oc not bracketed)' + const pceSimStr = Number.isFinite(pceDisplay) ? `${fmt4(pceDisplay)} %` : '— (V_oc not bracketed)' const lines: string[] = [ '=== Tandem J-V Metrics ===', - ` V_oc = ${fmt4(m.V_oc)} V`, - ` J_sc = ${fmt4(jscDisplay)} mA/cm²`, - ` FF = ${fmt4(m.FF)}`, - ` PCE = ${fmt4(pceDisplay)} %`, + ` V_oc = ${vocSimStr}`, + ` J_sc = ${jscSimStr}`, + ` FF = ${ffSimStr}`, + ` PCE = ${pceSimStr}`, '', ] @@ -35,10 +52,10 @@ function renderMetrics(data: TandemJVPayload): string { lines.push('--- Benchmark comparison ---') const b = data.benchmark if (b.source) lines.push(` Source: ${b.source}`) - if (b.V_oc != null) lines.push(` V_oc target = ${fmt4(b.V_oc)} V simulated = ${fmt4(m.V_oc)} V`) - if (b.J_sc != null) lines.push(` J_sc target = ${fmt4(b.J_sc)} mA/cm² simulated = ${fmt4(jscDisplay)} mA/cm²`) - if (b.FF != null) lines.push(` FF target = ${fmt4(b.FF)} simulated = ${fmt4(m.FF)}`) - if (b.PCE != null) lines.push(` PCE target = ${fmt4(b.PCE)} % simulated = ${fmt4(pceDisplay)} %`) + if (b.V_oc != null) lines.push(` V_oc target = ${fmt4(b.V_oc)} V simulated = ${vocSimStr}`) + if (b.J_sc != null) lines.push(` J_sc target = ${fmt4(b.J_sc)} mA/cm² simulated = ${jscSimStr}`) + if (b.FF != null) lines.push(` FF target = ${fmt4(b.FF)} simulated = ${ffSimStr}`) + if (b.PCE != null) lines.push(` PCE target = ${fmt4(b.PCE)} % simulated = ${pceSimStr}`) } return lines.join('\n') @@ -118,25 +135,74 @@ export function mountTandemPane(container: HTMLElement): void { const jobId = await startJob('tandem', null, params, configPath) setStatus('status-tandem', 'Running tandem simulation…') - streamJobEvents(jobId, { + streamJobEvents>(jobId, { onProgress: (ev) => progressBar.update(ev), - onResult: (data) => { - setStatus('status-tandem', 'Done') + onResult: (rawData) => { + const { pure: data, receipt } = extractExecutionPhysics(rawData) + const qual = formatQualificationBadge(receipt) + const vocValid = isTandemVocValid(data) + const diagNotes: string[] = [] + if (!vocValid) { + diagNotes.push('Tandem V_oc not bracketed or unavailable') + } + if ((data.failed_points?.length ?? 0) > 0) { + const details = data.failed_points! + .map(fp => `${fp.label ?? `#${fp.index}`} (${fp.reason})`) + .join('; ') + diagNotes.push(`Failed sweep points (${data.failed_points!.length}): ${details}`) + } + + if (diagNotes.length > 0) { + setStatus('status-tandem', `Done · Diagnostics: ${diagNotes.join(' | ')}`, true) + } else { + setStatus('status-tandem', 'Done') + } + progressBar.done() + if (data.top_layers || data.bot_layers) { stackViz.update(data.top_layers ?? [], data.bot_layers ?? []) } else { stackViz.clear() } + + resultsEl.replaceChildren() + const metaBar = document.createElement('div') + metaBar.className = 'tandem-execution-meta' + const manifestSpan = document.createElement('span') + manifestSpan.setAttribute('data-test', 'tandem-manifest-badge') + manifestSpan.title = receipt.summary + manifestSpan.textContent = receipt.badgeLabel + const qualSpan = document.createElement('span') + qualSpan.setAttribute('data-test', 'tandem-qualification-badge') + qualSpan.setAttribute('data-qualified', String(qual.qualified)) + qualSpan.title = qual.detail + qualSpan.textContent = qual.label + metaBar.append(manifestSpan, document.createTextNode(' · '), qualSpan) + resultsEl.appendChild(metaBar) + + if (diagNotes.length > 0) { + const warnBanner = document.createElement('div') + warnBanner.className = 'jv2d-warning' + warnBanner.setAttribute('role', 'alert') + warnBanner.setAttribute('data-test', 'tandem-diagnostic-warning') + warnBanner.textContent = diagNotes.join(' | ') + resultsEl.appendChild(warnBanner) + } + const pre = document.createElement('pre') pre.className = 'tandem-metrics-pre' pre.style.cssText = 'font-size:0.85rem;line-height:1.5;background:var(--surface-1,#1e1e2e);padding:12px;border-radius:6px;overflow:auto;' pre.textContent = renderMetrics(data) - resultsEl.innerHTML = '' resultsEl.appendChild(pre) }, onError: (msg) => { + progressBar.error(msg) setStatus('status-tandem', `Error: ${msg}`, true) - resultsEl.innerHTML = `
${msg}
` + const errPre = document.createElement('pre') + errPre.className = 'tandem-metrics-pre' + errPre.style.color = 'var(--error,#f38ba8)' + errPre.textContent = msg + resultsEl.replaceChildren(errPre) }, onDone: () => { btn.disabled = false @@ -144,8 +210,13 @@ export function mountTandemPane(container: HTMLElement): void { }) } catch (e: unknown) { const msg = e instanceof Error ? e.message : String(e) + progressBar.error(msg) setStatus('status-tandem', `Error: ${msg}`, true) - resultsEl.innerHTML = `
${msg}
` + const errPre = document.createElement('pre') + errPre.className = 'tandem-metrics-pre' + errPre.style.color = 'var(--error,#f38ba8)' + errPre.textContent = msg + resultsEl.replaceChildren(errPre) btn.disabled = false } }) diff --git a/web/src/workstation/panes/tpv-pane.ts b/web/src/workstation/panes/tpv-pane.ts index facf4fcb..999e9317 100644 --- a/web/src/workstation/panes/tpv-pane.ts +++ b/web/src/workstation/panes/tpv-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, TPVResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface TPVPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -97,18 +98,37 @@ export function mountTPVPane(container: HTMLElement, opts: TPVPaneOptions): void streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as TPVResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as TPVResult & { active_physics?: string }) const runResult: RunResult = { kind: 'tpv', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } opts.onRunComplete(active.id, run) progressBar.done() + const nonIdReason = pure.non_identifiable_reason ?? pure.fit?.non_identifiable_reason ?? null + const tauInvalid = + pure.tau === null || + !Number.isFinite(pure.tau) || + pure.tau <= 0 || + Boolean(nonIdReason) || + Boolean(pure.fit && pure.fit.status !== 'accepted') || + Boolean(pure.valid?.includes(false)) + if (tauInvalid || !Number.isFinite(pure.V_oc)) { + const reason = + nonIdReason ?? + (pure.fit && pure.fit.status !== 'accepted' ? pure.fit.status : null) ?? + (pure.valid?.includes(false) ? 'invalid trajectory points' : null) ?? + (!Number.isFinite(pure.V_oc) ? 'V_oc unavailable' : 'non-identifiable decay') + setStatus('status-tpv', `Done · τ non-identifiable (${reason})`, true) + return + } setStatus('status-tpv', 'Done') }, onError: showError, diff --git a/web/src/workstation/panes/voc-grain-sweep-pane.ts b/web/src/workstation/panes/voc-grain-sweep-pane.ts index d32d9192..b79d7ace 100644 --- a/web/src/workstation/panes/voc-grain-sweep-pane.ts +++ b/web/src/workstation/panes/voc-grain-sweep-pane.ts @@ -10,6 +10,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, VocGrainSweepResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface VocGrainSweepPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -103,24 +104,45 @@ export function mountVocGrainSweepPane( streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = - result as VocGrainSweepResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics( + result as VocGrainSweepResult & { active_physics?: string }, + ) const runResult: RunResult = { kind: 'voc_grain_sweep', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } opts.onRunComplete(active.id, run) progressBar.done() + const validVoc = pure.V_oc_V.filter( + (v, i) => v != null && Number.isFinite(v) && pure.voc_bracketed?.[i] !== false, + ) + const invalidCount = + Math.max( + pure.grain_sizes_nm.length - validVoc.length, + pure.failed_points?.length ?? 0, + ) + const rangeText = + validVoc.length > 0 + ? `V_oc range ${(Math.min(...validVoc) * 1e3).toFixed(1)}–${(Math.max(...validVoc) * 1e3).toFixed(1)} mV` + : 'V_oc unavailable' + if (invalidCount > 0) { + setStatus( + 'status-vgs', + `Done · ${pure.grain_sizes_nm.length} grain sizes · ${rangeText} · Diagnostics: ${invalidCount} failed/unbracketed point(s)`, + true, + ) + return + } setStatus( 'status-vgs', - `Done · ${pure.grain_sizes_nm.length} grain sizes · ` + - `V_oc range ${(Math.min(...pure.V_oc_V) * 1e3).toFixed(1)}–` + - `${(Math.max(...pure.V_oc_V) * 1e3).toFixed(1)} mV`, + `Done · ${pure.grain_sizes_nm.length} grain sizes · ${rangeText}`, ) }, onError: (msg) => { diff --git a/web/src/workstation/panes/voc-t-pane.ts b/web/src/workstation/panes/voc-t-pane.ts index cbca4714..70122caa 100644 --- a/web/src/workstation/panes/voc-t-pane.ts +++ b/web/src/workstation/panes/voc-t-pane.ts @@ -3,6 +3,7 @@ import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, VocTResult } from '../../types' import type { Run, RunResult } from '../types' +import { extractExecutionPhysics } from '../execution-physics' export interface VocTPaneOptions { getActiveDevice: () => { id: string; config: DeviceConfig } | null @@ -62,13 +63,15 @@ export function mountVocTPane(container: HTMLElement, opts: VocTPaneOptions): vo streamJobEvents(jobId, { onProgress: (ev) => progressBar.update(ev), onResult: (result) => { - const { active_physics, ...pure } = result as VocTResult & { active_physics?: string } + const { pure, receipt } = extractExecutionPhysics(result as VocTResult & { active_physics?: string }) const runResult: RunResult = { kind: 'voc_t', data: pure } const run: Run = { id: randomRunId(), timestamp: Date.now(), result: runResult, - activePhysics: active_physics ?? 'unknown', + activePhysics: receipt.summary, + executionPhysics: receipt, + scientificQualification: receipt.scientificQualification, durationMs: performance.now() - t0, deviceSnapshot: snapshot, } diff --git a/web/src/workstation/schema-handshake.ts b/web/src/workstation/schema-handshake.ts new file mode 100644 index 00000000..fc2f765e --- /dev/null +++ b/web/src/workstation/schema-handshake.ts @@ -0,0 +1,330 @@ +/** + * Workstation startup schema & execution-catalog digest handshake (P06-07). + * + * Verifies that generated frontend DTO metadata (`configurationSchemaSha256`) + * and backend `/configuration-schema` + `/experiments` (`X-Solarlab-Registry`, + * `X-Solarlab-Job-Schema`, `ETag`) agree on exact SHA-256 content digests. + * Any digest or contract mismatch surfaces an explicit `[role="alert"]` + * diagnostic banner and refuses silent field dropping or coercion. + */ +import { + configurationSchema, + configurationSchemaSha256, + type ConfigurationSchemaMetadata, +} from '../generated/configuration-schema' +import { ConfigurationSchemaError, fetchConfigurationSchema } from '../schema-client' + +const SHA256_HEX = /^[a-f0-9]{64}$/ + +export interface VerifiedCatalogIdentity { + readonly registrySha256: string + readonly jobSchemaSha256: string + readonly modelRegistrySha256: string + readonly bindingsCount: number + readonly bindingIds: readonly string[] +} + +export type WorkstationHandshakeResult = + | { + readonly status: 'verified' + readonly configurationSchemaSha256: string + readonly metadata: ConfigurationSchemaMetadata + readonly catalog: VerifiedCatalogIdentity | null + } + | { + readonly status: 'mismatch' + readonly code: 'identity_mismatch' | 'malformed' | 'catalog_mismatch' + readonly message: string + readonly expectedConfigurationSchemaSha256: string + readonly receivedRegistrySha256?: string + readonly receivedJobSchemaSha256?: string + } + | { + readonly status: 'error' + readonly code: 'verification_unavailable' | 'http' + readonly message: string + readonly expectedConfigurationSchemaSha256: string + } + | { + readonly status: 'unavailable' + readonly reason: string + readonly expectedConfigurationSchemaSha256: string + } + +export interface WorkstationHandshakeOptions { + readonly schemaEndpoint?: string | URL + readonly experimentsEndpoint?: string | URL +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +async function sha256Hex(bytes: ArrayBuffer): Promise { + const subtle = globalThis.crypto?.subtle + if (!subtle || typeof subtle.digest !== 'function') return null + const digest = await subtle.digest('SHA-256', bytes) + return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('') +} + +async function probeCatalogIdentity( + endpoint: string | URL, +): Promise< + | { kind: 'ok'; catalog: VerifiedCatalogIdentity } + | { kind: 'unavailable' } + | { + kind: 'mismatch' + message: string + receivedRegistrySha256?: string + receivedJobSchemaSha256?: string + } + | { kind: 'error'; message: string } +> { + let response: Response + try { + response = await fetch(endpoint) + } catch { + return { kind: 'unavailable' } + } + + if (response.status === 404 || response.status === 503) { + return { kind: 'unavailable' } + } + if (response.status === 409) { + return { + kind: 'mismatch', + message: 'Backend reported HTTP 409 schema_registry_mismatch on /experiments.', + } + } + if (!response.ok) { + return { + kind: 'error', + message: `Execution catalog probe failed with HTTP ${response.status}.`, + } + } + + const registryHeader = response.headers.get('X-Solarlab-Registry') ?? '' + const jobSchemaHeader = response.headers.get('X-Solarlab-Job-Schema') ?? '' + const etagHeader = response.headers.get('ETag') ?? response.headers.get('etag') ?? '' + + if (!SHA256_HEX.test(registryHeader) || !SHA256_HEX.test(jobSchemaHeader)) { + return { + kind: 'mismatch', + message: + 'Execution catalog response is missing valid SHA-256 X-Solarlab-Registry or X-Solarlab-Job-Schema headers.', + receivedRegistrySha256: registryHeader || undefined, + receivedJobSchemaSha256: jobSchemaHeader || undefined, + } + } + + const bytes = await response.arrayBuffer() + const bodyDigest = await sha256Hex(bytes) + if (bodyDigest === null) { + return { + kind: 'error', + message: 'WebCrypto SHA-256 digest is unavailable for execution catalog verification.', + } + } + if (bodyDigest !== registryHeader) { + return { + kind: 'mismatch', + message: `Execution catalog payload digest (${bodyDigest.slice(0, 12)}…) does not match X-Solarlab-Registry (${registryHeader.slice(0, 12)}…).`, + receivedRegistrySha256: registryHeader, + receivedJobSchemaSha256: jobSchemaHeader, + } + } + if (etagHeader && etagHeader !== `"${registryHeader}"`) { + return { + kind: 'mismatch', + message: `Execution catalog ETag (${etagHeader}) disagrees with X-Solarlab-Registry ("${registryHeader.slice(0, 12)}…").`, + receivedRegistrySha256: registryHeader, + receivedJobSchemaSha256: jobSchemaHeader, + } + } + + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) + } catch { + return { + kind: 'mismatch', + message: 'Execution catalog payload is not valid UTF-8 JSON.', + receivedRegistrySha256: registryHeader, + receivedJobSchemaSha256: jobSchemaHeader, + } + } + + if ( + !isRecord(parsed) || + parsed.schema !== 'solarlab.execution-catalog.v1' || + parsed.job_schema_sha256 !== jobSchemaHeader || + !SHA256_HEX.test(String(parsed.model_registry_sha256 ?? '')) || + !Array.isArray(parsed.bindings) + ) { + return { + kind: 'mismatch', + message: + 'Execution catalog body disagrees with X-Solarlab-Job-Schema or lacks required solarlab.execution-catalog.v1 fields.', + receivedRegistrySha256: registryHeader, + receivedJobSchemaSha256: jobSchemaHeader, + } + } + + const bindingIds = parsed.bindings + .filter(isRecord) + .map(b => String(b.experiment_id ?? '')) + .filter(Boolean) + + return { + kind: 'ok', + catalog: Object.freeze({ + registrySha256: registryHeader, + jobSchemaSha256: jobSchemaHeader, + modelRegistrySha256: String(parsed.model_registry_sha256), + bindingsCount: parsed.bindings.length, + bindingIds: Object.freeze(bindingIds), + }), + } +} + +export async function verifyWorkstationHandshake( + options: WorkstationHandshakeOptions = {}, +): Promise { + if (typeof globalThis.fetch !== 'function') { + return { + status: 'unavailable', + reason: 'fetch is not available in this environment', + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + + const schemaEndpoint = options.schemaEndpoint ?? '/configuration-schema' + const experimentsEndpoint = options.experimentsEndpoint ?? '/experiments' + + let metadata: ConfigurationSchemaMetadata | null = null + let schemaUnavailableReason: string | null = null + + try { + metadata = await fetchConfigurationSchema(schemaEndpoint) + if (metadata.schema_version !== configurationSchema.schema_version) { + return { + status: 'mismatch', + code: 'identity_mismatch', + message: `Configuration schema version "${String(metadata.schema_version)}" does not match client "${configurationSchema.schema_version}".`, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + } catch (err) { + if (err instanceof ConfigurationSchemaError) { + if (err.code === 'identity_mismatch' || err.code === 'malformed') { + return { + status: 'mismatch', + code: err.code, + message: err.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + if (err.code === 'verification_unavailable') { + return { + status: 'error', + code: 'verification_unavailable', + message: err.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + if (err.code === 'http') { + if (/\bHTTP (404|503)\b/.test(err.message)) { + schemaUnavailableReason = err.message + } else if (/\bHTTP 409\b/.test(err.message)) { + return { + status: 'mismatch', + code: 'identity_mismatch', + message: err.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } else { + return { + status: 'error', + code: 'http', + message: err.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + } + } else { + schemaUnavailableReason = err instanceof Error ? err.message : String(err) + } + } + + const catalogResult = await probeCatalogIdentity(experimentsEndpoint) + if (catalogResult.kind === 'mismatch') { + return { + status: 'mismatch', + code: 'catalog_mismatch', + message: catalogResult.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + receivedRegistrySha256: catalogResult.receivedRegistrySha256, + receivedJobSchemaSha256: catalogResult.receivedJobSchemaSha256, + } + } + if (catalogResult.kind === 'error') { + return { + status: 'error', + code: 'http', + message: catalogResult.message, + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + + if (metadata === null) { + return { + status: 'unavailable', + reason: schemaUnavailableReason ?? 'Configuration schema endpoint is not mounted', + expectedConfigurationSchemaSha256: configurationSchemaSha256, + } + } + + return { + status: 'verified', + configurationSchemaSha256, + metadata, + catalog: catalogResult.kind === 'ok' ? catalogResult.catalog : null, + } +} + +export function renderHandshakeBanner( + host: HTMLElement, + result: WorkstationHandshakeResult, +): void { + while (host.firstChild) host.removeChild(host.firstChild) + host.dataset.handshakeStatus = result.status + + if (result.status === 'verified') { + host.hidden = true + host.dataset.schemaSha256 = result.configurationSchemaSha256 + host.dataset.registrySha256 = result.catalog?.registrySha256 ?? '' + host.dataset.jobSchemaSha256 = result.catalog?.jobSchemaSha256 ?? '' + return + } + + if (result.status === 'unavailable') { + host.hidden = true + host.dataset.schemaSha256 = result.expectedConfigurationSchemaSha256 + return + } + + host.hidden = false + const banner = document.createElement('div') + banner.className = 'jv2d-warning schema-handshake-alert' + banner.setAttribute('role', 'alert') + banner.setAttribute('data-test', 'schema-handshake-alert') + banner.dataset.handshakeCode = result.code + const prefix = + result.status === 'mismatch' + ? 'Schema / registry version mismatch' + : 'Schema identity verification error' + banner.textContent = + `${prefix} (client DTO sha256:${result.expectedConfigurationSchemaSha256.slice(0, 12)}…): ` + + `${result.message} Silent field dropping or coercion is refused; reload or rebuild client DTOs to match the backend.` + host.appendChild(banner) +} diff --git a/web/src/workstation/shell.ts b/web/src/workstation/shell.ts index c558eff5..2b22774e 100644 --- a/web/src/workstation/shell.ts +++ b/web/src/workstation/shell.ts @@ -8,6 +8,7 @@ import { addExperiment, addRun, createEmptyWorkspace, + findRun, loadWorkspace, saveWorkspace, setActiveDevice, @@ -28,6 +29,15 @@ import type { MainPlotHandle } from './panes/main-plot-pane' import { presetsFromEntries, showWizard } from './wizard' import { configureDockLayout, restoreLayoutConfig } from './layout-persistence' import { bindMobileSidebarToggle } from './mobile-sidebar' +import { + renderHandshakeBanner, + verifyWorkstationHandshake, + type WorkstationHandshakeOptions, +} from './schema-handshake' +import { + formatQualificationBadge, + resolveRunExecutionPhysics, +} from './execution-physics' const DEFAULT_LAYOUT: LayoutConfig = { root: { @@ -72,7 +82,10 @@ function randomExperimentId(): string { return 'e-' + Math.random().toString(36).slice(2, 10) } -export async function mountWorkstation(root: HTMLElement): Promise { +export async function mountWorkstation( + root: HTMLElement, + options?: { handshake?: WorkstationHandshakeOptions }, +): Promise { root.innerHTML = `
@@ -80,6 +93,7 @@ export async function mountWorkstation(root: HTMLElement): Promise {

Solar cell simulator

+ Configuration · V2 DTO Steady J–V · new core 2D steady · new core Transient · new core @@ -88,12 +102,14 @@ export async function mountWorkstation(root: HTMLElement): Promise {
+
` + const handshakeHost = root.querySelector('#ws-handshake-banner')! const treeEl = root.querySelector('#ws-tree')! const dockEl = root.querySelector('#ws-dock')! const consoleEl = root.querySelector('#ws-console')! @@ -102,6 +118,13 @@ export async function mountWorkstation(root: HTMLElement): Promise { const consoleHandle: ConsoleHandle = mountConsole(consoleEl) + void verifyWorkstationHandshake(options?.handshake).then(handshake => { + renderHandshakeBanner(handshakeHost, handshake) + if (handshake.status === 'mismatch' || handshake.status === 'error') { + consoleHandle.log('Schema handshake error', handshake.message) + } + }) + // --- workspace state --- let workspace: Workspace = loadWorkspace() ?? createEmptyWorkspace('Untitled') if (workspace.devices.length === 0) { @@ -154,15 +177,45 @@ export async function mountWorkstation(root: HTMLElement): Promise { return id } + function syncConsolePhysics(): void { + if (workspace.activeDeviceId && workspace.activeExperimentId && workspace.activeRunId) { + const activeRun = findRun( + workspace, + workspace.activeDeviceId, + workspace.activeExperimentId, + workspace.activeRunId, + ) + if (activeRun) { + const receipt = resolveRunExecutionPhysics(activeRun) + const qual = formatQualificationBadge(receipt) + consoleHandle.setPhysics( + `${receipt.badgeLabel}${qual.explicitUnqualified ? ' · UNQUALIFIED' : ''}`, + `${receipt.summary} — ${qual.label}`, + ) + return + } + } + const active = workspace.devices.find(d => d.id === workspace.activeDeviceId) + if (active) { + consoleHandle.setPhysics( + `DECLARED (${tierLabel(active.tier)})`, + `Pre-run legacy mode declaration (not an execution manifest): ${tierPhysicsSummary(active.tier)}`, + ) + } + } + function commitRun(deviceId: string, kind: ExperimentKind, run: Run): void { const expId = ensureExperiment(deviceId, kind) workspace = addRun(workspace, deviceId, expId, run) workspace = setActiveRun(workspace, deviceId, expId, run.id) saveWorkspace(workspace) refreshTree() + syncConsolePhysics() mainPlot?.update(workspace) focusComponent('main-plot') - consoleHandle.log('Run complete', `${kind} · ${run.activePhysics}`) + const receipt = resolveRunExecutionPhysics(run) + const qual = formatQualificationBadge(receipt) + consoleHandle.log('Run complete', `${kind} · ${receipt.summary} · ${qual.label}`) } function focusComponent(componentType: string): void { @@ -186,8 +239,8 @@ export async function mountWorkstation(root: HTMLElement): Promise { if (active) { devicePanel?.setConfig(active.config) experimentPane?.updateDevice() - consoleHandle.setPhysics(tierLabel(active.tier), tierPhysicsSummary(active.tier)) } + syncConsolePhysics() } attachTreeHandlers(treeEl, { @@ -218,11 +271,8 @@ export async function mountWorkstation(root: HTMLElement): Promise { }, }) - // --- physics indicator for the initially-active device --- - const initialActive = workspace.devices.find(d => d.id === workspace.activeDeviceId) - if (initialActive) { - consoleHandle.setPhysics(tierLabel(initialActive.tier), tierPhysicsSummary(initialActive.tier)) - } + // --- physics indicator for the initially-active run or declared device --- + syncConsolePhysics() // --- Golden Layout --- const layout = new GoldenLayout(dockEl) @@ -252,7 +302,7 @@ export async function mountWorkstation(root: HTMLElement): Promise { experimentPane?.updateDevice(reason === 'preset') saveWorkspace(workspace) refreshTree() - consoleHandle.setPhysics(tierLabel(updated.tier), tierPhysicsSummary(updated.tier)) + syncConsolePhysics() }) }) }) diff --git a/web/src/workstation/tree.ts b/web/src/workstation/tree.ts index d3e18e6f..25d4a251 100644 --- a/web/src/workstation/tree.ts +++ b/web/src/workstation/tree.ts @@ -1,5 +1,10 @@ import type { Workspace, Device, Experiment, Run } from './types' import { describeActivePhysics } from '../active-physics' +import { getExperimentTreeLabelHTML } from './experiment-catalog' +import { + formatQualificationBadge, + resolveRunExecutionPhysics, +} from './execution-physics' function escapeHtml(s: string): string { return s @@ -11,45 +16,16 @@ function escapeHtml(s: string): string { } /** - * Compact tier badge with a hover tooltip that previews the active- - * physics summary that the device's current tier + parameters will - * activate at run time. The tooltip mirrors ``describeActivePhysics`` - * (frontend) and ``backend/main.py:_describe_active_physics`` so the - * pre-run preview matches the post-run truth in shape if not in - * verbosity. Visible text stays at the original 4-character tier name - * to avoid disturbing the tree-row layout. + * Compact pre-run legacy tier badge for a declared device configuration. + * Tooltip explicitly distinguishes pre-run declared parameters from post-run + * backend execution manifests. */ function tierBadge(d: Device): string { const tier = d.tier - const physics = describeActivePhysics(d.config) + const physics = `Pre-run declared configuration (not an execution manifest) — ${describeActivePhysics(d.config)}` return `${tier.toUpperCase()}` } -/** - * Returns experiment label as HTML. May contain tags for subscript - * typography (V_oc, L_g, J_0, etc.). Strings are hard-coded source - * constants, so callers can inject the result as innerHTML directly. - */ -function experimentLabelHTML(kind: Experiment['kind']): string { - switch (kind) { - case 'jv': return 'J–V Sweep' - case 'impedance': return 'Impedance' - case 'dynamic_defect_transient': return 'Defect–Ion Transient' - case 'degradation': return 'Degradation' - case 'tpv': return 'TPV' - case 'current_decomp': return 'Current Decomp.' - case 'spatial': return 'Spatial Profiles' - case 'dark_jv': return 'Dark J–V' - case 'suns_voc': return 'Suns–Voc' - case 'voc_t': return 'Voc(T)' - case 'eqe': return 'EQE / IPCE' - case 'el': return 'EL / ΔVnr' - case 'mott_schottky': return 'Mott–Schottky (C–V)' - case 'jv_2d': return 'J–V Sweep (2D)' - case 'voc_grain_sweep': return 'Voc(Lg) Grain Sweep' - } -} - function runLabel(r: Run): string { const t = new Date(r.timestamp) const hh = String(t.getHours()).padStart(2, '0') @@ -57,15 +33,31 @@ function runLabel(r: Run): string { return `Run ${hh}:${mm}` } +function runExecutionBadge(r: Run): string { + const receipt = resolveRunExecutionPhysics(r) + const qual = formatQualificationBadge(receipt) + const title = `${receipt.summary} | ${qual.detail}` + if (qual.explicitUnqualified) { + return `PREVIEW` + } + if (receipt.source === 'execution_manifest' || receipt.source === 'worker_result') { + return `MANIFEST` + } + return '' +} + function renderRun(deviceId: string, experimentId: string, r: Run, activeRunId: string | null): string { const active = r.id === activeRunId ? ' tree-node-active' : '' + const receipt = resolveRunExecutionPhysics(r) return `
+ data-run-id="${escapeHtml(r.id)}" + title="${escapeHtml(receipt.summary)}"> ▶ ${escapeHtml(runLabel(r))} + ${runExecutionBadge(r)}
` } @@ -77,7 +69,7 @@ function renderExperiment(deviceId: string, e: Experiment, ws: Workspace): strin data-device-id="${escapeHtml(deviceId)}" data-experiment-id="${escapeHtml(e.id)}"> 🧪 - ${experimentLabelHTML(e.kind)} + ${getExperimentTreeLabelHTML(e.kind)}
${runs}
` } diff --git a/web/src/workstation/types.ts b/web/src/workstation/types.ts index df0b51c2..f352fbd0 100644 --- a/web/src/workstation/types.ts +++ b/web/src/workstation/types.ts @@ -17,6 +17,7 @@ import type { JV2DResult, VocGrainSweepResult, } from '../types' +import type { ExecutionPhysicsReceipt } from './execution-physics' /** The root object persisted to localStorage. */ export interface Workspace { @@ -96,6 +97,10 @@ export interface Run { timestamp: number result: RunResult activePhysics: string + /** Authoritative backend execution-manifest / worker receipt (P06-08). */ + executionPhysics?: ExecutionPhysicsReceipt + /** Explicit backend scientific qualification flag (`false` for compatibility/engineering runs). */ + scientificQualification?: boolean | null durationMs: number /** Frozen DeviceConfig snapshot at the moment the run was dispatched. */ deviceSnapshot: DeviceConfig From 02ef9da2731b72756e822bacb40566f14fcff5a6 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 12 Nov 2026 23:37:52 +0800 Subject: [PATCH 11/46] [N] Add P04-13 systems/tandem and P05-04a open-circuit/TPV/degradation experiments - P04-13 external circuit, thermal balance, electrothermal, and 2T tandem: - external_circuit.py: post-processing and strict self-consistent forward/reverse monotone J-V wrappers for R_series and R_shunt without altering bulk PDEs. - thermal_balance.py: 0D module energy balance (Q_in = P_elec + Q_conv + Q_rad), convective/radiative linearized derivatives, and Brent equilibrium T_eq solver. - electrothermal.py: fresh-state-per-temperature isothermal J-V family (steady_jv and transient_jv_strict with mobile ions) and bracketed Brent operating-point energy-balance closure across device_plus_lumped_parasitics. - tandem_jv.py: full-stack joint TMM optics across [top, junction, bottom, back_reflector] with spectral photon-budget closure and parasitic exclusion, per-subcell electrical compilation with distinct identities, and Kirchhoff series-matched 2T J-V synthesis. - P05-04a charge-conserving open-circuit, TPV, and degradation snapshots: - open_circuit.py: bordered sparse (M + 1) floating-terminal Backward Euler integrator enforcing Gauss-Maxwell total port current I_carrier + I_ion + dD/dt = 0 on all faces and telescoping port-charge conservation. - tpv.py: explicit steady (ion-free) or finite-time soaked (mobile-ion) preconditioning, paired pulsed vs unpulsed control subtraction on identical time grids, and gated single-exponential decay extraction refusing truncated, non-monotonic, or multi-exponential traces. - degradation.py: frozen-ion electronic snapshot J-V sweeps preserving exact pointwise ion densities across all single/dual/shared-site species and coupled irreversible stress-damage absorber rebind snapshots. - Add 18 unit, integration, conservation, and live legacy-parity tests. --- src/solarlab/experiments/degradation.py | 1098 ++++++++++++++++ src/solarlab/experiments/electrothermal.py | 1109 +++++++++++++++++ src/solarlab/experiments/external_circuit.py | 705 +++++++++++ src/solarlab/experiments/open_circuit.py | 761 +++++++++++ src/solarlab/experiments/tandem_jv.py | 871 +++++++++++++ src/solarlab/experiments/thermal_balance.py | 638 ++++++++++ src/solarlab/experiments/tpv.py | 651 ++++++++++ .../integration/test_degradation_snapshots.py | 165 +++ .../test_external_circuit_electrothermal.py | 356 ++++++ tests/integration/test_tandem_jv.py | 310 +++++ tests/integration/test_tpv_open_circuit.py | 204 +++ .../experiments/test_systems_and_tpv_p05.py | 297 +++++ 12 files changed, 7165 insertions(+) create mode 100644 src/solarlab/experiments/degradation.py create mode 100644 src/solarlab/experiments/electrothermal.py create mode 100644 src/solarlab/experiments/external_circuit.py create mode 100644 src/solarlab/experiments/open_circuit.py create mode 100644 src/solarlab/experiments/tandem_jv.py create mode 100644 src/solarlab/experiments/thermal_balance.py create mode 100644 src/solarlab/experiments/tpv.py create mode 100644 tests/integration/test_degradation_snapshots.py create mode 100644 tests/integration/test_external_circuit_electrothermal.py create mode 100644 tests/integration/test_tandem_jv.py create mode 100644 tests/integration/test_tpv_open_circuit.py create mode 100644 tests/unit/experiments/test_systems_and_tpv_p05.py diff --git a/src/solarlab/experiments/degradation.py b/src/solarlab/experiments/degradation.py new file mode 100644 index 00000000..a85f9f7e --- /dev/null +++ b/src/solarlab/experiments/degradation.py @@ -0,0 +1,1098 @@ +"""Coupled ionic-stress degradation trajectories and frozen-ion J-V snapshots. + +Contract (P05-04 clause 3): +1. Between snapshot times ``t_eval_s``, the live ``CompiledIonicDevice1D`` + evolves under constant electrical bias ``V_bias_V`` and illumination + ``generation_scale`` via conservative Backward Euler steps of size + ``<= dt_max_s``. +2. At each snapshot ``t_k``: + - ``freeze_prepared_ions`` constructs an immobile-ion projection + (``D_ion = 0``, ``D_ion_neg = 0``) that preserves ``P0``, ``P0_neg``, + ``P_lim``, ``P_lim_neg``, and ``ion_site_contract`` bit-for-bit. + - ``measure_frozen_ion_snapshot`` solves the stationary ``3 * N`` electronic + system across ``probe_voltages_V`` against the exact frozen spatial ion + coordinate slice ``u_ion = state.u[3*N:]``, verifying 0-ULP ion-profile + invariance, identically zero ionic flux ``J_ion == 0``, and spatial current + continuity on every probe bias. +3. Material parameters (absorber ``tau_n``, ``tau_p``) are cold-rebound ONLY + when irreversible ``damage`` actually changes; zero-damage trajectories + perform zero redundant material rebinds (``material_rebind_count == 0``). +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any, cast + +import numpy as np +from scipy.sparse import csc_matrix + +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.ionic_1d import AssembledIonic1DProblem +from solarlab.equations.dc_1d import DC1DProblem +from solarlab.equations.implementation import use_assembled +from solarlab.equations.ionic_1d import ( + CompiledIonicDevice1D, + Ionic1DProblem, + IonicState1D, +) +from solarlab.experiments.electrothermal import has_declared_ions +from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics +from solarlab.solvers.nonlinear.ionic_1d import ( + IonicSteadyOptions, + solve_ionic_steady_state, +) +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import ( + CallableProblem, + Matrix, + ResidualScaling, + SolveBudget, + StepControl, +) +from solarlab.solvers.nonlinear.production import ( + HISTORICAL_MAX_ROW_V1, + POISSON_CONTACT_BALANCE_V1, + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions +from solarlab.solvers.time.assembled_ionic_backward_euler import ( + AssembledIonicBackwardEuler1DStep, +) +from solarlab.solvers.time.backward_euler import BackwardEuler1DStep +from solarlab.solvers.time.carrier_seed import transient_density_basin_seed +from solarlab.solvers.time.ionic_backward_euler import ( + IonicBackwardEuler1DStep, + step_accounting as ionic_step_accounting, +) + +__all__ = [ + "DegradationDamageProtocol", + "DegradationError", + "DegradationProtocol", + "DegradationResult", + "FrozenIonSnapshot", + "apply_absorber_damage", + "freeze_prepared_ions", + "measure_frozen_ion_snapshot", + "run_degradation", +] + + +class DegradationError(RuntimeError): + """Failed ionic stress step or frozen-ion snapshot certification.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +@dataclass(frozen=True) +class DegradationDamageProtocol: + """Optional irreversible ion-motion / pileup lifetime degradation law.""" + + motion_gain_m2_C: float = 0.0 + segregation_gain_s_1: float = 0.0 + lifetime_degradation_alpha: float = 1.0 + damage_rebind_threshold: float = 0.0 + + def __post_init__(self) -> None: + for name in ( + "motion_gain_m2_C", + "segregation_gain_s_1", + "lifetime_degradation_alpha", + "damage_rebind_threshold", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) < 0.0: + raise ValueError(f"{name} must be finite and >= 0") + object.__setattr__(self, name, float(raw)) + + +@dataclass(frozen=True) +class DegradationProtocol: + """Explicit constant-bias stress and frozen-ion J-V snapshot controls.""" + + V_bias_V: float = 0.9 + generation_scale: float = 1.0 + probe_generation_scale: float = 1.0 + precondition_time_s: float = 1e-3 + dt_max_s: float = 1.0 + settle_time_s: float = 0.0 + settle_steps: int = 4 + n_jv_points: int = 31 + V_max_V: float = 1.3 + incident_power_W_m2: float = 1000.0 + intervals_per_layer: int = 24 + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] | None = None + damage_protocol: DegradationDamageProtocol = DegradationDamageProtocol() + poisson_tolerance: float = 1e-10 + continuity_tolerance_A_m2: float = 1e-7 + contact_log_tolerance: float = 1e-12 + max_current_error_A_m2: float = 1e-6 + ion_balance_tolerance_m2_s: float = 1e10 + + def __post_init__(self) -> None: + if not _is_real_number(self.V_bias_V) or not math.isfinite(float(self.V_bias_V)): + raise ValueError("V_bias_V must be a finite real scalar") + object.__setattr__(self, "V_bias_V", float(self.V_bias_V)) + + for name in ( + "generation_scale", + "probe_generation_scale", + "precondition_time_s", + "settle_time_s", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) < 0.0: + raise ValueError(f"{name} must be finite and >= 0") + object.__setattr__(self, name, float(raw)) + + for name in ( + "dt_max_s", + "V_max_V", + "incident_power_W_m2", + "poisson_tolerance", + "continuity_tolerance_A_m2", + "contact_log_tolerance", + "max_current_error_A_m2", + "ion_balance_tolerance_m2_s", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ValueError(f"{name} must be finite and > 0") + object.__setattr__(self, name, float(raw)) + + if type(self.settle_steps) is not int or self.settle_steps < 1: + raise ValueError("settle_steps must be a positive integer") + if type(self.n_jv_points) is not int or self.n_jv_points < 3: + raise ValueError("n_jv_points must be an integer >= 3") + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if not isinstance(self.damage_protocol, DegradationDamageProtocol): + raise TypeError("damage_protocol must be a DegradationDamageProtocol") + + +@dataclass(frozen=True) +class FrozenIonSnapshot: + """Certified stationary electronic J-V probe at frozen spatial ion profiles.""" + + time_s: float + damage: float + voltage_V: np.ndarray + output_current_A_m2: np.ndarray + metrics: SteadyJVMetrics + positive_ion_density_m3: np.ndarray + negative_ion_density_m3: np.ndarray + positive_reference_m3: np.ndarray + negative_reference_m3: np.ndarray + max_ion_flux_m2_s: float + max_current_spread_A_m2: float + frozen_profile_exact: bool + live_compiled_identity: str + frozen_compiled_identity: str + + +@dataclass(frozen=True) +class DegradationResult: + """Time series of frozen-ion J-V snapshots under coupled ionic stress.""" + + t_s: np.ndarray + V_oc_V: np.ndarray + J_sc_A_m2: np.ndarray + FF: np.ndarray + PCE: np.ndarray + damage: np.ndarray + snapshots: tuple[FrozenIonSnapshot, ...] + material_rebind_count: int + snapshot_live_compiled_identities: tuple[str, ...] + snapshot_frozen_compiled_identities: tuple[str, ...] + base_prepared_sha256: str + result_sha256: str + + +def freeze_prepared_ions(prepared: PreparedDevice) -> PreparedDevice: + """Return a cold-resolved ``PreparedDevice`` with ``D_ion = D_ion_neg = 0``. + + Preserves ``P0``, ``P0_neg``, ``P_lim``, ``P_lim_neg``, and steric flags + unchanged so compensating background charge and finite-site coordinate maps + match the live ionic device bit-for-bit. + """ + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice") + editing = prepared.to_input().editing_data() + for mat in editing.get("materials", ()): + mat_p = mat.get("parameters") + if isinstance(mat_p, dict): + if "D_ion" in mat_p: + mat_p["D_ion"] = 0.0 + if "D_ion_neg" in mat_p: + mat_p["D_ion_neg"] = 0.0 + for lyr in editing.get("layers", ()): + lyr_p = lyr.setdefault("parameters", {}) + lyr_p["D_ion"] = 0.0 + lyr_p["D_ion_neg"] = 0.0 + return resolve_device( + DeviceInput.model_validate(editing), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +def apply_absorber_damage( + base_prepared: PreparedDevice, + damage: float, + *, + alpha: float = 1.0, + target_layer_id: str | None = None, +) -> PreparedDevice: + """Cold-rebind absorber ``tau_n, tau_p = tau_0 / (1 + alpha * damage)``.""" + if not isinstance(base_prepared, PreparedDevice): + raise TypeError("base_prepared must be a PreparedDevice") + if not _is_real_number(damage) or not math.isfinite(float(damage)) or float(damage) < 0.0: + raise ValueError("damage must be finite and >= 0") + if not _is_real_number(alpha) or not math.isfinite(float(alpha)) or float(alpha) < 0.0: + raise ValueError("alpha must be finite and >= 0") + + scale = 1.0 + float(alpha) * float(damage) + if scale == 1.0: + return base_prepared + + base_layers = {lyr.id: dict(lyr.parameters) for lyr in base_prepared.layers} + editing = base_prepared.to_input().editing_data() + updated = False + for lyr in editing.get("layers", ()): + lid = str(lyr["id"]) + is_target = ( + (lid == target_layer_id) + if target_layer_id is not None + else (lyr.get("role") == "absorber") + ) + if not is_target: + continue + orig = base_layers[lid] + tau_n0 = float(cast(float, orig["tau_n"])) + tau_p0 = float(cast(float, orig["tau_p"])) + lyr_p = lyr.setdefault("parameters", {}) + lyr_p["tau_n"] = tau_n0 / scale + lyr_p["tau_p"] = tau_p0 / scale + updated = True + + if not updated: + raise DegradationError( + "apply_absorber_damage found no matching absorber layer to update" + ) + return resolve_device( + DeviceInput.model_validate(editing), + base_prepared.defaults, + base_prepared.resources, + sources=base_prepared.sources, + ) + + +def _compile_ionic_pair( + prepared: PreparedDevice, + *, + intervals_per_layer: int, + ion_domain_layer: str | None, + ion_domain_endpoints: tuple[str, str] | None, +) -> tuple[CompiledIonicDevice1D, CompiledIonicDevice1D]: + has_ions, inferred_layer = has_declared_ions(prepared) + if not has_ions: + raise DegradationError( + "Degradation snapshots require a PreparedDevice with a declared ionic population" + ) + elec_layers = tuple(lyr for lyr in prepared.layers if lyr.role != "substrate") + chosen_layer = ion_domain_layer if ion_domain_layer is not None else inferred_layer + chosen_end = ( + ion_domain_endpoints + if ion_domain_endpoints is not None + else (("blocking", "blocking") if len(elec_layers) > 1 else None) + ) + live_compiled = compile_ionic_device_1d( + prepared, + intervals_per_layer=intervals_per_layer, + ion_domain_layer=chosen_layer, + ion_domain_endpoints=chosen_end, + ) + frozen_prep = freeze_prepared_ions(prepared) + frozen_compiled = compile_ionic_device_1d( + frozen_prep, + intervals_per_layer=intervals_per_layer, + ion_domain_layer=chosen_layer, + ion_domain_endpoints=chosen_end, + ) + return live_compiled, frozen_compiled + + +def _step_coupled_ionic( + compiled: CompiledIonicDevice1D, + prev_state: IonicState1D, + *, + voltage_V: float, + generation_scale: float, + dt_s: float, + poisson_tol: float, + continuity_tol: float, + contact_tol: float, + ion_balance_tol: float, + predictor: str = "previous", + _depth: int = 0, +) -> tuple[IonicState1D, dict[str, object]]: + assembled = use_assembled() + step = ( + cast( + IonicBackwardEuler1DStep, + AssembledIonicBackwardEuler1DStep( + AssembledIonic1DProblem(compiled, voltage_V, generation_scale), + prev_state, + dt_s, + ), + ) + if assembled + else IonicBackwardEuler1DStep( + Ionic1DProblem(compiled, voltage_V, generation_scale), + prev_state, + dt_s, + ) + ) + n_nodes, n_ion = compiled.node_count, compiled.ion_node_count + weights = np.r_[ + production_residual_scaling( + compiled.electronic_component, + poisson_tolerance=poisson_tol, + continuity_tolerance_A_m2=continuity_tol, + contact_log_tolerance=contact_tol, + ).row_weights, + np.full( + n_ion * compiled.ion_species_count, + n_ion / ion_balance_tol, + ), + ] + steps = np.r_[ + production_coordinates( + compiled.electronic_component, + potential_step_V=0.1, + quasi_fermi_step=2.0, + ).max_step, + np.full(n_ion * compiled.ion_species_count, 2.0), + ] + settings = NewtonSettings( + ResidualScaling(weights), + 1.0, + StepControl(steps), + SolveBudget(80, 640, 82, 24), + (), + False, + ) + elec_norm = production_convergence_norm( + compiled.electronic_component, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + assert elec_norm is not None + + def conv_norm(scaled: np.ndarray) -> float: + if scaled.shape != (compiled.state_size,) or not np.all(np.isfinite(scaled)): + return math.inf + return max( + elec_norm(scaled[: 3 * n_nodes]), + *( + math.fsum(abs(scaled[block]).tolist()) / n_ion + for block in compiled.ion_species_slices + ), + ) + + base_seed = step.initial_coordinates("previous", voltage_lift=True) + raw_e_step = BackwardEuler1DStep( + DC1DProblem(compiled.electronic_component, voltage_V, generation_scale), + prev_state.electronic_state, + dt_s, + ) + if predictor == "generation_inventory" and generation_scale > 0.0: + try: + seeded_e = transient_density_basin_seed( + raw_e_step, + base_seed[: 3 * n_nodes], + device=compiled.electronic_component, + voltage_V=voltage_V, + ) + seed = np.r_[seeded_e, base_seed[3 * n_nodes :]] + except ValueError: + seed = step.initial_coordinates(predictor, voltage_lift=True) + else: + seed = base_seed + + newton = solve_newton( + CallableProblem(step.residual, step.jacobian), + seed, + settings, + convergence_norm=conv_norm, + ) + if ( + (not newton.accepted or not np.all(np.isfinite(newton.state))) + and predictor != "generation_inventory" + and generation_scale > 0.0 + ): + try: + retry_e = transient_density_basin_seed( + raw_e_step, + base_seed[: 3 * n_nodes], + device=compiled.electronic_component, + voltage_V=voltage_V, + ) + newton = solve_newton( + CallableProblem(step.residual, step.jacobian), + np.r_[retry_e, base_seed[3 * n_nodes :]], + settings, + convergence_norm=conv_norm, + ) + except ValueError: + pass + if not newton.accepted or not np.all(np.isfinite(newton.state)): + if _depth < 4 and dt_s >= 4e-5: + v_mid = 0.5 * (prev_state.voltage_V + voltage_V) + mid_state, _ = _step_coupled_ionic( + compiled, + prev_state, + voltage_V=v_mid, + generation_scale=generation_scale, + dt_s=0.5 * dt_s, + poisson_tol=poisson_tol, + continuity_tol=continuity_tol, + contact_tol=contact_tol, + ion_balance_tol=ion_balance_tol, + predictor=predictor, + _depth=_depth + 1, + ) + return _step_coupled_ionic( + compiled, + mid_state, + voltage_V=voltage_V, + generation_scale=generation_scale, + dt_s=0.5 * dt_s, + poisson_tol=poisson_tol, + continuity_tol=continuity_tol, + contact_tol=contact_tol, + ion_balance_tol=ion_balance_tol, + predictor="previous", + _depth=_depth + 1, + ) + raise DegradationError( + f"Ionic Backward Euler step failed at V={voltage_V:.4f} V: {newton.termination.value}" + ) + next_state = compiled.state(newton.state, voltage_V=voltage_V) + acc = ionic_step_accounting(step, newton.state) + return next_state, acc + + +def _lift_electronic_voltage( + frozen_compiled: CompiledIonicDevice1D, + u_elec: np.ndarray, + v_old: float, + v_new: float, +) -> np.ndarray: + """Rebase carrier references and harmonically lift potential from v_old to v_new.""" + elec_comp = frozen_compiled.electronic_component + values = np.array( + elec_comp.rebase_coordinates(u_elec, v_old, v_new), dtype=float, copy=True + ) + if v_new != v_old: + n_nodes = elec_comp.node_count + res_f = 1.0 / elec_comp.poisson.face_capacitance_F_m2 + prof = np.r_[0.0, np.cumsum(res_f)] + prof /= prof[-1] + change = -elec_comp.voltage_polarity * (v_new - v_old) + before = values[:n_nodes].copy() + values[:n_nodes] += change * prof + shift = (values[:n_nodes] - before) / elec_comp.thermal_voltage_V + values[n_nodes : 2 * n_nodes] -= shift + values[2 * n_nodes :] -= shift + return values + + +def _solve_frozen_electronic_point( + frozen_compiled: CompiledIonicDevice1D, + u_elec_seed: np.ndarray, + u_ion_frozen: np.ndarray, + *, + voltage_V: float, + generation_scale: float, + poisson_tol: float, + continuity_tol: float, + contact_tol: float, +) -> tuple[np.ndarray, float, float, float]: + """Solve stationary ``3 * N`` electronic rows at exact frozen ``u_ion_frozen``.""" + n_elec = 3 * frozen_compiled.node_count + prob = ( + AssembledIonic1DProblem(frozen_compiled, voltage_V, generation_scale) + if use_assembled() + else Ionic1DProblem(frozen_compiled, voltage_V, generation_scale) + ) + weights = production_residual_scaling( + frozen_compiled.electronic_component, + poisson_tolerance=poisson_tol, + continuity_tolerance_A_m2=continuity_tol, + contact_log_tolerance=contact_tol, + ).row_weights + steps = production_coordinates( + frozen_compiled.electronic_component, + potential_step_V=0.1, + quasi_fermi_step=2.0, + ).max_step + settings = NewtonSettings( + ResidualScaling(weights), + 1.0, + StepControl(steps), + SolveBudget(100, 10000, 2000, 40), + (), + False, + ) + elec_norm = production_convergence_norm( + frozen_compiled.electronic_component, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + + def res_fn(u_e: np.ndarray) -> Matrix: + return prob.residual(np.r_[u_e, u_ion_frozen])[:n_elec] + + def jac_fn(u_e: np.ndarray) -> Matrix: + full_j = prob.jacobian(np.r_[u_e, u_ion_frozen]) + return cast(csc_matrix, full_j[:n_elec, :n_elec]).tocsc() + + newton = solve_newton( + CallableProblem(res_fn, jac_fn), + u_elec_seed, + settings, + convergence_norm=elec_norm, + ) + if not newton.accepted or not np.all(np.isfinite(newton.state)): + raise DegradationError( + f"Frozen-ion electronic steady solve failed at V={voltage_V:.4f} V: {newton.termination.value}" + ) + + u_full = np.r_[newton.state, u_ion_frozen] + raw_prob = Ionic1DProblem(frozen_compiled, voltage_V, generation_scale) + j_ion_pos = raw_prob.ion_fluxes(u_full, species="positive") + max_j_ion = float(np.max(np.abs(j_ion_pos))) + if frozen_compiled.ion_species_count == 2: + j_ion_neg = raw_prob.ion_fluxes(u_full, species="negative") + max_j_ion = max(max_j_ion, float(np.max(np.abs(j_ion_neg)))) + + elec_prob = raw_prob.electronic_problem + j_interior = elec_prob.current_density(newton.state) + j_contacts = elec_prob.contact_current_density(newton.state) + j_faces = np.r_[j_contacts[0], j_interior, j_contacts[1]] + spread = float(np.ptp(j_faces)) + polarity = float(frozen_compiled.electronic_component.voltage_polarity) + j_out = float(-polarity * j_faces[0]) + return newton.state, j_out, max_j_ion, spread + + +def measure_frozen_ion_snapshot( + live_compiled: CompiledIonicDevice1D, + frozen_compiled: CompiledIonicDevice1D, + live_state: IonicState1D, + probe_voltages_V: object, + *, + time_s: float = 0.0, + damage: float = 0.0, + generation_scale: float = 1.0, + settle_time_s: float = 0.0, + settle_steps: int = 4, + incident_power_W_m2: float = 1000.0, + poisson_tolerance: float = 1e-10, + continuity_tolerance_A_m2: float = 1e-7, + contact_log_tolerance: float = 1e-12, + max_current_error_A_m2: float = 1e-6, + ion_balance_tolerance_m2_s: float = 1e10, +) -> FrozenIonSnapshot: + """Measure a stationary J-V curve with spatial ion profiles frozen bit-for-bit.""" + if live_state.device_sha256 != live_compiled.identity: + raise ValueError("live_state does not belong to live_compiled") + if ( + not np.all(frozen_compiled.positive_ion_diffusivity_faces_m2_s == 0.0) + or ( + frozen_compiled.ion_species_count == 2 + and not np.all(frozen_compiled.negative_ion_diffusivity_faces_m2_s == 0.0) + ) + ): + raise ValueError("frozen_compiled must have identically zero ion diffusivity") + + v_probe = np.array(probe_voltages_V, dtype=float, copy=True) + if ( + v_probe.ndim != 1 + or v_probe.size < 2 + or not np.all(np.isfinite(v_probe)) + or not (np.all(np.diff(v_probe) > 0.0) or np.all(np.diff(v_probe) < 0.0)) + ): + raise ValueError("probe_voltages_V must be strictly monotonic 1-D finite voltages") + v_probe.setflags(write=False) + + n_elec = 3 * live_compiled.node_count + u_ion_snap = np.array(live_state.u[n_elec:], dtype=float, copy=True) + u_ion_snap.setflags(write=False) + + # Smoothly continue electronic coordinates from live_state.voltage_V to v0 + # while holding u_ion_snap bit-identical (0 ULP). + v0 = float(v_probe[0]) + u_elec_start = np.array(live_state.u[:n_elec], dtype=float, copy=True) + snap_state = frozen_compiled.state( + np.r_[ + frozen_compiled.electronic_component.rebase_coordinates( + u_elec_start, live_state.voltage_V, v0 + ), + u_ion_snap, + ], + voltage_V=v0, + ) + + # Verify 0-ULP bit-identical frozen ion profiles & reference backgrounds + if not np.array_equal( + snap_state.positive_ion_density_m3, live_state.positive_ion_density_m3 + ) or not np.array_equal( + snap_state.negative_ion_density_m3, live_state.negative_ion_density_m3 + ): + raise DegradationError( + "Frozen-ion device mapping altered spatial ion density profiles" + ) + if not np.array_equal( + frozen_compiled.positive_ion_reference_m3, + live_compiled.positive_ion_reference_m3, + ) or not np.array_equal( + frozen_compiled.negative_ion_reference_m3, + live_compiled.negative_ion_reference_m3, + ): + raise DegradationError( + "Frozen-ion device altered compensating P0 / P0_neg background density" + ) + + def advance_frozen_v( + u_prev: np.ndarray, + v_from: float, + v_to: float, + _depth: int = 0, + ) -> tuple[np.ndarray, float, float, float]: + lifted = _lift_electronic_voltage(frozen_compiled, u_prev, v_from, v_to) + try: + return _solve_frozen_electronic_point( + frozen_compiled, + lifted, + u_ion_snap, + voltage_V=v_to, + generation_scale=generation_scale, + poisson_tol=poisson_tolerance, + continuity_tol=continuity_tolerance_A_m2, + contact_tol=contact_log_tolerance, + ) + except DegradationError: + if _depth >= 5 or abs(v_to - v_from) < 1e-4: + raise + v_mid = 0.5 * (v_from + v_to) + u_mid, _, _, _ = advance_frozen_v(u_prev, v_from, v_mid, _depth + 1) + return advance_frozen_v(u_mid, v_mid, v_to, _depth + 1) + + # Relax electronic carriers at live_state.voltage_V first, then step smoothly to v0 + u_bridge, _, _, _ = advance_frozen_v( + u_elec_start, live_state.voltage_V, live_state.voltage_V + ) + if v0 != live_state.voltage_V: + n_bridge = max(1, int(math.ceil(abs(v0 - live_state.voltage_V) / 0.08))) + v_bridge = np.linspace(live_state.voltage_V, v0, n_bridge + 1) + for k_br in range(1, v_bridge.size): + u_bridge, _, _, _ = advance_frozen_v( + u_bridge, float(v_bridge[k_br - 1]), float(v_bridge[k_br]) + ) + snap_state = frozen_compiled.state(np.r_[u_bridge, u_ion_snap], voltage_V=v0) + + if settle_time_s > 0.0: + dt_settle = settle_time_s / settle_steps + for _ in range(settle_steps): + snap_state, _ = _step_coupled_ionic( + frozen_compiled, + snap_state, + voltage_V=v0, + generation_scale=generation_scale, + dt_s=dt_settle, + poisson_tol=poisson_tolerance, + continuity_tol=continuity_tolerance_A_m2, + contact_tol=contact_log_tolerance, + ion_balance_tol=ion_balance_tolerance_m2_s, + ) + if not np.array_equal(snap_state.u[n_elec:], u_ion_snap): + raise DegradationError( + "Frozen-ion carrier relaxation settle mutated immobile ion coordinates" + ) + + u_elec_cur = np.array(snap_state.u[:n_elec], dtype=float, copy=True) + v_prev = v0 + j_out = np.empty(v_probe.size, dtype=float) + max_ion_flux = 0.0 + max_spread = 0.0 + + for idx, v_val in enumerate(v_probe): + v_f = float(v_val) + u_elec_cur, j_k, flux_k, spread_k = advance_frozen_v( + u_elec_cur, v_prev, v_f + ) + if flux_k != 0.0: + raise DegradationError( + f"Nonzero ionic flux {flux_k:.3e} m^-2 s^-1 detected during frozen-ion probe" + ) + if spread_k > max_current_error_A_m2: + raise DegradationError( + f"Frozen-ion probe current spread {spread_k:.3e} A/m^2 > {max_current_error_A_m2:.3e} A/m^2 at V={v_f:.4f} V" + ) + probe_check = frozen_compiled.state(np.r_[u_elec_cur, u_ion_snap], voltage_V=v_f) + if not np.array_equal( + probe_check.positive_ion_density_m3, live_state.positive_ion_density_m3 + ) or not np.array_equal( + probe_check.negative_ion_density_m3, live_state.negative_ion_density_m3 + ): + raise DegradationError( + "Frozen-ion density drifted during voltage probe sweep" + ) + + j_out[idx] = j_k + max_ion_flux = max(max_ion_flux, flux_k) + max_spread = max(max_spread, spread_k) + v_prev = v_f + + j_out.setflags(write=False) + metrics = steady_jv_metrics( + v_probe, j_out, incident_power_W_m2=incident_power_W_m2 + ) + pos_prof = np.array(live_state.positive_ion_density_m3, dtype=float, copy=True) + neg_prof = np.array(live_state.negative_ion_density_m3, dtype=float, copy=True) + pos_ref = np.array( + frozen_compiled.positive_ion_reference_m3, dtype=float, copy=True + ) + neg_ref = np.array( + frozen_compiled.negative_ion_reference_m3, dtype=float, copy=True + ) + for arr in (pos_prof, neg_prof, pos_ref, neg_ref): + arr.setflags(write=False) + + return FrozenIonSnapshot( + time_s=float(time_s), + damage=float(damage), + voltage_V=v_probe, + output_current_A_m2=j_out, + metrics=metrics, + positive_ion_density_m3=pos_prof, + negative_ion_density_m3=neg_prof, + positive_reference_m3=pos_ref, + negative_reference_m3=neg_ref, + max_ion_flux_m2_s=max_ion_flux, + max_current_spread_A_m2=max_spread, + frozen_profile_exact=True, + live_compiled_identity=live_compiled.identity, + frozen_compiled_identity=frozen_compiled.identity, + ) + + +def _advance_damage( + damage_prev: float, + acc: dict[str, object], + state: IonicState1D, + compiled: CompiledIonicDevice1D, + dt_s: float, + dmg_prot: DegradationDamageProtocol, +) -> float: + inc = 0.0 + if dmg_prot.motion_gain_m2_C > 0.0: + j_ion = np.asarray(acc["ion_conduction_current_density_A_m2"], dtype=float) + mean_abs_j_ion = float(np.mean(np.abs(j_ion))) + inc += dmg_prot.motion_gain_m2_C * mean_abs_j_ion * dt_s + if dmg_prot.segregation_gain_s_1 > 0.0: + rel_pos = np.max( + np.abs(state.positive_ion_density_m3 - compiled.positive_ion_reference_m3) + / compiled.positive_ion_reference_m3 + ) + rel_max = float(rel_pos) + if compiled.ion_species_count == 2: + rel_neg = np.max( + np.abs( + state.negative_ion_density_m3 - compiled.negative_ion_reference_m3 + ) + / compiled.negative_ion_reference_m3 + ) + rel_max = max(rel_max, float(rel_neg)) + inc += dmg_prot.segregation_gain_s_1 * rel_max * dt_s + return damage_prev + inc + + +def run_degradation( + prepared: PreparedDevice, + t_eval_s: object, + protocol: DegradationProtocol | None = None, +) -> DegradationResult: + """Evolve coupled ionic stress and record frozen-ion J-V snapshots at ``t_eval_s``.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice") + prot = DegradationProtocol() if protocol is None else protocol + if not isinstance(prot, DegradationProtocol): + raise TypeError("protocol must be a DegradationProtocol") + + if np.iscomplexobj(t_eval_s): + raise ValueError("t_eval_s must be real-valued") + times = np.array(t_eval_s, dtype=float, copy=True) + if ( + times.ndim != 1 + or times.size < 2 + or not np.all(np.isfinite(times)) + or float(times[0]) < 0.0 + or np.any(np.diff(times) <= 0.0) + ): + raise ValueError( + "t_eval_s must be a 1-D strictly increasing nonnegative array with >= 2 samples" + ) + times.setflags(write=False) + + live_compiled, frozen_compiled = _compile_ionic_pair( + prepared, + intervals_per_layer=prot.intervals_per_layer, + ion_domain_layer=prot.ion_domain_layer, + ion_domain_endpoints=prot.ion_domain_endpoints, + ) + + # Start from dark 0 V equilibrium, then step cleanly to stress bias at t = 0 + steady_opts = IonicSteadyOptions( + electronic=SteadyOptions( + poisson_tolerance=prot.poisson_tolerance, + continuity_tolerance_A_m2=prot.continuity_tolerance_A_m2, + contact_log_tolerance=prot.contact_log_tolerance, + convergence_policy=HISTORICAL_MAX_ROW_V1, + ), + inventory_relative_tolerance=1e-11, + ion_balance_tolerance_m2_s=prot.ion_balance_tolerance_m2_s, + ion_flux_tolerance_m2_s=prot.ion_balance_tolerance_m2_s, + ion_logit_step=2.0, + inventory_row_node=live_compiled.ion_node_count - 1, + budget=SolveBudget(120, 960, 122, 12), + wall_s=30.0, + ) + init_sol = solve_ionic_steady_state( + live_compiled, + voltage_V=0.0, + generation_scale=0.0, + options=steady_opts, + initial_state=None, + ) + if not init_sol.accepted or init_sol.state is None: + raise DegradationError( + f"Initial 0 V dark ionic steady state failed: {init_sol.termination}" + ) + cur_state = init_sol.state + if prot.precondition_time_s > 0.0 and ( + prot.V_bias_V != 0.0 or prot.generation_scale != 0.0 + ): + n_v_steps = max(4, int(math.ceil(abs(prot.V_bias_V) / 0.15))) + total_pre = max(prot.precondition_time_s, 5e-4) + # First 3 steps smoothly turn on illumination at 0 V with dt >= 2e-5 s, + # followed by smooth voltage ramp to V_bias_V. + if prot.generation_scale > 0.0: + light_steps = [ + (0.0, prot.generation_scale * 1e-3, 2e-5), + (0.0, prot.generation_scale * 1e-1, 8e-5), + (0.0, prot.generation_scale, 2e-4), + ] + else: + light_steps = [] + rem_pre = max(total_pre - 3e-4, 2e-4) + v_ramp = np.linspace(0.0, prot.V_bias_V, n_v_steps + 1)[1:] + dt_v = rem_pre / n_v_steps + bias_steps = [(float(v_step), prot.generation_scale, dt_v) for v_step in v_ramp] + for idx_pre, (v_p, g_p, dt_pre) in enumerate(light_steps + bias_steps): + cur_state, _ = _step_coupled_ionic( + live_compiled, + cur_state, + voltage_V=v_p, + generation_scale=g_p, + dt_s=dt_pre, + poisson_tol=prot.poisson_tolerance, + continuity_tol=prot.continuity_tolerance_A_m2, + contact_tol=prot.contact_log_tolerance, + ion_balance_tol=prot.ion_balance_tolerance_m2_s, + predictor=( + "generation_inventory" + if (idx_pre == 0 and g_p > 0.0) + else "previous" + ), + ) + + # Advance from t = 0.0 to times[0] if times[0] > 0.0, or rebase electronic bias at t = 0 + t_cur = 0.0 + damage = 0.0 + cached_damage = 0.0 + rebind_count = 0 + + def maybe_rebind_for_damage( + dmg_val: float, state_in: IonicState1D + ) -> tuple[CompiledIonicDevice1D, CompiledIonicDevice1D, IonicState1D]: + nonlocal cached_damage, rebind_count, live_compiled, frozen_compiled + dmg_prot = prot.damage_protocol + if ( + dmg_prot.lifetime_degradation_alpha == 0.0 + or abs(dmg_val - cached_damage) <= dmg_prot.damage_rebind_threshold + or dmg_val == cached_damage + ): + return live_compiled, frozen_compiled, state_in + + damaged_prep = apply_absorber_damage( + prepared, + dmg_val, + alpha=dmg_prot.lifetime_degradation_alpha, + target_layer_id=live_compiled.domain_layer_id, + ) + new_live, new_frozen = _compile_ionic_pair( + damaged_prep, + intervals_per_layer=prot.intervals_per_layer, + ion_domain_layer=prot.ion_domain_layer, + ion_domain_endpoints=prot.ion_domain_endpoints, + ) + rebound_state = new_live.state(state_in.u, voltage_V=state_in.voltage_V) + live_compiled = new_live + frozen_compiled = new_frozen + cached_damage = dmg_val + rebind_count += 1 + return live_compiled, frozen_compiled, rebound_state + + def advance_interval(target_t: float, state_in: IonicState1D) -> IonicState1D: + nonlocal t_cur, damage + span = target_t - t_cur + if span <= 0.0: + return state_in + n_chunks = max(1, int(math.ceil(span / prot.dt_max_s))) + dt_chunk = span / n_chunks + st = state_in + for _ in range(n_chunks): + st, acc = _step_coupled_ionic( + live_compiled, + st, + voltage_V=prot.V_bias_V, + generation_scale=prot.generation_scale, + dt_s=dt_chunk, + poisson_tol=prot.poisson_tolerance, + continuity_tol=prot.continuity_tolerance_A_m2, + contact_tol=prot.contact_log_tolerance, + ion_balance_tol=prot.ion_balance_tolerance_m2_s, + ) + t_cur += dt_chunk + damage = _advance_damage( + damage, acc, st, live_compiled, dt_chunk, prot.damage_protocol + ) + _, _, st = maybe_rebind_for_damage(damage, st) + t_cur = target_t + return st + + if float(times[0]) > 0.0: + cur_state = advance_interval(float(times[0]), cur_state) + + v_probe = np.linspace(0.0, prot.V_max_V, prot.n_jv_points) + snapshots: list[FrozenIonSnapshot] = [] + + for idx_snap, t_snap in enumerate(times): + if idx_snap > 0: + cur_state = advance_interval(float(t_snap), cur_state) + snap = measure_frozen_ion_snapshot( + live_compiled, + frozen_compiled, + cur_state, + v_probe, + time_s=float(t_snap), + damage=damage, + generation_scale=prot.probe_generation_scale, + settle_time_s=prot.settle_time_s, + settle_steps=prot.settle_steps, + incident_power_W_m2=prot.incident_power_W_m2, + poisson_tolerance=prot.poisson_tolerance, + continuity_tolerance_A_m2=prot.continuity_tolerance_A_m2, + contact_log_tolerance=prot.contact_log_tolerance, + max_current_error_A_m2=prot.max_current_error_A_m2, + ion_balance_tolerance_m2_s=prot.ion_balance_tolerance_m2_s, + ) + snapshots.append(snap) + + voc_arr = np.array( + [ + float("nan") + if s.metrics.open_circuit_voltage_V is None + else s.metrics.open_circuit_voltage_V + for s in snapshots + ], + dtype=float, + ) + jsc_arr = np.array( + [ + float("nan") + if s.metrics.short_circuit_current_A_m2 is None + else s.metrics.short_circuit_current_A_m2 + for s in snapshots + ], + dtype=float, + ) + ff_arr = np.array( + [ + float("nan") if s.metrics.fill_factor is None else s.metrics.fill_factor + for s in snapshots + ], + dtype=float, + ) + pce_arr = np.array( + [ + float("nan") if s.metrics.efficiency is None else s.metrics.efficiency + for s in snapshots + ], + dtype=float, + ) + dmg_arr = np.array([s.damage for s in snapshots], dtype=float) + for arr in (voc_arr, jsc_arr, ff_arr, pce_arr, dmg_arr): + arr.setflags(write=False) + + live_ids = tuple(s.live_compiled_identity for s in snapshots) + frozen_ids = tuple(s.frozen_compiled_identity for s in snapshots) + + sha = _canonical_sha256( + { + "base_prepared_sha256": prepared.content_sha256, + "t_s": [float(x).hex() for x in times], + "damage": [float(x).hex() for x in dmg_arr], + "material_rebind_count": rebind_count, + "live_ids": list(live_ids), + "frozen_ids": list(frozen_ids), + "metrics": [asdict(s.metrics) for s in snapshots], + } + ) + return DegradationResult( + t_s=times, + V_oc_V=voc_arr, + J_sc_A_m2=jsc_arr, + FF=ff_arr, + PCE=pce_arr, + damage=dmg_arr, + snapshots=tuple(snapshots), + material_rebind_count=rebind_count, + snapshot_live_compiled_identities=live_ids, + snapshot_frozen_compiled_identities=frozen_ids, + base_prepared_sha256=prepared.content_sha256, + result_sha256=sha, + ) diff --git a/src/solarlab/experiments/electrothermal.py b/src/solarlab/experiments/electrothermal.py new file mode 100644 index 00000000..9b98c72a --- /dev/null +++ b/src/solarlab/experiments/electrothermal.py @@ -0,0 +1,1109 @@ +"""Coupled steady-state electrothermal operating-point solver (P04-13 / P05-04). + +At every trial temperature ``T`` visited by the bracketed root finder: +1. ``PreparedDevice`` is cold-rebound from its immutable declaration by setting + ``settings.T = T`` (leaving all 300 K layer parameters untouched so + ``compile_layer_parameters`` / ``compile_ionic_device_1d`` apply the exact + temperature laws ``Nc(T), Nv(T), Eg(T), ni(T), mu(T), B_rad(T), D_ion(T)``). +2. A fresh ``CompiledDevice1D`` or ``CompiledIonicDevice1D`` is compiled and + evaluated from a fresh equilibrium/steady state at ``T``: neither carrier nor + ionic state is ever inherited across trial temperatures. +3. The intrinsic J-V sweep is mapped through ``ExternalCircuitProtocol`` and the + operating-point terminal power ``P_elec_out(T)`` (sampled terminal MPP, + open-circuit, or fixed load) is inserted into ``LumpedThermalProtocol``. + +Electrothermal self-heating is mutually exclusive with an externally prescribed +temperature schedule ``T(t)``; non-isothermal PDE time stepping remains gated by +``TIME_DOMAIN_TEMPERATURE_QUALIFIED`` (``False``). +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any, Literal, cast + +import numpy as np +from scipy.optimize import brentq + +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.ionic_1d import AssembledIonic1DProblem +from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem +from solarlab.equations.implementation import use_assembled +from solarlab.equations.ionic_1d import ( + CompiledIonicDevice1D, + Ionic1DProblem, + IonicState1D, +) +from solarlab.experiments.external_circuit import ( + ExternalCircuitJVResult, + ExternalCircuitProtocol, + apply_external_circuit, +) +from solarlab.experiments.jv.steady import run_steady_jv +from solarlab.experiments.thermal_balance import ( + LumpedThermalProtocol, + ThermalPowerLedger, + thermal_power_ledger, +) +from solarlab.experiments.transient import ( + TransientOptions, + TransientProtocol, + solve_transient, +) +from solarlab.physics.band_structure import TIME_DOMAIN_TEMPERATURE_QUALIFIED +from solarlab.solvers.nonlinear.ionic_1d import ( + IonicSteadyOptions, + solve_ionic_steady_state, +) +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import ( + CallableProblem, + Matrix, + ResidualScaling, + SolveBudget, + StepControl, +) +from solarlab.solvers.nonlinear.production import ( + HISTORICAL_MAX_ROW_V1, + POISSON_CONTACT_BALANCE_V1, + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + density_basin_seed, + solve_steady_state, +) +from solarlab.solvers.time.assembled_ionic_backward_euler import ( + AssembledIonicBackwardEuler1DStep, +) +from solarlab.solvers.time.backward_euler import BackwardEuler1DStep +from solarlab.solvers.time.carrier_seed import transient_density_basin_seed +from solarlab.solvers.time.ionic_backward_euler import ( + IonicBackwardEuler1DStep, + step_accounting as ionic_step_accounting, +) + +__all__ = [ + "ElectrothermalCapabilityError", + "ElectrothermalConvergenceError", + "ElectrothermalError", + "ElectrothermalJVProtocol", + "ElectrothermalOperatingPointProtocol", + "ElectrothermalOperatingPointResult", + "ElectrothermalSourceError", + "ElectrothermalTemperatureEvaluation", + "compile_prepared_at_temperature", + "has_declared_ions", + "rebind_prepared_temperature", + "run_fresh_jv_at_temperature", + "solve_electrothermal_operating_point", +] + + +class ElectrothermalError(RuntimeError): + """Base error for electrothermal operating-point coupling.""" + + +class ElectrothermalCapabilityError(ElectrothermalError): + """Unsupported or mutually exclusive electrothermal capability request.""" + + +class ElectrothermalSourceError(ElectrothermalError): + """Intrinsic J-V or external-circuit evaluation failed certification.""" + + +class ElectrothermalConvergenceError(ElectrothermalError): + """Bracketed electrothermal root failed to converge within residual tolerances.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def has_declared_ions(prepared: PreparedDevice) -> tuple[bool, str | None]: + active_layers: list[str] = [] + for layer in prepared.layers: + if layer.role == "substrate": + continue + params = dict(layer.parameters) + if any( + float(cast(float, params[name])) != 0.0 + for name in ("P0", "P0_neg", "D_ion", "D_ion_neg") + ): + active_layers.append(layer.id) + if not active_layers: + return False, None + if len(active_layers) == 1: + return True, active_layers[0] + return True, None + + +def rebind_prepared_temperature( + prepared: PreparedDevice, + temperature_K: float, +) -> PreparedDevice: + """Return a cold-rebound ``PreparedDevice`` at ``temperature_K``.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice") + if ( + not _is_real_number(temperature_K) + or not math.isfinite(float(temperature_K)) + or float(temperature_K) <= 0.0 + ): + raise ValueError("temperature_K must be a finite positive real scalar") + + editing = prepared.to_input().editing_data() + editing.setdefault("settings", {})["T"] = float(temperature_K) + return resolve_device( + DeviceInput.model_validate(editing), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +def compile_prepared_at_temperature( + prepared: PreparedDevice, + temperature_K: float, + *, + intervals_per_layer: int = 24, + ion_domain_layer: str | None = None, + ion_domain_endpoints: tuple[str, str] | None = None, +) -> tuple[PreparedDevice, CompiledDevice1D | CompiledIonicDevice1D]: + """Cold-rebind and freshly compile ``prepared`` at ``temperature_K``.""" + rebound = rebind_prepared_temperature(prepared, temperature_K) + has_ions, inferred_layer = has_declared_ions(rebound) + if not has_ions: + return rebound, compile_device_1d( + rebound, intervals_per_layer=intervals_per_layer + ) + + electrical_layers = tuple( + layer for layer in rebound.layers if layer.role != "substrate" + ) + chosen_layer = ion_domain_layer if ion_domain_layer is not None else inferred_layer + chosen_endpoints = ion_domain_endpoints + if chosen_endpoints is None and len(electrical_layers) > 1: + chosen_endpoints = ("blocking", "blocking") + return rebound, compile_ionic_device_1d( + rebound, + intervals_per_layer=intervals_per_layer, + ion_domain_layer=chosen_layer, + ion_domain_endpoints=chosen_endpoints, + ) + + +@dataclass(frozen=True) +class ElectrothermalJVProtocol: + """Explicit fresh-state J-V evaluation contract at each trial temperature.""" + + intervals_per_layer: int = 24 + voltage_points_per_branch: int = 41 + scan_rate_V_s: float = 1.0 + voltage_max_V: float = 1.4 + substeps_per_point: int = 1 + precondition_time_s: float = 0.0 + incident_power_W_m2: float = 1000.0 + driver: Literal["transient_jv_strict", "steady_jv"] = "transient_jv_strict" + temperature_initialization: Literal["fresh_state_per_temperature"] = ( + "fresh_state_per_temperature" + ) + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] | None = None + poisson_tolerance: float = 1e-10 + continuity_tolerance_A_m2: float = 1e-7 + contact_log_tolerance: float = 1e-12 + ion_balance_tolerance_m2_s: float = 1e10 + wall_s_per_temperature: float = 30.0 + + def __post_init__(self) -> None: + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if ( + type(self.voltage_points_per_branch) is not int + or self.voltage_points_per_branch < 3 + ): + raise ValueError("voltage_points_per_branch must be an integer >= 3") + if type(self.substeps_per_point) is not int or self.substeps_per_point < 1: + raise ValueError("substeps_per_point must be an integer >= 1") + for name in ( + "scan_rate_V_s", + "voltage_max_V", + "incident_power_W_m2", + "poisson_tolerance", + "continuity_tolerance_A_m2", + "contact_log_tolerance", + "ion_balance_tolerance_m2_s", + "wall_s_per_temperature", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ValueError(f"{name} must be finite and positive") + object.__setattr__(self, name, float(raw)) + if ( + not _is_real_number(self.precondition_time_s) + or not math.isfinite(float(self.precondition_time_s)) + or float(self.precondition_time_s) < 0.0 + ): + raise ValueError("precondition_time_s must be finite and >= 0") + object.__setattr__(self, "precondition_time_s", float(self.precondition_time_s)) + if self.driver not in ("transient_jv_strict", "steady_jv"): + raise ValueError( + "driver must be 'transient_jv_strict' or 'steady_jv'" + ) + if self.temperature_initialization != "fresh_state_per_temperature": + raise ValueError( + "temperature_initialization must be 'fresh_state_per_temperature'" + ) + + @property + def sha256(self) -> str: + return _canonical_sha256(asdict(self)) + + +@dataclass(frozen=True) +class ElectrothermalOperatingPointProtocol: + """Operating-point selection and Brent root controls.""" + + temperature_absolute_tolerance_K: float = 1e-8 + power_residual_tolerance_W_m2: float = 1e-6 + maximum_root_iterations: int = 50 + operating_branch: Literal["forward", "reverse"] = "forward" + operating_point: Literal[ + "sampled_terminal_maximum_power", "open_circuit", "fixed_load" + ] = "sampled_terminal_maximum_power" + fixed_terminal_voltage_V: float | None = None + load_resistance_ohm_m2: float | None = None + circuit_control_volume: Literal["device_plus_lumped_parasitics"] = ( + "device_plus_lumped_parasitics" + ) + + def __post_init__(self) -> None: + for name in ( + "temperature_absolute_tolerance_K", + "power_residual_tolerance_W_m2", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ValueError(f"{name} must be finite and positive") + object.__setattr__(self, name, float(raw)) + if ( + type(self.maximum_root_iterations) is not int + or self.maximum_root_iterations < 1 + ): + raise ValueError("maximum_root_iterations must be a positive integer") + if self.operating_branch not in ("forward", "reverse"): + raise ValueError("operating_branch must be 'forward' or 'reverse'") + if self.operating_point not in ( + "sampled_terminal_maximum_power", + "open_circuit", + "fixed_load", + ): + raise ValueError( + f"Unsupported operating_point {self.operating_point!r}" + ) + if self.circuit_control_volume != "device_plus_lumped_parasitics": + raise ValueError( + "circuit_control_volume must be 'device_plus_lumped_parasitics'" + ) + if self.operating_point == "fixed_load": + has_v = self.fixed_terminal_voltage_V is not None + has_r = self.load_resistance_ohm_m2 is not None + if has_v == has_r: + raise ValueError( + "fixed_load requires exactly one of fixed_terminal_voltage_V or load_resistance_ohm_m2" + ) + if has_v: + assert self.fixed_terminal_voltage_V is not None + if not _is_real_number( + self.fixed_terminal_voltage_V + ) or not math.isfinite(float(self.fixed_terminal_voltage_V)): + raise ValueError("fixed_terminal_voltage_V must be finite") + object.__setattr__( + self, + "fixed_terminal_voltage_V", + float(self.fixed_terminal_voltage_V), + ) + if has_r: + assert self.load_resistance_ohm_m2 is not None + if ( + not _is_real_number(self.load_resistance_ohm_m2) + or not math.isfinite(float(self.load_resistance_ohm_m2)) + or float(self.load_resistance_ohm_m2) <= 0.0 + ): + raise ValueError( + "load_resistance_ohm_m2 must be finite and positive" + ) + object.__setattr__( + self, + "load_resistance_ohm_m2", + float(self.load_resistance_ohm_m2), + ) + else: + if ( + self.fixed_terminal_voltage_V is not None + or self.load_resistance_ohm_m2 is not None + ): + raise ValueError( + "fixed_terminal_voltage_V / load_resistance_ohm_m2 are allowed only when operating_point='fixed_load'" + ) + + @property + def sha256(self) -> str: + return _canonical_sha256(asdict(self)) + + +@dataclass(frozen=True) +class ElectrothermalTemperatureEvaluation: + """Single cold-rebound trial-temperature evaluation record.""" + + temperature_K: float + rebound_prepared_sha256: str + compiled_identity: str + terminal_voltage_V: float + terminal_current_A_m2: float + terminal_power_W_m2: float + power_balance_residual_W_m2: float + external_result_sha256: str + fresh_state_initialized: bool + source_certified: bool + + +@dataclass(frozen=True) +class ElectrothermalOperatingPointResult: + """Certified coupled steady-state electrothermal operating point.""" + + operating_temperature_K: float + temperature_rise_K: float + terminal_voltage_V: float + terminal_current_A_m2: float + terminal_power_W_m2: float + power_balance_residual_W_m2: float + thermal_ledger: ThermalPowerLedger + final_external_result: ExternalCircuitJVResult + temperature_evaluations: tuple[ElectrothermalTemperatureEvaluation, ...] + electrical_evaluations: int + root_iterations: int + base_prepared_sha256: str + thermal_protocol: LumpedThermalProtocol + circuit_protocol: ExternalCircuitProtocol + electrical_protocol: ElectrothermalJVProtocol + operating_protocol: ElectrothermalOperatingPointProtocol + time_domain_temperature_qualified: bool + mapping_sha256: str + certified: bool + + +def _step_ionic_be( + compiled: CompiledIonicDevice1D, + prev_state: IonicState1D, + *, + voltage_V: float, + generation_scale: float, + dt_s: float, + elec_prot: ElectrothermalJVProtocol, + predictor: str = "previous", + _depth: int = 0, +) -> tuple[IonicState1D, float]: + """Advance one conservative Backward Euler step on ``CompiledIonicDevice1D``.""" + assembled = use_assembled() + step = ( + cast( + IonicBackwardEuler1DStep, + AssembledIonicBackwardEuler1DStep( + AssembledIonic1DProblem(compiled, voltage_V, generation_scale), + prev_state, + dt_s, + ), + ) + if assembled + else IonicBackwardEuler1DStep( + Ionic1DProblem(compiled, voltage_V, generation_scale), + prev_state, + dt_s, + ) + ) + count, ion_count = compiled.node_count, compiled.ion_node_count + weights = np.r_[ + production_residual_scaling( + compiled.electronic_component, + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + ).row_weights, + np.full( + ion_count * compiled.ion_species_count, + ion_count / elec_prot.ion_balance_tolerance_m2_s, + ), + ] + steps = np.r_[ + production_coordinates( + compiled.electronic_component, + potential_step_V=0.1, + quasi_fermi_step=2.0, + ).max_step, + np.full(ion_count * compiled.ion_species_count, 2.0), + ] + settings = NewtonSettings( + ResidualScaling(weights), + 1.0, + StepControl(steps), + SolveBudget(80, 640, 82, 24), + (), + False, + ) + elec_norm = production_convergence_norm( + compiled.electronic_component, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + assert elec_norm is not None + + def conv_norm(scaled: np.ndarray) -> float: + if scaled.shape != (compiled.state_size,) or not np.all(np.isfinite(scaled)): + return math.inf + return max( + elec_norm(scaled[: 3 * count]), + *( + math.fsum(abs(scaled[block]).tolist()) / ion_count + for block in compiled.ion_species_slices + ), + ) + + base_seed = step.initial_coordinates("previous", voltage_lift=True) + raw_e_step = BackwardEuler1DStep( + DC1DProblem(compiled.electronic_component, voltage_V, generation_scale), + prev_state.electronic_state, + dt_s, + ) + if predictor == "generation_inventory" and generation_scale > 0.0: + try: + seeded_e = transient_density_basin_seed( + raw_e_step, + base_seed[: 3 * count], + device=compiled.electronic_component, + voltage_V=voltage_V, + ) + seed = np.r_[seeded_e, base_seed[3 * count :]] + except ValueError: + seed = step.initial_coordinates(predictor, voltage_lift=True) + else: + seed = base_seed + + def eval_res(y: np.ndarray) -> Matrix: + return step.residual(y) + + def eval_jac(y: np.ndarray) -> Matrix: + return step.jacobian(y) + + newton = solve_newton( + CallableProblem(eval_res, eval_jac), + seed, + settings, + convergence_norm=conv_norm, + ) + if ( + (not newton.accepted or not np.all(np.isfinite(newton.state))) + and predictor != "generation_inventory" + and generation_scale > 0.0 + ): + try: + retry_e = transient_density_basin_seed( + raw_e_step, + base_seed[: 3 * count], + device=compiled.electronic_component, + voltage_V=voltage_V, + ) + newton = solve_newton( + CallableProblem(eval_res, eval_jac), + np.r_[retry_e, base_seed[3 * count :]], + settings, + convergence_norm=conv_norm, + ) + except ValueError: + pass + if not newton.accepted or not np.all(np.isfinite(newton.state)): + if _depth < 4 and dt_s >= 4e-5: + v_mid = 0.5 * (prev_state.voltage_V + voltage_V) + mid_state, _ = _step_ionic_be( + compiled, + prev_state, + voltage_V=v_mid, + generation_scale=generation_scale, + dt_s=0.5 * dt_s, + elec_prot=elec_prot, + predictor=predictor, + _depth=_depth + 1, + ) + return _step_ionic_be( + compiled, + mid_state, + voltage_V=voltage_V, + generation_scale=generation_scale, + dt_s=0.5 * dt_s, + elec_prot=elec_prot, + predictor="previous", + _depth=_depth + 1, + ) + raise ElectrothermalSourceError( + f"Ionic Backward Euler step failed at V={voltage_V:.4f} V: {newton.termination.value}" + ) + next_state = compiled.state(newton.state, voltage_V=voltage_V) + acc = ionic_step_accounting(step, newton.state) + term_total = np.asarray(acc["terminal_total_current_density_A_m2"], dtype=float) + polarity = float(compiled.electronic_component.voltage_polarity) + return next_state, float(-polarity * term_total[0]) + + +def run_fresh_jv_at_temperature( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + elec_prot: ElectrothermalJVProtocol, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Run a fresh-state forward & reverse J-V sweep on ``compiled``.""" + v_fwd = np.linspace(0.0, elec_prot.voltage_max_V, elec_prot.voltage_points_per_branch) + v_rev = v_fwd[::-1].copy() + + if elec_prot.driver == "steady_jv": + if isinstance(compiled, CompiledDevice1D): + steady_opts = SteadyOptions( + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + ) + res_fwd = run_steady_jv( + compiled, + v_fwd, + generation_scale=1.0, + incident_power_W_m2=elec_prot.incident_power_W_m2, + options=steady_opts, + ) + res_rev = run_steady_jv( + compiled, + v_rev, + generation_scale=1.0, + incident_power_W_m2=elec_prot.incident_power_W_m2, + options=steady_opts, + ) + return v_fwd, res_fwd.output_current_A_m2, v_rev, res_rev.output_current_A_m2 + + ionic_opts = IonicSteadyOptions( + electronic=SteadyOptions( + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + convergence_policy=HISTORICAL_MAX_ROW_V1, + ), + inventory_relative_tolerance=1e-11, + ion_balance_tolerance_m2_s=elec_prot.ion_balance_tolerance_m2_s, + ion_flux_tolerance_m2_s=elec_prot.ion_balance_tolerance_m2_s, + ion_logit_step=2.0, + inventory_row_node=compiled.ion_node_count - 1, + budget=SolveBudget(120, 960, 122, 12), + wall_s=elec_prot.wall_s_per_temperature, + ) + polarity = float(compiled.electronic_component.voltage_polarity) + + def sweep_ionic_steady(voltages: np.ndarray) -> np.ndarray: + currents: np.ndarray = np.empty(voltages.size, dtype=float) + prev_u: np.ndarray | None = None + prev_v: float | None = None + for idx, v_val in enumerate(voltages): + v_f = float(v_val) + seed_state: IonicState1D | None = None + if prev_u is None: + dark_init = solve_ionic_steady_state( + compiled, + voltage_V=v_f, + generation_scale=0.0, + options=ionic_opts, + initial_state=None, + ) + if dark_init.accepted and dark_init.state is not None: + try: + seeded_e = density_basin_seed( + DC1DProblem(compiled.electronic_component, v_f, 1.0), + dark_init.state.electronic_state.u, + ) + seed_state = compiled.state( + np.r_[ + seeded_e, + dark_init.state.u[3 * compiled.node_count :], + ], + voltage_V=v_f, + ) + except ValueError: + seed_state = dark_init.state + elif prev_v is not None: + elec_u = compiled.electronic_component.rebase_coordinates( + prev_u[: 3 * compiled.node_count], prev_v, v_f + ) + seed_state = compiled.state( + np.r_[elec_u, prev_u[3 * compiled.node_count :]], + voltage_V=v_f, + ) + sol = solve_ionic_steady_state( + compiled, + voltage_V=v_f, + generation_scale=1.0, + options=ionic_opts, + initial_state=seed_state, + ) + if not sol.accepted or sol.state is None or sol.diagnostics is None: + raise ElectrothermalSourceError( + f"Ionic steady solve failed at V={v_f:.4f} V: {sol.termination}" + ) + tot = np.asarray( + sol.diagnostics["total_current_density_A_m2"], dtype=float + ) + currents[idx] = -polarity * float(tot[0]) + prev_u = sol.state.u + prev_v = v_f + return currents + + return v_fwd, sweep_ionic_steady(v_fwd), v_rev, sweep_ionic_steady(v_rev) + + # driver == "transient_jv_strict": triangular Backward Euler forward -> reverse + sub = elec_prot.substeps_per_point + dv = float(v_fwd[1] - v_fwd[0]) + dt_sub = dv / (elec_prot.scan_rate_V_s * sub) + + if isinstance(compiled, CompiledDevice1D): + steady_init_opts = SteadyOptions( + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + ) + steady0 = solve_steady_state( + compiled, + initial_state=None, + voltage_V=0.0, + generation_scale=1.0, + options=steady_init_opts, + ) + if not steady0.converged: + raise ElectrothermalSourceError( + "Initial 0 V steady state did not converge for transient_jv_strict" + ) + polarity = float(compiled.voltage_polarity) + j0 = float(-polarity * steady0.current_density_A_m2[0]) + + times_list: list[float] = [0.0] + volts_list: list[float] = [0.0] + t_cur = 0.0 + if elec_prot.precondition_time_s > 0.0: + n_pre = max(4, int(math.ceil(elec_prot.precondition_time_s / max(dt_sub, 1e-3)))) + for k in range(1, n_pre + 1): + t_cur = elec_prot.precondition_time_s * k / n_pre + times_list.append(t_cur) + volts_list.append(0.0) + + fwd_sample_indices: list[int] = [len(times_list) - 1] + for i in range(1, v_fwd.size): + v_a = float(v_fwd[i - 1]) + v_b = float(v_fwd[i]) + for s in range(1, sub + 1): + t_cur += dt_sub + times_list.append(t_cur) + volts_list.append(v_a + (v_b - v_a) * (s / sub)) + fwd_sample_indices.append(len(times_list) - 1) + + rev_sample_indices: list[int] = [len(times_list) - 1] + for i in range(1, v_rev.size): + v_a = float(v_rev[i - 1]) + v_b = float(v_rev[i]) + for s in range(1, sub + 1): + t_cur += dt_sub + times_list.append(t_cur) + volts_list.append(v_a + (v_b - v_a) * (s / sub)) + rev_sample_indices.append(len(times_list) - 1) + + t_arr: np.ndarray = np.asarray(times_list, dtype=float) + v_arr: np.ndarray = np.asarray(volts_list, dtype=float) + g_arr: np.ndarray = np.ones_like(t_arr) + tr_prot = TransientProtocol(times_s=t_arr, voltage_V=v_arr, generation_scale=g_arr) + tr_opts = TransientOptions( + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + potential_step_V=0.25, + quasi_fermi_step=2.0, + newton_budget=SolveBudget(60, 480, 62, 12), + max_steps=t_arr.size + 4, + wall_s=elec_prot.wall_s_per_temperature, + predictor="previous", + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + tr_res = solve_transient( + compiled, + steady0, + tr_prot, + options=tr_opts, + initial_options=steady_init_opts, + method="backward_euler", + ) + if not tr_res.completed: + raise ElectrothermalSourceError( + "transient_jv_strict Backward Euler sweep failed certification" + ) + + step_currents: np.ndarray = np.empty(t_arr.size, dtype=float) + step_currents[0] = j0 + for idx_step, attempt in enumerate(tr_res.attempts, start=1): + assert attempt.accounting is not None + term = np.asarray( + attempt.accounting["terminal_total_current_density_A_m2"], dtype=float + ) + step_currents[idx_step] = -polarity * float(term[0]) + + j_fwd = step_currents[np.asarray(fwd_sample_indices, dtype=int)] + j_rev = step_currents[np.asarray(rev_sample_indices, dtype=int)] + return v_fwd, j_fwd, v_rev, j_rev + + # Ionic transient_jv_strict: fresh dark 0 V equilibrium followed by explicit + # finite-time 0 V illuminated preconditioning and Backward Euler J-V scan + ionic_steady_opts = IonicSteadyOptions( + electronic=SteadyOptions( + poisson_tolerance=elec_prot.poisson_tolerance, + continuity_tolerance_A_m2=elec_prot.continuity_tolerance_A_m2, + contact_log_tolerance=elec_prot.contact_log_tolerance, + convergence_policy=HISTORICAL_MAX_ROW_V1, + ), + inventory_relative_tolerance=1e-11, + ion_balance_tolerance_m2_s=elec_prot.ion_balance_tolerance_m2_s, + ion_flux_tolerance_m2_s=elec_prot.ion_balance_tolerance_m2_s, + ion_logit_step=2.0, + inventory_row_node=compiled.ion_node_count - 1, + budget=SolveBudget(120, 960, 122, 12), + wall_s=elec_prot.wall_s_per_temperature, + ) + init_sol = solve_ionic_steady_state( + compiled, + voltage_V=0.0, + generation_scale=0.0, + options=ionic_steady_opts, + initial_state=None, + ) + if not init_sol.accepted or init_sol.state is None or init_sol.diagnostics is None: + raise ElectrothermalSourceError( + f"Initial dark 0 V ionic steady state failed: {init_sol.termination}" + ) + cur_state = init_sol.state + settle_s = ( + elec_prot.precondition_time_s + if elec_prot.precondition_time_s > 0.0 + else 1e-3 + ) + pre_steps: list[tuple[float, float]] = [ + (1e-3, 2e-5), + (1e-1, 8e-5), + (1.0, 2e-4), + ] + rem_s = max(settle_s - 3e-4, 2e-4) + n_rem = max(2, int(math.ceil(rem_s / max(dt_sub, 1e-3)))) + for _ in range(n_rem): + pre_steps.append((1.0, rem_s / n_rem)) + + j_cur = 0.0 + for idx_pre, (g_pre, dt_pre) in enumerate(pre_steps): + cur_state, j_cur = _step_ionic_be( + compiled, + cur_state, + voltage_V=0.0, + generation_scale=g_pre, + dt_s=dt_pre, + elec_prot=elec_prot, + predictor="generation_inventory" if idx_pre == 0 else "previous", + ) + + j_fwd = np.empty(v_fwd.size, dtype=float) + j_fwd[0] = j_cur + for i in range(1, v_fwd.size): + v_a = float(v_fwd[i - 1]) + v_b = float(v_fwd[i]) + for s in range(1, sub + 1): + v_step = v_a + (v_b - v_a) * (s / sub) + cur_state, j_cur = _step_ionic_be( + compiled, + cur_state, + voltage_V=v_step, + generation_scale=1.0, + dt_s=dt_sub, + elec_prot=elec_prot, + ) + j_fwd[i] = j_cur + + j_rev = np.empty(v_rev.size, dtype=float) + j_rev[0] = j_cur + for i in range(1, v_rev.size): + v_a = float(v_rev[i - 1]) + v_b = float(v_rev[i]) + for s in range(1, sub + 1): + v_step = v_a + (v_b - v_a) * (s / sub) + cur_state, j_cur = _step_ionic_be( + compiled, + cur_state, + voltage_V=v_step, + generation_scale=1.0, + dt_s=dt_sub, + elec_prot=elec_prot, + ) + j_rev[i] = j_cur + + return v_fwd, j_fwd, v_rev, j_rev + + +def _extract_operating_point( + external: ExternalCircuitJVResult, + op_prot: ElectrothermalOperatingPointProtocol, +) -> tuple[float, float, float]: + """Extract ``(V_term, J_term, P_term)`` according to ``op_prot``.""" + is_fwd = op_prot.operating_branch == "forward" + v_branch = external.V_terminal_fwd if is_fwd else external.V_terminal_rev + j_branch = external.J_terminal_fwd if is_fwd else external.J_terminal_rev + metrics = external.metrics_fwd if is_fwd else external.metrics_rev + + order = np.argsort(v_branch) + v_sorted = v_branch[order] + j_sorted = j_branch[order] + + if op_prot.operating_point == "open_circuit": + if metrics.open_circuit_voltage_V is None: + raise ElectrothermalSourceError( + f"{op_prot.operating_branch} terminal branch does not bracket open circuit" + ) + return float(metrics.open_circuit_voltage_V), 0.0, 0.0 + + if op_prot.operating_point == "sampled_terminal_maximum_power": + if metrics.open_circuit_voltage_V is None: + raise ElectrothermalSourceError( + f"{op_prot.operating_branch} terminal branch does not bracket open circuit" + ) + mask = (v_branch >= 0.0) & (v_branch <= metrics.open_circuit_voltage_V) + indices = np.flatnonzero(mask) + if indices.size == 0: + raise ElectrothermalSourceError( + f"{op_prot.operating_branch} terminal branch has no power-quadrant sample" + ) + p_branch = v_branch * j_branch + idx = int(indices[int(np.argmax(p_branch[indices]))]) + v_sel = float(v_branch[idx]) + j_sel = float(j_branch[idx]) + p_sel = float(p_branch[idx]) + if not math.isfinite(p_sel) or p_sel < 0.0: + raise ElectrothermalSourceError("non-physical terminal maximum power") + return v_sel, j_sel, p_sel + + # fixed_load + if op_prot.fixed_terminal_voltage_V is not None: + v_req = float(op_prot.fixed_terminal_voltage_V) + if not (float(v_sorted[0]) <= v_req <= float(v_sorted[-1])): + raise ElectrothermalSourceError( + f"fixed_terminal_voltage_V={v_req:.4f} V lies outside terminal sweep " + f"[{float(v_sorted[0]):.4f}, {float(v_sorted[-1]):.4f}] V" + ) + j_req = float(np.interp(v_req, v_sorted, j_sorted)) + return v_req, j_req, v_req * j_req + + assert op_prot.load_resistance_ohm_m2 is not None + r_load = float(op_prot.load_resistance_ohm_m2) + if metrics.open_circuit_voltage_V is None or metrics.short_circuit_current_A_m2 is None: + raise ElectrothermalSourceError( + "load_resistance_ohm_m2 operating point requires bracketed J_sc and V_oc" + ) + v_hi = float(metrics.open_circuit_voltage_V) + + def load_mismatch(v_val: float) -> float: + j_interp = float(np.interp(v_val, v_sorted, j_sorted)) + return v_val - r_load * j_interp + + v_load = float(brentq(load_mismatch, 0.0, v_hi, xtol=1e-12, maxiter=100)) + j_load = float(np.interp(v_load, v_sorted, j_sorted)) + return v_load, j_load, v_load * j_load + + +def solve_electrothermal_operating_point( + prepared: PreparedDevice, + thermal_protocol: LumpedThermalProtocol, + circuit_protocol: ExternalCircuitProtocol | None = None, + electrical_protocol: ElectrothermalJVProtocol | None = None, + operating_protocol: ElectrothermalOperatingPointProtocol | None = None, + *, + external_temperature_K: object = None, + temperature_schedule_K: object = None, +) -> ElectrothermalOperatingPointResult: + """Solve the coupled steady-state electrothermal operating point on ``[T_amb, T_max]``.""" + if external_temperature_K is not None or temperature_schedule_K is not None: + raise ElectrothermalCapabilityError( + "electrothermal self-heating is mutually exclusive with an external " + "temperature override or T(t) schedule" + ) + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice") + if not isinstance(thermal_protocol, LumpedThermalProtocol): + raise TypeError("thermal_protocol must be a LumpedThermalProtocol") + + circ_prot = ExternalCircuitProtocol() if circuit_protocol is None else circuit_protocol + if not isinstance(circ_prot, ExternalCircuitProtocol): + raise TypeError("circuit_protocol must be an ExternalCircuitProtocol") + + elec_prot = ElectrothermalJVProtocol() if electrical_protocol is None else electrical_protocol + if not isinstance(elec_prot, ElectrothermalJVProtocol): + raise TypeError("electrical_protocol must be an ElectrothermalJVProtocol") + + op_prot = ( + ElectrothermalOperatingPointProtocol() + if operating_protocol is None + else operating_protocol + ) + if not isinstance(op_prot, ElectrothermalOperatingPointProtocol): + raise TypeError("operating_protocol must be an ElectrothermalOperatingPointProtocol") + + evaluations: list[ElectrothermalTemperatureEvaluation] = [] + external_by_temp: dict[float, ExternalCircuitJVResult] = {} + eval_by_temp: dict[float, ElectrothermalTemperatureEvaluation] = {} + + def evaluate(temperature_K: float) -> ElectrothermalTemperatureEvaluation: + t_val = float(temperature_K) + cached = eval_by_temp.get(t_val) + if cached is not None: + return cached + + rebound, compiled = compile_prepared_at_temperature( + prepared, + t_val, + intervals_per_layer=elec_prot.intervals_per_layer, + ion_domain_layer=elec_prot.ion_domain_layer, + ion_domain_endpoints=elec_prot.ion_domain_endpoints, + ) + v_fwd, j_fwd, v_rev, j_rev = run_fresh_jv_at_temperature(compiled, elec_prot) + ext_res = apply_external_circuit( + (v_fwd, j_fwd, v_rev, j_rev), + circ_prot, + incident_power_W_m2=elec_prot.incident_power_W_m2, + ) + v_op, j_op, p_op = _extract_operating_point(ext_res, op_prot) + ledger = thermal_power_ledger( + t_val, + thermal_protocol, + exported_electrical_power_W_m2=p_op, + ) + record = ElectrothermalTemperatureEvaluation( + temperature_K=t_val, + rebound_prepared_sha256=rebound.content_sha256, + compiled_identity=compiled.identity, + terminal_voltage_V=v_op, + terminal_current_A_m2=j_op, + terminal_power_W_m2=p_op, + power_balance_residual_W_m2=ledger.net_storage_rate_W_m2, + external_result_sha256=ext_res.result_sha256, + fresh_state_initialized=True, + source_certified=True, + ) + evaluations.append(record) + eval_by_temp[t_val] = record + external_by_temp[t_val] = ext_res + return record + + t_amb = thermal_protocol.ambient_temperature_K + t_max = thermal_protocol.maximum_temperature_K + p_tol = op_prot.power_residual_tolerance_W_m2 + + lo_eval = evaluate(t_amb) + root_iterations = 0 + if abs(lo_eval.power_balance_residual_W_m2) <= p_tol: + t_star = t_amb + else: + if lo_eval.power_balance_residual_W_m2 < 0.0: + raise ElectrothermalConvergenceError( + f"Electrothermal storage rate is negative at T_amb={t_amb:.3f} K " + f"({lo_eval.power_balance_residual_W_m2:.4g} W/m^2)" + ) + hi_eval = evaluate(t_max) + if abs(hi_eval.power_balance_residual_W_m2) <= p_tol: + t_star = t_max + else: + if hi_eval.power_balance_residual_W_m2 > 0.0: + raise ElectrothermalConvergenceError( + f"Electrothermal root is not bracketed below T_max={t_max:.3f} K " + f"(f(T_max)={hi_eval.power_balance_residual_W_m2:.4g} W/m^2 > 0)" + ) + root_val, root_info = brentq( + lambda temp: evaluate(float(temp)).power_balance_residual_W_m2, + t_amb, + t_max, + xtol=op_prot.temperature_absolute_tolerance_K, + rtol=4.0 * float(np.finfo(float).eps), + maxiter=op_prot.maximum_root_iterations, + full_output=True, + disp=False, + ) + if not root_info.converged: + raise ElectrothermalConvergenceError( + "Electrothermal Brent root finder did not converge" + ) + t_star = float(root_val) + root_iterations = int(root_info.iterations) + + final_eval = evaluate(t_star) + if abs(final_eval.power_balance_residual_W_m2) > p_tol: + raise ElectrothermalConvergenceError( + f"Electrothermal power residual {abs(final_eval.power_balance_residual_W_m2):.3e} W/m^2 " + f"exceeds {p_tol:.3e} W/m^2" + ) + final_ext = external_by_temp[final_eval.temperature_K] + final_ledger = thermal_power_ledger( + final_eval.temperature_K, + thermal_protocol, + exported_electrical_power_W_m2=final_eval.terminal_power_W_m2, + ) + frozen_evals = tuple(evaluations) + mapping_sha = _canonical_sha256( + { + "base_prepared_sha256": prepared.content_sha256, + "thermal_protocol": asdict(thermal_protocol), + "circuit_protocol": asdict(circ_prot), + "electrical_protocol_sha256": elec_prot.sha256, + "operating_protocol_sha256": op_prot.sha256, + "operating_temperature_K": final_eval.temperature_K.hex(), + "final_external_sha256": final_ext.result_sha256, + "evaluation_count": len(frozen_evals), + } + ) + return ElectrothermalOperatingPointResult( + operating_temperature_K=final_eval.temperature_K, + temperature_rise_K=final_eval.temperature_K - t_amb, + terminal_voltage_V=final_eval.terminal_voltage_V, + terminal_current_A_m2=final_eval.terminal_current_A_m2, + terminal_power_W_m2=final_eval.terminal_power_W_m2, + power_balance_residual_W_m2=final_eval.power_balance_residual_W_m2, + thermal_ledger=final_ledger, + final_external_result=final_ext, + temperature_evaluations=frozen_evals, + electrical_evaluations=len(frozen_evals), + root_iterations=root_iterations, + base_prepared_sha256=prepared.content_sha256, + thermal_protocol=thermal_protocol, + circuit_protocol=circ_prot, + electrical_protocol=elec_prot, + operating_protocol=op_prot, + time_domain_temperature_qualified=bool(TIME_DOMAIN_TEMPERATURE_QUALIFIED), + mapping_sha256=mapping_sha, + certified=True, + ) diff --git a/src/solarlab/experiments/external_circuit.py b/src/solarlab/experiments/external_circuit.py new file mode 100644 index 00000000..6118c74f --- /dev/null +++ b/src/solarlab/experiments/external_circuit.py @@ -0,0 +1,705 @@ +"""External lumped DC and small-signal AC circuit wrappers for 1D experiments. + +System-level series resistance, shunt resistance, and external parallel +capacitance live strictly outside the 1D semiconductor drift-diffusion PDE: +device contacts and compiled parameters are never mutated. + +Sign and circuit conventions (photovoltaic output-positive): +- ``J_device > 0`` delivers positive power to an external load at ``V > 0``. +- The shunt branch sits across the device junction terminals ``V_junction``: + ``J_shunt = V_junction / R_shunt`` and ``J_terminal = J_device - J_shunt``. +- The series resistance sits between the junction/shunt node and the external + measurement terminals: ``V_terminal = V_junction - J_terminal * R_series``. +- Small-signal AC phasors follow ``exp(+i * omega * t)`` with passive input + admittance per unit area ``Y(omega)`` [S/m^2]: + ``Y_junc(omega) = Y_device(omega) + G_shunt + i * omega * C_ext``, + ``Y_terminal(omega) = Y_junc(omega) / (1 + R_series * Y_junc(omega))``. + +All electrical parasitics are area-normalized (``R_s``, ``R_sh`` in ``ohm*m^2``, +``C_ext`` in ``F/m^2``) and explicitly separated from lumped thermal parameters +(``C_th`` in ``J/(m^2*K)``). +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any + +import numpy as np + +from solarlab.experiments.jv.steady import ( + SteadyJVMetrics, + SteadyJVResult, + steady_jv_metrics, +) +from solarlab.experiments.impedance import SmallSignalResult1D +from solarlab.experiments.ionic_impedance import IonicImpedanceResult + +__all__ = [ + "EXTERNAL_AC_UNIT_SCHEMA", + "EXTERNAL_DC_UNIT_SCHEMA", + "ExternalACCircuitProtocol", + "ExternalACImpedanceResult", + "ExternalCircuitBranch", + "ExternalCircuitError", + "ExternalCircuitJVResult", + "ExternalCircuitProtocol", + "ExternalCircuitSteadyResult", + "ExternalCircuitTopologyError", + "apply_external_circuit", + "apply_external_circuit_steady", + "compose_external_ac_impedance", + "map_external_circuit_branch", +] + +EXTERNAL_DC_UNIT_SCHEMA: dict[str, str] = { + "series_resistance_ohm_m2": "ohm*m^2", + "shunt_resistance_ohm_m2": "ohm*m^2", +} + +EXTERNAL_AC_UNIT_SCHEMA: dict[str, str] = { + "series_resistance_ohm_m2": "ohm*m^2", + "shunt_resistance_ohm_m2": "ohm*m^2", + "external_capacitance_F_m2": "F/m^2", +} + + +class ExternalCircuitError(ValueError): + """Invalid external-circuit protocol or uncertified electrical input.""" + + +class ExternalCircuitTopologyError(ExternalCircuitError): + """External series drop folded or singularized the terminal coordinate.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def _array_hex_list(values: np.ndarray) -> list[str]: + flat = np.asarray(values, dtype=float).ravel() + return [float(x).hex() for x in flat] + + +def _complex_hex_list(values: np.ndarray) -> list[list[str]]: + flat = np.asarray(values, dtype=complex).ravel() + return [[float(z.real).hex(), float(z.imag).hex()] for z in flat] + + +def _freeze_float_1d(values: object, *, name: str, min_size: int = 1) -> np.ndarray: + if np.iscomplexobj(values): + raise ExternalCircuitError(f"{name} must be real-valued") + arr = np.array(values, dtype=float, copy=True) + if arr.ndim != 1 or arr.size < min_size or not np.all(np.isfinite(arr)): + raise ExternalCircuitError( + f"{name} must be a 1-D finite array with at least {min_size} sample(s)" + ) + arr.setflags(write=False) + return arr + + +def _freeze_complex_1d(values: object, *, name: str, min_size: int = 1) -> np.ndarray: + arr = np.array(values, dtype=complex, copy=True) + if arr.ndim != 1 or arr.size < min_size or not np.all(np.isfinite(arr)): + raise ExternalCircuitError( + f"{name} must be a 1-D finite complex array with at least {min_size} sample(s)" + ) + arr.setflags(write=False) + return arr + + +@dataclass(frozen=True) +class ExternalCircuitProtocol: + """Area-normalized lumped external DC parasitic elements.""" + + series_resistance_ohm_m2: float = 0.0 + shunt_resistance_ohm_m2: float | None = None + shunt_voltage_reference: str = "junction" + current_convention: str = "photovoltaic_output_positive" + + def __post_init__(self) -> None: + if not _is_real_number(self.series_resistance_ohm_m2): + raise ExternalCircuitError("series_resistance_ohm_m2 must be a real scalar") + rs = float(self.series_resistance_ohm_m2) + if not math.isfinite(rs) or rs < 0.0: + raise ExternalCircuitError( + f"series_resistance_ohm_m2 must be finite and >= 0, got {self.series_resistance_ohm_m2!r}" + ) + object.__setattr__(self, "series_resistance_ohm_m2", rs) + + if self.shunt_resistance_ohm_m2 is not None: + if not _is_real_number(self.shunt_resistance_ohm_m2): + raise ExternalCircuitError( + "shunt_resistance_ohm_m2 must be None or a positive real scalar" + ) + rsh = float(self.shunt_resistance_ohm_m2) + if not math.isfinite(rsh) or rsh <= 0.0: + raise ExternalCircuitError( + f"shunt_resistance_ohm_m2 must be finite and > 0 when set, got {self.shunt_resistance_ohm_m2!r}" + ) + object.__setattr__(self, "shunt_resistance_ohm_m2", rsh) + + if self.shunt_voltage_reference != "junction": + raise ExternalCircuitError( + f"Unsupported shunt_voltage_reference {self.shunt_voltage_reference!r}; only 'junction' is supported" + ) + if self.current_convention != "photovoltaic_output_positive": + raise ExternalCircuitError( + f"Unsupported current_convention {self.current_convention!r}; " + "only 'photovoltaic_output_positive' is supported" + ) + + @property + def parameter_units(self) -> dict[str, str]: + return dict(EXTERNAL_DC_UNIT_SCHEMA) + + +@dataclass(frozen=True) +class ExternalCircuitBranch: + """Mapped single-branch J-V curve with explicit series/shunt loss accounting.""" + + direction: str + V_junction: np.ndarray + J_device: np.ndarray + V_terminal: np.ndarray + J_terminal: np.ndarray + J_shunt: np.ndarray + series_voltage_drop_V: np.ndarray + power_terminal_W_m2: np.ndarray + series_loss_W_m2: np.ndarray + shunt_loss_W_m2: np.ndarray + metrics: SteadyJVMetrics + + +@dataclass(frozen=True) +class ExternalCircuitSteadyResult: + """Single-branch steady J-V curve mapped to external terminals.""" + + protocol: ExternalCircuitProtocol + branch: ExternalCircuitBranch + incident_power_W_m2: float | None + source_identity: str | None + source_sha256: str + result_sha256: str + + +@dataclass(frozen=True) +class ExternalCircuitJVResult: + """Forward and reverse J-V branches mapped to external terminals.""" + + protocol: ExternalCircuitProtocol + V_junction_fwd: np.ndarray + J_device_fwd: np.ndarray + V_terminal_fwd: np.ndarray + J_terminal_fwd: np.ndarray + J_shunt_fwd: np.ndarray + metrics_fwd: SteadyJVMetrics + V_junction_rev: np.ndarray + J_device_rev: np.ndarray + V_terminal_rev: np.ndarray + J_terminal_rev: np.ndarray + J_shunt_rev: np.ndarray + metrics_rev: SteadyJVMetrics + hysteresis_index: float | None + incident_power_W_m2: float | None + source_certified: bool + source_sha256: str + result_sha256: str + + +@dataclass(frozen=True) +class ExternalACCircuitProtocol: + """Area-normalized lumped external small-signal AC parasitic network. + + ``external_capacitance_F_m2`` has units of ``F/m^2`` (electrical areal + capacitance across the junction port) and never aliases lumped thermal + heat capacity ``J/(m^2*K)``. + """ + + series_resistance_ohm_m2: float = 0.0 + shunt_resistance_ohm_m2: float | None = None + external_capacitance_F_m2: float = 0.0 + shunt_branch_reference: str = "junction" + phasor_convention: str = "exp(+i omega t)" + + def __post_init__(self) -> None: + if not _is_real_number(self.series_resistance_ohm_m2): + raise ExternalCircuitError("series_resistance_ohm_m2 must be a real scalar") + rs = float(self.series_resistance_ohm_m2) + if not math.isfinite(rs) or rs < 0.0: + raise ExternalCircuitError( + f"series_resistance_ohm_m2 must be finite and >= 0, got {self.series_resistance_ohm_m2!r}" + ) + object.__setattr__(self, "series_resistance_ohm_m2", rs) + + if self.shunt_resistance_ohm_m2 is not None: + if not _is_real_number(self.shunt_resistance_ohm_m2): + raise ExternalCircuitError( + "shunt_resistance_ohm_m2 must be None or a positive real scalar" + ) + rsh = float(self.shunt_resistance_ohm_m2) + if not math.isfinite(rsh) or rsh <= 0.0: + raise ExternalCircuitError( + f"shunt_resistance_ohm_m2 must be finite and > 0 when set, got {self.shunt_resistance_ohm_m2!r}" + ) + object.__setattr__(self, "shunt_resistance_ohm_m2", rsh) + + if not _is_real_number(self.external_capacitance_F_m2): + raise ExternalCircuitError("external_capacitance_F_m2 must be a real scalar") + cext = float(self.external_capacitance_F_m2) + if not math.isfinite(cext) or cext < 0.0: + raise ExternalCircuitError( + f"external_capacitance_F_m2 must be finite and >= 0, got {self.external_capacitance_F_m2!r}" + ) + object.__setattr__(self, "external_capacitance_F_m2", cext) + + if self.shunt_branch_reference != "junction": + raise ExternalCircuitError( + f"Unsupported shunt_branch_reference {self.shunt_branch_reference!r}; only 'junction' is supported" + ) + if self.phasor_convention != "exp(+i omega t)": + raise ExternalCircuitError( + f"Unsupported phasor_convention {self.phasor_convention!r}; only 'exp(+i omega t)' is supported" + ) + + @property + def parameter_units(self) -> dict[str, str]: + return dict(EXTERNAL_AC_UNIT_SCHEMA) + + +@dataclass(frozen=True) +class ExternalACImpedanceResult: + """Small-signal AC admittance/impedance after external lumped composition.""" + + protocol: ExternalACCircuitProtocol + frequency_Hz: np.ndarray + angular_frequency_rad_s: np.ndarray + device_admittance_S_m2: np.ndarray + shunt_admittance_S_m2: np.ndarray + junction_admittance_S_m2: np.ndarray + terminal_admittance_S_m2: np.ndarray + terminal_impedance_ohm_m2: np.ndarray | None + source_identity: str | None + source_sha256: str + result_sha256: str + + @property + def admittance_density_S_m2(self) -> np.ndarray: + return self.terminal_admittance_S_m2 + + @property + def impedance_area_ohm_m2(self) -> np.ndarray: + if self.terminal_impedance_ohm_m2 is not None: + return self.terminal_impedance_ohm_m2 + if np.any(self.terminal_admittance_S_m2 == 0.0): + raise ExternalCircuitTopologyError( + "zero terminal admittance has no finite impedance-area product" + ) + inv = 1.0 / self.terminal_admittance_S_m2 + if not np.all(np.isfinite(inv)): + raise ExternalCircuitTopologyError( + "terminal impedance-area product overflows binary64" + ) + inv.setflags(write=False) + return inv + + +def _require_strict_monotonic(v: np.ndarray, *, label: str) -> int: + dv = np.diff(v) + if np.all(dv > 0.0): + return 1 + if np.all(dv < 0.0): + return -1 + raise ExternalCircuitTopologyError( + f"{label} voltage coordinates are not strictly monotonic" + ) + + +def map_external_circuit_branch( + V_junction: object, + J_device: object, + protocol: ExternalCircuitProtocol, + *, + direction: str = "steady", + incident_power_W_m2: float | None = None, +) -> ExternalCircuitBranch: + """Map one strictly monotonic device J-V branch to external terminals.""" + if not isinstance(protocol, ExternalCircuitProtocol): + raise ExternalCircuitError("protocol must be an ExternalCircuitProtocol") + if direction not in {"forward", "reverse", "steady"}: + raise ExternalCircuitError( + f"direction must be 'forward', 'reverse', or 'steady', got {direction!r}" + ) + if incident_power_W_m2 is not None and ( + not _is_real_number(incident_power_W_m2) + or not math.isfinite(float(incident_power_W_m2)) + or float(incident_power_W_m2) <= 0.0 + ): + raise ExternalCircuitError("incident_power_W_m2 must be None or finite positive") + + v_junc = _freeze_float_1d(V_junction, name=f"V_junction ({direction})", min_size=2) + j_dev = _freeze_float_1d(J_device, name=f"J_device ({direction})", min_size=2) + if v_junc.shape != j_dev.shape: + raise ExternalCircuitError( + f"V_junction and J_device ({direction}) must have identical shapes, " + f"got {v_junc.shape} and {j_dev.shape}" + ) + junc_orient = _require_strict_monotonic(v_junc, label=f"{direction} junction") + if direction == "forward" and junc_orient != 1: + raise ExternalCircuitError( + "forward branch junction voltages must be strictly increasing" + ) + if direction == "reverse" and junc_orient != -1: + raise ExternalCircuitError( + "reverse branch junction voltages must be strictly decreasing" + ) + + if protocol.shunt_resistance_ohm_m2 is None: + j_shunt = np.zeros_like(v_junc) + else: + j_shunt = v_junc / protocol.shunt_resistance_ohm_m2 + + j_term = j_dev - j_shunt + v_drop = j_term * protocol.series_resistance_ohm_m2 + v_term = v_junc - v_drop + if not np.all(np.isfinite(v_term)) or not np.all(np.isfinite(j_term)): + raise ExternalCircuitError( + f"nonfinite terminal J-V samples produced on {direction} branch" + ) + + term_orient = _require_strict_monotonic( + v_term, + label=( + f"{direction} terminal (series_resistance_ohm_m2=" + f"{protocol.series_resistance_ohm_m2:g} folded the sweep)" + ), + ) + if term_orient != junc_orient: + raise ExternalCircuitTopologyError( + f"{direction} terminal voltage orientation reversed relative to junction sweep" + ) + + p_term = v_term * j_term + p_series = (j_term * j_term) * protocol.series_resistance_ohm_m2 + p_shunt = v_junc * j_shunt + + for arr in (j_shunt, j_term, v_drop, v_term, p_term, p_series, p_shunt): + arr.setflags(write=False) + + metrics = steady_jv_metrics( + v_term, + j_term, + incident_power_W_m2=( + None if incident_power_W_m2 is None else float(incident_power_W_m2) + ), + ) + return ExternalCircuitBranch( + direction=direction, + V_junction=v_junc, + J_device=j_dev, + V_terminal=v_term, + J_terminal=j_term, + J_shunt=j_shunt, + series_voltage_drop_V=v_drop, + power_terminal_W_m2=p_term, + series_loss_W_m2=p_series, + shunt_loss_W_m2=p_shunt, + metrics=metrics, + ) + + +def apply_external_circuit_steady( + source: SteadyJVResult | tuple[object, object], + protocol: ExternalCircuitProtocol, + *, + incident_power_W_m2: float | None = None, +) -> ExternalCircuitSteadyResult: + """Apply an external DC circuit to a certified ``SteadyJVResult`` or ``(V, J)`` pair.""" + if isinstance(source, SteadyJVResult): + if len(source.solutions) != source.voltage_V.size or any( + not pt.converged for pt in source.solutions + ): + raise ExternalCircuitError( + "SteadyJVResult contains uncertified steady-state points" + ) + v_in: object = source.voltage_V + j_in: object = source.output_current_A_m2 + p_in = source.incident_power_W_m2 if incident_power_W_m2 is None else incident_power_W_m2 + source_identity: str | None = source.compiled_identity + elif isinstance(source, tuple) and len(source) == 2: + v_in, j_in = source + p_in = incident_power_W_m2 + source_identity = None + else: + raise ExternalCircuitError( + "source must be a SteadyJVResult or a (V_junction, J_device) tuple" + ) + + branch = map_external_circuit_branch( + v_in, j_in, protocol, direction="steady", incident_power_W_m2=p_in + ) + source_sha = _canonical_sha256( + { + "V_junction": _array_hex_list(branch.V_junction), + "J_device": _array_hex_list(branch.J_device), + "source_identity": source_identity, + } + ) + result_sha = _canonical_sha256( + { + "source_sha256": source_sha, + "protocol": asdict(protocol), + "V_terminal": _array_hex_list(branch.V_terminal), + "J_terminal": _array_hex_list(branch.J_terminal), + "metrics": asdict(branch.metrics), + } + ) + return ExternalCircuitSteadyResult( + protocol=protocol, + branch=branch, + incident_power_W_m2=None if p_in is None else float(p_in), + source_identity=source_identity, + source_sha256=source_sha, + result_sha256=result_sha, + ) + + +def _hysteresis_index( + metrics_fwd: SteadyJVMetrics, + metrics_rev: SteadyJVMetrics, +) -> float | None: + p_fwd = metrics_fwd.maximum_power_W_m2 + p_rev = metrics_rev.maximum_power_W_m2 + if p_fwd is None or p_rev is None or not math.isfinite(p_rev) or p_rev <= 0.0: + return None + return float((p_rev - p_fwd) / p_rev) + + +def apply_external_circuit( + jv: Any, + protocol: ExternalCircuitProtocol, + *, + incident_power_W_m2: float | None = None, +) -> ExternalCircuitJVResult: + """Map a dual-branch (forward + reverse) J-V sweep to external terminals. + + Accepts either a dual-branch sweep object exposing ``(V_fwd, J_fwd, V_rev, J_rev)`` + (refusing ``certified is False`` or ``completed is False``) or a 4-tuple + ``(V_fwd, J_fwd, V_rev, J_rev)``. + """ + if isinstance(jv, tuple) and len(jv) == 4: + v_fwd_raw, j_fwd_raw, v_rev_raw, j_rev_raw = jv + source_certified = True + elif all(hasattr(jv, attr) for attr in ("V_fwd", "J_fwd", "V_rev", "J_rev")): + if getattr(jv, "certified", True) is False or getattr(jv, "completed", True) is False: + raise ExternalCircuitError( + "apply_external_circuit refuses an uncertified or incomplete J-V sweep" + ) + v_fwd_raw = jv.V_fwd + j_fwd_raw = jv.J_fwd + v_rev_raw = jv.V_rev + j_rev_raw = jv.J_rev + source_certified = bool(getattr(jv, "certified", True)) + else: + raise ExternalCircuitError( + "jv must provide (V_fwd, J_fwd, V_rev, J_rev) attributes or be a 4-tuple" + ) + + fwd = map_external_circuit_branch( + v_fwd_raw, + j_fwd_raw, + protocol, + direction="forward", + incident_power_W_m2=incident_power_W_m2, + ) + rev = map_external_circuit_branch( + v_rev_raw, + j_rev_raw, + protocol, + direction="reverse", + incident_power_W_m2=incident_power_W_m2, + ) + hi = _hysteresis_index(fwd.metrics, rev.metrics) + + source_sha = _canonical_sha256( + { + "V_junction_fwd": _array_hex_list(fwd.V_junction), + "J_device_fwd": _array_hex_list(fwd.J_device), + "V_junction_rev": _array_hex_list(rev.V_junction), + "J_device_rev": _array_hex_list(rev.J_device), + "source_certified": source_certified, + } + ) + result_sha = _canonical_sha256( + { + "source_sha256": source_sha, + "protocol": asdict(protocol), + "V_terminal_fwd": _array_hex_list(fwd.V_terminal), + "J_terminal_fwd": _array_hex_list(fwd.J_terminal), + "V_terminal_rev": _array_hex_list(rev.V_terminal), + "J_terminal_rev": _array_hex_list(rev.J_terminal), + "metrics_fwd": asdict(fwd.metrics), + "metrics_rev": asdict(rev.metrics), + "hysteresis_index": hi, + } + ) + return ExternalCircuitJVResult( + protocol=protocol, + V_junction_fwd=fwd.V_junction, + J_device_fwd=fwd.J_device, + V_terminal_fwd=fwd.V_terminal, + J_terminal_fwd=fwd.J_terminal, + J_shunt_fwd=fwd.J_shunt, + metrics_fwd=fwd.metrics, + V_junction_rev=rev.V_junction, + J_device_rev=rev.J_device, + V_terminal_rev=rev.V_terminal, + J_terminal_rev=rev.J_terminal, + J_shunt_rev=rev.J_shunt, + metrics_rev=rev.metrics, + hysteresis_index=hi, + incident_power_W_m2=( + None if incident_power_W_m2 is None else float(incident_power_W_m2) + ), + source_certified=source_certified, + source_sha256=source_sha, + result_sha256=result_sha, + ) + + +def compose_external_ac_impedance( + source: SmallSignalResult1D | IonicImpedanceResult | tuple[object, object], + protocol: ExternalACCircuitProtocol, +) -> ExternalACImpedanceResult: + """Compose small-signal device admittance with external ``(R_s, R_sh, C_ext)``. + + Under the ``exp(+i * omega * t)`` phasor convention: + ``Y_shunt(omega) = G_shunt + i * omega * C_ext``, + ``Y_junc(omega) = Y_device(omega) + Y_shunt(omega)``, + ``Y_terminal(omega) = Y_junc(omega) / (1 + R_series * Y_junc(omega))``. + + Neither ``source`` nor any compiled semiconductor device is mutated. + """ + if not isinstance(protocol, ExternalACCircuitProtocol): + raise ExternalCircuitError("protocol must be an ExternalACCircuitProtocol") + + if isinstance(source, SmallSignalResult1D): + freq = _freeze_float_1d(source.frequency_Hz, name="frequency_Hz", min_size=1) + y_dev = _freeze_complex_1d( + source.admittance_density_S_m2, name="admittance_density_S_m2", min_size=1 + ) + source_identity: str | None = source.compiled_identity + elif isinstance(source, IonicImpedanceResult): + if not source.completed: + raise ExternalCircuitError( + "compose_external_ac_impedance refuses an incomplete IonicImpedanceResult" + ) + freq = _freeze_float_1d( + source.requested_frequencies_Hz, name="requested_frequencies_Hz", min_size=1 + ) + admittances: list[complex] = [] + for attempt in source.attempts: + if not attempt.accepted or attempt.observation is None: + raise ExternalCircuitError( + "IonicImpedanceResult contains an unaccepted frequency attempt" + ) + raw_y = attempt.observation.get("admittance_density_S_m2") + if raw_y is None: + raise ExternalCircuitError( + "IonicImpedanceAttempt observation omits admittance_density_S_m2" + ) + admittances.append(complex(raw_y)) + y_dev = _freeze_complex_1d( + admittances, name="admittance_density_S_m2", min_size=1 + ) + source_identity = source.compiled_identity + elif isinstance(source, tuple) and len(source) == 2: + freq = _freeze_float_1d(source[0], name="frequency_Hz", min_size=1) + y_dev = _freeze_complex_1d( + source[1], name="admittance_density_S_m2", min_size=1 + ) + source_identity = None + else: + raise ExternalCircuitError( + "source must be SmallSignalResult1D, IonicImpedanceResult, or (frequency_Hz, admittance_S_m2)" + ) + + if freq.shape != y_dev.shape: + raise ExternalCircuitError( + f"frequency_Hz and admittance_density_S_m2 shapes disagree: {freq.shape} vs {y_dev.shape}" + ) + if np.any(freq < 0.0): + raise ExternalCircuitError("frequency_Hz must be nonnegative") + + omega = 2.0 * np.pi * freq + omega.setflags(write=False) + + g_shunt = ( + 0.0 + if protocol.shunt_resistance_ohm_m2 is None + else 1.0 / protocol.shunt_resistance_ohm_m2 + ) + y_shunt = g_shunt + 1j * omega * protocol.external_capacitance_F_m2 + y_junc = y_dev + y_shunt + denom = 1.0 + protocol.series_resistance_ohm_m2 * y_junc + if np.any(denom == 0.0) or not np.all(np.isfinite(denom)): + raise ExternalCircuitTopologyError( + "1 + R_series * Y_junction vanished or overflowed during AC circuit composition" + ) + y_term = y_junc / denom + if not np.all(np.isfinite(y_term)): + raise ExternalCircuitError("nonfinite terminal admittance in AC composition") + + z_term: np.ndarray | None + if np.all(y_junc != 0.0): + candidate_z = protocol.series_resistance_ohm_m2 + 1.0 / y_junc + if np.all(np.isfinite(candidate_z)): + candidate_z.setflags(write=False) + z_term = candidate_z + else: + z_term = None + else: + z_term = None + + for arr in (y_shunt, y_junc, y_term): + arr.setflags(write=False) + + source_sha = _canonical_sha256( + { + "frequency_Hz": _array_hex_list(freq), + "device_admittance_S_m2": _complex_hex_list(y_dev), + "source_identity": source_identity, + } + ) + result_sha = _canonical_sha256( + { + "source_sha256": source_sha, + "protocol": asdict(protocol), + "terminal_admittance_S_m2": _complex_hex_list(y_term), + } + ) + return ExternalACImpedanceResult( + protocol=protocol, + frequency_Hz=freq, + angular_frequency_rad_s=omega, + device_admittance_S_m2=y_dev, + shunt_admittance_S_m2=y_shunt, + junction_admittance_S_m2=y_junc, + terminal_admittance_S_m2=y_term, + terminal_impedance_ohm_m2=z_term, + source_identity=source_identity, + source_sha256=source_sha, + result_sha256=result_sha, + ) diff --git a/src/solarlab/experiments/open_circuit.py b/src/solarlab/experiments/open_circuit.py new file mode 100644 index 00000000..3080ed14 --- /dev/null +++ b/src/solarlab/experiments/open_circuit.py @@ -0,0 +1,761 @@ +"""Charge-conserving floating-terminal (open-circuit) Backward Euler integrator. + +At genuine open circuit, zero external terminal current means zero Gauss-Maxwell +total port current density: + + I_total,port = I_carrier,port + I_ion,port + dD_port / dt = 0 + +NEVER steady conduction current ``I_cond = 0`` (which drops ``dD_port / dt`` and +turns dynamic photovoltage relaxation into an unphysical algebraic clamp). + +At each Backward Euler step ``[t_{k-1}, t_k]``, the ``(M + 1)``-unknown system +``z = [y; V_terminal]`` solves all ``M`` physical PDE Backward Euler rows +simultaneously with ``I_total,left(y, V_terminal) = 0`` via bordered sparse +Newton iteration, certifying all-face Maxwell current closure and telescoping +port-charge conservation. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import cast + +import numpy as np +from scipy.sparse import bmat, csc_matrix, diags +from scipy.sparse.linalg import splu + +from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem, State1D +from solarlab.equations.ionic_1d import ( + CompiledIonicDevice1D, + Ionic1DProblem, + IonicState1D, +) +from solarlab.solvers.nonlinear.production import ( + POISSON_CONTACT_BALANCE_V1, + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.time.backward_euler import ( + BackwardEuler1DStep, + step_accounting as electronic_step_accounting, +) +from solarlab.solvers.time.carrier_seed import transient_density_basin_seed +from solarlab.solvers.time.ionic_backward_euler import ( + IonicBackwardEuler1DStep, + step_accounting as ionic_step_accounting, +) + +__all__ = [ + "OpenCircuitError", + "OpenCircuitOptions", + "OpenCircuitStepDiagnostics", + "OpenCircuitTrajectory", + "geometric_series_capacitance_F_m2", + "integrate_open_circuit", +] + + +class OpenCircuitError(RuntimeError): + """Floating-terminal Backward Euler step failed convergence or conservation.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def geometric_series_capacitance_F_m2( + device: CompiledDevice1D | CompiledIonicDevice1D, +) -> float: + """Return total series geometric capacitance ``(sum_f 1 / C_f)^(-1)`` [F/m^2].""" + comp = ( + device.electronic_component + if isinstance(device, CompiledIonicDevice1D) + else device + ) + inv_sum = float(np.sum(1.0 / comp.poisson.face_capacitance_F_m2)) + return 1.0 / inv_sum + + +@dataclass(frozen=True) +class OpenCircuitOptions: + """Numerical tolerances and Newton controls for floating-terminal integration.""" + + poisson_tolerance: float = 1e-12 + continuity_tolerance_A_m2: float = 1e-8 + contact_log_tolerance: float = 1e-12 + ion_balance_tolerance_m2_s: float = 1e9 + max_current_error_A_m2: float = 1e-7 + max_voltage_error_V: float = 1e-6 + potential_step_V: float = 0.1 + quasi_fermi_step: float = 2.0 + ion_logit_step: float = 2.0 + terminal_voltage_step_V: float = 0.15 + max_newton_iterations: int = 80 + fd_epsilon: float = 1e-8 + + def __post_init__(self) -> None: + for name in ( + "poisson_tolerance", + "continuity_tolerance_A_m2", + "contact_log_tolerance", + "ion_balance_tolerance_m2_s", + "max_current_error_A_m2", + "max_voltage_error_V", + "potential_step_V", + "quasi_fermi_step", + "ion_logit_step", + "terminal_voltage_step_V", + "fd_epsilon", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ValueError(f"{name} must be finite and positive") + object.__setattr__(self, name, float(raw)) + if type(self.max_newton_iterations) is not int or self.max_newton_iterations < 4: + raise ValueError("max_newton_iterations must be an integer >= 4") + + +@dataclass(frozen=True) +class OpenCircuitStepDiagnostics: + """Per-step conservation and solver diagnostics at floating terminal bias.""" + + start_s: float + end_s: float + dt_s: float + generation_scale: float + terminal_voltage_V: float + newton_iterations: int + scaled_residual: float + left_conduction_current_A_m2: float + left_displacement_current_A_m2: float + left_total_current_A_m2: float + max_face_total_current_A_m2: float + interval_charge_residual_C_m2: float + + +@dataclass(frozen=True) +class OpenCircuitTrajectory: + """Certified floating-terminal trajectory ``V_oc(t)`` and conservation ledger.""" + + times_s: np.ndarray + generation_scale: np.ndarray + terminal_voltage_V: np.ndarray + left_conduction_current_A_m2: np.ndarray + left_displacement_current_A_m2: np.ndarray + left_total_current_A_m2: np.ndarray + max_face_total_current_A_m2: np.ndarray + cumulative_charge_residual_C_m2: float + charge_voltage_error_V: float + geometric_capacitance_F_m2: float + states: tuple[State1D | IonicState1D, ...] + step_diagnostics: tuple[OpenCircuitStepDiagnostics, ...] + compiled_identity: str + certified: bool + + +def _left_port_support_indices( + device: CompiledDevice1D | CompiledIonicDevice1D, +) -> tuple[int, ...]: + """Exact state indices entering ``I_total,left(y, V)``.""" + comp = ( + device.electronic_component + if isinstance(device, CompiledIonicDevice1D) + else device + ) + n_nodes = comp.node_count + cols: list[int] = [0, 1, n_nodes, n_nodes + 1, 2 * n_nodes, 2 * n_nodes + 1] + if isinstance(device, CompiledIonicDevice1D) and int(device.ion_node_indices[0]) == 0: + for block in device.ion_species_slices: + cols.append(int(block.start)) + return tuple(cols) + + +def _eval_step_and_port( + device: CompiledDevice1D | CompiledIonicDevice1D, + prev_state: State1D | IonicState1D, + dt_s: float, + generation_scale: float, + y: np.ndarray, + voltage_V: float, +) -> tuple[ + BackwardEuler1DStep | IonicBackwardEuler1DStep, + np.ndarray, + dict[str, object], + float, +]: + if isinstance(device, CompiledDevice1D): + assert isinstance(prev_state, State1D) + step_e = BackwardEuler1DStep( + DC1DProblem(device, voltage_V=voltage_V, generation_scale=generation_scale), + prev_state, + dt_s, + ) + acc = electronic_step_accounting(step_e, y) + res_pde = np.asarray(acc["backward_euler_residual"], dtype=float) + term_tot = np.asarray(acc["terminal_total_current_density_A_m2"], dtype=float) + return step_e, res_pde, acc, float(term_tot[0]) + + assert isinstance(prev_state, IonicState1D) + step_i = IonicBackwardEuler1DStep( + Ionic1DProblem(device, voltage_V=voltage_V, generation_scale=generation_scale), + prev_state, + dt_s, + ) + acc_i = ionic_step_accounting(step_i, y) + res_pde_i = np.asarray(acc_i["backward_euler_residual"], dtype=float) + term_tot_i = np.asarray(acc_i["terminal_total_current_density_A_m2"], dtype=float) + return step_i, res_pde_i, acc_i, float(term_tot_i[0]) + + +def _solve_floating_step( + device: CompiledDevice1D | CompiledIonicDevice1D, + prev_state: State1D | IonicState1D, + prev_voltage_V: float, + dt_s: float, + generation_scale: float, + options: OpenCircuitOptions, + support_cols: tuple[int, ...], + predictor: str = "previous", +) -> tuple[State1D | IonicState1D, float, OpenCircuitStepDiagnostics, float, float]: + """Solve one bordered ``(M + 1)`` open-circuit Backward Euler step.""" + comp = ( + device.electronic_component + if isinstance(device, CompiledIonicDevice1D) + else device + ) + m_size = ( + device.state_size + if isinstance(device, CompiledIonicDevice1D) + else 3 * comp.node_count + ) + + # Build row weights and max coordinate step bounds + elec_weights = production_residual_scaling( + comp, + poisson_tolerance=options.poisson_tolerance, + continuity_tolerance_A_m2=options.continuity_tolerance_A_m2, + contact_log_tolerance=options.contact_log_tolerance, + ).row_weights + elec_steps = production_coordinates( + comp, + potential_step_V=options.potential_step_V, + quasi_fermi_step=options.quasi_fermi_step, + ).max_step + if isinstance(device, CompiledIonicDevice1D): + ion_len = device.ion_node_count * device.ion_species_count + pde_weights = np.r_[ + elec_weights, + np.full(ion_len, device.ion_node_count / options.ion_balance_tolerance_m2_s), + ] + pde_steps = np.r_[elec_steps, np.full(ion_len, options.ion_logit_step)] + else: + pde_weights = elec_weights + pde_steps = elec_steps + + row_weights = np.r_[pde_weights, 1.0 / options.max_current_error_A_m2] + row_scale = diags(row_weights, format="csc") + max_steps = np.r_[pde_steps, options.terminal_voltage_step_V] + elec_norm = production_convergence_norm( + comp, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + assert elec_norm is not None + n_elec = 3 * comp.node_count + + def eval_scaled_norm(scaled_vec: np.ndarray) -> float: + if not np.all(np.isfinite(scaled_vec)): + return math.inf + val = max(elec_norm(scaled_vec[:n_elec]), abs(float(scaled_vec[-1]))) + if isinstance(device, CompiledIonicDevice1D): + n_ion = device.ion_node_count + for block in device.ion_species_slices: + val = max( + val, + math.fsum(abs(scaled_vec[block]).tolist()) / n_ion, + ) + return val + + # Seed at previous terminal voltage (zero voltage jump, exact previous inventory) + if isinstance(device, CompiledDevice1D): + assert isinstance(prev_state, State1D) + seed_step = BackwardEuler1DStep( + DC1DProblem( + device, voltage_V=prev_voltage_V, generation_scale=generation_scale + ), + prev_state, + dt_s, + ) + y_cur = seed_step.initial_coordinates("previous", voltage_lift=False) + if predictor == "generation_inventory" and generation_scale > 0.0: + try: + y_cur = transient_density_basin_seed( + seed_step, y_cur, device=device, voltage_V=prev_voltage_V + ) + except ValueError: + y_cur = seed_step.initial_coordinates(predictor, voltage_lift=False) + else: + assert isinstance(prev_state, IonicState1D) + seed_step_i = IonicBackwardEuler1DStep( + Ionic1DProblem( + device, voltage_V=prev_voltage_V, generation_scale=generation_scale + ), + prev_state, + dt_s, + ) + y_cur = seed_step_i.initial_coordinates("previous", voltage_lift=False) + if predictor == "generation_inventory" and generation_scale > 0.0: + try: + seeded_e = transient_density_basin_seed( + seed_step_i.electronic_step, + y_cur[:n_elec], + device=comp, + voltage_V=prev_voltage_V, + ) + y_cur = np.r_[seeded_e, y_cur[n_elec:]] + except ValueError: + y_cur = seed_step_i.initial_coordinates(predictor, voltage_lift=False) + + v_cur = float(prev_voltage_V) + eps = options.fd_epsilon + + # Harmonic potential lift + carrier reference rebase tangent vector g_vec: + # Perturbing y -> y + dv * g_vec as V -> V + dv updates contact potentials + # harmonically while holding bulk physical densities (n, p, P) fixed. + n_nodes = comp.node_count + res_faces = 1.0 / comp.poisson.face_capacitance_F_m2 + harm_prof = np.r_[0.0, np.cumsum(res_faces)] + harm_prof /= harm_prof[-1] + d_phi_dv = -comp.voltage_polarity * harm_prof + ref_0 = comp.carrier_reference_energies(0.0) + ref_1 = comp.carrier_reference_energies(1.0) + d_ref_n = ref_1[0] - ref_0[0] + d_ref_p = ref_1[1] - ref_0[1] + g_vec: np.ndarray = np.zeros(m_size, dtype=float) + g_vec[:n_nodes] = d_phi_dv + g_vec[n_nodes : 2 * n_nodes] = (-d_ref_n - d_phi_dv) / comp.thermal_voltage_V + g_vec[2 * n_nodes : 3 * n_nodes] = (-d_ref_p - d_phi_dv) / comp.thermal_voltage_V + + def extract_step_currents( + acc_map: dict[str, object], + ) -> tuple[float, float, float, float]: + if isinstance(device, CompiledDevice1D): + t_cond = float( + np.asarray( + acc_map["terminal_conduction_current_density_A_m2"], dtype=float + )[0] + ) + t_disp = float( + np.asarray( + acc_map["terminal_displacement_current_density_A_m2"], dtype=float + )[0] + ) + int_t = np.asarray(acc_map["total_current_density_A_m2"], dtype=float) + term_t = np.asarray( + acc_map["terminal_total_current_density_A_m2"], dtype=float + ) + all_t = np.r_[term_t[0], int_t, term_t[1]] + d_left = t_disp * dt_s + else: + all_c = np.asarray(acc_map["conduction_current_density_A_m2"], dtype=float) + all_d = np.asarray( + acc_map["displacement_current_density_A_m2"], dtype=float + ) + all_t = np.asarray(acc_map["total_current_density_A_m2"], dtype=float) + int_d = np.asarray(acc_map["interval_displacement_C_m2"], dtype=float) + t_cond = float(all_c[0]) + t_disp = float(all_d[0]) + d_left = float(int_d[0]) + return t_cond, t_disp, d_left, float(np.max(np.abs(all_t))) + + for it in range(1, options.max_newton_iterations + 1): + step_obj, res_pde, acc, i_left = _eval_step_and_port( + device, prev_state, dt_s, generation_scale, y_cur, v_cur + ) + full_res = np.r_[res_pde, i_left] + scaled_norm = eval_scaled_norm(row_weights * full_res) + term_cond, term_disp, delta_d_left, max_face = extract_step_currents(acc) + if ( + scaled_norm <= 1.0 + and abs(i_left) <= options.max_current_error_A_m2 + and max_face <= options.max_current_error_A_m2 + ): + new_state: State1D | IonicState1D = device.state(y_cur, voltage_V=v_cur) + dq_step = dt_s * term_cond + delta_d_left + diag = OpenCircuitStepDiagnostics( + start_s=0.0, + end_s=0.0, + dt_s=dt_s, + generation_scale=generation_scale, + terminal_voltage_V=v_cur, + newton_iterations=it - 1, + scaled_residual=scaled_norm, + left_conduction_current_A_m2=term_cond, + left_displacement_current_A_m2=term_disp, + left_total_current_A_m2=i_left, + max_face_total_current_A_m2=max_face, + interval_charge_residual_C_m2=dq_step, + ) + return new_state, v_cur, diag, dq_step, max_face + + # Assemble bordered Jacobian in physical-density lifted chart (dw, dV) + # where dy = dw + dV * g_vec: + # [ J_yy dR_pde/dV|_{dw=0} ] + # [ dI/dy dI/dV|_{dw=0} ] + j_yy = step_obj.jacobian(y_cur) + + # Row M: dI_left / dy on support_cols via central differences + row_data: list[float] = [] + row_cols: list[int] = [] + for col in support_cols: + h_y = eps * max(1.0, abs(float(y_cur[col]))) + y_plus = y_cur.copy() + y_plus[col] += h_y + y_minus = y_cur.copy() + y_minus[col] -= h_y + _, _, _, i_p = _eval_step_and_port( + device, prev_state, dt_s, generation_scale, y_plus, v_cur + ) + _, _, _, i_m = _eval_step_and_port( + device, prev_state, dt_s, generation_scale, y_minus, v_cur + ) + deriv = (i_p - i_m) / (2.0 * h_y) + if deriv != 0.0: + row_cols.append(col) + row_data.append(deriv) + + j_vy = csc_matrix( + ( + np.asarray(row_data, dtype=float), + (np.zeros(len(row_cols), dtype=int), np.asarray(row_cols, dtype=int)), + ), + shape=(1, m_size), + ) + + # Column M: directional derivative along (g_vec, 1) via central difference in V + h_v = eps * max(1.0, abs(v_cur)) + _, res_vp, _, i_vp = _eval_step_and_port( + device, + prev_state, + dt_s, + generation_scale, + y_cur + h_v * g_vec, + v_cur + h_v, + ) + _, res_vm, _, i_vm = _eval_step_and_port( + device, + prev_state, + dt_s, + generation_scale, + y_cur - h_v * g_vec, + v_cur - h_v, + ) + d_res_dv = ((res_vp - res_vm) / (2.0 * h_v)).reshape(m_size, 1) + d_i_dv = np.array([[(i_vp - i_vm) / (2.0 * h_v)]], dtype=float) + + scaled_res = row_weights * full_res + bordered = cast( + csc_matrix, + row_scale + @ bmat( + [[j_yy, csc_matrix(d_res_dv)], [j_vy, csc_matrix(d_i_dv)]], + format="csc", + ), + ) + try: + lu = splu(bordered) + delta_chart = np.asarray(lu.solve(-scaled_res), dtype=float) + except RuntimeError as exc: + raise OpenCircuitError(f"Singular bordered Jacobian: {exc}") from exc + if delta_chart.shape != (m_size + 1,) or not np.all(np.isfinite(delta_chart)): + raise OpenCircuitError("Nonfinite bordered Newton step in integrate_open_circuit") + + delta_w = delta_chart[:m_size] + delta_v = float(delta_chart[m_size]) + delta_y = delta_w + delta_v * g_vec + + # Coordinate-wise step bound on chart increment (dw, dV) + Deuflhard monotonicity + step_norm = float(np.max(np.abs(delta_chart) / max_steps)) + alpha = 1.0 / max(1.0, step_norm) + + accepted_line = False + best_simp = math.inf + best_y = y_cur + alpha * delta_y + best_v = float(v_cur + alpha * delta_v) + for _ls in range(12): + cand_y = y_cur + alpha * delta_y + cand_v = float(v_cur + alpha * delta_v) + try: + _, cand_pde, cand_acc, cand_i = _eval_step_and_port( + device, prev_state, dt_s, generation_scale, cand_y, cand_v + ) + cand_scaled = row_weights * np.r_[cand_pde, cand_i] + cand_scaled_norm = eval_scaled_norm(cand_scaled) + _, _, _, cand_max_face = extract_step_currents(cand_acc) + simp_dz = np.asarray(lu.solve(-cand_scaled), dtype=float) + simp_norm = float(np.max(np.abs(simp_dz) / max_steps)) + except (ValueError, FloatingPointError, RuntimeError): + cand_scaled_norm = math.inf + cand_max_face = math.inf + simp_norm = math.inf + if math.isfinite(simp_norm) and simp_norm < best_simp: + best_simp = simp_norm + best_y, best_v = cand_y, cand_v + if math.isfinite(simp_norm) and ( + simp_norm <= (1.0 - 1e-4 * alpha) * step_norm + or cand_scaled_norm < (1.0 - 1e-4 * alpha) * scaled_norm + or (cand_scaled_norm <= 1.0 and step_norm <= 1e-2) + or ( + cand_scaled_norm <= 1.0 + and abs(cand_i) <= options.max_current_error_A_m2 + and cand_max_face <= options.max_current_error_A_m2 + ) + ): + best_y, best_v = cand_y, cand_v + accepted_line = True + break + alpha *= 0.5 + if not accepted_line and not math.isfinite(best_simp): + raise OpenCircuitError("Floating-terminal Newton backtracking failed") + y_cur, v_cur = best_y, best_v + + raise OpenCircuitError( + f"Open-circuit Backward Euler step failed to converge in {options.max_newton_iterations} Newton iterations" + ) + + +def _advance_floating_interval( + device: CompiledDevice1D | CompiledIonicDevice1D, + prev_state: State1D | IonicState1D, + prev_voltage_V: float, + t_prev: float, + t_next: float, + g_prev: float, + g_next: float, + options: OpenCircuitOptions, + support_cols: tuple[int, ...], + _depth: int = 0, +) -> tuple[State1D | IonicState1D, float, OpenCircuitStepDiagnostics, float, float]: + dt_s = t_next - t_prev + pred = "generation_inventory" if (g_prev == 0.0 and g_next > 0.0) else "previous" + try: + return _solve_floating_step( + device, + prev_state, + prev_voltage_V, + dt_s, + g_next, + options, + support_cols, + predictor=pred, + ) + except OpenCircuitError: + if _depth >= 5 or dt_s < 2e-8: + raise + t_mid = 0.5 * (t_prev + t_next) + g_mid = 0.5 * (g_prev + g_next) if g_prev != g_next else g_next + mid_state, mid_v, diag1, dq1, mf1 = _advance_floating_interval( + device, + prev_state, + prev_voltage_V, + t_prev, + t_mid, + g_prev, + g_mid, + options, + support_cols, + _depth=_depth + 1, + ) + end_state, end_v, diag2, dq2, mf2 = _advance_floating_interval( + device, + mid_state, + mid_v, + t_mid, + t_next, + g_mid, + g_next, + options, + support_cols, + _depth=_depth + 1, + ) + dq_tot = dq1 + dq2 + mf_tot = max(mf1, mf2) + combined = OpenCircuitStepDiagnostics( + start_s=t_prev, + end_s=t_next, + dt_s=dt_s, + generation_scale=g_next, + terminal_voltage_V=end_v, + newton_iterations=diag1.newton_iterations + diag2.newton_iterations, + scaled_residual=max(diag1.scaled_residual, diag2.scaled_residual), + left_conduction_current_A_m2=diag2.left_conduction_current_A_m2, + left_displacement_current_A_m2=diag2.left_displacement_current_A_m2, + left_total_current_A_m2=diag2.left_total_current_A_m2, + max_face_total_current_A_m2=mf_tot, + interval_charge_residual_C_m2=dq_tot, + ) + return end_state, end_v, combined, dq_tot, mf_tot + + +def integrate_open_circuit( + device: CompiledDevice1D | CompiledIonicDevice1D, + initial_state: State1D | IonicState1D, + times_s: object, + generation_scale: object, + *, + initial_voltage_V: float | None = None, + options: OpenCircuitOptions | None = None, +) -> OpenCircuitTrajectory: + """Integrate ``device`` along ``times_s`` under zero total external port current.""" + if not isinstance(device, (CompiledDevice1D, CompiledIonicDevice1D)): + raise TypeError("device must be a CompiledDevice1D or CompiledIonicDevice1D") + if isinstance(device, CompiledDevice1D) and not isinstance(initial_state, State1D): + raise TypeError("CompiledDevice1D requires an initial State1D") + if isinstance(device, CompiledIonicDevice1D) and not isinstance( + initial_state, IonicState1D + ): + raise TypeError("CompiledIonicDevice1D requires an initial IonicState1D") + if initial_state.device_sha256 != device.identity: + raise ValueError("initial_state belongs to a different compiled device") + + opts = OpenCircuitOptions() if options is None else options + if not isinstance(opts, OpenCircuitOptions): + raise TypeError("options must be an OpenCircuitOptions") + + if np.iscomplexobj(times_s) or np.iscomplexobj(generation_scale): + raise ValueError("times_s and generation_scale must be real-valued") + t_arr = np.array(times_s, dtype=float, copy=True) + g_arr = np.array(generation_scale, dtype=float, copy=True) + if ( + t_arr.ndim != 1 + or t_arr.size < 2 + or not np.all(np.isfinite(t_arr)) + or np.any(np.diff(t_arr) <= 0.0) + ): + raise ValueError("times_s must be a 1-D strictly increasing finite array") + if g_arr.shape != t_arr.shape or not np.all(np.isfinite(g_arr)) or np.any(g_arr < 0.0): + raise ValueError( + "generation_scale must match times_s shape with finite nonnegative values" + ) + t_arr.setflags(write=False) + g_arr.setflags(write=False) + + v0 = float(initial_state.voltage_V if initial_voltage_V is None else initial_voltage_V) + if not math.isfinite(v0): + raise ValueError("initial_voltage_V must be finite") + if v0 != initial_state.voltage_V: + if isinstance(device, CompiledDevice1D): + assert isinstance(initial_state, State1D) + rebased_u = device.rebase_coordinates( + initial_state.u, initial_state.voltage_V, v0 + ) + cur_state: State1D | IonicState1D = device.state(rebased_u, voltage_V=v0) + else: + assert isinstance(initial_state, IonicState1D) + n_e = 3 * device.node_count + rebased_e = device.electronic_component.rebase_coordinates( + initial_state.u[:n_e], initial_state.voltage_V, v0 + ) + cur_state = device.state( + np.r_[rebased_e, initial_state.u[n_e:]], voltage_V=v0 + ) + else: + cur_state = initial_state + + support_cols = _left_port_support_indices(device) + c_geom = geometric_series_capacitance_F_m2(device) + + n_pts = t_arr.size + v_hist = np.empty(n_pts, dtype=float) + i_cond_hist = np.empty(n_pts, dtype=float) + i_disp_hist = np.empty(n_pts, dtype=float) + i_tot_hist = np.empty(n_pts, dtype=float) + max_face_hist = np.empty(n_pts, dtype=float) + + v_hist[0] = v0 + i_cond_hist[0] = 0.0 + i_disp_hist[0] = 0.0 + i_tot_hist[0] = 0.0 + max_face_hist[0] = 0.0 + + states_out: list[State1D | IonicState1D] = [cur_state] + diags_out: list[OpenCircuitStepDiagnostics] = [] + cum_dq = 0.0 + cur_v = v0 + + for k in range(1, n_pts): + t_prev = float(t_arr[k - 1]) + t_next = float(t_arr[k]) + dt_s = t_next - t_prev + g_prev = float(g_arr[k - 1]) + g_next = float(g_arr[k]) + + next_state, next_v, raw_diag, dq_step, max_face = _advance_floating_interval( + device, + cur_state, + cur_v, + t_prev, + t_next, + g_prev, + g_next, + opts, + support_cols, + ) + if max_face > opts.max_current_error_A_m2: + raise OpenCircuitError( + f"Step [{t_prev:.3e}, {t_next:.3e}] s violated all-face Maxwell open-circuit gate: " + f"max|I_total|={max_face:.3e} A/m^2 > {opts.max_current_error_A_m2:.3e} A/m^2" + ) + cum_dq += dq_step + step_diag = OpenCircuitStepDiagnostics( + start_s=t_prev, + end_s=t_next, + dt_s=dt_s, + generation_scale=g_next, + terminal_voltage_V=next_v, + newton_iterations=raw_diag.newton_iterations, + scaled_residual=raw_diag.scaled_residual, + left_conduction_current_A_m2=raw_diag.left_conduction_current_A_m2, + left_displacement_current_A_m2=raw_diag.left_displacement_current_A_m2, + left_total_current_A_m2=raw_diag.left_total_current_A_m2, + max_face_total_current_A_m2=max_face, + interval_charge_residual_C_m2=dq_step, + ) + v_hist[k] = next_v + i_cond_hist[k] = step_diag.left_conduction_current_A_m2 + i_disp_hist[k] = step_diag.left_displacement_current_A_m2 + i_tot_hist[k] = step_diag.left_total_current_A_m2 + max_face_hist[k] = max_face + states_out.append(next_state) + diags_out.append(step_diag) + cur_state = next_state + cur_v = next_v + + v_err = abs(cum_dq) / c_geom + if v_err > opts.max_voltage_error_V: + raise OpenCircuitError( + f"Cumulative telescoping charge voltage error {v_err:.3e} V exceeds {opts.max_voltage_error_V:.3e} V" + ) + + for arr in (v_hist, i_cond_hist, i_disp_hist, i_tot_hist, max_face_hist): + arr.setflags(write=False) + + return OpenCircuitTrajectory( + times_s=t_arr, + generation_scale=g_arr, + terminal_voltage_V=v_hist, + left_conduction_current_A_m2=i_cond_hist, + left_displacement_current_A_m2=i_disp_hist, + left_total_current_A_m2=i_tot_hist, + max_face_total_current_A_m2=max_face_hist, + cumulative_charge_residual_C_m2=cum_dq, + charge_voltage_error_V=v_err, + geometric_capacitance_F_m2=c_geom, + states=tuple(states_out), + step_diagnostics=tuple(diags_out), + compiled_identity=device.identity, + certified=True, + ) diff --git a/src/solarlab/experiments/tandem_jv.py b/src/solarlab/experiments/tandem_jv.py new file mode 100644 index 00000000..61ecd0f3 --- /dev/null +++ b/src/solarlab/experiments/tandem_jv.py @@ -0,0 +1,871 @@ +"""Monolithic two-terminal (2T) tandem J-V experiment and joint TMM optics. + +Execution contract (P04-13 / P05-04): +1. A single joint transfer-matrix (TMM) optical solve runs over the complete + tandem optical stack: + ``[top_cell.layers, junction_stack, bottom_cell.layers, back_reflector?]`` + producing a closed ``PhotonBudget`` (``max |1 - R - T - sum A - dropped| <= 1e-12``) + and exact cell-averaged generation profiles ``G_top(x_top)`` and ``G_bot(x_bot)`` + on each sub-cell's exact ``INTEGER_ENDPOINT_V1`` electrical control volumes. +2. Photons absorbed in optical-only layers (front substrates, recombination + junction stack, optional back reflector) are accounted as parasitic + absorption and never generate carriers in either sub-cell. +3. Each sub-cell is cold-rebound with its node-exact ``fixed_generation`` + ``ResourceTable`` and solved independently without cross-sub-cell state sharing. +4. ``series_match_jv`` combines the top and bottom J-V curves under ideal ohmic + or ``V_junction``-offset series current matching, failing closed when the + sub-cell current ranges do not overlap. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any, Literal, cast + +import numpy as np + +from solarlab.config.resolve_device import resolve_device, resolve_tandem +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput, TandemInput +from solarlab.device.resolved import PreparedDevice, PreparedTandem +from solarlab.equations.dc_1d import CompiledDevice1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D +from solarlab.experiments.electrothermal import ( + ElectrothermalJVProtocol, + has_declared_ions, + run_fresh_jv_at_temperature, +) +from solarlab.experiments.jv.steady import ( + SteadyJVMetrics, + run_steady_jv, + steady_jv_metrics, +) +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.mesh import INTEGER_ENDPOINT_V1, build_geometry, multilayer_grid +from solarlab.mesh.geometry import ControlVolumeGeometry1D +from solarlab.physics.generation.optical_binding import ( + PhotonBudget, + constant_index_optical_constants, +) +from solarlab.physics.generation.spectrum import sample_nk_table, wavelength_grid_m +from solarlab.physics.generation.transfer_matrix import ( + TMMLayer, + dropped_multipass_fraction, + tmm_absorbed_photon_flux_per_cell, + tmm_cumulative_absorptance, + tmm_reflectance, + tmm_transmittance, +) +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state + +__all__ = [ + "PHOTON_BUDGET_TOLERANCE", + "TandemCapabilityError", + "TandemGenerationResult", + "TandemJVProtocol", + "TandemJVResult", + "compute_tandem_generation", + "prepare_subcell_with_fixed_generation", + "run_tandem_jv", + "series_match_jv", +] + +PHOTON_BUDGET_TOLERANCE: float = 1e-12 +PLANCK_CONSTANT_J_S: float = 6.62607015e-34 +SPEED_OF_LIGHT_M_S: float = 299792458.0 + + +class TandemCapabilityError(ValueError): + """Unsupported tandem configuration or failed optical photon closure.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +@dataclass(frozen=True) +class TandemGenerationResult: + """Joint TMM optical solution and control-volume sub-cell generation profiles.""" + + top_nodes_m: np.ndarray + top_cell_measures_m: np.ndarray + top_generation_m3_s: np.ndarray + bottom_nodes_m: np.ndarray + bottom_cell_measures_m: np.ndarray + bottom_generation_m3_s: np.ndarray + photon_budget: PhotonBudget + top_absorbed_m2_s: float + bottom_absorbed_m2_s: float + parasitic_fraction: float + incident_power_W_m2: float + optical_stack_sha256: str + + +@dataclass(frozen=True) +class TandemJVProtocol: + """Explicit 2T tandem optical + electrical sweep controls.""" + + intervals_per_layer: int | Sequence[int] = 24 + voltage_points_per_subcell: int = 81 + top_voltage_min_V: float = -0.2 + top_voltage_max_V: float = 1.4 + bottom_voltage_min_V: float = -0.2 + bottom_voltage_max_V: float = 1.0 + matched_points: int = 121 + junction_voltage_offset_V: float = 0.0 + k_floor: float = 1e-6 + driver: Literal["steady_jv", "transient_jv_strict"] = "steady_jv" + scan_rate_V_s: float = 1.0 + spectrum_name: str | None = None + incident_power_W_m2: float | None = None + + def __post_init__(self) -> None: + if isinstance(self.intervals_per_layer, bool): + raise ValueError("intervals_per_layer must be an int or int sequence") + if isinstance(self.intervals_per_layer, int): + if self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be >= 2") + else: + counts = tuple(self.intervals_per_layer) + if not counts or any(type(c) is not int or c < 2 for c in counts): + raise ValueError("intervals_per_layer sequence requires ints >= 2") + object.__setattr__(self, "intervals_per_layer", counts) + + if ( + type(self.voltage_points_per_subcell) is not int + or self.voltage_points_per_subcell < 3 + ): + raise ValueError("voltage_points_per_subcell must be an integer >= 3") + if type(self.matched_points) is not int or self.matched_points < 3: + raise ValueError("matched_points must be an integer >= 3") + for name in ( + "top_voltage_min_V", + "top_voltage_max_V", + "bottom_voltage_min_V", + "bottom_voltage_max_V", + "junction_voltage_offset_V", + "k_floor", + "scan_rate_V_s", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)): + raise ValueError(f"{name} must be a finite real scalar") + object.__setattr__(self, name, float(raw)) + if self.top_voltage_max_V <= self.top_voltage_min_V: + raise ValueError("top_voltage_max_V must exceed top_voltage_min_V") + if self.bottom_voltage_max_V <= self.bottom_voltage_min_V: + raise ValueError("bottom_voltage_max_V must exceed bottom_voltage_min_V") + if self.k_floor < 0.0: + raise ValueError("k_floor must be >= 0") + if self.scan_rate_V_s <= 0.0: + raise ValueError("scan_rate_V_s must be > 0") + if self.driver not in ("steady_jv", "transient_jv_strict"): + raise ValueError("driver must be 'steady_jv' or 'transient_jv_strict'") + if self.incident_power_W_m2 is not None: + if ( + not _is_real_number(self.incident_power_W_m2) + or not math.isfinite(float(self.incident_power_W_m2)) + or float(self.incident_power_W_m2) <= 0.0 + ): + raise ValueError("incident_power_W_m2 must be None or finite positive") + object.__setattr__( + self, "incident_power_W_m2", float(self.incident_power_W_m2) + ) + + +@dataclass(frozen=True) +class TandemJVResult: + """Monolithic 2T series-matched tandem J-V curves, metrics, and photon budget.""" + + V_fwd: np.ndarray + J_fwd: np.ndarray + V_rev: np.ndarray + J_rev: np.ndarray + metrics_fwd: SteadyJVMetrics + metrics_rev: SteadyJVMetrics + hysteresis_index: float | None + top_V_fwd: np.ndarray + top_J_fwd: np.ndarray + top_V_rev: np.ndarray + top_J_rev: np.ndarray + top_metrics_fwd: SteadyJVMetrics + bottom_V_fwd: np.ndarray + bottom_J_fwd: np.ndarray + bottom_V_rev: np.ndarray + bottom_J_rev: np.ndarray + bottom_metrics_fwd: SteadyJVMetrics + optics: TandemGenerationResult + incident_power_W_m2: float + top_compiled_identity: str + bottom_compiled_identity: str + tandem_prepared_sha256: str + result_sha256: str + + +def _subcell_geometry( + prepared: PreparedDevice, + intervals_per_layer: int | Sequence[int], +) -> ControlVolumeGeometry1D: + """Build the exact ``INTEGER_ENDPOINT_V1`` electrical geometry of ``compile_device_1d``.""" + data = prepared.to_mapping() + settings = data["settings"] + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + grid = {entry["layer"]: entry for entry in data["electrical_grid"]} + if isinstance(intervals_per_layer, int): + weights = np.asarray( + [grid.get(layer.id, {}).get("interval_weight", 1.0) for layer in layers], + dtype=float, + ) + counts = ( + np.maximum(2, np.rint(intervals_per_layer * weights / np.mean(weights))) + .astype(int) + .tolist() + ) + else: + counts = list(intervals_per_layer) + if len(counts) != len(layers): + raise TandemCapabilityError( + f"sub-cell {data['id']}: interval sequence length {len(counts)} != {len(layers)} electrical layers" + ) + for idx, layer in enumerate(layers): + p = dict(layer.parameters) + if settings["band_grading"] and ( + p["Eg_back"] is not None or p["chi_back"] is not None + ): + counts[idx] *= int(cast(int, p["grading_N_mult"])) + alphas = [float(grid.get(layer.id, {}).get("alpha", 3.0)) for layer in layers] + thicknesses = [layer.thickness for layer in layers] + nodes = multilayer_grid(list(zip(thicknesses, counts)), alpha=alphas) + return build_geometry(INTEGER_ENDPOINT_V1, nodes, np.cumsum(thicknesses)[:-1]) + + +def _resolve_spectrum_table( + tandem: PreparedTandem, + explicit_name: str | None, +) -> ResourceTable: + top_spec = tandem.top_cell.to_mapping()["declaration"].get("spectrum") + bot_spec = tandem.bottom_cell.to_mapping()["declaration"].get("spectrum") + if explicit_name is not None: + chosen = explicit_name + elif top_spec is not None and bot_spec is not None: + if top_spec != bot_spec: + raise TandemCapabilityError( + f"top_cell spectrum {top_spec!r} and bottom_cell spectrum {bot_spec!r} disagree" + ) + chosen = str(top_spec) + elif top_spec is not None: + chosen = str(top_spec) + elif bot_spec is not None: + chosen = str(bot_spec) + else: + raise TandemCapabilityError( + "2T tandem TMM requires an explicit spectrum resource on top_cell, bottom_cell, or TandemJVProtocol.spectrum_name" + ) + return tandem.resources.get(chosen, "spectrum") + + +def compute_tandem_generation( + tandem: PreparedTandem, + *, + intervals_top: int | Sequence[int] = 24, + intervals_bottom: int | Sequence[int] = 24, + spectrum_name: str | None = None, + k_floor: float = 1e-6, +) -> TandemGenerationResult: + """Solve joint coherent TMM optics across the full 2T tandem stack.""" + if not isinstance(tandem, PreparedTandem): + raise TypeError("tandem must be a PreparedTandem") + if not _is_real_number(k_floor) or not math.isfinite(float(k_floor)) or float(k_floor) < 0.0: + raise ValueError("k_floor must be finite and >= 0") + k_min = float(k_floor) + + meta = tandem.to_mapping() + if meta["junction_model"] != "ideal_ohmic": + raise TandemCapabilityError( + f"Unsupported junction_model {meta['junction_model']!r}; only 'ideal_ohmic' is supported" + ) + if meta["light_direction"] != "top_first": + raise TandemCapabilityError( + f"Unsupported light_direction {meta['light_direction']!r}; only 'top_first' is supported" + ) + + spec_table = _resolve_spectrum_table(tandem, spectrum_name) + wl_m = np.array(spec_table.array[:, 0], dtype=float, copy=True) + wl_nm = wl_m * 1e9 + spectral_flux = np.array(spec_table.array[:, 1], dtype=float, copy=True) + + geom_top = _subcell_geometry(tandem.top_cell, intervals_top) + geom_bot = _subcell_geometry(tandem.bottom_cell, intervals_bottom) + + tmm_layers: list[TMMLayer] = [] + layer_names: list[str] = [] + layer_electrical: list[bool] = [] + dep_records: list[dict[str, Any]] = [] + + def append_device_layers(cell: PreparedDevice, prefix: str) -> tuple[float, float]: + """Append all layers of ``cell`` and return ``(elec_start_m, elec_end_m)``.""" + sub_prefix_m = 0.0 + elec_total_m = 0.0 + seen_elec = False + stack_start_m = sum(item.d for item in tmm_layers) + for layer in cell.layers: + params = dict(layer.parameters) + if layer.cigs_graded_optics_json is not None: + raise TandemCapabilityError( + f"{prefix}.{layer.id}: graded CIGS optics is not bound in 2T tandem" + ) + incoh = bool(params["incoherent"]) + if incoh and len(tmm_layers) > 0: + raise TandemCapabilityError( + f"{prefix}.{layer.id}: only the very first optical layer of the tandem may be incoherent" + ) + if layer.optical is not None: + if params["n_optical"] is not None: + raise TandemCapabilityError( + f"{prefix}.{layer.id}: cannot specify both optical_material and n_optical" + ) + native = layer.optical.array + n_arr, k_arr = sample_nk_table( + native[:, 0] * 1e9, + native[:, 1], + native[:, 2], + wl_nm, + material=layer.optical.name, + ) + nk_sha = layer.optical.content_sha256 + else: + if params["n_optical"] is None: + raise TandemCapabilityError( + f"{prefix}.{layer.id}: requires optical_material or explicit n_optical" + ) + n_arr, k_arr = constant_index_optical_constants( + wl_nm, + absorption_coefficient_m1=float(cast(float, params["alpha"])), + refractive_index=float(cast(float, params["n_optical"])), + ) + nk_sha = "constant_index" + k_eff = np.maximum(k_arr, k_min) + is_elec = layer.role != "substrate" + if not is_elec: + if seen_elec: + raise TandemCapabilityError( + f"{prefix}.{layer.id}: substrate layers must form a front prefix" + ) + sub_prefix_m += layer.thickness + else: + seen_elec = True + elec_total_m += layer.thickness + + tmm_layers.append( + TMMLayer(d=layer.thickness, n=n_arr, k=k_eff, incoherent=incoh) + ) + layer_names.append(f"{prefix}:{layer.id}") + layer_electrical.append(is_elec) + dep_records.append( + { + "name": f"{prefix}:{layer.id}", + "thickness_m": float(layer.thickness).hex(), + "incoherent": incoh, + "electrical": is_elec, + "nk_sha256": nk_sha, + } + ) + elec_start = stack_start_m + sub_prefix_m + return elec_start, elec_start + elec_total_m + + def append_optical_only(opt_entry: Any, role_prefix: str) -> None: + incoh = bool(opt_entry.incoherent) + if incoh and len(tmm_layers) > 0: + raise TandemCapabilityError( + f"{role_prefix}.{opt_entry.id}: mid-stack or back optical layers cannot be incoherent" + ) + res = tandem.resources.get(opt_entry.optical_material, "nk") + native = res.array + n_arr, k_arr = sample_nk_table( + native[:, 0] * 1e9, + native[:, 1], + native[:, 2], + wl_nm, + material=res.name, + ) + k_eff = np.maximum(k_arr, k_min) + d_m = float(opt_entry.normalized_data()["thickness"]) + tmm_layers.append(TMMLayer(d=d_m, n=n_arr, k=k_eff, incoherent=incoh)) + layer_names.append(f"{role_prefix}:{opt_entry.id}") + layer_electrical.append(False) + dep_records.append( + { + "name": f"{role_prefix}:{opt_entry.id}", + "thickness_m": d_m.hex(), + "incoherent": incoh, + "electrical": False, + "nk_sha256": res.content_sha256, + } + ) + + tandem_input = tandem.to_input() + top_elec_start_m, _top_elec_end_m = append_device_layers(tandem.top_cell, "top") + for j_layer in tandem_input.junction_stack: + append_optical_only(j_layer, "junction") + bot_elec_start_m, _bot_elec_end_m = append_device_layers( + tandem.bottom_cell, "bottom" + ) + if tandem_input.back_reflector is not None: + append_optical_only(tandem_input.back_reflector, "back_reflector") + + boundaries = np.r_[0.0, np.cumsum([lyr.d for lyr in tmm_layers])] + cum_abs = tmm_cumulative_absorptance( + tmm_layers, wl_m, boundaries, boundaries, n_ambient=1.0, n_substrate=1.0 + ) + layer_abs = cum_abs[1:, :] - cum_abs[:-1, :] + refl = tmm_reflectance(tmm_layers, wl_m, n_ambient=1.0, n_substrate=1.0) + trans = tmm_transmittance(tmm_layers, wl_m, n_ambient=1.0, n_substrate=1.0) + dropped = dropped_multipass_fraction( + tmm_layers, wl_m, n_ambient=1.0, n_substrate=1.0 + ) + + budget = PhotonBudget( + wavelengths_nm=wl_nm, + incident_spectral_m2_s_m=spectral_flux, + reflectance=refl, + transmittance=trans, + layer_absorptance=layer_abs, + dropped_multipass=dropped, + layer_names=tuple(layer_names), + layer_electrical=tuple(layer_electrical), + ) + closure_err = float(np.max(np.abs(budget.spectral_closure_residual()))) + if not math.isfinite(closure_err) or closure_err > PHOTON_BUDGET_TOLERANCE: + raise TandemCapabilityError( + f"Joint 2T tandem TMM photon budget failed closure: max residual {closure_err:.3e} > {PHOTON_BUDGET_TOLERANCE:.3e}" + ) + + top_faces = geom_top.cell_faces_m + top_elec_start_m + top_absorbed_cells = tmm_absorbed_photon_flux_per_cell( + tmm_layers, wl_m, spectral_flux, top_faces, boundaries, 1.0, 1.0 + ) + g_top = top_absorbed_cells / geom_top.cell_measures_m + + bot_faces = geom_bot.cell_faces_m + bot_elec_start_m + bot_absorbed_cells = tmm_absorbed_photon_flux_per_cell( + tmm_layers, wl_m, spectral_flux, bot_faces, boundaries, 1.0, 1.0 + ) + g_bot = bot_absorbed_cells / geom_bot.cell_measures_m + + if not np.all(np.isfinite(g_top)) or not np.all(np.isfinite(g_bot)): + raise TandemCapabilityError("Nonfinite sub-cell generation profile in 2T tandem") + g_top = np.maximum(g_top, 0.0) + g_bot = np.maximum(g_bot, 0.0) + + top_abs_flux = float(np.sum(g_top * geom_top.cell_measures_m)) + bot_abs_flux = float(np.sum(g_bot * geom_bot.cell_measures_m)) + inc_flux = budget.incident_m2_s + tol_flux = PHOTON_BUDGET_TOLERANCE * max(1.0, inc_flux) + if abs((top_abs_flux + bot_abs_flux) - budget.electrical_absorbed_m2_s) > 10.0 * tol_flux: + raise TandemCapabilityError( + "Sub-cell control-volume generation sum disagrees with joint TMM electrical absorption" + ) + + parasitic_frac = ( + 0.0 if inc_flux <= 0.0 else float(budget.parasitic_absorbed_m2_s / inc_flux) + ) + photon_energy_J = (PLANCK_CONSTANT_J_S * SPEED_OF_LIGHT_M_S) / wavelength_grid_m( + wl_nm + ) + inc_power_W_m2 = float( + np.trapezoid(spectral_flux * photon_energy_J, x=wavelength_grid_m(wl_nm)) + ) + + top_nodes = np.array(geom_top.nodes_m, dtype=float, copy=True) + top_w = np.array(geom_top.cell_measures_m, dtype=float, copy=True) + bot_nodes = np.array(geom_bot.nodes_m, dtype=float, copy=True) + bot_w = np.array(geom_bot.cell_measures_m, dtype=float, copy=True) + for arr in (top_nodes, top_w, g_top, bot_nodes, bot_w, g_bot): + arr.setflags(write=False) + + opt_sha = _canonical_sha256( + { + "tandem_sha256": tandem.content_sha256, + "spectrum_sha256": spec_table.content_sha256, + "k_floor": k_min.hex(), + "layers": dep_records, + } + ) + return TandemGenerationResult( + top_nodes_m=top_nodes, + top_cell_measures_m=top_w, + top_generation_m3_s=g_top, + bottom_nodes_m=bot_nodes, + bottom_cell_measures_m=bot_w, + bottom_generation_m3_s=g_bot, + photon_budget=budget, + top_absorbed_m2_s=top_abs_flux, + bottom_absorbed_m2_s=bot_abs_flux, + parasitic_fraction=parasitic_frac, + incident_power_W_m2=inc_power_W_m2, + optical_stack_sha256=opt_sha, + ) + + +def prepare_subcell_with_fixed_generation( + subcell: PreparedDevice, + nodes_m: np.ndarray, + generation_m3_s: np.ndarray, + *, + resource_name: str, +) -> PreparedDevice: + """Bind a joint-TMM ``fixed_generation`` table onto an electrical sub-cell.""" + payload_bytes = json.dumps( + { + "coordinate_m": [float(x) for x in nodes_m], + "generation_m3_s": [float(g) for g in generation_m3_s], + }, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + src_doc = SourceDocument(id=f"tandem_fixed_gen_{resource_name}", content=payload_bytes) + gen_table = ResourceTable(name=resource_name, kind="fixed_generation", source=src_doc) + retained_tables = tuple( + tbl for tbl in subcell.resources.tables if tbl.name != resource_name + ) + merged_resources = ResourceLibrary(tables=(*retained_tables, gen_table)) + + editing = subcell.to_input().editing_data() + editing["spectrum"] = None + editing["fixed_generation"] = resource_name + for mat in editing.get("materials", ()): + mat_params = mat.get("parameters") + if isinstance(mat_params, dict): + mat_params.pop("optical_material", None) + mat_params.pop("n_optical", None) + for lyr in editing.get("layers", ()): + lyr_params = lyr.setdefault("parameters", {}) + lyr_params["optical_material"] = None + lyr_params["n_optical"] = None + if lyr.get("role") == "substrate": + lyr_params["alpha"] = 0.0 + + retained_sources = tuple( + src for src in subcell.sources if src.id != src_doc.id + ) + return resolve_device( + DeviceInput.model_validate(editing), + subcell.defaults, + merged_resources, + sources=(*retained_sources, src_doc), + ) + + +def series_match_jv( + top_J: object, + top_V: object, + bot_J: object, + bot_V: object, + *, + V_junction: float = 0.0, + n_points: int = 121, +) -> tuple[np.ndarray, np.ndarray]: + """Series-match two sub-cell J-V curves at common current densities ``J``. + + Returns ``(V_tandem, J_tandem)`` ordered by strictly increasing ``V_tandem``, + explicitly including ``J = 0`` whenever open circuit lies inside the overlap + bracket ``[j_lo, j_hi]``. Raises ``ValueError`` when the sub-cell current + ranges do not overlap. + """ + if not _is_real_number(V_junction) or not math.isfinite(float(V_junction)): + raise ValueError("V_junction must be a finite real scalar") + if type(n_points) is not int or n_points < 3: + raise ValueError("n_points must be an integer >= 3") + + j1 = np.asarray(top_J, dtype=float) + v1 = np.asarray(top_V, dtype=float) + j2 = np.asarray(bot_J, dtype=float) + v2 = np.asarray(bot_V, dtype=float) + for name, arr in (("top_J", j1), ("top_V", v1), ("bot_J", j2), ("bot_V", v2)): + if arr.ndim != 1 or arr.size < 2 or not np.all(np.isfinite(arr)): + raise ValueError(f"{name} must be a 1-D finite array with >= 2 samples") + if j1.shape != v1.shape or j2.shape != v2.shape: + raise ValueError("sub-cell J and V arrays must have matching shapes") + + ord1 = np.argsort(j1) + j1_s, v1_s = j1[ord1], v1[ord1] + ord2 = np.argsort(j2) + j2_s, v2_s = j2[ord2], v2[ord2] + + # Collapse any exact duplicate current samples before 1D inverse interpolation + j1_u, idx1 = np.unique(j1_s, return_index=True) + v1_u = v1_s[idx1] + j2_u, idx2 = np.unique(j2_s, return_index=True) + v2_u = v2_s[idx2] + if j1_u.size < 2 or j2_u.size < 2: + raise ValueError("sub-cell J curves must span a nonzero current range") + + j_lo = max(float(j1_u[0]), float(j2_u[0])) + j_hi = min(float(j1_u[-1]), float(j2_u[-1])) + if j_lo >= j_hi: + raise ValueError( + f"Sub-cell J ranges do not overlap: top=[{j1_u[0]:.4g}, {j1_u[-1]:.4g}] A/m^2, " + f"bottom=[{j2_u[0]:.4g}, {j2_u[-1]:.4g}] A/m^2" + ) + + native_overlap = np.r_[ + j1_u[(j1_u >= j_lo) & (j1_u <= j_hi)], + j2_u[(j2_u >= j_lo) & (j2_u <= j_hi)], + ] + j_grid = np.unique(np.r_[np.linspace(j_lo, j_hi, n_points), native_overlap]) + if j_lo < 0.0 < j_hi and not np.any(np.abs(j_grid) <= 1e-15): + j_grid = np.sort(np.r_[j_grid, 0.0]) + + v_top_interp = np.interp(j_grid, j1_u, v1_u) + v_bot_interp = np.interp(j_grid, j2_u, v2_u) + v_tandem = v_top_interp + v_bot_interp + float(V_junction) + + v_order = np.argsort(v_tandem) + v_sorted = v_tandem[v_order] + j_sorted = j_grid[v_order] + + # Ensure strictly increasing voltages + v_unique, u_idx = np.unique(v_sorted, return_index=True) + j_unique = j_sorted[u_idx] + if v_unique.size < 2: + raise ValueError("series-matched tandem voltage grid collapsed to < 2 unique points") + + v_out = np.array(v_unique, dtype=float, copy=True) + j_out = np.array(j_unique, dtype=float, copy=True) + v_out.setflags(write=False) + j_out.setflags(write=False) + return v_out, j_out + + +def _run_subcell_jv( + prepared: PreparedDevice, + v_min: float, + v_max: float, + protocol: TandemJVProtocol, + incident_power_W_m2: float, +) -> tuple[ + CompiledDevice1D | CompiledIonicDevice1D, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, +]: + has_ions, inferred_layer = has_declared_ions(prepared) + if not has_ions and protocol.driver == "steady_jv": + compiled = compile_device_1d( + prepared, intervals_per_layer=protocol.intervals_per_layer + ) + v_fwd = np.linspace(v_min, v_max, protocol.voltage_points_per_subcell) + v_rev = v_fwd[::-1].copy() + res_fwd = run_steady_jv( + compiled, + v_fwd, + generation_scale=1.0, + incident_power_W_m2=incident_power_W_m2, + options=SteadyOptions(), + ) + state = res_fwd.solutions[-1].state + rev_currents: list[float] = [] + for v in v_rev: + sol = solve_steady_state( + compiled, + initial_state=state, + voltage_V=float(v), + generation_scale=1.0, + options=SteadyOptions(), + ) + state = sol.state + rev_currents.append( + -float(compiled.voltage_polarity) + * float(sol.current_density_A_m2[0]) + ) + j_rev: np.ndarray = np.asarray(rev_currents, dtype=float) + j_rev.setflags(write=False) + v_rev.setflags(write=False) + return ( + compiled, + res_fwd.voltage_V, + res_fwd.output_current_A_m2, + v_rev, + j_rev, + ) + + # Ionic or transient_jv_strict sub-cell + electrical_layers = tuple( + layer for layer in prepared.layers if layer.role != "substrate" + ) + compiled_any: CompiledDevice1D | CompiledIonicDevice1D + if has_ions: + endpoints = ("blocking", "blocking") if len(electrical_layers) > 1 else None + compiled_any = compile_ionic_device_1d( + prepared, + intervals_per_layer=protocol.intervals_per_layer, + ion_domain_layer=inferred_layer, + ion_domain_endpoints=endpoints, + ) + else: + compiled_any = compile_device_1d( + prepared, intervals_per_layer=protocol.intervals_per_layer + ) + + helper_prot = ElectrothermalJVProtocol( + intervals_per_layer=( + protocol.intervals_per_layer + if isinstance(protocol.intervals_per_layer, int) + else 24 + ), + voltage_points_per_branch=protocol.voltage_points_per_subcell, + scan_rate_V_s=protocol.scan_rate_V_s, + voltage_max_V=v_max, + incident_power_W_m2=incident_power_W_m2, + driver=protocol.driver, + ) + v_f, j_f, v_r, j_r = run_fresh_jv_at_temperature(compiled_any, helper_prot) + return compiled_any, v_f, j_f, v_r, j_r + + +def run_tandem_jv( + tandem: PreparedTandem | TandemInput, + protocol: TandemJVProtocol | None = None, + *, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, + sources: tuple[SourceDocument, ...] = (), +) -> TandemJVResult: + """Execute joint coherent TMM optics and series-matched 2T tandem J-V sweeps.""" + if isinstance(tandem, TandemInput): + if defaults is None or resources is None: + raise ValueError( + "defaults and resources are required when tandem is passed as TandemInput" + ) + prepared_tandem = resolve_tandem(tandem, defaults, resources, sources=sources) + elif isinstance(tandem, PreparedTandem): + prepared_tandem = tandem + else: + raise TypeError("tandem must be a PreparedTandem or TandemInput") + + prot = TandemJVProtocol() if protocol is None else protocol + if not isinstance(prot, TandemJVProtocol): + raise TypeError("protocol must be a TandemJVProtocol") + + optics = compute_tandem_generation( + prepared_tandem, + intervals_top=prot.intervals_per_layer, + intervals_bottom=prot.intervals_per_layer, + spectrum_name=prot.spectrum_name, + k_floor=prot.k_floor, + ) + p_in = ( + optics.incident_power_W_m2 + if prot.incident_power_W_m2 is None + else prot.incident_power_W_m2 + ) + + top_bound = prepare_subcell_with_fixed_generation( + prepared_tandem.top_cell, + optics.top_nodes_m, + optics.top_generation_m3_s, + resource_name="tandem_top_fixed_generation", + ) + bot_bound = prepare_subcell_with_fixed_generation( + prepared_tandem.bottom_cell, + optics.bottom_nodes_m, + optics.bottom_generation_m3_s, + resource_name="tandem_bottom_fixed_generation", + ) + + top_comp, top_vf, top_jf, top_vr, top_jr = _run_subcell_jv( + top_bound, prot.top_voltage_min_V, prot.top_voltage_max_V, prot, p_in + ) + bot_comp, bot_vf, bot_jf, bot_vr, bot_jr = _run_subcell_jv( + bot_bound, prot.bottom_voltage_min_V, prot.bottom_voltage_max_V, prot, p_in + ) + + v_fwd, j_fwd = series_match_jv( + top_jf, + top_vf, + bot_jf, + bot_vf, + V_junction=prot.junction_voltage_offset_V, + n_points=prot.matched_points, + ) + v_rev_asc, j_rev_asc = series_match_jv( + top_jr, + top_vr, + bot_jr, + bot_vr, + V_junction=prot.junction_voltage_offset_V, + n_points=prot.matched_points, + ) + v_rev = np.array(v_rev_asc[::-1], dtype=float, copy=True) + j_rev = np.array(j_rev_asc[::-1], dtype=float, copy=True) + v_rev.setflags(write=False) + j_rev.setflags(write=False) + + m_fwd = steady_jv_metrics(v_fwd, j_fwd, incident_power_W_m2=p_in) + m_rev = steady_jv_metrics(v_rev, j_rev, incident_power_W_m2=p_in) + top_m = steady_jv_metrics(top_vf, top_jf, incident_power_W_m2=p_in) + bot_m = steady_jv_metrics(bot_vf, bot_jf, incident_power_W_m2=p_in) + + hi: float | None = None + if ( + m_fwd.maximum_power_W_m2 is not None + and m_rev.maximum_power_W_m2 is not None + and m_rev.maximum_power_W_m2 > 0.0 + ): + hi = float( + (m_rev.maximum_power_W_m2 - m_fwd.maximum_power_W_m2) + / m_rev.maximum_power_W_m2 + ) + + res_sha = _canonical_sha256( + { + "tandem_prepared_sha256": prepared_tandem.content_sha256, + "optical_stack_sha256": optics.optical_stack_sha256, + "top_compiled_identity": top_comp.identity, + "bottom_compiled_identity": bot_comp.identity, + "metrics_fwd": asdict(m_fwd), + "metrics_rev": asdict(m_rev), + } + ) + return TandemJVResult( + V_fwd=v_fwd, + J_fwd=j_fwd, + V_rev=v_rev, + J_rev=j_rev, + metrics_fwd=m_fwd, + metrics_rev=m_rev, + hysteresis_index=hi, + top_V_fwd=top_vf, + top_J_fwd=top_jf, + top_V_rev=top_vr, + top_J_rev=top_jr, + top_metrics_fwd=top_m, + bottom_V_fwd=bot_vf, + bottom_J_fwd=bot_jf, + bottom_V_rev=bot_vr, + bottom_J_rev=bot_jr, + bottom_metrics_fwd=bot_m, + optics=optics, + incident_power_W_m2=p_in, + top_compiled_identity=top_comp.identity, + bottom_compiled_identity=bot_comp.identity, + tandem_prepared_sha256=prepared_tandem.content_sha256, + result_sha256=res_sha, + ) diff --git a/src/solarlab/experiments/thermal_balance.py b/src/solarlab/experiments/thermal_balance.py new file mode 100644 index 00000000..683f4a64 --- /dev/null +++ b/src/solarlab/experiments/thermal_balance.py @@ -0,0 +1,638 @@ +"""Lumped areal thermal-balance ledger, steady-state root, and transient ODE. + +Thermodynamic boundary (``system_boundary = 'device_plus_lumped_parasitics'``): +the semiconductor stack together with any lumped external series/shunt +resistive parasitics forms a single isothermal control volume at temperature +``T`` [K], exchanging power with ambient ``T_amb`` [K] and exported electrical +power ``P_elec_out = V_terminal * J_terminal`` [W/m^2]: + + C_th * dT/dt = P_absorbed + Q_internal - P_elec_out + - h * (T - T_amb) - epsilon * sigma * (T^4 - T_amb^4) + +Series ``J_terminal^2 * R_s`` and shunt ``V_junction^2 / R_sh`` Joule heat stay +inside the control volume and are accounted for ONCE through the reduction of +``P_elec_out`` relative to ``P_absorbed``: they are never added a second time. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any + +import numpy as np +from scipy.integrate import solve_ivp +from scipy.optimize import brentq + +__all__ = [ + "STEFAN_BOLTZMANN_W_M2_K4", + "THERMAL_UNIT_SCHEMA", + "LumpedThermalProtocol", + "ThermalBalanceError", + "ThermalEnergySourceError", + "ThermalIntegrationProtocol", + "ThermalPowerLedger", + "ThermalSteadyStateError", + "ThermalSteadyStateResult", + "ThermalTransientError", + "ThermalTransientResult", + "run_lumped_thermal_transient", + "solve_lumped_thermal_steady_state", + "thermal_power_ledger", +] + +STEFAN_BOLTZMANN_W_M2_K4: float = 5.670374419e-8 + +THERMAL_UNIT_SCHEMA: dict[str, str] = { + "absorbed_optical_power_W_m2": "W/m^2", + "ambient_temperature_K": "K", + "areal_heat_capacity_J_m2_K": "J/(m^2*K)", + "heat_transfer_coefficient_W_m2_K": "W/(m^2*K)", + "emissivity": "1", + "maximum_temperature_K": "K", + "constant_internal_heat_W_m2": "W/m^2", +} + + +class ThermalBalanceError(ValueError): + """Invalid lumped thermal protocol or thermodynamic domain.""" + + +class ThermalEnergySourceError(ThermalBalanceError): + """Exported electrical power exceeds available input power without a declared source.""" + + +class ThermalSteadyStateError(RuntimeError): + """Lumped thermal steady-state root is not bracketed or failed to converge.""" + + +class ThermalTransientError(RuntimeError): + """Lumped thermal transient integration failed or violated energy conservation.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def _array_hex_list(values: np.ndarray) -> list[str]: + flat = np.asarray(values, dtype=float).ravel() + return [float(x).hex() for x in flat] + + +@dataclass(frozen=True) +class LumpedThermalProtocol: + """Explicit areal lumped thermal boundary and heat-capacity parameters.""" + + absorbed_optical_power_W_m2: float + ambient_temperature_K: float = 300.0 + areal_heat_capacity_J_m2_K: float = 1000.0 + heat_transfer_coefficient_W_m2_K: float = 10.0 + emissivity: float = 0.0 + maximum_temperature_K: float = 450.0 + constant_internal_heat_W_m2: float = 0.0 + system_boundary: str = "device_plus_lumped_parasitics" + + def __post_init__(self) -> None: + fields = ( + "absorbed_optical_power_W_m2", + "ambient_temperature_K", + "areal_heat_capacity_J_m2_K", + "heat_transfer_coefficient_W_m2_K", + "emissivity", + "maximum_temperature_K", + "constant_internal_heat_W_m2", + ) + for name in fields: + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)): + raise ThermalBalanceError(f"{name} must be a finite real number") + object.__setattr__(self, name, float(raw)) + + if self.absorbed_optical_power_W_m2 < 0.0: + raise ThermalBalanceError("absorbed_optical_power_W_m2 must be >= 0") + if self.ambient_temperature_K <= 0.0: + raise ThermalBalanceError("ambient_temperature_K must be > 0 K") + if self.areal_heat_capacity_J_m2_K <= 0.0: + raise ThermalBalanceError("areal_heat_capacity_J_m2_K must be > 0 J/(m^2*K)") + if self.heat_transfer_coefficient_W_m2_K < 0.0: + raise ThermalBalanceError("heat_transfer_coefficient_W_m2_K must be >= 0") + if not 0.0 <= self.emissivity <= 1.0: + raise ThermalBalanceError("emissivity must lie in [0, 1]") + if ( + self.heat_transfer_coefficient_W_m2_K == 0.0 + and self.emissivity == 0.0 + ): + raise ThermalBalanceError( + "at least one cooling channel (heat_transfer_coefficient_W_m2_K > 0 or emissivity > 0) is required" + ) + if self.maximum_temperature_K <= self.ambient_temperature_K: + raise ThermalBalanceError( + "maximum_temperature_K must exceed ambient_temperature_K" + ) + if self.constant_internal_heat_W_m2 < 0.0: + raise ThermalBalanceError("constant_internal_heat_W_m2 must be >= 0") + if self.system_boundary != "device_plus_lumped_parasitics": + raise ThermalBalanceError( + f"Unsupported system_boundary {self.system_boundary!r}; " + "only 'device_plus_lumped_parasitics' is supported" + ) + + @property + def parameter_units(self) -> dict[str, str]: + return dict(THERMAL_UNIT_SCHEMA) + + +@dataclass(frozen=True) +class ThermalIntegrationProtocol: + """Explicit ODE integration controls for lumped thermal transients.""" + + method: str = "DOP853" + rtol: float = 1e-10 + atol_temperature_K: float = 1e-12 + atol_energy_J_m2: float = 1e-10 + max_step_s: float = math.inf + energy_closure_atol_J_m2: float = 1e-6 + energy_closure_rtol: float = 1e-8 + + def __post_init__(self) -> None: + if self.method not in {"RK45", "DOP853", "Radau", "BDF"}: + raise ThermalBalanceError( + f"Unsupported ODE method {self.method!r}; expected RK45, DOP853, Radau, or BDF" + ) + for name in ( + "rtol", + "atol_temperature_K", + "atol_energy_J_m2", + "energy_closure_atol_J_m2", + "energy_closure_rtol", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ThermalBalanceError(f"{name} must be finite and > 0") + object.__setattr__(self, name, float(raw)) + if not _is_real_number(self.max_step_s) or float(self.max_step_s) <= 0.0: + raise ThermalBalanceError("max_step_s must be > 0") + object.__setattr__(self, "max_step_s", float(self.max_step_s)) + + +@dataclass(frozen=True) +class ThermalPowerLedger: + """Instantaneous first-law areal power balance at temperature ``T``.""" + + temperature_K: float + absorbed_optical_power_W_m2: float + constant_internal_heat_W_m2: float + exported_electrical_power_W_m2: float + net_heating_power_W_m2: float + convective_loss_W_m2: float + radiative_loss_W_m2: float + total_cooling_loss_W_m2: float + net_storage_rate_W_m2: float + + +@dataclass(frozen=True) +class ThermalSteadyStateResult: + """Certified steady-state lumped thermal operating point.""" + + protocol: LumpedThermalProtocol + temperature_K: float + ledger: ThermalPowerLedger + root_calls: int + root_iterations: int + converged: bool + power_residual_W_m2: float + tolerance_W_m2: float + result_sha256: str + + +@dataclass(frozen=True) +class ThermalTransientResult: + """Certified lumped thermal transient trajectory and cumulative energy closure.""" + + protocol: LumpedThermalProtocol + integration: ThermalIntegrationProtocol + t_s: np.ndarray + temperature_K: np.ndarray + exported_electrical_power_W_m2: np.ndarray + net_heating_power_W_m2: np.ndarray + convective_loss_W_m2: np.ndarray + radiative_loss_W_m2: np.ndarray + cumulative_absorbed_J_m2: np.ndarray + cumulative_internal_heat_J_m2: np.ndarray + cumulative_exported_electrical_J_m2: np.ndarray + cumulative_convective_loss_J_m2: np.ndarray + cumulative_radiative_loss_J_m2: np.ndarray + stored_thermal_energy_change_J_m2: np.ndarray + energy_closure_residual_J_m2: np.ndarray + max_abs_energy_closure_residual_J_m2: float + nfev: int + certified: bool + result_sha256: str + + +def thermal_power_ledger( + temperature_K: float, + protocol: LumpedThermalProtocol, + *, + exported_electrical_power_W_m2: float = 0.0, + allow_external_electrical_drive: bool = False, +) -> ThermalPowerLedger: + """Evaluate instantaneous areal heating, cooling, and storage rate at ``T``.""" + if not isinstance(protocol, LumpedThermalProtocol): + raise ThermalBalanceError("protocol must be a LumpedThermalProtocol") + if not _is_real_number(temperature_K) or not math.isfinite(float(temperature_K)): + raise ThermalBalanceError("temperature_K must be a finite real scalar") + t_val = float(temperature_K) + if t_val <= 0.0: + raise ThermalBalanceError(f"temperature_K must be > 0 K, got {t_val}") + + if not _is_real_number(exported_electrical_power_W_m2) or not math.isfinite( + float(exported_electrical_power_W_m2) + ): + raise ThermalBalanceError( + "exported_electrical_power_W_m2 must be a finite real scalar" + ) + p_elec = float(exported_electrical_power_W_m2) + + p_abs = protocol.absorbed_optical_power_W_m2 + q_int = protocol.constant_internal_heat_W_m2 + available_input = p_abs + q_int + tol = 1e-12 * max(1.0, abs(available_input)) + if not allow_external_electrical_drive and p_elec > available_input + tol: + raise ThermalEnergySourceError( + f"exported_electrical_power_W_m2 ({p_elec:.6g} W/m^2) exceeds " + f"absorbed + internal input ({available_input:.6g} W/m^2)" + ) + + q_heat = available_input - p_elec + t_amb = protocol.ambient_temperature_K + q_conv = protocol.heat_transfer_coefficient_W_m2_K * (t_val - t_amb) + q_rad = ( + protocol.emissivity + * STEFAN_BOLTZMANN_W_M2_K4 + * (t_val**4 - t_amb**4) + ) + q_cool = q_conv + q_rad + q_net = q_heat - q_cool + + return ThermalPowerLedger( + temperature_K=t_val, + absorbed_optical_power_W_m2=p_abs, + constant_internal_heat_W_m2=q_int, + exported_electrical_power_W_m2=p_elec, + net_heating_power_W_m2=q_heat, + convective_loss_W_m2=q_conv, + radiative_loss_W_m2=q_rad, + total_cooling_loss_W_m2=q_cool, + net_storage_rate_W_m2=q_net, + ) + + +def solve_lumped_thermal_steady_state( + protocol: LumpedThermalProtocol, + *, + exported_electrical_power_fn: Callable[[float], float] | None = None, + xtol_K: float = 1e-11, + rtol: float = 1e-12, + maxiter: int = 100, + residual_atol_W_m2: float = 1e-7, + allow_external_electrical_drive: bool = False, + lower_temperature_K: float | None = None, + upper_temperature_K: float | None = None, +) -> ThermalSteadyStateResult: + """Solve ``net_storage_rate_W_m2(T*) = 0`` via bracketed Brent root finding.""" + if not isinstance(protocol, LumpedThermalProtocol): + raise ThermalBalanceError("protocol must be a LumpedThermalProtocol") + if type(maxiter) is not int or maxiter < 4: + raise ThermalBalanceError("maxiter must be an integer >= 4") + for name, val in ( + ("xtol_K", xtol_K), + ("rtol", rtol), + ("residual_atol_W_m2", residual_atol_W_m2), + ): + if not _is_real_number(val) or not math.isfinite(float(val)) or float(val) <= 0.0: + raise ThermalBalanceError(f"{name} must be finite and > 0") + + t_lo = ( + protocol.ambient_temperature_K + if lower_temperature_K is None + else float(lower_temperature_K) + ) + t_hi = ( + protocol.maximum_temperature_K + if upper_temperature_K is None + else float(upper_temperature_K) + ) + if not (0.0 < t_lo < t_hi <= protocol.maximum_temperature_K): + raise ThermalBalanceError( + f"Invalid temperature bracket [{t_lo}, {t_hi}] within (0, {protocol.maximum_temperature_K}]" + ) + + p_fn: Callable[[float], float] = ( + (lambda _t: 0.0) + if exported_electrical_power_fn is None + else exported_electrical_power_fn + ) + cache: dict[float, ThermalPowerLedger] = {} + calls = 0 + + def eval_ledger(temp_K: float) -> ThermalPowerLedger: + nonlocal calls + t_key = float(temp_K) + cached = cache.get(t_key) + if cached is not None: + return cached + calls += 1 + p_out = float(p_fn(t_key)) + led = thermal_power_ledger( + t_key, + protocol, + exported_electrical_power_W_m2=p_out, + allow_external_electrical_drive=allow_external_electrical_drive, + ) + cache[t_key] = led + return led + + f_lo = eval_ledger(t_lo).net_storage_rate_W_m2 + if abs(f_lo) <= residual_atol_W_m2: + led_star = eval_ledger(t_lo) + sha = _canonical_sha256( + { + "protocol": asdict(protocol), + "temperature_K": float(t_lo).hex(), + "ledger": asdict(led_star), + } + ) + return ThermalSteadyStateResult( + protocol=protocol, + temperature_K=t_lo, + ledger=led_star, + root_calls=calls, + root_iterations=0, + converged=True, + power_residual_W_m2=led_star.net_storage_rate_W_m2, + tolerance_W_m2=float(residual_atol_W_m2), + result_sha256=sha, + ) + + f_hi = eval_ledger(t_hi).net_storage_rate_W_m2 + if f_lo * f_hi > 0.0: + raise ThermalSteadyStateError( + f"Thermal steady-state root is not bracketed on [{t_lo:.4f}, {t_hi:.4f}] K: " + f"f(T_lo)={f_lo:.6g} W/m^2, f(T_hi)={f_hi:.6g} W/m^2" + ) + + t_root, root_info = brentq( + lambda t_val: eval_ledger(float(t_val)).net_storage_rate_W_m2, + t_lo, + t_hi, + xtol=float(xtol_K), + rtol=float(rtol), + maxiter=maxiter, + full_output=True, + disp=False, + ) + led_star = eval_ledger(float(t_root)) + if not root_info.converged or abs(led_star.net_storage_rate_W_m2) > float( + residual_atol_W_m2 + ): + raise ThermalSteadyStateError( + f"Thermal steady-state brentq failed residual gate: " + f"|f(T*)|={abs(led_star.net_storage_rate_W_m2):.3e} W/m^2 > {residual_atol_W_m2:.3e} W/m^2" + ) + + sha = _canonical_sha256( + { + "protocol": asdict(protocol), + "temperature_K": float(t_root).hex(), + "ledger": asdict(led_star), + } + ) + return ThermalSteadyStateResult( + protocol=protocol, + temperature_K=float(t_root), + ledger=led_star, + root_calls=calls, + root_iterations=int(root_info.iterations), + converged=True, + power_residual_W_m2=led_star.net_storage_rate_W_m2, + tolerance_W_m2=float(residual_atol_W_m2), + result_sha256=sha, + ) + + +def run_lumped_thermal_transient( + protocol: LumpedThermalProtocol, + t_eval_s: object, + *, + initial_temperature_K: float | None = None, + exported_electrical_power_fn: Callable[[float, float], float] | None = None, + integration: ThermalIntegrationProtocol | None = None, + allow_external_electrical_drive: bool = False, +) -> ThermalTransientResult: + """Integrate ``C_th * dT/dt`` alongside cumulative energy ledgers and verify closure.""" + if not isinstance(protocol, LumpedThermalProtocol): + raise ThermalBalanceError("protocol must be a LumpedThermalProtocol") + integ = ThermalIntegrationProtocol() if integration is None else integration + if not isinstance(integ, ThermalIntegrationProtocol): + raise ThermalBalanceError("integration must be a ThermalIntegrationProtocol") + + if np.iscomplexobj(t_eval_s): + raise ThermalBalanceError("t_eval_s must be real-valued") + times = np.array(t_eval_s, dtype=float, copy=True) + if ( + times.ndim != 1 + or times.size < 2 + or not np.all(np.isfinite(times)) + or np.any(np.diff(times) <= 0.0) + ): + raise ThermalBalanceError( + "t_eval_s must be a 1-D strictly increasing array with at least two finite times" + ) + times.setflags(write=False) + + t0_K = ( + protocol.ambient_temperature_K + if initial_temperature_K is None + else float(initial_temperature_K) + ) + if not (0.0 < t0_K <= protocol.maximum_temperature_K): + raise ThermalBalanceError( + f"initial_temperature_K ({t0_K}) must lie in (0, {protocol.maximum_temperature_K}]" + ) + + p_fn: Callable[[float, float], float] = ( + (lambda _time_s, _temp_K: 0.0) + if exported_electrical_power_fn is None + else exported_electrical_power_fn + ) + c_th = protocol.areal_heat_capacity_J_m2_K + + def rhs(time_s: float, state: np.ndarray) -> np.ndarray: + temp_K = float(state[0]) + if temp_K <= 0.0: + raise ThermalTransientError( + f"non-physical nonpositive trial temperature {temp_K} K at t={time_s} s" + ) + p_elec = float(p_fn(float(time_s), temp_K)) + led = thermal_power_ledger( + temp_K, + protocol, + exported_electrical_power_W_m2=p_elec, + allow_external_electrical_drive=allow_external_electrical_drive, + ) + return np.array( + [ + led.net_storage_rate_W_m2 / c_th, + led.absorbed_optical_power_W_m2, + led.constant_internal_heat_W_m2, + led.exported_electrical_power_W_m2, + led.convective_loss_W_m2, + led.radiative_loss_W_m2, + ], + dtype=float, + ) + + y0 = np.array([t0_K, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=float) + atol_vec = np.array( + [ + integ.atol_temperature_K, + integ.atol_energy_J_m2, + integ.atol_energy_J_m2, + integ.atol_energy_J_m2, + integ.atol_energy_J_m2, + integ.atol_energy_J_m2, + ], + dtype=float, + ) + sol = solve_ivp( + rhs, + (float(times[0]), float(times[-1])), + y0, + method=integ.method, + t_eval=times, + rtol=integ.rtol, + atol=atol_vec, + max_step=integ.max_step_s, + ) + if not sol.success or sol.y.shape != (6, times.size): + raise ThermalTransientError( + f"Thermal transient integration failed: {sol.message}" + ) + + temp_hist = np.array(sol.y[0], dtype=float, copy=True) + if np.any(temp_hist <= 0.0) or np.any(temp_hist > protocol.maximum_temperature_K): + raise ThermalTransientError( + f"Thermal transient temperature left (0, {protocol.maximum_temperature_K}] K" + ) + e_abs = np.array(sol.y[1], dtype=float, copy=True) + e_int = np.array(sol.y[2], dtype=float, copy=True) + e_elec = np.array(sol.y[3], dtype=float, copy=True) + e_conv = np.array(sol.y[4], dtype=float, copy=True) + e_rad = np.array(sol.y[5], dtype=float, copy=True) + + p_elec_arr = np.empty(times.size, dtype=float) + q_heat_arr = np.empty(times.size, dtype=float) + q_conv_arr = np.empty(times.size, dtype=float) + q_rad_arr = np.empty(times.size, dtype=float) + for k in range(times.size): + p_val = float(p_fn(float(times[k]), float(temp_hist[k]))) + led_k = thermal_power_ledger( + float(temp_hist[k]), + protocol, + exported_electrical_power_W_m2=p_val, + allow_external_electrical_drive=allow_external_electrical_drive, + ) + p_elec_arr[k] = led_k.exported_electrical_power_W_m2 + q_heat_arr[k] = led_k.net_heating_power_W_m2 + q_conv_arr[k] = led_k.convective_loss_W_m2 + q_rad_arr[k] = led_k.radiative_loss_W_m2 + + delta_u = c_th * (temp_hist - t0_K) + net_flow = e_abs + e_int - e_elec - e_conv - e_rad + closure_res = delta_u - net_flow + max_res = float(np.max(np.abs(closure_res))) + scale = float( + np.max( + np.abs(e_abs) + + np.abs(e_int) + + np.abs(e_elec) + + np.abs(e_conv) + + np.abs(e_rad) + + np.abs(delta_u) + ) + ) + allowed = integ.energy_closure_atol_J_m2 + integ.energy_closure_rtol * max( + 1.0, scale + ) + if max_res > allowed: + raise ThermalTransientError( + f"Cumulative thermal energy closure residual {max_res:.3e} J/m^2 exceeds {allowed:.3e} J/m^2" + ) + + for arr in ( + temp_hist, + p_elec_arr, + q_heat_arr, + q_conv_arr, + q_rad_arr, + e_abs, + e_int, + e_elec, + e_conv, + e_rad, + delta_u, + closure_res, + ): + arr.setflags(write=False) + + sha = _canonical_sha256( + { + "protocol": asdict(protocol), + "integration": { + "method": integ.method, + "rtol": integ.rtol, + "atol_temperature_K": integ.atol_temperature_K, + "atol_energy_J_m2": integ.atol_energy_J_m2, + "max_step_s": ( + "inf" if math.isinf(integ.max_step_s) else integ.max_step_s + ), + }, + "t_s": _array_hex_list(times), + "temperature_K": _array_hex_list(temp_hist), + "max_abs_energy_closure_residual_J_m2": max_res.hex(), + } + ) + return ThermalTransientResult( + protocol=protocol, + integration=integ, + t_s=times, + temperature_K=temp_hist, + exported_electrical_power_W_m2=p_elec_arr, + net_heating_power_W_m2=q_heat_arr, + convective_loss_W_m2=q_conv_arr, + radiative_loss_W_m2=q_rad_arr, + cumulative_absorbed_J_m2=e_abs, + cumulative_internal_heat_J_m2=e_int, + cumulative_exported_electrical_J_m2=e_elec, + cumulative_convective_loss_J_m2=e_conv, + cumulative_radiative_loss_J_m2=e_rad, + stored_thermal_energy_change_J_m2=delta_u, + energy_closure_residual_J_m2=closure_res, + max_abs_energy_closure_residual_J_m2=max_res, + nfev=int(sol.nfev), + certified=True, + result_sha256=sha, + ) diff --git a/src/solarlab/experiments/tpv.py b/src/solarlab/experiments/tpv.py new file mode 100644 index 00000000..0ca0d511 --- /dev/null +++ b/src/solarlab/experiments/tpv.py @@ -0,0 +1,651 @@ +"""Transient photovoltage (TPV) experiment with paired unpulsed control baseline. + +Contract (P05-04 clauses 1 & 5): +1. Preconditioning is explicit and reproducible: + - Ion-free ``CompiledDevice1D`` solves the exact 1-sun open-circuit steady + state ``(state_oc, V_oc)`` via bracketed Brent root finding from a fixed + lower bracket ``0.0 V`` (never an order-dependent floating guess). + - Mobile-ion ``CompiledIonicDevice1D`` executes a finite-time illuminated + open-circuit preconditioning soak of duration ``soak_duration_s`` via + ``integrate_open_circuit`` and explicitly records + ``initial_state_source = 'finite_time_illuminated_preconditioned'`` with + ``equilibrium_claimed = False``. +2. Both the pulsed trajectory (``1 + delta_G_frac`` on ``(0, t_pulse]``, ``1`` + on ``(t_pulse, t_pulse + t_decay]``) and the matched unpulsed control + trajectory (``1`` throughout ``(0, t_pulse + t_decay]``) start from the + exact same ``(state_oc, V_oc)`` on the exact same time grid using the + charge-conserving floating-terminal Backward Euler integrator + (``I_carrier + I_ion + dD/dt = 0``). +3. ``delta_V = V_pulsed - V_control`` isolates the perturbation response from + any baseline drift. +4. ``fit_tpv_decay`` fits ``tau_s`` ONLY when single-exponential identifiability + holds; non-monotonic, sign-changing, truncated, or multi-exponential decays + return ``tau_s = None`` and an explicit ``non_identifiable_reason``. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +import hashlib +import json +import math +from typing import Any + +import numpy as np +from scipy.optimize import brentq, least_squares + +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CompiledDevice1D, State1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, IonicState1D +from solarlab.experiments.electrothermal import has_declared_ions +from solarlab.experiments.open_circuit import ( + OpenCircuitOptions, + OpenCircuitTrajectory, + integrate_open_circuit, +) +from solarlab.solvers.nonlinear.ionic_1d import ( + IonicSteadyOptions, + solve_ionic_steady_state, +) +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import HISTORICAL_MAX_ROW_V1 +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state + +__all__ = [ + "TPVDecayFit", + "TPVError", + "TPVProtocol", + "TPVResult", + "fit_tpv_decay", + "run_tpv", + "solve_illuminated_voc_state", +] + + +class TPVError(RuntimeError): + """Invalid TPV protocol or failed open-circuit preconditioning/integration.""" + + +def _is_real_number(value: object) -> bool: + return isinstance(value, (int, float, np.floating, np.integer)) and not isinstance( + value, bool + ) + + +def _canonical_sha256(payload: dict[str, Any]) -> str: + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +@dataclass(frozen=True) +class TPVDecayFit: + """Single-exponential identifiability outcome for post-pulse ``delta_V(t)``.""" + + tau_s: float | None + amplitude_V: float + status: str + non_identifiable_reason: str | None + points: int + r_squared: float | None + normalized_max_error: float | None + + +@dataclass(frozen=True) +class TPVProtocol: + """Explicit TPV perturbation, sampling, and preconditioning controls.""" + + delta_G_frac: float = 0.05 + t_pulse_s: float = 1e-6 + t_decay_s: float = 5e-5 + pulse_points: int = 10 + decay_points: int = 80 + decay_grid: str = "geometric" + soak_duration_s: float = 1e-3 + soak_steps: int = 20 + voc_upper_bound_V: float = 1.6 + intervals_per_layer: int = 24 + open_circuit_options: OpenCircuitOptions = OpenCircuitOptions() + + def __post_init__(self) -> None: + for name in ( + "delta_G_frac", + "t_pulse_s", + "t_decay_s", + "voc_upper_bound_V", + ): + raw = getattr(self, name) + if not _is_real_number(raw) or not math.isfinite(float(raw)) or float(raw) <= 0.0: + raise ValueError(f"{name} must be finite and positive") + object.__setattr__(self, name, float(raw)) + if ( + not _is_real_number(self.soak_duration_s) + or not math.isfinite(float(self.soak_duration_s)) + or float(self.soak_duration_s) < 0.0 + ): + raise ValueError("soak_duration_s must be finite and >= 0") + object.__setattr__(self, "soak_duration_s", float(self.soak_duration_s)) + + if type(self.pulse_points) is not int or self.pulse_points < 2: + raise ValueError("pulse_points must be an integer >= 2") + if type(self.decay_points) is not int or self.decay_points < 5: + raise ValueError("decay_points must be an integer >= 5") + if type(self.soak_steps) is not int or self.soak_steps < 2: + raise ValueError("soak_steps must be an integer >= 2") + if type(self.intervals_per_layer) is not int or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be an integer >= 2") + if self.decay_grid not in {"linear", "geometric"}: + raise ValueError("decay_grid must be 'linear' or 'geometric'") + if not isinstance(self.open_circuit_options, OpenCircuitOptions): + raise TypeError("open_circuit_options must be an OpenCircuitOptions") + + +@dataclass(frozen=True) +class TPVResult: + """Paired pulsed/control open-circuit TPV trajectory and decay fit.""" + + t: np.ndarray + V: np.ndarray + V_control: np.ndarray + delta_V: np.ndarray + V_oc: float + delta_V_0: float + tau: float | None + decay_fit: TPVDecayFit + pulsed_trajectory: OpenCircuitTrajectory + control_trajectory: OpenCircuitTrajectory + preconditioning_trajectory: OpenCircuitTrajectory | None + initial_state_source: str + equilibrium_claimed: bool + max_baseline_drift_V: float + max_current_error_A_m2: float + charge_voltage_error_V: float + compiled_identity: str + result_sha256: str + + +def fit_tpv_decay( + t_decay_rel_s: object, + delta_V_decay: object, + *, + min_amplitude_V: float = 1e-9, + tail_floor_fraction: float = 1e-3, + min_points: int = 5, + min_efolds: float = 1.0, + monotonicity_atol_fraction: float = 1e-4, + min_r_squared: float = 0.995, + max_normalized_error: float = 0.02, +) -> TPVDecayFit: + """Fit ``delta_V(t) = A * exp(-t / tau)`` or refuse with an explicit reason.""" + t_raw = np.asarray(t_decay_rel_s, dtype=float) + y_raw = np.asarray(delta_V_decay, dtype=float) + if ( + t_raw.ndim != 1 + or y_raw.shape != t_raw.shape + or t_raw.size < 2 + or not np.all(np.isfinite(t_raw)) + or not np.all(np.isfinite(y_raw)) + or np.any(np.diff(t_raw) < 0.0) + ): + raise ValueError("t_decay_rel_s and delta_V_decay must be matched 1-D finite arrays") + + t_rel = t_raw - float(t_raw[0]) + amp0 = float(y_raw[0]) + if not math.isfinite(amp0) or amp0 <= min_amplitude_V: + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="no_signal", + non_identifiable_reason=( + f"initial post-pulse perturbation {amp0:.3e} V <= min_amplitude_V ({min_amplitude_V:.3e} V)" + ), + points=0, + r_squared=None, + normalized_max_error=None, + ) + + floor_v = tail_floor_fraction * amp0 + if np.any(y_raw < -floor_v): + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="sign_change", + non_identifiable_reason=( + "differential photovoltage changed sign below noise floor during decay" + ), + points=int(y_raw.size), + r_squared=None, + normalized_max_error=None, + ) + + below = np.flatnonzero(y_raw <= floor_v) + end_idx = int(below[0]) if below.size > 0 else int(y_raw.size) + t_win = t_rel[:end_idx] + y_win = y_raw[:end_idx] + + if y_win.size < min_points: + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="insufficient_points", + non_identifiable_reason=( + f"only {y_win.size} decay sample(s) above tail floor (< min_points={min_points})" + ), + points=int(y_win.size), + r_squared=None, + normalized_max_error=None, + ) + + diffs = np.diff(y_win) + if np.any(diffs > monotonicity_atol_fraction * amp0): + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="non_monotonic", + non_identifiable_reason=( + "post-pulse differential photovoltage is non-monotonic (re-rising tail)" + ), + points=int(y_win.size), + r_squared=None, + normalized_max_error=None, + ) + + efolds_observed = math.log(amp0 / float(y_win[-1])) + if efolds_observed < min_efolds - 1e-6: + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="insufficient_decay_window", + non_identifiable_reason=( + f"decay window spans {efolds_observed:.3f} e-folds (< required {min_efolds:.3f})" + ), + points=int(y_win.size), + r_squared=None, + normalized_max_error=None, + ) + + # Initial guess from log-linear regression + log_y = np.log(y_win) + slope, intercept = np.polyfit(t_win, log_y, 1) + tau_guess = max(1e-15, -1.0 / float(slope)) if slope < 0.0 else float(t_win[-1]) + amp_guess = max(min_amplitude_V, math.exp(float(intercept))) + + def residuals(params: np.ndarray) -> np.ndarray: + a_p, tau_p = float(params[0]), float(params[1]) + return a_p * np.exp(-t_win / tau_p) - y_win + + lsq = least_squares( + residuals, + x0=np.array([amp_guess, tau_guess], dtype=float), + bounds=(np.array([0.0, 1e-18]), np.array([10.0 * amp0 + 1.0, 1e6 * max(1.0, float(t_win[-1]))])), + xtol=1e-13, + ftol=1e-13, + gtol=1e-13, + ) + amp_fit = float(lsq.x[0]) + tau_fit = float(lsq.x[1]) + y_pred = amp_fit * np.exp(-t_win / tau_fit) + ss_res = float(np.sum((y_win - y_pred) ** 2)) + ss_tot = float(np.sum((y_win - np.mean(y_win)) ** 2)) + r2 = 1.0 if ss_tot == 0.0 else 1.0 - ss_res / ss_tot + norm_err = float(np.max(np.abs(y_win - y_pred)) / amp0) + + if not lsq.success or r2 < min_r_squared or norm_err > max_normalized_error: + return TPVDecayFit( + tau_s=None, + amplitude_V=amp0, + status="not_single_exponential", + non_identifiable_reason=( + f"decay deviates from single exponential (R^2={r2:.5f} vs >= {min_r_squared}, " + f"normalized_max_error={norm_err:.4f} vs <= {max_normalized_error})" + ), + points=int(y_win.size), + r_squared=r2, + normalized_max_error=norm_err, + ) + + return TPVDecayFit( + tau_s=tau_fit, + amplitude_V=amp_fit, + status="single_exponential", + non_identifiable_reason=None, + points=int(y_win.size), + r_squared=r2, + normalized_max_error=norm_err, + ) + + +def solve_illuminated_voc_state( + compiled: CompiledDevice1D, + *, + generation_scale: float = 1.0, + upper_bound_V: float = 1.6, + current_tol_A_m2: float = 1e-9, + steady_options: SteadyOptions | None = None, +) -> tuple[State1D, float]: + """Find the exact ion-free steady ``(state_oc, V_oc)`` from fixed lower bracket ``0.0 V``.""" + if not isinstance(compiled, CompiledDevice1D): + raise TypeError("compiled must be a CompiledDevice1D") + opts = SteadyOptions() if steady_options is None else steady_options + polarity = float(compiled.voltage_polarity) + + sol_0 = solve_steady_state( + compiled, + initial_state=None, + voltage_V=0.0, + generation_scale=generation_scale, + options=opts, + ) + if not sol_0.converged: + raise TPVError("0 V illuminated steady state failed to converge") + j_0 = float(-polarity * sol_0.current_density_A_m2[0]) + if j_0 <= 0.0: + raise TPVError( + f"Device produces nonpositive short-circuit photocurrent ({j_0:.4g} A/m^2); V_oc is not in (0, {upper_bound_V}] V" + ) + + # March deterministically from 0 V to bracket V_oc reliably without basin jumps + coarse_v = np.linspace(0.0, upper_bound_V, 17) + prev_state = sol_0.state + v_lo = 0.0 + state_lo = sol_0.state + j_lo = j_0 + v_hi: float | None = None + for v_cand in coarse_v[1:]: + sol_c = solve_steady_state( + compiled, + initial_state=prev_state, + voltage_V=float(v_cand), + generation_scale=generation_scale, + options=opts, + ) + if not sol_c.converged: + raise TPVError(f"Steady state failed while bracketing V_oc at V={v_cand:.4f} V") + j_c = float(-polarity * sol_c.current_density_A_m2[0]) + if j_c <= 0.0: + v_hi = float(v_cand) + break + v_lo = float(v_cand) + state_lo = sol_c.state + j_lo = j_c + prev_state = sol_c.state + + if v_hi is None: + raise TPVError( + f"Open-circuit voltage exceeds upper_bound_V={upper_bound_V:.4f} V" + ) + _ = j_lo + + best: dict[str, Any] = {"state": state_lo, "v": v_lo} + + def current_at(v_trial: float) -> float: + sol_t = solve_steady_state( + compiled, + initial_state=state_lo, + voltage_V=float(v_trial), + generation_scale=generation_scale, + options=opts, + ) + if not sol_t.converged: + raise TPVError(f"Steady solve failed during V_oc Brent search at {v_trial:.6f} V") + j_val = float(-polarity * sol_t.current_density_A_m2[0]) + best["state"] = sol_t.state + best["v"] = float(v_trial) + return j_val + + v_root = float(brentq(current_at, v_lo, v_hi, xtol=1e-13, rtol=1e-13, maxiter=80)) + sol_final = solve_steady_state( + compiled, + initial_state=state_lo, + voltage_V=v_root, + generation_scale=generation_scale, + options=opts, + ) + if not sol_final.converged: + raise TPVError("Final V_oc steady state failed certification") + j_final = abs(float(-polarity * sol_final.current_density_A_m2[0])) + if j_final > max(current_tol_A_m2, opts.continuity_tolerance_A_m2 * 10.0): + raise TPVError( + f"Residual conduction current at V_oc ({j_final:.3e} A/m^2) exceeds tolerance" + ) + return sol_final.state, v_root + + +def _precondition_ionic_open_circuit( + compiled: CompiledIonicDevice1D, + protocol: TPVProtocol, +) -> tuple[IonicState1D, float, OpenCircuitTrajectory]: + """Finite-time illuminated open-circuit preconditioning from dark 0 V.""" + if protocol.soak_duration_s <= 0.0: + raise TPVError( + "Mobile-ion TPV requires positive soak_duration_s for explicit finite-time preconditioning" + ) + steady_opts = IonicSteadyOptions( + electronic=SteadyOptions( + poisson_tolerance=protocol.open_circuit_options.poisson_tolerance, + continuity_tolerance_A_m2=protocol.open_circuit_options.continuity_tolerance_A_m2, + contact_log_tolerance=protocol.open_circuit_options.contact_log_tolerance, + convergence_policy=HISTORICAL_MAX_ROW_V1, + ), + inventory_relative_tolerance=1e-11, + ion_balance_tolerance_m2_s=protocol.open_circuit_options.ion_balance_tolerance_m2_s, + ion_flux_tolerance_m2_s=protocol.open_circuit_options.ion_balance_tolerance_m2_s, + ion_logit_step=protocol.open_circuit_options.ion_logit_step, + inventory_row_node=compiled.ion_node_count - 1, + budget=SolveBudget(120, 960, 122, 12), + wall_s=30.0, + ) + dark0 = solve_ionic_steady_state( + compiled, + voltage_V=0.0, + generation_scale=0.0, + options=steady_opts, + initial_state=None, + ) + if not dark0.accepted or dark0.state is None: + raise TPVError( + f"Dark 0 V initial state failed before TPV preconditioning: {dark0.termination}" + ) + + # Smooth illumination turn-on followed by geometric open-circuit soak to + # soak_duration_s (keeping dt >= 2e-5 s so finite-site ionic storage rates + # stay free of floating-point subtraction noise while resolving carrier and + # ionic redistribution). + if protocol.soak_duration_s <= 1e-4: + soak_t = np.linspace(0.0, protocol.soak_duration_s, max(5, protocol.soak_steps + 1)) + soak_g = np.ones_like(soak_t) + soak_g[0] = 0.0 + if soak_g.size >= 4: + soak_g[1] = 1e-3 + soak_g[2] = 1e-1 + else: + n_tail = max(3, protocol.soak_steps - 2) + t_ramp1 = min(2e-5, 0.1 * protocol.soak_duration_s) + t_ramp2 = min(1e-4, 0.3 * protocol.soak_duration_s) + soak_t = np.r_[ + 0.0, + t_ramp1, + t_ramp2, + np.geomspace(t_ramp2 * 2.0, protocol.soak_duration_s, n_tail), + ] + soak_g = np.ones_like(soak_t) + soak_g[0] = 0.0 + soak_g[1] = 1e-3 + soak_g[2] = 1e-1 + pre_traj = integrate_open_circuit( + compiled, + dark0.state, + soak_t, + soak_g, + initial_voltage_V=0.0, + options=protocol.open_circuit_options, + ) + final_state = pre_traj.states[-1] + assert isinstance(final_state, IonicState1D) + return final_state, float(pre_traj.terminal_voltage_V[-1]), pre_traj + + +def _build_tpv_schedule( + protocol: TPVProtocol, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]: + """Build matched ``(times_s, gen_pulsed, gen_control, pulse_end_index)``.""" + t_pulse_grid = np.linspace(0.0, protocol.t_pulse_s, protocol.pulse_points + 1) + if protocol.decay_grid == "geometric": + dt0 = max(1e-11, 0.05 * (protocol.t_pulse_s / protocol.pulse_points)) + decay_offsets = np.geomspace( + dt0, protocol.t_decay_s, protocol.decay_points + ) + else: + decay_offsets = np.linspace( + protocol.t_decay_s / protocol.decay_points, + protocol.t_decay_s, + protocol.decay_points, + ) + t_decay_grid = protocol.t_pulse_s + decay_offsets + times_s = np.r_[t_pulse_grid, t_decay_grid] + pulse_end_idx = int(protocol.pulse_points) + + gen_control = np.ones_like(times_s) + gen_pulsed = np.ones_like(times_s) + gen_pulsed[1 : pulse_end_idx + 1] = 1.0 + protocol.delta_G_frac + return times_s, gen_pulsed, gen_control, pulse_end_idx + + +def run_tpv( + target: PreparedDevice | CompiledDevice1D | CompiledIonicDevice1D, + protocol: TPVProtocol | None = None, + *, + ion_domain_layer: str | None = None, + ion_domain_endpoints: tuple[str, str] | None = None, +) -> TPVResult: + """Execute paired pulsed + control open-circuit TPV and extract ``TPVDecayFit``.""" + prot = TPVProtocol() if protocol is None else protocol + if not isinstance(prot, TPVProtocol): + raise TypeError("protocol must be a TPVProtocol") + + if isinstance(target, PreparedDevice): + has_ions, inferred_layer = has_declared_ions(target) + if not has_ions: + compiled: CompiledDevice1D | CompiledIonicDevice1D = compile_device_1d( + target, intervals_per_layer=prot.intervals_per_layer + ) + else: + elec_layers = tuple( + lyr for lyr in target.layers if lyr.role != "substrate" + ) + chosen_layer = ( + ion_domain_layer if ion_domain_layer is not None else inferred_layer + ) + chosen_end = ( + ion_domain_endpoints + if ion_domain_endpoints is not None + else (("blocking", "blocking") if len(elec_layers) > 1 else None) + ) + compiled = compile_ionic_device_1d( + target, + intervals_per_layer=prot.intervals_per_layer, + ion_domain_layer=chosen_layer, + ion_domain_endpoints=chosen_end, + ) + elif isinstance(target, (CompiledDevice1D, CompiledIonicDevice1D)): + compiled = target + else: + raise TypeError( + "target must be PreparedDevice, CompiledDevice1D, or CompiledIonicDevice1D" + ) + + pre_traj: OpenCircuitTrajectory | None + if isinstance(compiled, CompiledDevice1D): + state_oc: State1D | IonicState1D + state_oc, v_oc = solve_illuminated_voc_state( + compiled, + generation_scale=1.0, + upper_bound_V=prot.voc_upper_bound_V, + current_tol_A_m2=prot.open_circuit_options.max_current_error_A_m2, + ) + init_source = "steady_illuminated_open_circuit" + eq_claimed = True + pre_traj = None + else: + state_oc, v_oc, pre_traj = _precondition_ionic_open_circuit(compiled, prot) + init_source = "finite_time_illuminated_preconditioned" + eq_claimed = False + + times_s, gen_pulsed, gen_control, pulse_end_idx = _build_tpv_schedule(prot) + + pulsed_traj = integrate_open_circuit( + compiled, + state_oc, + times_s, + gen_pulsed, + initial_voltage_V=v_oc, + options=prot.open_circuit_options, + ) + control_traj = integrate_open_circuit( + compiled, + state_oc, + times_s, + gen_control, + initial_voltage_V=v_oc, + options=prot.open_circuit_options, + ) + + v_pulsed = pulsed_traj.terminal_voltage_V + v_ctrl = control_traj.terminal_voltage_V + delta_v = np.array(v_pulsed - v_ctrl, dtype=float, copy=True) + delta_v.setflags(write=False) + + delta_v_0 = float(delta_v[pulse_end_idx]) + t_decay_slice = times_s[pulse_end_idx:] - float(times_s[pulse_end_idx]) + dv_decay_slice = delta_v[pulse_end_idx:] + fit = fit_tpv_decay(t_decay_slice, dv_decay_slice) + + max_drift = float(np.max(np.abs(v_ctrl - v_oc))) + max_i_err = float( + max( + np.max(pulsed_traj.max_face_total_current_A_m2), + np.max(control_traj.max_face_total_current_A_m2), + ) + ) + v_charge_err = float( + max( + pulsed_traj.charge_voltage_error_V, + control_traj.charge_voltage_error_V, + ) + ) + + sha = _canonical_sha256( + { + "compiled_identity": compiled.identity, + "initial_state_source": init_source, + "equilibrium_claimed": eq_claimed, + "V_oc": float(v_oc).hex(), + "delta_V_0": delta_v_0.hex(), + "decay_fit": asdict(fit), + "max_current_error_A_m2": max_i_err.hex(), + "charge_voltage_error_V": v_charge_err.hex(), + } + ) + return TPVResult( + t=times_s, + V=v_pulsed, + V_control=v_ctrl, + delta_V=delta_v, + V_oc=float(v_oc), + delta_V_0=delta_v_0, + tau=fit.tau_s, + decay_fit=fit, + pulsed_trajectory=pulsed_traj, + control_trajectory=control_traj, + preconditioning_trajectory=pre_traj, + initial_state_source=init_source, + equilibrium_claimed=eq_claimed, + max_baseline_drift_V=max_drift, + max_current_error_A_m2=max_i_err, + charge_voltage_error_V=v_charge_err, + compiled_identity=compiled.identity, + result_sha256=sha, + ) diff --git a/tests/integration/test_degradation_snapshots.py b/tests/integration/test_degradation_snapshots.py new file mode 100644 index 00000000..488f70b8 --- /dev/null +++ b/tests/integration/test_degradation_snapshots.py @@ -0,0 +1,165 @@ +"""Integration tests for P05-04a frozen-ion J-V snapshots & coupled degradation trajectories.""" + +from __future__ import annotations + +from pathlib import Path +import sys + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from examples.research_1d.ionic_multilayer import ( # noqa: E402 + prepare_confined_dual_ion_device, + prepare_confined_ion_device, +) +from examples.research_1d.shared_site_ionic_fixture import ( # noqa: E402 + prepare_confined_shared_site_ion_device, +) +from solarlab.config.resolve_device import resolve_device # noqa: E402 +from solarlab.device.inputs import DeviceInput # noqa: E402 +from solarlab.device.resolved import PreparedDevice # noqa: E402 +from solarlab.experiments.degradation import ( # noqa: E402 + DegradationDamageProtocol, + DegradationProtocol, + freeze_prepared_ions, + run_degradation, +) + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> object: + with threadpool_limits(limits=1): + yield + + +def _with_fast_diffusivities( + prepared: PreparedDevice, + *, + d_pos: float, + d_neg: float | None = None, +) -> PreparedDevice: + editing = prepared.to_input().editing_data() + absorber = next(lyr for lyr in editing["layers"] if lyr["role"] == "absorber") + absorber["parameters"]["D_ion"] = d_pos + if d_neg is not None: + absorber["parameters"]["D_ion_neg"] = d_neg + return resolve_device( + DeviceInput.model_validate(editing), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +@pytest.mark.parametrize( + "species_mode", + ["single_species", "dual_independent", "dual_shared_site"], +) +def test_frozen_ion_snapshots_preserve_exact_profiles_and_zero_rebind_across_all_steric_modes( + species_mode: str, +) -> None: + if species_mode == "single_species": + dev = _with_fast_diffusivities(prepare_confined_ion_device(), d_pos=1e-13) + elif species_mode == "dual_independent": + dev = prepare_confined_dual_ion_device( + positive_diffusivity_m2_s=1e-13, + negative_diffusivity_m2_s=5e-14, + ) + else: + dev = prepare_confined_shared_site_ion_device( + positive_diffusivity_m2_s=1e-13, + negative_diffusivity_m2_s=5e-14, + ) + + frozen = freeze_prepared_ions(dev) + for lyr_live, lyr_froz in zip(dev.layers, frozen.layers, strict=True): + p_live = dict(lyr_live.parameters) + p_froz = dict(lyr_froz.parameters) + assert p_froz["D_ion"] == 0.0 + assert p_froz["D_ion_neg"] == 0.0 + assert p_froz["P0"] == p_live["P0"] + assert p_froz["P0_neg"] == p_live["P0_neg"] + assert p_froz["P_lim"] == p_live["P_lim"] + assert p_froz["P_lim_neg"] == p_live["P_lim_neg"] + + prot = DegradationProtocol( + V_bias_V=0.85, + generation_scale=1.0, + precondition_time_s=1e-3, + dt_max_s=0.05, + n_jv_points=17, + V_max_V=1.24, + intervals_per_layer=8, + ) + res = run_degradation(dev, [0.0, 0.05, 0.15], prot) + + # 1. Zero irreversible damage -> zero material rebinds, single compiled identity + assert res.material_rebind_count == 0 + assert len(set(res.snapshot_live_compiled_identities)) == 1 + assert len(set(res.snapshot_frozen_compiled_identities)) == 1 + np.testing.assert_array_equal(res.damage, np.zeros(3)) + + # 2. Every snapshot certifies 0-ULP frozen-ion invariance & identically zero ion flux + for snap in res.snapshots: + assert snap.frozen_profile_exact is True + assert snap.max_ion_flux_m2_s == 0.0 + assert snap.max_current_spread_A_m2 <= prot.max_current_error_A_m2 + assert snap.metrics.open_circuit_voltage_V is not None + assert snap.metrics.efficiency is not None + + # 3. Live stress between snapshots moves mobile ions away from t=0 profile + pos_delta = float( + np.max( + np.abs( + res.snapshots[-1].positive_ion_density_m3 + - res.snapshots[0].positive_ion_density_m3 + ) + ) + ) + assert pos_delta > 1e19 + if species_mode != "single_species": + neg_delta = float( + np.max( + np.abs( + res.snapshots[-1].negative_ion_density_m3 + - res.snapshots[0].negative_ion_density_m3 + ) + ) + ) + assert neg_delta > 1e19 + + +def test_coupled_irreversible_lifetime_damage_rebinds_absorber_and_degrades_voc_and_pce() -> None: + dev = _with_fast_diffusivities(prepare_confined_ion_device(), d_pos=2e-13) + prot = DegradationProtocol( + V_bias_V=0.6, + generation_scale=1.0, + precondition_time_s=1e-3, + dt_max_s=0.05, + n_jv_points=21, + V_max_V=1.24, + intervals_per_layer=8, + damage_protocol=DegradationDamageProtocol( + motion_gain_m2_C=80.0, + segregation_gain_s_1=4.0, + lifetime_degradation_alpha=3.5, + damage_rebind_threshold=0.0, + ), + ) + res = run_degradation(dev, [0.0, 0.1, 0.25], prot) + + assert res.damage[0] == 0.0 + assert res.damage[1] > 0.0 + assert res.damage[2] > res.damage[1] + assert res.material_rebind_count >= 2 + assert len(set(res.snapshot_live_compiled_identities)) == 3 + assert len(set(res.snapshot_frozen_compiled_identities)) == 3 + + # Reduced SRH lifetime monotonically degrades V_oc and PCE + assert res.V_oc_V[2] < res.V_oc_V[0] + assert res.PCE[2] < res.PCE[0] diff --git a/tests/integration/test_external_circuit_electrothermal.py b/tests/integration/test_external_circuit_electrothermal.py new file mode 100644 index 00000000..0dc9dbbc --- /dev/null +++ b/tests/integration/test_external_circuit_electrothermal.py @@ -0,0 +1,356 @@ +"""Integration and legacy-parity tests for P04-13 external circuit & electrothermal coupling.""" + +from __future__ import annotations + +from pathlib import Path +import sys + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from examples.research_1d import optical_generation as optical_example # noqa: E402 +from examples.research_1d.ionic_multilayer import ( # noqa: E402 + prepare_confined_ion_device, +) +from perovskite_sim.experiments import ( # noqa: E402 + external_circuit as legacy_external_circuit, + thermal_balance as legacy_thermal_balance, +) +from solarlab.config.resolve_device import resolve_device # noqa: E402 +from solarlab.device.compile_1d import compile_device_1d # noqa: E402 +from solarlab.device.inputs import DeviceInput # noqa: E402 +from solarlab.device.resolved import PreparedDevice # noqa: E402 +from solarlab.experiments.electrothermal import ( # noqa: E402 + ElectrothermalCapabilityError, + ElectrothermalJVProtocol, + ElectrothermalOperatingPointProtocol, + solve_electrothermal_operating_point, +) +from solarlab.experiments.external_circuit import ( # noqa: E402 + ExternalACCircuitProtocol, + ExternalCircuitProtocol, + apply_external_circuit_steady, + compose_external_ac_impedance, + map_external_circuit_branch, +) +from solarlab.experiments.impedance import solve_impedance # noqa: E402 +from solarlab.experiments.jv.steady import run_steady_jv # noqa: E402 +from solarlab.experiments.thermal_balance import ( # noqa: E402 + LumpedThermalProtocol, + ThermalIntegrationProtocol, + run_lumped_thermal_transient, + solve_lumped_thermal_steady_state, + thermal_power_ledger, +) +from solarlab.solvers.nonlinear.steady_1d import ( # noqa: E402 + SteadyOptions, + solve_steady_state, +) + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> object: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def illuminated_prepared() -> PreparedDevice: + return optical_example.prepare_case() + + +@pytest.fixture(scope="module") +def illuminated_ionic_prepared(illuminated_prepared: PreparedDevice) -> PreparedDevice: + base_ion = prepare_confined_ion_device() + doc = illuminated_prepared.to_input().editing_data() + doc["id"] = "illuminated_confined_ion_electrothermal" + doc["settings"]["ion_steric_diffusion_only"] = True + absorber = next(lyr for lyr in doc["layers"] if lyr["role"] == "absorber") + absorber["parameters"].update(P0=1e24, P_lim=1e27, D_ion=1e-16, E_a_ion=0.58) + _ = base_ion + return resolve_device( + DeviceInput.model_validate(doc), + illuminated_prepared.defaults, + illuminated_prepared.resources, + sources=illuminated_prepared.sources, + ) + + +def test_legacy_parity_external_circuit_and_thermal_balance( + illuminated_prepared: PreparedDevice, +) -> None: + compiled = compile_device_1d(illuminated_prepared, intervals_per_layer=(8, 8, 8)) + voltages = np.linspace(0.0, 1.25, 31) + steady_jv = run_steady_jv( + compiled, voltages, generation_scale=1.0, incident_power_W_m2=1000.0 + ) + + sl_dc = ExternalCircuitProtocol( + series_resistance_ohm_m2=7.5e-4, + shunt_resistance_ohm_m2=0.25, + ) + leg_dc = legacy_external_circuit.ExternalCircuitProtocol( + series_resistance_ohm_m2=7.5e-4, + shunt_resistance_ohm_m2=0.25, + ) + sl_branch = map_external_circuit_branch( + steady_jv.voltage_V, + steady_jv.output_current_A_m2, + sl_dc, + incident_power_W_m2=1000.0, + ) + leg_branch = legacy_external_circuit.map_external_circuit_branch( + steady_jv.voltage_V, + steady_jv.output_current_A_m2, + leg_dc, + ) + np.testing.assert_array_equal(sl_branch.V_terminal, leg_branch.terminal_voltage_V) + np.testing.assert_array_equal(sl_branch.J_terminal, leg_branch.terminal_current_A_m2) + np.testing.assert_array_equal(sl_branch.J_shunt, leg_branch.shunt_current_A_m2) + np.testing.assert_array_equal( + sl_branch.series_voltage_drop_V, leg_branch.series_voltage_drop_V + ) + np.testing.assert_array_equal( + sl_branch.power_terminal_W_m2, leg_branch.terminal_power_W_m2 + ) + + sl_th = LumpedThermalProtocol( + absorbed_optical_power_W_m2=820.0, + ambient_temperature_K=298.15, + areal_heat_capacity_J_m2_K=950.0, + heat_transfer_coefficient_W_m2_K=18.5, + emissivity=0.82, + constant_internal_heat_W_m2=12.0, + maximum_temperature_K=400.0, + ) + leg_th = legacy_thermal_balance.LumpedThermalProtocol( + absorbed_optical_power_W_m2=820.0, + ambient_temperature_K=298.15, + areal_heat_capacity_J_m2_K=950.0, + heat_transfer_coefficient_W_m2_K=18.5, + emissivity=0.82, + constant_internal_heat_W_m2=12.0, + maximum_temperature_K=400.0, + ) + p_exp = float(np.max(sl_branch.power_terminal_W_m2)) + + sl_ledger = thermal_power_ledger( + 325.0, sl_th, exported_electrical_power_W_m2=p_exp + ) + leg_ledger = legacy_thermal_balance.thermal_power_ledger( + leg_th, temperature_K=325.0, terminal_electrical_export_W_m2=p_exp + ) + assert sl_ledger.net_storage_rate_W_m2 == pytest.approx( + leg_ledger.net_heating_W_m2, rel=1e-14, abs=1e-14 + ) + + sl_ss = solve_lumped_thermal_steady_state( + sl_th, exported_electrical_power_fn=lambda _t: p_exp + ) + leg_ss = legacy_thermal_balance.solve_lumped_thermal_steady_state( + leg_th, terminal_electrical_export_W_m2=p_exp + ) + assert sl_ss.temperature_K == pytest.approx( + leg_ss.temperature_K, rel=1e-12, abs=1e-11 + ) + + t_eval = np.linspace(0.0, 180.0, 37) + sl_int = ThermalIntegrationProtocol(method="DOP853") + leg_int = legacy_thermal_balance.ThermalIntegrationProtocol( + initial_temperature_K=298.15, duration_s=180.0, sample_count=37 + ) + sl_tr = run_lumped_thermal_transient( + sl_th, + t_eval, + initial_temperature_K=298.15, + exported_electrical_power_fn=lambda _t, _temp: p_exp, + integration=sl_int, + ) + leg_tr = legacy_thermal_balance.run_lumped_thermal_transient( + leg_th, leg_int, terminal_electrical_export_W_m2=p_exp + ) + np.testing.assert_allclose( + sl_tr.temperature_K, leg_tr.temperature_K, rtol=1e-9, atol=1e-8 + ) + assert sl_tr.certified and leg_tr.certified + + +def test_external_dc_and_small_signal_ac_on_compiled_1d_device( + illuminated_prepared: PreparedDevice, +) -> None: + compiled = compile_device_1d(illuminated_prepared, intervals_per_layer=(8, 8, 8)) + voltages = np.linspace(0.0, 1.25, 26) + steady_jv = run_steady_jv( + compiled, voltages, generation_scale=1.0, incident_power_W_m2=1000.0 + ) + + dc_prot = ExternalCircuitProtocol( + series_resistance_ohm_m2=8e-4, + shunt_resistance_ohm_m2=0.2, + ) + mapped = apply_external_circuit_steady(steady_jv, dc_prot) + assert mapped.source_identity == compiled.identity + assert mapped.branch.metrics.open_circuit_voltage_V is not None + assert steady_jv.metrics.open_circuit_voltage_V is not None + assert ( + mapped.branch.metrics.open_circuit_voltage_V + < steady_jv.metrics.open_circuit_voltage_V + ) + assert ( + mapped.branch.metrics.maximum_power_W_m2 is not None + and steady_jv.metrics.maximum_power_W_m2 is not None + and mapped.branch.metrics.maximum_power_W_m2 + < steady_jv.metrics.maximum_power_W_m2 + ) + + dc_point = solve_steady_state( + compiled, voltage_V=0.6, generation_scale=1.0, options=SteadyOptions() + ) + freqs = np.array([10.0, 1e3, 1e5, 1e7], dtype=float) + ac_dev = solve_impedance(compiled, dc_point, freqs) + y_before = ac_dev.admittance_density_S_m2.copy() + + ac_prot = ExternalACCircuitProtocol( + series_resistance_ohm_m2=5e-4, + shunt_resistance_ohm_m2=0.25, + external_capacitance_F_m2=2e-5, + ) + ac_ext = compose_external_ac_impedance(ac_dev, ac_prot) + + # Original SmallSignalResult1D and CompiledDevice1D remain completely unmutated + np.testing.assert_array_equal(ac_dev.admittance_density_S_m2, y_before) + assert ac_ext.source_identity == compiled.identity + + omega = 2.0 * np.pi * freqs + expected_z = 5e-4 + 1.0 / (y_before + (1.0 / 0.25) + 1j * omega * 2e-5) + np.testing.assert_allclose( + ac_ext.impedance_area_ohm_m2, expected_z, rtol=1e-13, atol=1e-14 + ) + + +def test_electrothermal_operating_point_modes_fresh_rebinding_and_mutual_exclusion( + illuminated_prepared: PreparedDevice, +) -> None: + thermal_prot = LumpedThermalProtocol( + absorbed_optical_power_W_m2=800.0, + ambient_temperature_K=300.0, + areal_heat_capacity_J_m2_K=800.0, + heat_transfer_coefficient_W_m2_K=22.0, + emissivity=0.8, + maximum_temperature_K=345.0, + ) + circuit_prot = ExternalCircuitProtocol( + series_resistance_ohm_m2=4e-4, + shunt_resistance_ohm_m2=0.5, + ) + elec_prot = ElectrothermalJVProtocol( + intervals_per_layer=10, + voltage_points_per_branch=25, + scan_rate_V_s=2.0, + voltage_max_V=1.22, + incident_power_W_m2=1000.0, + driver="steady_jv", + ) + + with pytest.raises(ElectrothermalCapabilityError): + solve_electrothermal_operating_point( + illuminated_prepared, + thermal_prot, + circuit_prot, + elec_prot, + external_temperature_K=320.0, + ) + + res_mpp = solve_electrothermal_operating_point( + illuminated_prepared, + thermal_prot, + circuit_prot, + elec_prot, + ElectrothermalOperatingPointProtocol( + operating_point="sampled_terminal_maximum_power" + ), + ) + assert res_mpp.certified + assert res_mpp.time_domain_temperature_qualified is False + assert 300.0 < res_mpp.operating_temperature_K < 345.0 + assert res_mpp.terminal_power_W_m2 > 0.0 + assert abs(res_mpp.power_balance_residual_W_m2) <= 1e-6 + + rebound_hashes = {ev.rebound_prepared_sha256 for ev in res_mpp.temperature_evaluations} + compiled_ids = {ev.compiled_identity for ev in res_mpp.temperature_evaluations} + assert len(rebound_hashes) == res_mpp.electrical_evaluations + assert len(compiled_ids) == res_mpp.electrical_evaluations + assert all(ev.fresh_state_initialized for ev in res_mpp.temperature_evaluations) + + res_oc = solve_electrothermal_operating_point( + illuminated_prepared, + thermal_prot, + circuit_prot, + elec_prot, + ElectrothermalOperatingPointProtocol(operating_point="open_circuit"), + ) + assert res_oc.certified + assert res_oc.terminal_power_W_m2 == 0.0 + assert res_oc.terminal_current_A_m2 == 0.0 + assert res_oc.operating_temperature_K > res_mpp.operating_temperature_K + + res_load = solve_electrothermal_operating_point( + illuminated_prepared, + thermal_prot, + circuit_prot, + elec_prot, + ElectrothermalOperatingPointProtocol( + operating_point="fixed_load", + load_resistance_ohm_m2=0.005, + ), + ) + assert res_load.certified + assert res_load.terminal_voltage_V == pytest.approx( + 0.005 * res_load.terminal_current_A_m2, rel=1e-9, abs=1e-9 + ) + assert ( + res_mpp.operating_temperature_K + < res_load.operating_temperature_K + < res_oc.operating_temperature_K + ) + + +def test_electrothermal_transient_strict_with_mobile_ions_never_carries_ionic_state( + illuminated_ionic_prepared: PreparedDevice, +) -> None: + thermal_prot = LumpedThermalProtocol( + absorbed_optical_power_W_m2=750.0, + ambient_temperature_K=300.0, + heat_transfer_coefficient_W_m2_K=28.0, + emissivity=0.6, + maximum_temperature_K=340.0, + ) + elec_prot = ElectrothermalJVProtocol( + intervals_per_layer=8, + voltage_points_per_branch=15, + scan_rate_V_s=1.0, + voltage_max_V=1.28, + substeps_per_point=2, + incident_power_W_m2=1000.0, + driver="transient_jv_strict", + ) + res = solve_electrothermal_operating_point( + illuminated_ionic_prepared, + thermal_prot, + ExternalCircuitProtocol(series_resistance_ohm_m2=2e-4), + elec_prot, + ElectrothermalOperatingPointProtocol( + temperature_absolute_tolerance_K=1e-2, + power_residual_tolerance_W_m2=0.5, + ), + ) + assert res.certified + assert 300.0 < res.operating_temperature_K < 340.0 + assert len({ev.compiled_identity for ev in res.temperature_evaluations}) == len( + res.temperature_evaluations + ) diff --git a/tests/integration/test_tandem_jv.py b/tests/integration/test_tandem_jv.py new file mode 100644 index 00000000..0fc20141 --- /dev/null +++ b/tests/integration/test_tandem_jv.py @@ -0,0 +1,310 @@ +"""Integration and legacy-parity tests for P04-13 2T monolithic tandem J-V and joint TMM optics.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +import sys +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from examples.research_1d.steady import load_device # noqa: E402 +from perovskite_sim.experiments import tandem_jv as legacy_tandem_jv # noqa: E402 +from solarlab.config.resolve_device import resolve_tandem # noqa: E402 +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q # noqa: E402 + +K_B = 1.380649e-23 +from solarlab.device.inputs import TandemInput # noqa: E402 +from solarlab.device.resolved import PreparedTandem # noqa: E402 +from solarlab.experiments.tandem_jv import ( # noqa: E402 + PHOTON_BUDGET_TOLERANCE, + TandemCapabilityError, + TandemJVProtocol, + compute_tandem_generation, + run_tandem_jv, + series_match_jv, +) +from solarlab.materials.resources import ResourceLibrary, ResourceTable # noqa: E402 +from solarlab.materials.source import SourceDocument # noqa: E402 + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> object: + with threadpool_limits(limits=1): + yield + + +def _intrinsic_density_300K(nc300: float, nv300: float, eg_eV: float) -> float: + return math.sqrt(nc300 * nv300) * math.exp(-eg_eV * Q / (2.0 * K_B * 300.0)) + + +def _set_layer_band_structure( + layer_doc: dict[str, Any], + *, + chi_eV: float, + eg_eV: float, + thickness_m: float | None = None, +) -> None: + if thickness_m is not None: + layer_doc["thickness"] = thickness_m + params = layer_doc["parameters"] + nc300 = float(params["Nc300"]) + nv300 = float(params["Nv300"]) + ni = _intrinsic_density_300K(nc300, nv300, eg_eV) + params.update(chi=chi_eV, Eg=eg_eV, ni=ni, n1=ni, p1=ni) + + +@pytest.fixture(scope="module") +def prepared_monolithic_tandem() -> PreparedTandem: + base = load_device() + wavelengths_nm = (400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900) + + spec_csv = "wavelength_nm,spectral_flux_m-2_s-1_m-1\n" + "".join( + f"{wl},4.5e27\n" for wl in wavelengths_nm + ) + top_nk_csv = "wavelength_nm,n,k\n" + "".join( + f"{wl},{2.55 if wl <= 650 else 2.40},{0.18 if wl <= 650 else 0.0}\n" + for wl in wavelengths_nm + ) + junc_nk_csv = "wavelength_nm,n,k\n" + "".join( + f"{wl},2.05,0.015\n" for wl in wavelengths_nm + ) + bot_nk_csv = "wavelength_nm,n,k\n" + "".join( + f"{wl},2.70,0.16\n" for wl in wavelengths_nm + ) + back_nk_csv = "wavelength_nm,n,k\n" + "".join( + f"{wl},0.25,3.20\n" for wl in wavelengths_nm + ) + + tables = ( + ResourceTable( + "tandem_photons", + "spectrum", + SourceDocument("tandem.photons.csv", spec_csv.encode("utf-8")), + ), + ResourceTable( + "top_widegap_nk", + "nk", + SourceDocument("tandem.top_nk.csv", top_nk_csv.encode("utf-8")), + ), + ResourceTable( + "ito_junction_nk", + "nk", + SourceDocument("tandem.junc_nk.csv", junc_nk_csv.encode("utf-8")), + ), + ResourceTable( + "bot_narrowgap_nk", + "nk", + SourceDocument("tandem.bot_nk.csv", bot_nk_csv.encode("utf-8")), + ), + ResourceTable( + "ag_back_nk", + "nk", + SourceDocument("tandem.back_nk.csv", back_nk_csv.encode("utf-8")), + ), + ) + + top_doc = base.to_input().editing_data() + top_doc["id"] = "tandem_top_widegap_pin" + top_doc["spectrum"] = "tandem_photons" + top_doc["settings"]["Phi"] = 0.0 + for lyr in top_doc["layers"]: + p = lyr["parameters"] + p.update(alpha=0.0, incoherent=False) + if lyr["id"] == "htl": + _set_layer_band_structure(lyr, chi_eV=3.55, eg_eV=1.90) + p.update(optical_material=None, n_optical=1.95) + elif lyr["id"] == "absorber": + _set_layer_band_structure( + lyr, chi_eV=3.85, eg_eV=1.68, thickness_m=2.5e-7 + ) + p.update(optical_material="top_widegap_nk", n_optical=None) + else: + p.update(optical_material=None, n_optical=2.05) + + bot_doc = base.to_input().editing_data() + bot_doc["id"] = "tandem_bottom_narrowgap_pin" + bot_doc["spectrum"] = "tandem_photons" + bot_doc["settings"]["Phi"] = 0.0 + for lyr in bot_doc["layers"]: + p = lyr["parameters"] + p.update(alpha=0.0, incoherent=False) + if lyr["id"] == "htl": + _set_layer_band_structure(lyr, chi_eV=3.65, eg_eV=1.65) + p.update(optical_material=None, n_optical=2.00) + elif lyr["id"] == "absorber": + _set_layer_band_structure( + lyr, chi_eV=3.95, eg_eV=1.42, thickness_m=4.5e-7 + ) + p.update(optical_material="bot_narrowgap_nk", n_optical=None) + else: + p.update(optical_material=None, n_optical=2.10) + + tandem_doc: dict[str, Any] = { + "schema_version": "solarlab.tandem-preparation.v1", + "id": "monolithic_2t_research_tandem", + "source_schema_version": 1, + "device_type": "tandem_2T_monolithic", + "top_cell": top_doc, + "bottom_cell": bot_doc, + "top_cell_reference": "inline:top_widegap_pin", + "bottom_cell_reference": "inline:bottom_narrowgap_pin", + "junction_model": "ideal_ohmic", + "light_direction": "top_first", + "junction_stack": [ + { + "id": "recomb_ito", + "name": "ITO recombination layer", + "thickness": 2.0e-8, + "optical_material": "ito_junction_nk", + "incoherent": False, + } + ], + "back_reflector": { + "id": "ag_reflector", + "name": "Ag back reflector", + "thickness": 1.0e-7, + "optical_material": "ag_back_nk", + "incoherent": False, + }, + } + raw_src = SourceDocument( + "tandem.declaration.json", + json.dumps(tandem_doc, sort_keys=True, separators=(",", ":")).encode("utf-8"), + ) + lib = ResourceLibrary(tables=tables) + return resolve_tandem( + TandemInput.model_validate(tandem_doc), + base.defaults, + lib, + sources=(*base.sources, raw_src, *(tbl.source for tbl in tables)), + ) + + +def test_joint_tmm_tandem_photon_budget_closure_and_parasitic_exclusion( + prepared_monolithic_tandem: PreparedTandem, +) -> None: + optics = compute_tandem_generation( + prepared_monolithic_tandem, + intervals_top=(8, 8, 8), + intervals_bottom=(8, 8, 8), + ) + + # 1. Exact spectral photon conservation across [top, junction, bottom, back_reflector] + closure_res = optics.photon_budget.spectral_closure_residual() + assert float(np.max(np.abs(closure_res))) <= PHOTON_BUDGET_TOLERANCE + + # 2. Control-volume integrated sub-cell generation matches joint TMM electrical absorption + total_subcell_gen = optics.top_absorbed_m2_s + optics.bottom_absorbed_m2_s + assert total_subcell_gen == pytest.approx( + optics.photon_budget.electrical_absorbed_m2_s, rel=1e-12 + ) + assert optics.top_absorbed_m2_s > 0.0 + assert optics.bottom_absorbed_m2_s > 0.0 + + # 3. Parasitic absorption in ITO recombination layer + Ag back reflector is > 0 + # and strictly excluded from sub-cell carrier generation + assert optics.photon_budget.parasitic_absorbed_m2_s > 0.0 + assert 0.0 < optics.parasitic_fraction < 1.0 + assert ( + total_subcell_gen + optics.photon_budget.parasitic_absorbed_m2_s + == pytest.approx( + float(np.sum(optics.photon_budget.layer_absorbed_m2_s)), rel=1e-12 + ) + ) + + +def test_monolithic_2t_tandem_jv_voc_addition_current_limiting_and_legacy_parity( + prepared_monolithic_tandem: PreparedTandem, +) -> None: + prot = TandemJVProtocol( + intervals_per_layer=8, + voltage_points_per_subcell=37, + top_voltage_min_V=-1.05, + top_voltage_max_V=1.34, + bottom_voltage_min_V=-0.1, + bottom_voltage_max_V=1.08, + matched_points=101, + ) + res = run_tandem_jv(prepared_monolithic_tandem, prot) + + assert res.top_compiled_identity != res.bottom_compiled_identity + assert res.top_metrics_fwd.open_circuit_voltage_V is not None + assert res.bottom_metrics_fwd.open_circuit_voltage_V is not None + assert res.metrics_fwd.open_circuit_voltage_V is not None + assert res.metrics_fwd.short_circuit_current_A_m2 is not None + assert res.top_metrics_fwd.short_circuit_current_A_m2 is not None + assert res.bottom_metrics_fwd.short_circuit_current_A_m2 is not None + + # 1. Series voltage addition at open circuit: V_oc_tandem == V_oc_top + V_oc_bot + voc_sum = ( + res.top_metrics_fwd.open_circuit_voltage_V + + res.bottom_metrics_fwd.open_circuit_voltage_V + ) + assert res.metrics_fwd.open_circuit_voltage_V == pytest.approx(voc_sum, abs=2e-3) + assert res.metrics_fwd.open_circuit_voltage_V > 2.0 + + # 2. Tandem short-circuit current is bounded by the current-limiting sub-cell + limiting_jsc = min( + res.top_metrics_fwd.short_circuit_current_A_m2, + res.bottom_metrics_fwd.short_circuit_current_A_m2, + ) + assert res.metrics_fwd.short_circuit_current_A_m2 == pytest.approx( + limiting_jsc, rel=0.025 + ) + + # 3. Live parity against perovskite_sim.experiments.tandem_jv.series_match_jv + leg_j, _leg_vt, _leg_vb, leg_v = legacy_tandem_jv.series_match_jv( + res.top_J_fwd, + res.top_V_fwd, + res.bottom_J_fwd, + res.bottom_V_fwd, + V_junction=-0.035, + ) + sl_v_off, sl_j_off = series_match_jv( + res.top_J_fwd, + res.top_V_fwd, + res.bottom_J_fwd, + res.bottom_V_fwd, + V_junction=-0.035, + n_points=101, + ) + leg_voc = float(np.interp(0.0, leg_j, leg_v)) + sl_voc = float(np.interp(0.0, sl_j_off[::-1], sl_v_off[::-1])) + assert sl_voc == pytest.approx(leg_voc, abs=1e-12) + assert sl_voc == pytest.approx( + res.metrics_fwd.open_circuit_voltage_V - 0.035, abs=2e-3 + ) + + # 4. Spectrum conflict guard fails closed + bad_top = prepared_monolithic_tandem.top_cell.to_input().editing_data() + bad_top["spectrum"] = "nonexistent_other_spectrum" + bad_tandem_doc = prepared_monolithic_tandem.to_input().editing_data() + bad_tandem_doc["top_cell"] = bad_top + extra_tbl = ResourceTable( + "nonexistent_other_spectrum", + "spectrum", + SourceDocument( + "other.csv", + b"wavelength_nm,spectral_flux_m-2_s-1_m-1\n400,1e27\n900,1e27\n", + ), + ) + merged_lib = ResourceLibrary( + tables=(*prepared_monolithic_tandem.resources.tables, extra_tbl) + ) + bad_prepared = resolve_tandem( + TandemInput.model_validate(bad_tandem_doc), + prepared_monolithic_tandem.defaults, + merged_lib, + sources=(*prepared_monolithic_tandem.sources, extra_tbl.source), + ) + with pytest.raises(TandemCapabilityError, match="disagree"): + compute_tandem_generation(bad_prepared, intervals_top=4, intervals_bottom=4) diff --git a/tests/integration/test_tpv_open_circuit.py b/tests/integration/test_tpv_open_circuit.py new file mode 100644 index 00000000..13f340c3 --- /dev/null +++ b/tests/integration/test_tpv_open_circuit.py @@ -0,0 +1,204 @@ +"""Integration and legacy-parity tests for P05-04a charge-conserving open-circuit & TPV.""" + +from __future__ import annotations + +from pathlib import Path +import sys + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from examples.research_1d.ionic_multilayer import ( # noqa: E402 + prepare_confined_ion_device, +) +from examples.research_1d.steady import load_device # noqa: E402 +from perovskite_sim.experiments import tpv as legacy_tpv # noqa: E402 +from solarlab.config.resolve_device import resolve_device # noqa: E402 +from solarlab.device.compile_1d import compile_device_1d # noqa: E402 +from solarlab.device.inputs import DeviceInput # noqa: E402 +from solarlab.device.resolved import PreparedDevice # noqa: E402 +from solarlab.experiments.open_circuit import ( # noqa: E402 + OpenCircuitOptions, + integrate_open_circuit, +) +from solarlab.experiments.tpv import ( # noqa: E402 + TPVError, + TPVProtocol, + fit_tpv_decay, + run_tpv, + solve_illuminated_voc_state, +) + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> object: + with threadpool_limits(limits=1): + yield + + +def test_open_circuit_integrator_enforces_maxwell_total_current_and_charge_conservation() -> None: + prepared = load_device() + compiled = compile_device_1d(prepared, intervals_per_layer=(8, 8, 8)) + + state_half, v_half = solve_illuminated_voc_state( + compiled, generation_scale=0.5, upper_bound_V=1.3 + ) + _, v_full = solve_illuminated_voc_state( + compiled, generation_scale=1.0, upper_bound_V=1.3 + ) + assert v_full > v_half > 1.0 + + # Step illumination from 0.5 sun to 1.0 sun under genuine floating-terminal open circuit + times_s = np.r_[0.0, np.geomspace(1e-8, 8e-5, 22)] + gen_scale = np.ones_like(times_s) + gen_scale[0] = 0.5 + + traj = integrate_open_circuit( + compiled, + state_half, + times_s, + gen_scale, + initial_voltage_V=v_half, + options=OpenCircuitOptions( + max_current_error_A_m2=1e-7, + max_voltage_error_V=1e-6, + ), + ) + assert traj.certified + + # 1. Total Maxwell current (I_cond + dD/dt) vanishes on ALL faces at EVERY step + assert float(np.max(traj.max_face_total_current_A_m2)) <= 1e-7 + np.testing.assert_allclose( + traj.left_conduction_current_A_m2 + traj.left_displacement_current_A_m2, + traj.left_total_current_A_m2, + rtol=0.0, + atol=1e-12, + ) + + # 2. Dynamic capacitive charging (NOT the unphysical steady I_cond == 0 clamp, + # which would jump instantaneously to v_full at step 1!) + assert v_half < float(traj.terminal_voltage_V[1]) < v_full - 0.010 + assert float(np.max(np.abs(traj.left_conduction_current_A_m2))) > 1e-9 + assert float(np.max(np.abs(traj.left_displacement_current_A_m2))) > 1e-9 + + # 3. Telescoping port charge error stays below 1 uV and V_oc(t) relaxes to 1-sun steady V_oc + assert traj.charge_voltage_error_V < 1e-6 + assert traj.terminal_voltage_V[-1] == pytest.approx(v_full, abs=1e-4) + + +def test_ion_free_tpv_single_exponential_extraction_truncation_refusal_and_legacy_parity() -> None: + prepared = load_device() + prot = TPVProtocol( + delta_G_frac=0.01, + t_pulse_s=1e-6, + t_decay_s=2e-5, + pulse_points=5, + decay_points=25, + decay_grid="linear", + voc_upper_bound_V=1.3, + intervals_per_layer=8, + ) + res = run_tpv(prepared, prot) + + assert res.initial_state_source == "steady_illuminated_open_circuit" + assert res.equilibrium_claimed is True + assert res.preconditioning_trajectory is None + assert res.max_baseline_drift_V < 1e-8 + assert res.max_current_error_A_m2 <= 1e-7 + assert res.charge_voltage_error_V < 1e-6 + assert res.delta_V_0 > 0.0 + assert res.decay_fit.status == "single_exponential" + assert res.tau is not None and res.tau > 0.0 + + # Live parity check against perovskite_sim.experiments.tpv.fit_tpv_decay on the solved decay trace + pulse_end = prot.pulse_points + t_rel = res.t[pulse_end:] - float(res.t[pulse_end]) + dv_rel = res.delta_V[pulse_end:] + leg_fit = legacy_tpv.fit_tpv_decay(t_rel, dv_rel, noise_floor_V=1e-9) + assert leg_fit.status == "accepted" + assert leg_fit.tau_s is not None + assert res.tau == pytest.approx(leg_fit.tau_s, rel=5e-3) + + # Also verify non-identifiable refusal parity vs legacy fit_tpv_decay + short_prot = TPVProtocol( + delta_G_frac=0.05, + t_pulse_s=5e-7, + t_decay_s=1e-7, + pulse_points=4, + decay_points=8, + voc_upper_bound_V=1.3, + intervals_per_layer=8, + ) + short_res = run_tpv(prepared, short_prot) + assert short_res.tau is None + assert short_res.decay_fit.status == "insufficient_decay_window" + assert short_res.decay_fit.non_identifiable_reason is not None + + t_short = short_res.t[short_prot.pulse_points :] - float( + short_res.t[short_prot.pulse_points] + ) + leg_short = legacy_tpv.fit_tpv_decay( + t_short, short_res.delta_V[short_prot.pulse_points :], noise_floor_V=1e-9 + ) + assert leg_short.tau_s is None + assert leg_short.status == "insufficient_decay_window" + _ = fit_tpv_decay + + +def test_mobile_ion_tpv_paired_control_subtraction_under_active_baseline_drift() -> None: + base_ion = prepare_confined_ion_device() + editing = base_ion.to_input().editing_data() + absorber = next(lyr for lyr in editing["layers"] if lyr["role"] == "absorber") + # Fast diffusivity so ionic open-circuit baseline drift is actively evolving on sub-ms timescales + absorber["parameters"]["D_ion"] = 2e-12 + fast_ion_prepared: PreparedDevice = resolve_device( + DeviceInput.model_validate(editing), + base_ion.defaults, + base_ion.resources, + sources=base_ion.sources, + ) + + prot = TPVProtocol( + delta_G_frac=0.05, + t_pulse_s=2e-5, + t_decay_s=3e-4, + pulse_points=2, + decay_points=14, + decay_grid="linear", + soak_duration_s=5e-4, + soak_steps=6, + voc_upper_bound_V=1.3, + intervals_per_layer=8, + ) + res = run_tpv(fast_ion_prepared, prot) + + # 1. Explicit finite-time preconditioning provenance (never claims ionic equilibrium) + assert res.initial_state_source == "finite_time_illuminated_preconditioned" + assert res.equilibrium_claimed is False + assert res.preconditioning_trajectory is not None + assert res.preconditioning_trajectory.certified + + # 2. Pulsed and unpulsed control start from bit-identical (state_oc, V_oc) + s0_pulsed = res.pulsed_trajectory.states[0] + s0_ctrl = res.control_trajectory.states[0] + np.testing.assert_array_equal(s0_pulsed.u, s0_ctrl.u) + assert res.V[0] == res.V_control[0] == res.V_oc + + # 3. Unpulsed control captures nonzero ionic baseline drift while delta_V isolates pulse + assert res.max_baseline_drift_V > 1e-6 + np.testing.assert_allclose(res.delta_V, res.V - res.V_control, rtol=0.0, atol=1e-15) + assert res.delta_V_0 > 0.0 + assert res.max_current_error_A_m2 <= 1e-7 + assert res.charge_voltage_error_V < 1e-6 + + # 4. Zero soak_duration_s on mobile-ion device is refused + with pytest.raises(TPVError, match="soak_duration_s"): + run_tpv( + fast_ion_prepared, + TPVProtocol(soak_duration_s=0.0, intervals_per_layer=8), + ) diff --git a/tests/unit/experiments/test_systems_and_tpv_p05.py b/tests/unit/experiments/test_systems_and_tpv_p05.py new file mode 100644 index 00000000..6cb16ee8 --- /dev/null +++ b/tests/unit/experiments/test_systems_and_tpv_p05.py @@ -0,0 +1,297 @@ +"""Unit tests for P04-13 external circuits/thermal balance/tandem matching and P05-04 TPV decay.""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +from solarlab.experiments.external_circuit import ( + EXTERNAL_AC_UNIT_SCHEMA, + EXTERNAL_DC_UNIT_SCHEMA, + ExternalACCircuitProtocol, + ExternalCircuitError, + ExternalCircuitProtocol, + ExternalCircuitTopologyError, + apply_external_circuit, + apply_external_circuit_steady, + compose_external_ac_impedance, + map_external_circuit_branch, +) +from solarlab.experiments.tandem_jv import series_match_jv +from solarlab.experiments.thermal_balance import ( + STEFAN_BOLTZMANN_W_M2_K4, + THERMAL_UNIT_SCHEMA, + LumpedThermalProtocol, + ThermalBalanceError, + ThermalEnergySourceError, + ThermalIntegrationProtocol, + ThermalSteadyStateError, + run_lumped_thermal_transient, + solve_lumped_thermal_steady_state, + thermal_power_ledger, +) +from solarlab.experiments.tpv import fit_tpv_decay + + +def test_external_dc_mapping_conventions_losses_and_folding_guard() -> None: + # Ideal linear photovoltaic source: J_dev(V) = 200 - 200 * V (J_sc = 200 A/m^2, V_oc = 1.0 V) + v_junc = np.linspace(0.0, 1.1, 12) + j_dev = 200.0 - 200.0 * v_junc + + prot = ExternalCircuitProtocol( + series_resistance_ohm_m2=5e-4, + shunt_resistance_ohm_m2=0.05, + ) + branch = map_external_circuit_branch( + v_junc, j_dev, prot, direction="forward", incident_power_W_m2=1000.0 + ) + + # Shunt sits across V_junction; series drop uses J_terminal: + expected_shunt = v_junc / 0.05 + expected_j_term = j_dev - expected_shunt + expected_v_term = v_junc - expected_j_term * 5e-4 + + np.testing.assert_allclose(branch.J_shunt, expected_shunt, rtol=0.0, atol=1e-14) + np.testing.assert_allclose(branch.J_terminal, expected_j_term, rtol=0.0, atol=1e-14) + np.testing.assert_allclose(branch.V_terminal, expected_v_term, rtol=0.0, atol=1e-14) + + # Power conservation between junction output and terminal export + parasitic Joule heat: + # V_junc * J_dev == V_term * J_term + J_term^2 * R_s + V_junc^2 / R_sh + p_junction = v_junc * j_dev + p_accounted = ( + branch.power_terminal_W_m2 + branch.series_loss_W_m2 + branch.shunt_loss_W_m2 + ) + np.testing.assert_allclose(p_accounted, p_junction, rtol=1e-14, atol=1e-12) + + # Analytic V_oc with R_sh = 0.05 ohm*m^2: 200 - 200*V - 20*V = 0 => V_oc = 200 / 220 = 10/11 V + assert branch.metrics.open_circuit_voltage_V == pytest.approx( + 10.0 / 11.0, rel=1e-12 + ) + assert not branch.V_terminal.flags.writeable + + # Dual-branch wrapper & steady tuple wrapper + dual = apply_external_circuit( + (v_junc, j_dev, v_junc[::-1], j_dev[::-1]), + prot, + incident_power_W_m2=1000.0, + ) + assert dual.hysteresis_index == pytest.approx(0.0, abs=1e-14) + steady_res = apply_external_circuit_steady( + (v_junc, j_dev), prot, incident_power_W_m2=1000.0 + ) + assert steady_res.branch.metrics.open_circuit_voltage_V == pytest.approx( + 10.0 / 11.0, rel=1e-12 + ) + + # Folding guard: non-monotonic J_dev where R_s * dJ/dV > 1 folds V_terminal + v_fold = np.array([0.0, 0.5, 1.0]) + j_fold = np.array([0.0, 200.0, 100.0]) # dJ/dV = +400 A/(m^2 V) on [0, 0.5] + with pytest.raises(ExternalCircuitTopologyError): + map_external_circuit_branch( + v_fold, + j_fold, + ExternalCircuitProtocol(series_resistance_ohm_m2=0.01), + direction="forward", + ) + + with pytest.raises(ExternalCircuitError): + ExternalCircuitProtocol(series_resistance_ohm_m2=-1e-4) + with pytest.raises(ExternalCircuitError): + ExternalCircuitProtocol(shunt_resistance_ohm_m2=0.0) + + +def test_external_ac_composition_and_unit_schema_separation() -> None: + # Unit schemas keep electrical F/m^2 strictly distinct from thermal J/(m^2*K) + assert EXTERNAL_DC_UNIT_SCHEMA["series_resistance_ohm_m2"] == "ohm*m^2" + assert EXTERNAL_AC_UNIT_SCHEMA["external_capacitance_F_m2"] == "F/m^2" + assert THERMAL_UNIT_SCHEMA["areal_heat_capacity_J_m2_K"] == "J/(m^2*K)" + assert "areal_heat_capacity_J_m2_K" not in EXTERNAL_AC_UNIT_SCHEMA + assert "external_capacitance_F_m2" not in THERMAL_UNIT_SCHEMA + + freqs = np.array([0.0, 1e2, 1e5, 1e9], dtype=float) + omega = 2.0 * np.pi * freqs + # Synthetic device: parallel G_dev = 25 S/m^2 and C_dev = 1e-4 F/m^2 + y_dev = 25.0 + 1j * omega * 1e-4 + + # 1. Zero-parasitic composition is the exact identity + zero_res = compose_external_ac_impedance( + (freqs, y_dev), ExternalACCircuitProtocol() + ) + np.testing.assert_allclose( + zero_res.terminal_admittance_S_m2, y_dev, rtol=0.0, atol=1e-15 + ) + + # 2. Full R_s + R_sh + C_ext composition matches exact network impedance + rs = 2e-4 + rsh = 0.1 + cext = 5e-5 + ac_prot = ExternalACCircuitProtocol( + series_resistance_ohm_m2=rs, + shunt_resistance_ohm_m2=rsh, + external_capacitance_F_m2=cext, + ) + ac_res = compose_external_ac_impedance((freqs, y_dev), ac_prot) + + expected_y_junc = y_dev + (1.0 / rsh) + 1j * omega * cext + expected_z_term = rs + 1.0 / expected_y_junc + expected_y_term = 1.0 / expected_z_term + + np.testing.assert_allclose( + ac_res.junction_admittance_S_m2, expected_y_junc, rtol=1e-14, atol=1e-14 + ) + np.testing.assert_allclose( + ac_res.terminal_admittance_S_m2, expected_y_term, rtol=1e-14, atol=1e-14 + ) + np.testing.assert_allclose( + ac_res.impedance_area_ohm_m2, expected_z_term, rtol=1e-14, atol=1e-14 + ) + # High-frequency limit approaches R_s + assert ac_res.impedance_area_ohm_m2[-1].real == pytest.approx(rs, rel=1e-4) + + +def test_lumped_thermal_ledger_steady_state_and_transient_energy_closure() -> None: + prot = LumpedThermalProtocol( + absorbed_optical_power_W_m2=900.0, + ambient_temperature_K=300.0, + areal_heat_capacity_J_m2_K=500.0, + heat_transfer_coefficient_W_m2_K=15.0, + emissivity=0.85, + maximum_temperature_K=420.0, + ) + + # Exporting more power than absorbed without external drive is refused + with pytest.raises(ThermalEnergySourceError): + thermal_power_ledger(310.0, prot, exported_electrical_power_W_m2=950.0) + + # Steady-state temperature root with temperature-dependent exported power P_out(T) + def p_export(temp_K: float) -> float: + return max(0.0, 200.0 * (1.0 - 0.004 * (temp_K - 300.0))) + + steady = solve_lumped_thermal_steady_state( + prot, exported_electrical_power_fn=p_export + ) + assert steady.converged + assert 300.0 < steady.temperature_K < 420.0 + # Verify Stefan-Boltzmann + Newton cooling balance directly + dt = steady.temperature_K - 300.0 + expected_cool = 15.0 * dt + 0.85 * STEFAN_BOLTZMANN_W_M2_K4 * ( + steady.temperature_K**4 - 300.0**4 + ) + assert expected_cool == pytest.approx( + 900.0 - p_export(steady.temperature_K), abs=1e-8 + ) + + # Unbracketed maximum_temperature_K fails closed + too_tight = LumpedThermalProtocol( + absorbed_optical_power_W_m2=900.0, + ambient_temperature_K=300.0, + heat_transfer_coefficient_W_m2_K=15.0, + emissivity=0.85, + maximum_temperature_K=305.0, + ) + with pytest.raises(ThermalSteadyStateError): + solve_lumped_thermal_steady_state(too_tight) + + with pytest.raises(ThermalBalanceError): + LumpedThermalProtocol( + absorbed_optical_power_W_m2=500.0, + heat_transfer_coefficient_W_m2_K=0.0, + emissivity=0.0, + ) + + # Transient integration relaxes toward the exact steady root and closes energy + t_eval = np.linspace(0.0, 250.0, 51) + tr = run_lumped_thermal_transient( + prot, + t_eval, + initial_temperature_K=300.0, + exported_electrical_power_fn=lambda _t, temp_K: p_export(temp_K), + integration=ThermalIntegrationProtocol(method="DOP853"), + ) + assert tr.certified + assert tr.max_abs_energy_closure_residual_J_m2 < 1e-6 + assert tr.temperature_K[-1] == pytest.approx(steady.temperature_K, rel=1e-4) + + +def test_series_match_jv_analytic_open_circuit_and_non_overlap_guard() -> None: + # Linear sub-cells: + # Top: V_top(J) = 1.2 - 0.002 * J (J_sc = 600? No: at V=0 => J=600; restrict J in [-50, 150]) + # Bottom: V_bot(J) = 0.8 - 0.001 * J + v_top = np.linspace(-0.1, 1.3, 141) + j_top = (1.2 - v_top) / 0.002 # J from 650 down to -50 + v_bot = np.linspace(-0.1, 0.9, 101) + j_bot = (0.8 - v_bot) / 0.001 # J from 900 down to -100 + + v_tan, j_tan = series_match_jv( + j_top, v_top, j_bot, v_bot, V_junction=0.05, n_points=81 + ) + assert np.all(np.diff(v_tan) > 0.0) + # J = 0 is explicitly injected => V_oc = 1.2 + 0.8 + 0.05 = 2.05 V + assert np.any(np.isclose(j_tan, 0.0, atol=1e-15)) + v_at_zero = float(np.interp(0.0, j_tan[::-1], v_tan[::-1])) + assert v_at_zero == pytest.approx(2.05, abs=1e-12) + + # Non-overlapping current ranges raise ValueError + with pytest.raises(ValueError, match="do not overlap"): + series_match_jv( + np.array([100.0, 200.0]), + np.array([0.0, 1.0]), + np.array([-50.0, 50.0]), + np.array([0.0, 1.0]), + ) + + +def test_fit_tpv_decay_single_exponential_and_all_refusal_modes() -> None: + tau_true = 1.25e-5 + amp_true = 4.5e-3 + t_grid = np.linspace(0.0, 6.0 * tau_true, 60) + y_clean = amp_true * np.exp(-t_grid / tau_true) + + good = fit_tpv_decay(t_grid, y_clean) + assert good.status == "single_exponential" + assert good.non_identifiable_reason is None + assert good.tau_s == pytest.approx(tau_true, rel=1e-6) + assert good.amplitude_V == pytest.approx(amp_true, rel=1e-6) + assert good.r_squared is not None and good.r_squared > 0.999999 + + # 1. Zero / negative amplitude -> no_signal + no_sig = fit_tpv_decay(t_grid, np.zeros_like(t_grid)) + assert no_sig.tau_s is None + assert no_sig.status == "no_signal" + assert no_sig.non_identifiable_reason is not None + + # 2. Sign change -> sign_change + y_flip = y_clean.copy() + y_flip[20:] = -0.2 * amp_true + flipped = fit_tpv_decay(t_grid, y_flip) + assert flipped.tau_s is None + assert flipped.status == "sign_change" + assert flipped.non_identifiable_reason is not None + + # 3. Non-monotonic bounce -> non_monotonic + y_bump = y_clean.copy() + y_bump[15:25] += 0.15 * amp_true + bumped = fit_tpv_decay(t_grid, y_bump) + assert bumped.tau_s is None + assert bumped.status == "non_monotonic" + assert bumped.non_identifiable_reason is not None + + # 4. Truncated window (< 1 e-fold) -> insufficient_decay_window + t_short = np.linspace(0.0, 0.4 * tau_true, 20) + short_fit = fit_tpv_decay(t_short, amp_true * np.exp(-t_short / tau_true)) + assert short_fit.tau_s is None + assert short_fit.status == "insufficient_decay_window" + assert short_fit.non_identifiable_reason is not None + assert not math.isnan(short_fit.amplitude_V) + + # 5. Bi-exponential mixture -> not_single_exponential + t_bi = np.geomspace(1e-8, 2e-4, 80) - 1e-8 + y_bi = 0.5 * amp_true * np.exp(-t_bi / 1e-6) + 0.5 * amp_true * np.exp( + -t_bi / 5e-5 + ) + bi_fit = fit_tpv_decay(t_bi, y_bi) + assert bi_fit.tau_s is None + assert bi_fit.status == "not_single_exponential" + assert bi_fit.non_identifiable_reason is not None From 784e4c4342c73f71c7f06425dd979baa7678540b Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Fri, 13 Nov 2026 01:04:40 +0800 Subject: [PATCH 12/46] feat(experiments): add P05-01b working-point transfer and P05-05 identifiability/solarscale --- src/solarlab/experiments/evaluation_report.py | 1171 +++++++++ src/solarlab/experiments/identifiability.py | 1896 ++++++++++++++ src/solarlab/experiments/solarscale.py | 2324 +++++++++++++++++ .../experiments/working_point_transfer.py | 1914 ++++++++++++++ .../test_identifiability_parity.py | 267 ++ .../test_solarscale_screening_parity.py | 452 ++++ .../test_working_point_transfer.py | 511 ++++ .../test_working_point_and_identifiability.py | 671 +++++ 8 files changed, 9206 insertions(+) create mode 100644 src/solarlab/experiments/evaluation_report.py create mode 100644 src/solarlab/experiments/identifiability.py create mode 100644 src/solarlab/experiments/solarscale.py create mode 100644 src/solarlab/experiments/working_point_transfer.py create mode 100644 tests/integration/test_identifiability_parity.py create mode 100644 tests/integration/test_solarscale_screening_parity.py create mode 100644 tests/integration/test_working_point_transfer.py create mode 100644 tests/unit/experiments/test_working_point_and_identifiability.py diff --git a/src/solarlab/experiments/evaluation_report.py b/src/solarlab/experiments/evaluation_report.py new file mode 100644 index 00000000..1546059c --- /dev/null +++ b/src/solarlab/experiments/evaluation_report.py @@ -0,0 +1,1171 @@ +"""Material evaluation report pack for SolarScale -> SolarLab 1D workflows. + +Ports the SolarScale material evaluation report pack onto ``solarlab``'s native +1D device compilation and steady-state solver stack without legacy +``perovskite_sim`` dependencies or silent physics fallbacks. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +import csv +from dataclasses import asdict, dataclass, is_dataclass +import json +import math +from pathlib import Path +from typing import Any, Literal, TypeVar + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +from numpy.typing import NDArray +from scipy.optimize import brentq +import yaml + +from solarlab.device.compile_1d import CapabilityError +from solarlab.device.defaults import DefaultCatalog +from solarlab.equations.dc_1d import State1D +from solarlab.experiments.solarscale import ( + advance_electronic_steady_1d, + compile_solarscale_electronic_1d, + manifest_sha256, + prepare_solarscale_device, + solve_solarscale_jv_1d, +) +from solarlab.materials.resources import ResourceLibrary +from solarlab.solvers.nonlinear.steady_1d import solve_steady_state + +__all__ = [ + "DFT_PARAMETER_TARGETS", + "FIGURE_QUALITY_BY_PROFILE", + "ReportProfile", + "ReportQualityError", + "SolarScaleSunsVocResult", + "run_material_evaluation_report", + "run_solarscale_suns_voc_1d", +] + +_T = TypeVar("_T") + +DFT_PARAMETER_TARGETS: dict[str, str | None] = { + "band_gap_hse_ev": "absorber.Eg", + "dielectric_static_avg": "absorber.eps_r", + "electron_mobility_cm2_v_s": "absorber.mu_n", + "hole_mobility_cm2_v_s": "absorber.mu_p", + "ion_diffusion_coefficient_m2_s": "absorber.D_ion", + "ion_activation_energy_ev": "absorber.E_a_ion", + "electron_effective_mass_m0": None, + "hole_effective_mass_m0": None, + "slme_0p5um": None, + "absorption_edge_ev": None, +} + +ReportProfile = Literal["smoke", "diagnostic", "production"] +FIGURE_QUALITY_BY_PROFILE: dict[ReportProfile, str] = { + "smoke": "workflow_smoke", + "diagnostic": "diagnostic_only", + "production": "production_candidate", +} + + +class ReportQualityError(RuntimeError): + """Raised when a production report would look physical but fails quality gates.""" + + +@dataclass(frozen=True) +class SolarScaleSunsVocResult: + """Native 1D steady Suns-V_oc and pseudo-J-V screening result.""" + + suns: NDArray[np.float64] + V_oc: NDArray[np.float64] + J_sc: NDArray[np.float64] + J_pseudo_V: NDArray[np.float64] + J_pseudo_J: NDArray[np.float64] + pseudo_FF: float + ideality_factor: float + compiled_identity: str + scientific_qualification: bool = False + + +def _compute_pseudo_ff( + v_arr: NDArray[np.float64], + j_arr: NDArray[np.float64], + v_oc_ref: float, + j_sc_ref: float, +) -> float: + if v_oc_ref <= 0.0 or j_sc_ref <= 0.0: + return float("nan") + mask = (v_arr > 0.0) & (v_arr < v_oc_ref) & (j_arr > 0.0) & (j_arr < j_sc_ref) + v_q = np.concatenate(([0.0], v_arr[mask], [v_oc_ref])) + j_q = np.concatenate(([j_sc_ref], j_arr[mask], [0.0])) + order = np.argsort(v_q) + v_s = v_q[order] + j_s = j_q[order] + v_grid: NDArray[np.float64] = np.linspace(0.0, v_oc_ref, 500, dtype=np.float64) + j_grid = np.interp(v_grid, v_s, j_s) + p_max = float(np.max(v_grid * j_grid)) + return p_max / (v_oc_ref * j_sc_ref) + + +def run_solarscale_suns_voc_1d( + config_or_path: str | Path | Mapping[str, Any], + *, + suns_levels: Sequence[float] = (0.1, 1.0, 10.0), + N_grid: int = 20, + t_settle: float = 5.0e-4, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> SolarScaleSunsVocResult: + """Execute a native 1D steady Suns-V_oc and pseudo-J-V sweep.""" + _ = t_settle + suns_sorted = np.array(sorted({float(s) for s in suns_levels}), dtype=np.float64) + if suns_sorted.size == 0: + raise ValueError("suns_levels must be non-empty") + if np.any(~np.isfinite(suns_sorted)) or np.any(suns_sorted <= 0.0): + raise ValueError("suns_levels must be finite and positive") + + _, device = compile_solarscale_electronic_1d( + config_or_path, N_grid=int(N_grid), defaults=defaults, resources=resources + ) + polarity = float(device.voltage_polarity) + v_T = float(device.thermal_voltage_V) + eg_ceiling = float(np.min(device.parameters.band_structure.physical_band_gap_eV)) + v_limit = max(1.6, eg_ceiling + 0.35) + + from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + + steady_opts = SteadyOptions(max_iterations=250, max_bias_step_V=0.025) + dark_sol = solve_steady_state( + device, voltage_V=0.0, generation_scale=0.0, options=steady_opts + ) + j_dark = -polarity * float(dark_sol.current_density_A_m2[0]) + + v_oc_arr = np.zeros_like(suns_sorted) + j_sc_arr = np.zeros_like(suns_sorted) + + for k, x_sun in enumerate(suns_sorted): + gen_scale = float(x_sun) + sc_sol = solve_steady_state( + device, voltage_V=0.0, generation_scale=gen_scale, options=steady_opts + ) + j_zero = -polarity * float(sc_sol.current_density_A_m2[0]) + j_sc_arr[k] = j_zero - j_dark + if j_zero <= 0.0: + v_oc_arr[k] = 0.0 + continue + + v_lo = 0.0 + j_lo = j_zero + seed_state: State1D = sc_sol.state + v_hi = 0.0 + j_hi = j_lo + step_v = 0.025 + bracketed = False + while v_hi < v_limit: + v_try = min(v_hi + step_v, v_limit) + sol_try = advance_electronic_steady_1d( + device, + seed_state, + v_try, + generation_scale=gen_scale, + options=steady_opts, + ) + j_try = -polarity * float(sol_try.current_density_A_m2[0]) + if j_try <= 0.0: + v_hi = v_try + j_hi = j_try + bracketed = True + break + v_lo = v_try + j_lo = j_try + seed_state = sol_try.state + v_hi = v_try + + if not bracketed: + raise RuntimeError( + f"Suns-Voc failed to bracket V_oc up to {v_limit:.3f} V at {gen_scale:g} suns" + ) + if j_hi == 0.0: + v_oc_arr[k] = v_hi + continue + + cached_seed: dict[str, State1D] = {"state": seed_state} + + def _j_at_v(v_eval: float) -> float: + sol_v = solve_steady_state( + device, + initial_state=cached_seed["state"], + voltage_V=float(v_eval), + generation_scale=gen_scale, + options=steady_opts, + ) + cached_seed["state"] = sol_v.state + return -polarity * float(sol_v.current_density_A_m2[0]) + + root_v = float(brentq(_j_at_v, v_lo, v_hi, xtol=1.0e-7, maxiter=40)) + v_oc_arr[k] = root_v + + if suns_sorted.size >= 2 and np.all(v_oc_arr > 0.0) and v_T > 0.0: + slope = float(np.polyfit(np.log(suns_sorted), v_oc_arr, 1)[0]) + ideality = slope / v_T + else: + ideality = float("nan") + + idx_ref = int(np.argmin(np.abs(suns_sorted - 1.0))) + v_oc_ref = float(v_oc_arr[idx_ref]) + j_sc_ref = float(j_sc_arr[idx_ref]) + j_pseudo_v = v_oc_arr.copy() + j_pseudo_j = j_sc_ref - j_sc_arr + pseudo_ff = _compute_pseudo_ff(j_pseudo_v, j_pseudo_j, v_oc_ref, j_sc_ref) + + return SolarScaleSunsVocResult( + suns=suns_sorted, + V_oc=v_oc_arr, + J_sc=j_sc_arr, + J_pseudo_V=j_pseudo_v, + J_pseudo_J=j_pseudo_j, + pseudo_FF=pseudo_ff, + ideality_factor=ideality, + compiled_identity=device.identity, + scientific_qualification=False, + ) + + +def _run_degradation_1d( + config_path: Path, + *, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, + **kwargs: Any, +) -> Any: + _ = kwargs + prepared, _ = prepare_solarscale_device(config_path, defaults=defaults, resources=resources) + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + has_ions = any( + float(dict(layer.parameters)["P0"] or 0.0) > 0.0 + or float(dict(layer.parameters)["P0_neg"] or 0.0) > 0.0 + for layer in elec_layers + ) + if not has_ions: + raise CapabilityError( + "ion_migration_degradation_requires_mobile_ions: P0 == 0 on all electrical layers" + ) + raise CapabilityError( + "long_horizon_degradation_unbound_in_screening_report: use explicit ionic_transient workflows" + ) + + +def _run_eqe_1d( + config_path: Path, + *, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, + **kwargs: Any, +) -> Any: + _ = kwargs + # Validate config resolution first, then refuse unbound wavelength-resolved EQE without n/k resources. + prepare_solarscale_device(config_path, defaults=defaults, resources=resources) + raise CapabilityError( + "wavelength_resolved_eqe_requires_material_nk_resources: optical n/k tables are unavailable" + ) + + +def run_material_evaluation_report( + *, + config_path: str | Path, + material_record_path: str | Path, + device_results_path: str | Path, + out_dir: str | Path, + quick: bool = False, + profile: ReportProfile = "diagnostic", + material_id: str | None = None, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, + settings_override: Mapping[str, Mapping[str, Any]] | None = None, +) -> dict[str, Any]: + """Create a deterministic material evaluation report pack for one SolarScale config.""" + config_file = Path(config_path) + record_file = Path(material_record_path) + device_results_file = Path(device_results_path) + out = Path(out_dir) + figures = out / "figures" + out.mkdir(parents=True, exist_ok=True) + figures.mkdir(parents=True, exist_ok=True) + + config = _load_yaml(config_file) + resolved_profile = _resolve_profile(profile=profile, quick=quick) + if resolved_profile == "production": + _validate_production_config(config) + + resolved_material_id = ( + material_id or _config_material_id(config) or _first_record_id(record_file) + ) + record = _select_material_record(_load_json(record_file), resolved_material_id) + device_results = _load_json(device_results_file) + device_record = _select_device_result(device_results, resolved_material_id, config_file) + + dft_summary = _dft_parameter_summary(record, config, device_record) + dft_json = out / "dft_parameter_summary.json" + dft_csv = out / "dft_parameter_summary.csv" + dft_json.write_text(json.dumps(dft_summary, indent=2, sort_keys=True), encoding="utf-8") + _write_dft_summary_csv(dft_csv, dft_summary) + + device_metrics = _device_metrics_summary(device_results, device_record, resolved_material_id) + settings = _profile_settings(resolved_profile) + if settings_override is not None: + for exp_key, exp_vals in settings_override.items(): + if exp_key in settings: + settings[exp_key] = {**settings[exp_key], **dict(exp_vals)} + else: + settings[exp_key] = dict(exp_vals) + + figure_paths: dict[str, str] = {} + figure_quality: dict[str, dict[str, Any]] = {} + experiment_status: dict[str, Any] = {} + blocking_reasons: list[str] = [] + optical_blocking_reasons: list[str] = [] + if resolved_profile == "production": + optical_blocking_reasons = _production_optical_blocking_reasons(config) + blocking_reasons.extend(optical_blocking_reasons) + blocking_reasons.extend(_production_band_alignment_blocking_reasons(config)) + else: + blocking_reasons.append(f"report profile {resolved_profile!r} is not publication-grade") + + jv_result = _run_experiment( + "jv", + experiment_status, + lambda: solve_solarscale_jv_1d( + config_file, + defaults=defaults, + resources=resources, + **settings["jv"], + ), + ) + if jv_result is not None: + if resolved_profile == "production": + jv_reasons = _production_jv_blocking_reasons(jv_result) + if jv_reasons: + failure_path = out / "evaluation_failure.json" + failure_path.write_text( + json.dumps( + { + "schema": "solarlab.material_evaluation_failure", + "schema_version": "0.1", + "material_id": resolved_material_id, + "profile": resolved_profile, + "blocking_reasons": jv_reasons, + }, + indent=2, + sort_keys=True, + ), + encoding="utf-8", + ) + raise ReportQualityError( + "Production JV quality gate failed: " + "; ".join(jv_reasons) + ) + jv_fig = figures / "jv_curve.png" + _plot_jv(jv_fig, jv_result) + figure_paths["jv_curve"] = str(jv_fig) + _record_figure_quality(figure_quality, "jv_curve", jv_fig, resolved_profile) + device_metrics["quick_experiments"]["jv"] = _jv_metrics_dict(jv_result) + else: + if resolved_profile == "production": + failure_path = out / "evaluation_failure.json" + err_msg = str(experiment_status["jv"]["error_message"]) + failure_path.write_text( + json.dumps( + { + "schema": "solarlab.material_evaluation_failure", + "schema_version": "0.1", + "material_id": resolved_material_id, + "profile": resolved_profile, + "blocking_reasons": [f"Production JV solver failed: {err_msg}"], + }, + indent=2, + sort_keys=True, + ), + encoding="utf-8", + ) + raise ReportQualityError("Production JV solver failed: " + err_msg) + jv_fig = figures / "jv_curve.png" + _plot_error(jv_fig, "JV sweep failed", str(experiment_status["jv"]["error_message"])) + figure_paths["jv_curve"] = str(jv_fig) + _record_figure_quality( + figure_quality, "jv_curve", jv_fig, resolved_profile, status="publication_blocked" + ) + + suns_result = _run_experiment( + "suns_voc", + experiment_status, + lambda: run_solarscale_suns_voc_1d( + config_file, + defaults=defaults, + resources=resources, + **settings["suns_voc"], + ), + ) + if suns_result is not None: + suns_path = figures / "suns_voc.png" + pseudo_path = figures / "pseudo_jv.png" + _plot_suns_voc(suns_path, suns_result) + _plot_pseudo_jv(pseudo_path, suns_result) + figure_paths["suns_voc"] = str(suns_path) + figure_paths["pseudo_jv"] = str(pseudo_path) + _record_figure_quality(figure_quality, "suns_voc", suns_path, resolved_profile) + _record_figure_quality(figure_quality, "pseudo_jv", pseudo_path, resolved_profile) + device_metrics["quick_experiments"]["suns_voc"] = _jsonable_dataclass(suns_result) + else: + for name, title in (("suns_voc", "Suns-Voc failed"), ("pseudo_jv", "Pseudo-JV failed")): + err_fig = figures / f"{name}.png" + _plot_error(err_fig, title, str(experiment_status["suns_voc"]["error_message"])) + figure_paths[name] = str(err_fig) + _record_figure_quality( + figure_quality, name, err_fig, resolved_profile, status="publication_blocked" + ) + + degradation_result = _run_experiment( + "degradation", + experiment_status, + lambda: _run_degradation_1d( + config_file, + defaults=defaults, + resources=resources, + **settings["degradation"], + ), + ) + if degradation_result is not None: + deg_fig = figures / "degradation.png" + _plot_degradation(deg_fig, degradation_result) + figure_paths["degradation"] = str(deg_fig) + _record_figure_quality(figure_quality, "degradation", deg_fig, resolved_profile) + device_metrics["quick_experiments"]["degradation"] = _jsonable_dataclass(degradation_result) + else: + deg_fig = figures / "degradation.png" + _plot_error( + deg_fig, "Degradation failed", str(experiment_status["degradation"]["error_message"]) + ) + figure_paths["degradation"] = str(deg_fig) + _record_figure_quality( + figure_quality, "degradation", deg_fig, resolved_profile, status="publication_blocked" + ) + + eqe_result = _run_experiment( + "eqe", + experiment_status, + lambda: _run_eqe_1d( + config_file, + defaults=defaults, + resources=resources, + **settings["eqe"], + ), + ) + if eqe_result is not None: + eqe_fig = figures / "eqe.png" + _plot_eqe(eqe_fig, eqe_result) + figure_paths["eqe"] = str(eqe_fig) + _record_figure_quality( + figure_quality, + "eqe", + eqe_fig, + resolved_profile, + status="publication_blocked" if optical_blocking_reasons else None, + ) + device_metrics["quick_experiments"]["eqe"] = _jsonable_dataclass(eqe_result) + else: + if resolved_profile == "production": + blocking_reasons.append( + "EQE skipped because material-specific optical n/k data are unavailable or incomplete" + ) + skip_path = figures / "eqe_skip_reason.json" + skip_payload = { + "schema": "solarlab.eqe_skip_reason", + "schema_version": "0.1", + "material_id": resolved_material_id, + "profile": resolved_profile, + "quality_status": ( + "publication_blocked" + if resolved_profile == "production" + else FIGURE_QUALITY_BY_PROFILE[resolved_profile] + ), + "reason": experiment_status["eqe"]["error_message"], + "policy": "EQE is skipped when wavelength-resolved optical n/k data are unavailable or incomplete.", + } + skip_path.write_text(json.dumps(skip_payload, indent=2, sort_keys=True), encoding="utf-8") + figure_paths["eqe_skip_reason"] = str(skip_path) + _record_figure_quality( + figure_quality, + "eqe_skip_reason", + skip_path, + resolved_profile, + status="publication_blocked" if resolved_profile == "production" else None, + ) + + gates_path = figures / "screening_gates.png" + _plot_screening_gates(gates_path, record) + figure_paths["screening_gates"] = str(gates_path) + _record_figure_quality(figure_quality, "screening_gates", gates_path, resolved_profile) + + physics_quality_status = _physics_quality_status(resolved_profile, blocking_reasons) + publication_ready = resolved_profile == "production" and not blocking_reasons + quality_summary: dict[str, Any] = { + "report_profile": resolved_profile, + "physics_quality_status": physics_quality_status, + "publication_ready": publication_ready, + "blocking_reasons": blocking_reasons, + "figure_quality": figure_quality, + "scientific_qualification": False, + } + device_metrics["experiment_status"] = experiment_status + device_metrics.update(quality_summary) + device_metrics_json = out / "device_metrics.json" + device_metrics_json.write_text( + json.dumps(device_metrics, indent=2, sort_keys=True), encoding="utf-8" + ) + + report_path = out / "report.md" + report_path.write_text( + _render_report_md( + material_id=resolved_material_id, + config_path=config_file, + material_record_path=record_file, + device_results_path=device_results_file, + dft_summary=dft_summary, + device_metrics=device_metrics, + figure_paths=figure_paths, + quality_summary=quality_summary, + ), + encoding="utf-8", + ) + + manifest: dict[str, Any] = { + "schema": "solarlab.material_evaluation_report", + "schema_version": "0.1", + "material_id": resolved_material_id, + "config_path": str(config_file), + "material_record_path": str(record_file), + "device_results_path": str(device_results_file), + "out_dir": str(out), + "report_profile": resolved_profile, + "physics_quality_status": physics_quality_status, + "publication_ready": publication_ready, + "scientific_qualification": False, + "blocking_reasons": blocking_reasons, + "report_path": str(report_path), + "dft_parameter_summary_json": str(dft_json), + "dft_parameter_summary_csv": str(dft_csv), + "device_metrics_json": str(device_metrics_json), + "figures": figure_paths, + "figure_quality": figure_quality, + "experiment_status": experiment_status, + } + manifest_path = out / "evaluation_manifest.json" + manifest["manifest_path"] = str(manifest_path) + manifest["manifest_sha256"] = manifest_sha256(manifest) + manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8") + return manifest + + +def _load_json(path: Path) -> dict[str, Any]: + loaded = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(loaded, dict): + raise ValueError(f"Expected JSON object in {path}") + return loaded + + +def _load_yaml(path: Path) -> dict[str, Any]: + loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if not isinstance(loaded, dict): + raise ValueError(f"Expected YAML mapping in {path}") + return loaded + + +def _config_material_id(config: Mapping[str, Any]) -> str | None: + source = config.get("source") + if isinstance(source, Mapping) and source.get("material_id"): + return str(source["material_id"]) + return None + + +def _first_record_id(path: Path) -> str: + payload = _load_json(path) + records = payload.get("records") + if isinstance(records, list) and records and isinstance(records[0], Mapping): + if records[0].get("material_id"): + return str(records[0]["material_id"]) + if payload.get("material_id"): + return str(payload["material_id"]) + raise ValueError(f"No material_id found in {path}") + + +def _select_material_record(payload: Mapping[str, Any], material_id: str) -> dict[str, Any]: + if payload.get("material_id") == material_id: + return dict(payload) + for record in payload.get("records", []) or []: + if isinstance(record, Mapping) and str(record.get("material_id")) == material_id: + return dict(record) + raise ValueError(f"Material {material_id!r} not found in material record payload") + + +def _select_device_result( + payload: Mapping[str, Any], material_id: str, config_path: Path +) -> dict[str, Any]: + candidates = payload.get("records", []) or [] + config_resolved = str(config_path) + for record in candidates: + if ( + isinstance(record, Mapping) + and str(record.get("material_id")) == material_id + and str(record.get("config_path")) == config_resolved + ): + return dict(record) + for record in candidates: + if isinstance(record, Mapping) and str(record.get("material_id")) == material_id: + return dict(record) + return {} + + +def _dft_parameter_summary( + record: Mapping[str, Any], + config: Mapping[str, Any], + device_record: Mapping[str, Any], +) -> dict[str, Any]: + source = config.get("source") if isinstance(config.get("source"), Mapping) else {} + assert isinstance(source, Mapping) + mapped = dict(source.get("mapped_parameters", {}) or device_record.get("mapped_parameters", {}) or {}) + metadata = dict( + source.get("material_metadata", {}) or device_record.get("material_metadata", {}) or {} + ) + properties = record.get("properties", {}) or {} + rows: list[dict[str, Any]] = [] + for name, target in DFT_PARAMETER_TARGETS.items(): + prop = properties.get(name) if isinstance(properties, Mapping) else None + if isinstance(prop, Mapping): + value = prop.get("value") + unit = prop.get("unit", "") + prov_raw = prop.get("provenance") + provenance = prov_raw if isinstance(prov_raw, Mapping) else {} + else: + value = metadata.get(name) + unit = "" + provenance = {} + rows.append( + { + "parameter": name, + "value": value, + "unit": unit, + "provenance_kind": provenance.get( + "kind", "metadata" if name in metadata else "missing" + ), + "provenance_source": provenance.get("source", ""), + "target": target, + "mapped_value": mapped.get(target) if target else None, + "used_by_solarlab": bool(target and target in mapped), + } + ) + return { + "schema": "solarlab.dft_parameter_summary", + "schema_version": "0.1", + "material_id": record.get("material_id"), + "mapped_parameters": mapped, + "material_metadata": metadata, + "parameters": rows, + } + + +def _write_dft_summary_csv(path: Path, summary: Mapping[str, Any]) -> None: + fieldnames = [ + "parameter", + "value", + "unit", + "provenance_kind", + "provenance_source", + "target", + "mapped_value", + "used_by_solarlab", + ] + with path.open("w", encoding="utf-8", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(summary.get("parameters", []) or []) + + +def _device_metrics_summary( + device_results: Mapping[str, Any], + device_record: Mapping[str, Any], + material_id: str, +) -> dict[str, Any]: + return { + "schema": "solarlab.material_device_metrics", + "schema_version": "0.1", + "material_id": material_id, + "simulation_status": device_record.get("simulation_status"), + "JV_metrics": device_record.get("JV_metrics"), + "sweep_values": device_record.get("sweep_values", {}), + "warnings": device_record.get("warnings", []), + "error": device_record.get("error"), + "device_results_summary": device_results.get("summary", {}), + "quick_experiments": {}, + } + + +def _resolve_profile(*, profile: ReportProfile, quick: bool) -> ReportProfile: + if quick: + return "smoke" + if profile not in {"smoke", "diagnostic", "production"}: + raise ValueError(f"Unknown report profile {profile!r}") + return profile + + +def _validate_production_config(config: Mapping[str, Any]) -> None: + source = config.get("source") if isinstance(config.get("source"), Mapping) else {} + assert isinstance(source, Mapping) + if not source.get("activate_bandgap"): + raise ReportQualityError( + "Production report requires activate_bandgap=True in the generated SolarLab config source" + ) + layers = config.get("layers") + if not isinstance(layers, list): + raise ReportQualityError("Production report requires a SolarLab config with layers") + invalid: list[str] = [] + absorber_has_optics = False + for layer in layers: + if not isinstance(layer, Mapping) or layer.get("role") == "substrate": + continue + role = str(layer.get("role") or layer.get("name") or "layer") + chi = _optional_float(layer.get("chi")) + eg = _optional_float(layer.get("Eg")) + if chi is None or eg is None or eg <= 0.0: + invalid.append(role) + if layer.get("role") == "absorber" and layer.get("optical_material"): + absorber_has_optics = True + if invalid: + raise ReportQualityError( + "Production report requires chi and positive Eg on every electrical layer; invalid layers: " + + ", ".join(invalid) + ) + if not absorber_has_optics: + raise ReportQualityError( + "Production report requires absorber optical_material for EQE/TMM provenance" + ) + + +def _production_optical_blocking_reasons(config: Mapping[str, Any]) -> list[str]: + source = config.get("source") if isinstance(config.get("source"), Mapping) else {} + assert isinstance(source, Mapping) + if source.get("schema") != "solarlab.solarscale_import_config": + return [] + absorber = _config_absorber_layer(config) + optical_material = str(absorber.get("optical_material") or "").strip() if absorber else "" + meta_raw = source.get("material_metadata") + metadata = meta_raw if isinstance(meta_raw, Mapping) else {} + optical_provenance = ( + source.get("optical_material_provenance") + or source.get("nk_provenance") + or metadata.get("optical_material_provenance") + or metadata.get("nk_provenance") + ) + reasons: list[str] = [] + if optical_material == "MAPbI3": + reasons.append( + "Production optical policy blocked: absorber optical_material is the MAPbI3 template placeholder, not material-specific n/k evidence" + ) + if not optical_provenance: + reasons.append( + "Production optical policy blocked: material-specific optical n/k provenance is missing" + ) + return reasons + + +def _production_band_alignment_blocking_reasons(config: Mapping[str, Any]) -> list[str]: + source = config.get("source") if isinstance(config.get("source"), Mapping) else {} + assert isinstance(source, Mapping) + if source.get("schema") != "solarlab.solarscale_import_config": + return [] + meta_raw = source.get("material_metadata") + metadata = meta_raw if isinstance(meta_raw, Mapping) else {} + map_raw = source.get("mapped_parameters") + mapped = map_raw if isinstance(map_raw, Mapping) else {} + absorber = _config_absorber_layer(config) + reasons: list[str] = [] + provenance = source.get("band_alignment_provenance") or metadata.get( + "band_alignment_provenance" + ) + if not provenance: + reasons.append( + "Production band-alignment policy blocked: absorber electron affinity provenance is missing" + ) + if "absorber.chi" not in mapped and metadata.get("electron_affinity_ev") is None: + reasons.append( + "Production band-alignment policy blocked: electron_affinity_ev was not mapped to absorber chi" + ) + if absorber is None or _optional_float(absorber.get("chi")) is None: + reasons.append("Production band-alignment policy blocked: absorber chi is missing") + return reasons + + +def _config_absorber_layer(config: Mapping[str, Any]) -> Mapping[str, Any] | None: + layers = config.get("layers") + if not isinstance(layers, list): + return None + for layer in layers: + if isinstance(layer, Mapping) and layer.get("role") == "absorber": + return layer + return None + + +def _optional_float(value: Any) -> float | None: + if value is None: + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _profile_settings(profile: ReportProfile) -> dict[str, dict[str, Any]]: + if profile == "smoke": + return _smoke_settings() + if profile == "production": + return _production_settings() + return _diagnostic_settings() + + +def _smoke_settings() -> dict[str, dict[str, Any]]: + return { + "jv": {"N_grid": 12, "n_points": 4, "v_rate": 5.0, "V_max": 0.2}, + "suns_voc": {"suns_levels": (0.5, 1.0, 2.0), "N_grid": 20, "t_settle": 5.0e-4}, + "degradation": { + "t_end": 5.0, + "n_snapshots": 2, + "V_bias": 0.9, + "N_grid": 20, + "dt_max": 1.0, + "metric_n_points": 4, + "metric_settle_time": 1.0e-3, + }, + "eqe": { + "wavelengths_nm": [450.0, 650.0, 850.0], + "N_grid": 20, + "t_settle": 5.0e-4, + }, + } + + +def _diagnostic_settings() -> dict[str, dict[str, Any]]: + settings = _smoke_settings() + settings["jv"] = {"N_grid": 30, "n_points": 8, "v_rate": 5.0, "V_max": 1.4} + settings["suns_voc"] = { + "suns_levels": (0.1, 1.0, 3.0, 10.0), + "N_grid": 30, + "t_settle": 5.0e-4, + } + return settings + + +def _production_settings() -> dict[str, dict[str, Any]]: + settings = _diagnostic_settings() + settings["jv"] = {"N_grid": 60, "n_points": 16, "v_rate": 0.5, "V_max": 1.4} + settings["suns_voc"] = { + "suns_levels": (0.1, 0.5, 1.0, 3.0, 10.0), + "N_grid": 50, + "t_settle": 1.0e-2, + } + return settings + + +def _run_experiment( + name: str, status: dict[str, Any], fn: Callable[[], _T] +) -> _T | None: + try: + result = fn() + except Exception as exc: + status[name] = { + "status": "skipped" if name == "eqe" else "failed", + "error_type": type(exc).__name__, + "error_message": str(exc), + } + return None + status[name] = {"status": "completed"} + return result + + +def _plot_jv(path: Path, result: Any) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.plot(np.asarray(result.V_fwd), _j_to_mA_cm2(result.J_fwd), marker="o", label="forward") + ax.plot(np.asarray(result.V_rev), _j_to_mA_cm2(result.J_rev), marker="s", label="reverse") + ax.axhline(0.0, color="0.25", linewidth=0.8) + ax.set_xlabel("Voltage (V)") + ax.set_ylabel("Current density (mA cm$^{-2}$)") + ax.set_title("Quick JV sweep") + ax.legend() + ax.grid(True, alpha=0.25) + _savefig(fig, path) + + +def _plot_suns_voc(path: Path, result: Any) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.semilogx(np.asarray(result.suns), np.asarray(result.V_oc), marker="o") + ax.set_xlabel("Illumination (suns)") + ax.set_ylabel("$V_{oc}$ (V)") + ax.set_title("Suns-Voc") + ax.grid(True, which="both", alpha=0.25) + _savefig(fig, path) + + +def _plot_pseudo_jv(path: Path, result: Any) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.plot(np.asarray(result.J_pseudo_V), _j_to_mA_cm2(result.J_pseudo_J), marker="o") + ax.axhline(0.0, color="0.25", linewidth=0.8) + ax.set_xlabel("Voltage (V)") + ax.set_ylabel("Pseudo current density (mA cm$^{-2}$)") + ax.set_title(f"Pseudo-JV, pseudo-FF={_fmt_float(result.pseudo_FF)}") + ax.grid(True, alpha=0.25) + _savefig(fig, path) + + +def _plot_degradation(path: Path, result: Any) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.plot(np.asarray(result.t), np.asarray(result.PCE), marker="o", label="PCE") + ax.set_xlabel("Stress time (s)") + ax.set_ylabel("PCE") + ax.set_title("Quick degradation proxy") + ax.grid(True, alpha=0.25) + ax.legend() + _savefig(fig, path) + + +def _plot_eqe(path: Path, result: Any) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.plot(np.asarray(result.wavelengths_nm), np.asarray(result.EQE), marker="o") + ax.set_xlabel("Wavelength (nm)") + ax.set_ylabel("EQE") + ax.set_ylim(bottom=0.0) + ax.set_title("External quantum efficiency") + ax.grid(True, alpha=0.25) + _savefig(fig, path) + + +def _plot_screening_gates(path: Path, record: Mapping[str, Any]) -> None: + scr_raw = record.get("screening") + scr = scr_raw if isinstance(scr_raw, Mapping) else {} + gates_raw = scr.get("gates") + gates = gates_raw if isinstance(gates_raw, Mapping) else {} + names = list(gates) or ["no_gates"] + statuses = [_gate_status(gates.get(name)) for name in names] if gates else ["missing"] + colors = { + "pass": "#2b8a3e", + "fail": "#c92a2a", + "missing": "#868e96", + "unknown": "#1c7ed6", + } + fig, ax = plt.subplots(figsize=(max(6.4, len(names) * 1.15), 4.2)) + ax.bar( + range(len(names)), + [1] * len(names), + color=[colors.get(status, colors["unknown"]) for status in statuses], + ) + ax.set_xticks(range(len(names)), names, rotation=30, ha="right") + ax.set_yticks([]) + ax.set_title("SolarScale screening gates") + for idx, status in enumerate(statuses): + ax.text( + idx, + 0.5, + status, + ha="center", + va="center", + color="white", + fontsize=9, + fontweight="bold", + ) + _savefig(fig, path) + + +def _record_figure_quality( + figure_quality: dict[str, dict[str, Any]], + name: str, + path: Path, + profile: ReportProfile, + *, + status: str | None = None, +) -> None: + quality_status = status or FIGURE_QUALITY_BY_PROFILE[profile] + figure_quality[name] = { + "path": str(path), + "profile": profile, + "quality_status": quality_status, + } + + +def _production_jv_blocking_reasons(result: Any) -> list[str]: + reasons: list[str] = [] + for label, metrics in (("forward", result.metrics_fwd), ("reverse", result.metrics_rev)): + if not bool(getattr(metrics, "voc_bracketed", False)): + reasons.append(f"{label} JV did not bracket Voc") + for field_name in ("V_oc", "J_sc", "FF", "PCE"): + value = getattr(metrics, field_name) + if value is None or not math.isfinite(float(value)): + reasons.append(f"{label} JV metric {field_name} is not finite") + if float(getattr(metrics, "V_oc")) <= 0.0: + reasons.append(f"{label} JV metric V_oc is sentinel or non-positive") + if float(getattr(metrics, "PCE")) <= 0.0: + reasons.append(f"{label} JV metric PCE is sentinel or non-positive") + return reasons + + +def _physics_quality_status(profile: ReportProfile, blocking_reasons: list[str]) -> str: + if blocking_reasons: + return "publication_blocked" + return FIGURE_QUALITY_BY_PROFILE[profile] + + +def _plot_error(path: Path, title: str, message: str) -> None: + fig, ax = plt.subplots(figsize=(6.4, 4.2)) + ax.axis("off") + ax.text(0.5, 0.65, title, ha="center", va="center", fontsize=14, fontweight="bold") + ax.text(0.5, 0.42, message[:240], ha="center", va="center", wrap=True, fontsize=10) + _savefig(fig, path) + + +def _savefig(fig: Any, path: Path) -> None: + fig.tight_layout() + fig.savefig(path, dpi=180) + plt.close(fig) + + +def _j_to_mA_cm2(values: Any) -> NDArray[np.float64]: + return np.asarray(values, dtype=np.float64) * 0.1 + + +def _gate_status(value: Any) -> str: + if isinstance(value, bool): + return "pass" if value else "fail" + if isinstance(value, str): + lower = value.strip().lower() + return lower if lower in {"pass", "fail", "missing"} else "unknown" + if isinstance(value, Mapping): + status = value.get("status") + if isinstance(status, str): + lower = status.strip().lower() + return lower if lower in {"pass", "fail", "missing"} else "unknown" + if "passed" in value: + return "pass" if bool(value["passed"]) else "fail" + if value is None: + return "missing" + return "unknown" + + +def _jv_metrics_dict(result: Any) -> dict[str, Any]: + return { + "forward": _jsonable_dataclass(result.metrics_fwd), + "reverse": _jsonable_dataclass(result.metrics_rev), + "hysteresis_index": _json_number(result.hysteresis_index), + } + + +def _jsonable_dataclass(value: Any) -> Any: + if is_dataclass(value) and not isinstance(value, type): + return {key: _jsonable_dataclass(item) for key, item in asdict(value).items()} + if isinstance(value, np.ndarray): + return [_json_number(item) for item in value.tolist()] + if isinstance(value, (list, tuple)): + return [_jsonable_dataclass(item) for item in value] + if isinstance(value, Mapping): + return {str(key): _jsonable_dataclass(item) for key, item in value.items()} + return _json_number(value) + + +def _json_number(value: Any) -> Any: + if isinstance(value, (np.floating, float)): + out = float(value) + return out if math.isfinite(out) else None + if isinstance(value, (np.integer, int)) and not isinstance(value, bool): + return int(value) + if isinstance(value, (np.bool_, bool)): + return bool(value) + return value + + +def _fmt_float(value: Any) -> str: + try: + number = float(value) + except (TypeError, ValueError): + return "n/a" + return f"{number:.3g}" if math.isfinite(number) else "n/a" + + +def _render_report_md( + *, + material_id: str, + config_path: Path, + material_record_path: Path, + device_results_path: Path, + dft_summary: Mapping[str, Any], + device_metrics: Mapping[str, Any], + figure_paths: Mapping[str, str], + quality_summary: Mapping[str, Any], +) -> str: + jv = device_metrics.get("JV_metrics") or {} + forward = jv.get("forward") if isinstance(jv, Mapping) else {} + rows = [ + f"# SolarScale x SolarLab Evaluation: {material_id}", + "", + "## Inputs", + f"- Config: `{config_path}`", + f"- Material record: `{material_record_path}`", + f"- Device results: `{device_results_path}`", + "", + "## DFT/MD Parameters", + "| Parameter | Value | Unit | Provenance | SolarLab target | Used |", + "| --- | ---: | --- | --- | --- | --- |", + ] + for row in dft_summary.get("parameters", []) or []: + if not isinstance(row, Mapping): + continue + raw_val = row.get("value") + val_str = _fmt_float(raw_val) if isinstance(raw_val, (int, float)) else str(raw_val) + rows.append( + "| {parameter} | {value} | {unit} | {provenance_kind} | {target} | {used} |".format( + parameter=row.get("parameter"), + value=val_str, + unit=row.get("unit") or "", + provenance_kind=row.get("provenance_kind") or "", + target=row.get("target") or "metadata only", + used="yes" if row.get("used_by_solarlab") else "no", + ) + ) + rows.extend( + [ + "", + "## Device Metrics", + f"- Status: `{device_metrics.get('simulation_status')}`", + f"- Voc: `{_fmt_float(_dict_get(forward, 'V_oc'))}` V", + f"- Jsc: `{_fmt_float(_dict_get(forward, 'J_sc'))}` A/m^2", + f"- FF: `{_fmt_float(_dict_get(forward, 'FF'))}`", + f"- PCE: `{_fmt_float(_dict_get(forward, 'PCE'))}`", + "", + "## Quality", + f"- Profile: `{quality_summary.get('report_profile')}`", + f"- Physics quality status: `{quality_summary.get('physics_quality_status')}`", + f"- Publication ready: `{quality_summary.get('publication_ready')}`", + "", + "## Figures", + ] + ) + for name, path in figure_paths.items(): + rows.append(f"- {name}: `{path}`") + rows.extend(["", "## Notes"]) + warnings = list(device_metrics.get("warnings", []) or []) + warnings.extend(quality_summary.get("blocking_reasons", []) or []) + if warnings: + rows.extend(f"- {warning}" for warning in warnings) + else: + rows.append("- No device-result warnings were reported.") + rows.append("- Smoke and diagnostic figures are not publication-grade device evidence.") + return "\n".join(rows) + "\n" + + +def _dict_get(value: Any, key: str) -> Any: + return value.get(key) if isinstance(value, Mapping) else None diff --git a/src/solarlab/experiments/identifiability.py b/src/solarlab/experiments/identifiability.py new file mode 100644 index 00000000..4a36d8b0 --- /dev/null +++ b/src/solarlab/experiments/identifiability.py @@ -0,0 +1,1896 @@ +"""Fail-closed parameter identifiability, Fisher/SVD, collinearity, and profile-likelihood runner. + +Implements ``P05-05`` clause 3 natively in ``solarlab.experiments`` with zero +legacy package imports: +1. Bit-exact ``M``-class parity for the synthetic interface-SRH scaling benchmark + (``InterfaceSRHIdentifiabilityProtocol``, ``InterfaceSRHIdentifiabilityResult``, + ``build_interface_srh_identifiability_protocol``, + ``run_interface_srh_identifiability``), preserving ``protocol.sha256`` and + ``result.mapping_sha256`` digests while separating a valid identifiability + analysis from identifiability of ``N_t * sigma * calibration_factor``. +2. Brun-style column-normalized ``collinearity_index``, subset collinearity maps, + and connected ``confounded_parameter_groups`` diagnostics. +3. General protocol-based sensitivity / Fisher / profile-likelihood analysis + (``run_protocol_identifiability``) over arbitrary ``solarlab`` forward + observables with explicit retention of every failed sample coordinate and + reason (``FailedSampleRecord``), plus ``ExperimentResult`` envelope export. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +import dataclasses +from dataclasses import dataclass +import hashlib +import itertools +import json +import math +from numbers import Real +from typing import Any, Literal, Self, SupportsInt +import weakref + +import numpy as np +from numpy.typing import NDArray +from scipy.optimize import least_squares + +from solarlab.contracts import ELEMENTARY_CHARGE_C +from solarlab.experiments.results import EVIDENCE_LABELS, ExperimentResult, encode_array + +Q = ELEMENTARY_CHARGE_C + +ParameterName = Literal[ + "trap_density_cm2", + "capture_cross_section_scale", + "calibration_factor", +] +ObservableFamily = Literal[ + "recombination_only", + "recombination_plus_charge", +] + +PARAMETER_NAMES: tuple[ParameterName, ...] = ( + "trap_density_cm2", + "capture_cross_section_scale", + "calibration_factor", +) +OBSERVABLE_FAMILIES: tuple[ObservableFamily, ...] = ( + "recombination_only", + "recombination_plus_charge", +) + + +class IdentifiabilityError(ValueError): + """Base class for invalid identifiability protocols or evidence.""" + + +class IdentifiabilityForwardError(IdentifiabilityError): + """Raised when the frozen forward model cannot be evaluated.""" + + +def _finite(value: object, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{field} must be a real number") + number = float(value) + if not math.isfinite(number): + raise ValueError(f"{field} must be finite") + return 0.0 if number == 0.0 else number + + +def _positive(value: object, field: str) -> float: + number = _finite(value, field) + if number <= 0.0: + raise ValueError(f"{field} must be positive") + return number + + +def _nonnegative(value: object, field: str) -> float: + number = _finite(value, field) + if number < 0.0: + raise ValueError(f"{field} must be non-negative") + return number + + +def _integer(value: object, field: str, *, minimum: int) -> int: + if isinstance(value, bool): + raise TypeError(f"{field} must be an integer >= {minimum}") + if not isinstance(value, (int, float, Real)): + raise TypeError(f"{field} must be an integer >= {minimum}") + try: + integer = int(value) if isinstance(value, (int, float, SupportsInt)) else int(float(value)) + except (TypeError, ValueError, OverflowError) as exc: + raise TypeError(f"{field} must be an integer >= {minimum}") from exc + if integer != value or integer < minimum: + raise ValueError(f"{field} must be an integer >= {minimum}") + return integer + + +def _json_ready(value: Any) -> Any: + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return { + field.name: _json_ready(getattr(value, field.name)) + for field in dataclasses.fields(value) + } + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (tuple, list)): + return [_json_ready(item) for item in value] + if isinstance(value, float): + if not math.isfinite(value): + raise ValueError("identifiability document contains a non-finite float") + return 0.0 if value == 0.0 else value + if value is None or isinstance(value, (str, bool, int)): + return value + raise TypeError( + "identifiability document contains a non-JSON value of type " + f"{type(value).__name__}" + ) + + +def _canonical_json(value: Any) -> str: + return json.dumps( + _json_ready(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + +def _exact_keys(payload: Mapping[str, Any], cls: type, label: str) -> None: + expected = {field.name for field in dataclasses.fields(cls)} + actual = set(payload) + if actual != expected: + raise IdentifiabilityError( + f"{label} keys do not match schema; " + f"missing={sorted(expected - actual)}, extra={sorted(actual - expected)}" + ) + + +def _sha256(value: object, field: str) -> str: + if ( + not isinstance(value, str) + or len(value) != 64 + or any(character not in "0123456789abcdef" for character in value) + ): + raise ValueError(f"{field} must be a lowercase SHA-256 digest") + return value + + +def _interface_recombination_rate( + n: float, + p: float, + ni_sq: float, + n1: float, + p1: float, + v_n: float, + v_p: float, +) -> float: + """Surface SRH recombination rate [m^-2 s^-1] matching constitutive formula.""" + if v_n <= 0.0 or v_p <= 0.0: + return 0.0 + denominator = (n + n1) / v_p + (p + p1) / v_n + return (n * p - ni_sq) / denominator + + +def _equilibrium_referenced_interface_trap_charge( + occupancy: float | np.ndarray, + equilibrium_occupancy: float | np.ndarray, + trap_density_m2: float | np.ndarray, +) -> np.ndarray: + """Signed incremental interface trap sheet charge ``-q * N_t * (f - f_eq)`` [C m^-2].""" + f, f_eq, density = np.broadcast_arrays( + np.asarray(occupancy, dtype=float), + np.asarray(equilibrium_occupancy, dtype=float), + np.asarray(trap_density_m2, dtype=float), + ) + if not (np.all(np.isfinite(f)) and np.all(np.isfinite(f_eq)) and np.all(np.isfinite(density))): + raise ValueError("occupancies and trap_density_m2 must be finite") + if np.any((f < 0.0) | (f > 1.0)): + raise ValueError("occupancy must lie in [0, 1]") + if np.any((f_eq < 0.0) | (f_eq > 1.0)): + raise ValueError("equilibrium_occupancy must lie in [0, 1]") + if np.any(density < 0.0): + raise ValueError("trap_density_m2 must be non-negative") + return -Q * density * (f - f_eq) + + +@dataclass(frozen=True, slots=True) +class FailedSampleRecord: + """Explicit record of a failed forward sample coordinate and error reason.""" + + stage: str + coordinates_log10: tuple[float, ...] + error_type: str + error_message: str + + def __post_init__(self) -> None: + if not isinstance(self.stage, str) or not self.stage.strip(): + raise ValueError("stage must be a non-empty string") + coords = tuple(_finite(v, "coordinates_log10") for v in self.coordinates_log10) + if not coords: + raise ValueError("coordinates_log10 must be non-empty") + if not isinstance(self.error_type, str) or not self.error_type.strip(): + raise ValueError("error_type must be a non-empty string") + if not isinstance(self.error_message, str) or not self.error_message.strip(): + raise ValueError("error_message must be a non-empty string") + object.__setattr__(self, "coordinates_log10", coords) + + +def collinearity_index( + weighted_jacobian: Sequence[Sequence[float]] | np.ndarray, + *, + svd_relative_threshold: float = 1.0e-7, +) -> float | None: + """Compute Brun et al. (2001) collinearity index ``gamma = 1 / sigma_min(J_norm)``. + + Each column of ``weighted_jacobian`` is normalized to unit Euclidean norm. + Returns ``None`` when any column has zero norm or when the normalized column + set is numerically rank-deficient (``sigma_min <= svd_relative_threshold * sigma_max``). + """ + threshold_rel = _positive(svd_relative_threshold, "svd_relative_threshold") + if threshold_rel >= 1.0: + raise ValueError("svd_relative_threshold must be below 1") + jac: NDArray[np.float64] = np.asarray(weighted_jacobian, dtype=float) + if jac.ndim != 2 or jac.shape[0] < 1 or jac.shape[1] < 1 or not np.all(np.isfinite(jac)): + raise ValueError("weighted_jacobian must be a finite non-empty 2D matrix") + col_norms = np.linalg.norm(jac, axis=0) + if np.any(col_norms <= 0.0) or not np.all(np.isfinite(col_norms)): + return None + normalized = jac / col_norms[np.newaxis, :] + singular = np.linalg.svd(normalized, compute_uv=False) + if singular.size < jac.shape[1] or singular[0] <= 0.0: + return None + sigma_min = float(singular[-1]) + if sigma_min <= threshold_rel * float(singular[0]): + return None + return float(1.0 / sigma_min) + + +def subset_collinearity_indices( + weighted_jacobian: Sequence[Sequence[float]] | np.ndarray, + parameter_names: Sequence[str], + *, + svd_relative_threshold: float = 1.0e-7, +) -> dict[tuple[str, ...], float | None]: + """Compute ``collinearity_index`` across every parameter subset of size >= 2.""" + jac: NDArray[np.float64] = np.asarray(weighted_jacobian, dtype=float) + names = tuple(str(name) for name in parameter_names) + if jac.ndim != 2 or jac.shape[1] != len(names): + raise ValueError("parameter_names length must match weighted_jacobian column count") + out: dict[tuple[str, ...], float | None] = {} + for size in range(2, len(names) + 1): + for indices in itertools.combinations(range(len(names)), size): + subset_names = tuple(names[i] for i in indices) + out[subset_names] = collinearity_index( + jac[:, list(indices)], + svd_relative_threshold=svd_relative_threshold, + ) + return out + + +def confounded_parameter_groups( + weighted_jacobian: Sequence[Sequence[float]] | np.ndarray, + parameter_names: Sequence[str], + *, + svd_relative_threshold: float = 1.0e-7, + collinearity_limit: float = 1.0e6, +) -> tuple[tuple[str, ...], ...]: + """Identify connected groups of parameters participating in nullspace/collinear directions.""" + jac: NDArray[np.float64] = np.asarray(weighted_jacobian, dtype=float) + names = tuple(str(name) for name in parameter_names) + count = len(names) + if jac.ndim != 2 or jac.shape[1] != count: + raise ValueError("parameter_names length must match weighted_jacobian column count") + if count == 0: + return () + + col_norms = np.linalg.norm(jac, axis=0) + adj: dict[int, set[int]] = {i: set() for i in range(count)} + + # Zero-sensitivity columns are individually unidentifiable; group any collinear pairs/triples. + nonzero = col_norms > 0.0 + if np.all(nonzero): + normalized = jac / col_norms[np.newaxis, :] + _u, singular, vh = np.linalg.svd(normalized, full_matrices=True) + cutoff = max(svd_relative_threshold * float(singular[0]), 1.0 / max(collinearity_limit, 1.0)) + rank = int(np.count_nonzero(singular > cutoff)) + for vec in vh[rank:]: + active = [idx for idx, val in enumerate(vec) if abs(float(val)) > 1.0e-4] + for a, b in itertools.combinations(active, 2): + adj[a].add(b) + adj[b].add(a) + + visited: set[int] = set() + groups: list[tuple[str, ...]] = [] + for idx in range(count): + if idx in visited: + continue + if not nonzero[idx]: + visited.add(idx) + groups.append((names[idx],)) + continue + if not adj[idx]: + continue + stack = [idx] + comp: list[int] = [] + while stack: + cur = stack.pop() + if cur in visited: + continue + visited.add(cur) + comp.append(cur) + stack.extend(adj[cur] - visited) + comp.sort() + if len(comp) >= 2: + groups.append(tuple(names[i] for i in comp)) + return tuple(groups) + + +@dataclass(frozen=True, slots=True) +class IdentifiabilityParameter: + """One bounded base-10 logarithmic synthetic parameter.""" + + name: ParameterName + lower_log10: float + upper_log10: float + truth_log10: float + estimated: bool = True + + def __post_init__(self) -> None: + if self.name not in PARAMETER_NAMES: + raise ValueError(f"unsupported identifiability parameter {self.name!r}") + lower = _finite(self.lower_log10, "lower_log10") + upper = _finite(self.upper_log10, "upper_log10") + truth = _finite(self.truth_log10, "truth_log10") + if not lower < upper: + raise ValueError("parameter lower_log10 must be below upper_log10") + if not lower < truth < upper: + raise ValueError("parameter truth_log10 must lie strictly inside bounds") + if not isinstance(self.estimated, bool): + raise TypeError("parameter estimated flag must be boolean") + object.__setattr__(self, "lower_log10", lower) + object.__setattr__(self, "upper_log10", upper) + object.__setattr__(self, "truth_log10", truth) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("identifiability parameter must be a mapping") + _exact_keys(payload, cls, "identifiability parameter") + return cls(**dict(payload)) + + +@dataclass(frozen=True, slots=True) +class InterfaceCarrierCondition: + """One positive carrier-density pair sampled by the synthetic model.""" + + electron_density_m3: float + hole_density_m3: float + + def __post_init__(self) -> None: + object.__setattr__( + self, + "electron_density_m3", + _positive(self.electron_density_m3, "electron_density_m3"), + ) + object.__setattr__( + self, + "hole_density_m3", + _positive(self.hole_density_m3, "hole_density_m3"), + ) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("interface carrier condition must be a mapping") + _exact_keys(payload, cls, "interface carrier condition") + return cls(**dict(payload)) + + +@dataclass(frozen=True, slots=True) +class InterfaceSRHIdentifiabilityProtocol: + """Frozen synthetic recovery and local-identifiability contract.""" + + parameters: tuple[IdentifiabilityParameter, ...] + carrier_conditions: tuple[InterfaceCarrierCondition, ...] + intrinsic_density_squared_m6: float + trap_electron_density_m3: float + trap_hole_density_m3: float + base_sigma_n_cm2: float + base_sigma_p_cm2: float + thermal_velocity_cm_s: float + equilibrium_occupancy: float + observable_family: ObservableFamily + rate_relative_standard_deviation: float + charge_relative_standard_deviation: float + standard_deviation_floor_fraction: float + synthetic_noise_sigma_multiplier: float + noise_seed: int + finite_difference_step_log10: float + svd_relative_threshold: float + expected_rank: int + condition_number_limit: float + truth_recovery_tolerance_log10: float + multistart_fractions: tuple[tuple[float, ...], ...] + profile_grid_count: int + least_squares_max_nfev: int + failure_standardized_residual: float + schema_version: Literal[1] = 1 + model: Literal["production_interface_srh_scaling"] = "production_interface_srh_scaling" + model_version: Literal[1] = 1 + coordinate_system: Literal["base10_log_parameters"] = "base10_log_parameters" + optimizer: Literal["scipy_least_squares_trf"] = "scipy_least_squares_trf" + profile_method: Literal["fixed_parameter_reoptimization"] = "fixed_parameter_reoptimization" + forward_failure_policy: Literal["penalize_and_invalidate"] = "penalize_and_invalidate" + + def __post_init__(self) -> None: + if self.schema_version != 1 or self.model_version != 1: + raise ValueError("identifiability schema/model version must be 1") + if self.model != "production_interface_srh_scaling": + raise ValueError("unsupported identifiability forward model") + if self.coordinate_system != "base10_log_parameters": + raise ValueError("identifiability parameters must use base-10 logs") + if self.optimizer != "scipy_least_squares_trf": + raise ValueError("unsupported identifiability optimizer") + if self.profile_method != "fixed_parameter_reoptimization": + raise ValueError("unsupported profile method") + if self.forward_failure_policy != "penalize_and_invalidate": + raise ValueError("forward failures must be penalized and invalidate evidence") + if self.observable_family not in OBSERVABLE_FAMILIES: + raise ValueError("unsupported observable family") + + parameters = tuple(self.parameters) + if tuple(parameter.name for parameter in parameters) != PARAMETER_NAMES: + raise ValueError( + "parameters must contain the canonical trap/capture/calibration order" + ) + if not any(parameter.estimated for parameter in parameters): + raise ValueError("at least one identifiability parameter must be estimated") + object.__setattr__(self, "parameters", parameters) + + conditions = tuple(self.carrier_conditions) + if len(conditions) < 3 or not all( + isinstance(item, InterfaceCarrierCondition) for item in conditions + ): + raise ValueError("at least three carrier conditions are required") + condition_pairs = { + (item.electron_density_m3.hex(), item.hole_density_m3.hex()) + for item in conditions + } + if len(condition_pairs) != len(conditions): + raise ValueError("carrier conditions must be unique") + object.__setattr__(self, "carrier_conditions", conditions) + + for name in ( + "intrinsic_density_squared_m6", + "trap_electron_density_m3", + "trap_hole_density_m3", + "base_sigma_n_cm2", + "base_sigma_p_cm2", + "thermal_velocity_cm_s", + "rate_relative_standard_deviation", + "charge_relative_standard_deviation", + "standard_deviation_floor_fraction", + "finite_difference_step_log10", + "svd_relative_threshold", + "condition_number_limit", + "truth_recovery_tolerance_log10", + "failure_standardized_residual", + ): + object.__setattr__(self, name, _positive(getattr(self, name), name)) + occupancy = _finite(self.equilibrium_occupancy, "equilibrium_occupancy") + if not 0.0 <= occupancy <= 1.0: + raise ValueError("equilibrium_occupancy must lie in [0, 1]") + object.__setattr__(self, "equilibrium_occupancy", occupancy) + noise = _nonnegative( + self.synthetic_noise_sigma_multiplier, + "synthetic_noise_sigma_multiplier", + ) + object.__setattr__(self, "synthetic_noise_sigma_multiplier", noise) + if self.standard_deviation_floor_fraction >= 1.0: + raise ValueError("standard_deviation_floor_fraction must be below 1") + if self.svd_relative_threshold >= 1.0: + raise ValueError("svd_relative_threshold must be below 1") + + seed = _integer(self.noise_seed, "noise_seed", minimum=0) + object.__setattr__(self, "noise_seed", seed) + estimated_count = len(self.estimated_parameters) + rank = _integer(self.expected_rank, "expected_rank", minimum=1) + if rank > estimated_count: + raise ValueError("expected_rank exceeds estimated parameter count") + object.__setattr__(self, "expected_rank", rank) + profile_count = _integer(self.profile_grid_count, "profile_grid_count", minimum=5) + if profile_count % 2 == 0: + raise ValueError("profile_grid_count must be odd") + object.__setattr__(self, "profile_grid_count", profile_count) + object.__setattr__( + self, + "least_squares_max_nfev", + _integer(self.least_squares_max_nfev, "least_squares_max_nfev", minimum=10), + ) + + starts = tuple( + tuple(float(value) for value in row) for row in self.multistart_fractions + ) + if len(starts) < 3 or any(len(row) != estimated_count for row in starts): + raise ValueError( + "multistart_fractions require at least three dimension-matched rows" + ) + if any( + not math.isfinite(value) or not 0.0 < value < 1.0 + for row in starts + for value in row + ): + raise ValueError("multistart fractions must lie strictly inside (0, 1)") + if len(set(starts)) != len(starts): + raise ValueError("multistart fractions must be unique") + object.__setattr__(self, "multistart_fractions", starts) + + @property + def estimated_parameters(self) -> tuple[IdentifiabilityParameter, ...]: + return tuple(parameter for parameter in self.parameters if parameter.estimated) + + def to_dict(self) -> dict[str, Any]: + return _json_ready(self) + + def canonical_json(self) -> str: + return _canonical_json(self) + + def to_json(self) -> str: + return self.canonical_json() + + @property + def sha256(self) -> str: + return hashlib.sha256(self.canonical_json().encode("ascii")).hexdigest() + + @classmethod + def from_json(cls, raw: str) -> Self: + payload = json.loads(raw) + if not isinstance(payload, Mapping): + raise TypeError("identifiability protocol JSON must decode to an object") + return cls.from_dict(payload) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("identifiability protocol must be a mapping") + _exact_keys(payload, cls, "identifiability protocol") + values = dict(payload) + raw_parameters = values["parameters"] + raw_conditions = values["carrier_conditions"] + if not isinstance(raw_parameters, Sequence) or isinstance(raw_parameters, (str, bytes)): + raise TypeError("protocol parameters must be a sequence") + if not isinstance(raw_conditions, Sequence) or isinstance(raw_conditions, (str, bytes)): + raise TypeError("protocol carrier_conditions must be a sequence") + values["parameters"] = tuple( + IdentifiabilityParameter.from_dict(item) for item in raw_parameters + ) + values["carrier_conditions"] = tuple( + InterfaceCarrierCondition.from_dict(item) for item in raw_conditions + ) + values["multistart_fractions"] = tuple( + tuple(row) for row in values["multistart_fractions"] + ) + return cls(**values) + + +@dataclass(frozen=True, slots=True) +class IdentifiabilityFitAttempt: + """One bounded least-squares attempt from one declared start.""" + + start_log10: tuple[float, ...] + solution_log10: tuple[float, ...] + chi_square: float + standardized_residual_linf: float + success: bool + status: int + function_evaluations: int + + def __post_init__(self) -> None: + start = tuple(_finite(value, "start_log10") for value in self.start_log10) + solution = tuple(_finite(value, "solution_log10") for value in self.solution_log10) + if not start or len(start) != len(solution): + raise ValueError("fit attempt coordinates must be nonempty and aligned") + object.__setattr__(self, "start_log10", start) + object.__setattr__(self, "solution_log10", solution) + object.__setattr__(self, "chi_square", _nonnegative(self.chi_square, "chi_square")) + object.__setattr__( + self, + "standardized_residual_linf", + _nonnegative(self.standardized_residual_linf, "standardized_residual_linf"), + ) + if not isinstance(self.success, bool): + raise TypeError("fit attempt success must be boolean") + object.__setattr__(self, "status", int(self.status)) + object.__setattr__( + self, + "function_evaluations", + _integer(self.function_evaluations, "function_evaluations", minimum=1), + ) + + +@dataclass(frozen=True, slots=True) +class IdentifiabilityProfile: + """Fixed-parameter profile with all remaining parameters re-optimized.""" + + parameter_name: str + parameter_values_log10: tuple[float, ...] + chi_square: tuple[float, ...] + successful: tuple[bool, ...] + + def __post_init__(self) -> None: + if not isinstance(self.parameter_name, str) or not self.parameter_name.strip(): + raise ValueError("profile parameter_name must be a non-empty string") + values = tuple( + _finite(value, "parameter_values_log10") for value in self.parameter_values_log10 + ) + costs = tuple(_nonnegative(value, "profile chi_square") for value in self.chi_square) + flags = tuple(self.successful) + if not values or len(values) != len(costs) or len(values) != len(flags): + raise ValueError("profile arrays must be nonempty and aligned") + if any(not isinstance(flag, bool) for flag in flags): + raise TypeError("profile successful values must be boolean") + if any(right <= left for left, right in zip(values, values[1:], strict=False)): + raise ValueError("profile parameter values must be strictly increasing") + object.__setattr__(self, "parameter_values_log10", values) + object.__setattr__(self, "chi_square", costs) + object.__setattr__(self, "successful", flags) + + +def _finite_matrix( + values: Sequence[Sequence[float]], + *, + rows: int, + columns: int, + field: str, +) -> tuple[tuple[float, ...], ...]: + matrix = tuple(tuple(_finite(value, field) for value in row) for row in values) + if len(matrix) != rows or any(len(row) != columns for row in matrix): + raise ValueError(f"{field} must have shape ({rows}, {columns})") + return matrix + + +_FAILED_SAMPLES_REGISTRY: weakref.WeakKeyDictionary[ + InterfaceSRHIdentifiabilityResult, tuple[FailedSampleRecord, ...] +] = weakref.WeakKeyDictionary() + + +def _result_unsigned_document(result: InterfaceSRHIdentifiabilityResult) -> dict[str, Any]: + return { + field.name: _json_ready(getattr(result, field.name)) + for field in dataclasses.fields(result) + if field.name != "mapping_sha256" + } + + +@dataclass(frozen=True) +class InterfaceSRHIdentifiabilityResult: + """Immutable synthetic fit, Fisher/SVD, nullspace, collinearity, and profile evidence.""" + + protocol: InterfaceSRHIdentifiabilityProtocol + protocol_sha256: str + observable_labels: tuple[str, ...] + observable_units: tuple[str, ...] + observed_values: tuple[float, ...] + standard_deviations: tuple[float, ...] + truth_values: tuple[float, ...] + best_fit_log10: tuple[float, ...] + best_fit_values: tuple[float, ...] + best_chi_square: float + best_standardized_residual_linf: float + weighted_jacobian: tuple[tuple[float, ...], ...] + fisher_information: tuple[tuple[float, ...], ...] + fisher_correlation: tuple[tuple[float, ...], ...] + singular_values: tuple[float, ...] + numerical_rank: int + condition_number: float | None + nullspace_vectors: tuple[tuple[float, ...], ...] + fit_attempts: tuple[IdentifiabilityFitAttempt, ...] + profiles: tuple[IdentifiabilityProfile, ...] + forward_failure_count: int + rank_expectation_met: bool + truth_recovered: bool + all_multistarts_converged: bool + profiles_completed: bool + parameters_identifiable: bool + analysis_certified: bool + mapping_sha256: str + + def __post_init__(self) -> None: + if not isinstance(self.protocol, InterfaceSRHIdentifiabilityProtocol): + raise TypeError("protocol must be InterfaceSRHIdentifiabilityProtocol") + protocol_hash = _sha256(self.protocol_sha256, "protocol_sha256") + if protocol_hash != self.protocol.sha256: + raise ValueError("protocol_sha256 does not match protocol") + object.__setattr__(self, "protocol_sha256", protocol_hash) + + labels = tuple(self.observable_labels) + units = tuple(self.observable_units) + observed = tuple(_finite(value, "observed_values") for value in self.observed_values) + deviations = tuple( + _positive(value, "standard_deviations") for value in self.standard_deviations + ) + if ( + not labels + or len(set(labels)) != len(labels) + or len(labels) != len(units) + or len(labels) != len(observed) + or len(labels) != len(deviations) + ): + raise ValueError("observable evidence arrays must be unique and aligned") + object.__setattr__(self, "observable_labels", labels) + object.__setattr__(self, "observable_units", units) + object.__setattr__(self, "observed_values", observed) + object.__setattr__(self, "standard_deviations", deviations) + + estimated = self.protocol.estimated_parameters + count = len(estimated) + truth_values = tuple(_positive(value, "truth_values") for value in self.truth_values) + best_log = tuple(_finite(value, "best_fit_log10") for value in self.best_fit_log10) + best_values = tuple(_positive(value, "best_fit_values") for value in self.best_fit_values) + if len(truth_values) != count or len(best_log) != count or len(best_values) != count: + raise ValueError("parameter result arrays do not match estimated parameters") + if any( + not math.isclose(value, 10.0**coordinate, rel_tol=2.0e-15) + for value, coordinate in zip(best_values, best_log, strict=True) + ): + raise ValueError("best_fit_values do not match best_fit_log10") + object.__setattr__(self, "truth_values", truth_values) + object.__setattr__(self, "best_fit_log10", best_log) + object.__setattr__(self, "best_fit_values", best_values) + object.__setattr__( + self, "best_chi_square", _nonnegative(self.best_chi_square, "best_chi_square") + ) + object.__setattr__( + self, + "best_standardized_residual_linf", + _nonnegative( + self.best_standardized_residual_linf, + "best_standardized_residual_linf", + ), + ) + + jacobian = _finite_matrix( + self.weighted_jacobian, + rows=len(labels), + columns=count, + field="weighted_jacobian", + ) + fisher = _finite_matrix( + self.fisher_information, + rows=count, + columns=count, + field="fisher_information", + ) + correlation = _finite_matrix( + self.fisher_correlation, + rows=count, + columns=count, + field="fisher_correlation", + ) + object.__setattr__(self, "weighted_jacobian", jacobian) + object.__setattr__(self, "fisher_information", fisher) + object.__setattr__(self, "fisher_correlation", correlation) + singular = tuple(_nonnegative(value, "singular_values") for value in self.singular_values) + if len(singular) != count or any( + right > left for left, right in zip(singular, singular[1:], strict=False) + ): + raise ValueError("singular_values must be descending and dimension matched") + object.__setattr__(self, "singular_values", singular) + rank = _integer(self.numerical_rank, "numerical_rank", minimum=1) + if rank > count: + raise ValueError("numerical_rank exceeds parameter count") + object.__setattr__(self, "numerical_rank", rank) + if self.condition_number is not None: + condition = _positive(self.condition_number, "condition_number") + if rank != count: + raise ValueError("rank-deficient result must use condition_number=None") + object.__setattr__(self, "condition_number", condition) + elif rank == count: + raise ValueError("full-rank result requires a finite condition number") + nullspace = _finite_matrix( + self.nullspace_vectors, + rows=count - rank, + columns=count, + field="nullspace_vectors", + ) + object.__setattr__(self, "nullspace_vectors", nullspace) + + attempts = tuple(self.fit_attempts) + profiles = tuple(self.profiles) + if len(attempts) != len(self.protocol.multistart_fractions) or not all( + isinstance(item, IdentifiabilityFitAttempt) for item in attempts + ): + raise ValueError("fit attempts do not match protocol starts") + if any(item.parameter_name not in PARAMETER_NAMES for item in profiles): + raise ValueError("profile parameter is not supported") + if tuple(item.parameter_name for item in profiles) != tuple( + parameter.name for parameter in estimated + ): + raise ValueError("profiles do not match estimated parameter order") + object.__setattr__(self, "fit_attempts", attempts) + object.__setattr__(self, "profiles", profiles) + failures = _integer(self.forward_failure_count, "forward_failure_count", minimum=0) + object.__setattr__(self, "forward_failure_count", failures) + + expected_rank_match = rank == self.protocol.expected_rank + full_rank = rank == count + expected_flags = { + "rank_expectation_met": expected_rank_match, + "all_multistarts_converged": all(item.success for item in attempts), + "profiles_completed": all(all(item.successful) for item in profiles), + "parameters_identifiable": ( + full_rank + and self.condition_number is not None + and self.condition_number <= self.protocol.condition_number_limit + ), + } + for name, expected in expected_flags.items(): + actual = getattr(self, name) + if not isinstance(actual, bool) or actual != expected: + raise ValueError(f"{name} does not match identifiability evidence") + truth_error = max( + abs(coordinate - parameter.truth_log10) + for coordinate, parameter in zip(best_log, estimated, strict=True) + ) + expected_recovery = ( + expected_flags["parameters_identifiable"] + and truth_error <= self.protocol.truth_recovery_tolerance_log10 + ) + if not isinstance(self.truth_recovered, bool) or self.truth_recovered != expected_recovery: + raise ValueError("truth_recovered does not match fit evidence") + expected_certified = ( + expected_rank_match + and expected_flags["all_multistarts_converged"] + and expected_flags["profiles_completed"] + and failures == 0 + and (expected_recovery if full_rank else True) + ) + if ( + not isinstance(self.analysis_certified, bool) + or self.analysis_certified != expected_certified + ): + raise ValueError("analysis_certified does not match evidence") + + mapping = _sha256(self.mapping_sha256, "mapping_sha256") + expected_mapping = hashlib.sha256( + _canonical_json(_result_unsigned_document(self)).encode("ascii") + ).hexdigest() + if mapping != expected_mapping: + raise ValueError("mapping_sha256 does not match result evidence") + object.__setattr__(self, "mapping_sha256", mapping) + + def to_dict(self) -> dict[str, Any]: + return _json_ready(self) + + def to_json(self) -> str: + return _canonical_json(self) + + @classmethod + def from_dict(cls, payload: Mapping[str, Any]) -> Self: + if not isinstance(payload, Mapping): + raise TypeError("identifiability result must be a mapping") + _exact_keys(payload, cls, "identifiability result") + values = dict(payload) + values["protocol"] = InterfaceSRHIdentifiabilityProtocol.from_dict(values["protocol"]) + for seq_field in ( + "observable_labels", + "observable_units", + "observed_values", + "standard_deviations", + "truth_values", + "best_fit_log10", + "best_fit_values", + "singular_values", + ): + values[seq_field] = tuple(values[seq_field]) + for mat_field in ( + "weighted_jacobian", + "fisher_information", + "fisher_correlation", + "nullspace_vectors", + ): + values[mat_field] = tuple(tuple(row) for row in values[mat_field]) + values["fit_attempts"] = tuple( + IdentifiabilityFitAttempt( + start_log10=tuple(item["start_log10"]), + solution_log10=tuple(item["solution_log10"]), + chi_square=item["chi_square"], + standardized_residual_linf=item["standardized_residual_linf"], + success=item["success"], + status=item["status"], + function_evaluations=item["function_evaluations"], + ) + for item in values["fit_attempts"] + ) + values["profiles"] = tuple( + IdentifiabilityProfile( + parameter_name=item["parameter_name"], + parameter_values_log10=tuple(item["parameter_values_log10"]), + chi_square=tuple(item["chi_square"]), + successful=tuple(item["successful"]), + ) + for item in values["profiles"] + ) + return cls(**values) + + @classmethod + def from_json(cls, raw: str) -> Self: + payload = json.loads(raw) + if not isinstance(payload, Mapping): + raise TypeError("identifiability result JSON must decode to an object") + return cls.from_dict(payload) + + @property + def collinearity_index(self) -> float | None: + return collinearity_index( + self.weighted_jacobian, + svd_relative_threshold=self.protocol.svd_relative_threshold, + ) + + @property + def subset_collinearity(self) -> dict[tuple[str, ...], float | None]: + names = [p.name for p in self.protocol.estimated_parameters] + return subset_collinearity_indices( + self.weighted_jacobian, + names, + svd_relative_threshold=self.protocol.svd_relative_threshold, + ) + + @property + def confounded_parameter_groups(self) -> tuple[tuple[str, ...], ...]: + names = [p.name for p in self.protocol.estimated_parameters] + return confounded_parameter_groups( + self.weighted_jacobian, + names, + svd_relative_threshold=self.protocol.svd_relative_threshold, + collinearity_limit=self.protocol.condition_number_limit, + ) + + @property + def failed_samples(self) -> tuple[FailedSampleRecord, ...]: + return _FAILED_SAMPLES_REGISTRY.get(self, ()) + + +def _default_multistarts(dimension: int) -> tuple[tuple[float, ...], ...]: + corners = tuple( + tuple(0.2 if bit == 0 else 0.8 for bit in bits) + for bits in itertools.product((0, 1), repeat=dimension) + ) + center = (0.5,) * dimension + return (center, *corners) + + +def _expected_structural_rank( + estimated_names: tuple[ParameterName, ...], + observable_family: ObservableFamily, +) -> int: + rate_row: NDArray[np.float64] = np.ones((1, len(estimated_names)), dtype=float) + rows: list[NDArray[np.float64]] = [rate_row] + if observable_family == "recombination_plus_charge": + charge_row: NDArray[np.float64] = np.array( + [[1.0 if name == "trap_density_cm2" else 0.0 for name in estimated_names]], + dtype=float, + ) + if np.any(charge_row): + rows.append(charge_row) + return int(np.linalg.matrix_rank(np.vstack(rows))) + + +def build_interface_srh_identifiability_protocol( + *, + observable_family: ObservableFamily = "recombination_plus_charge", + estimated_parameters: Sequence[ParameterName] = PARAMETER_NAMES, + carrier_condition_count: int = 7, + finite_difference_step_log10: float = 1.0e-4, + synthetic_noise_sigma_multiplier: float = 0.0, + noise_seed: int = 1729, +) -> InterfaceSRHIdentifiabilityProtocol: + """Build the canonical constitutive synthetic interface-SRH benchmark.""" + if observable_family not in OBSERVABLE_FAMILIES: + raise ValueError("unsupported observable family") + requested = tuple(estimated_parameters) + if not requested or len(set(requested)) != len(requested): + raise ValueError("estimated_parameters must be nonempty and unique") + if any(name not in PARAMETER_NAMES for name in requested): + raise ValueError("estimated_parameters contains an unsupported name") + count = _integer(carrier_condition_count, "carrier_condition_count", minimum=3) + electron_axis = np.geomspace(1.0e16, 1.0e22, count) + hole_axis = electron_axis[::-1] + conditions = tuple( + InterfaceCarrierCondition(float(n), float(p)) + for n, p in zip(electron_axis, hole_axis, strict=True) + ) + parameters = ( + IdentifiabilityParameter( + "trap_density_cm2", + lower_log10=8.0, + upper_log10=14.0, + truth_log10=12.0, + estimated="trap_density_cm2" in requested, + ), + IdentifiabilityParameter( + "capture_cross_section_scale", + lower_log10=-2.0, + upper_log10=2.0, + truth_log10=0.0, + estimated="capture_cross_section_scale" in requested, + ), + IdentifiabilityParameter( + "calibration_factor", + lower_log10=-6.0, + upper_log10=0.0, + truth_log10=-3.0, + estimated="calibration_factor" in requested, + ), + ) + estimated_order = tuple( + parameter.name for parameter in parameters if parameter.estimated + ) + expected_rank = _expected_structural_rank(estimated_order, observable_family) + return InterfaceSRHIdentifiabilityProtocol( + parameters=parameters, + carrier_conditions=conditions, + intrinsic_density_squared_m6=1.0e32, + trap_electron_density_m3=1.0e16, + trap_hole_density_m3=1.0e16, + base_sigma_n_cm2=1.0e-15, + base_sigma_p_cm2=3.0e-16, + thermal_velocity_cm_s=1.0e7, + equilibrium_occupancy=0.5, + observable_family=observable_family, + rate_relative_standard_deviation=0.02, + charge_relative_standard_deviation=0.02, + standard_deviation_floor_fraction=1.0e-6, + synthetic_noise_sigma_multiplier=synthetic_noise_sigma_multiplier, + noise_seed=noise_seed, + finite_difference_step_log10=finite_difference_step_log10, + svd_relative_threshold=1.0e-7, + expected_rank=expected_rank, + condition_number_limit=1.0e8, + truth_recovery_tolerance_log10=5.0e-5, + multistart_fractions=_default_multistarts(len(estimated_order)), + profile_grid_count=9, + least_squares_max_nfev=400, + failure_standardized_residual=1.0e6, + ) + + +def _full_parameter_log_values( + protocol: InterfaceSRHIdentifiabilityProtocol, + estimated_log_values: np.ndarray, +) -> dict[ParameterName, float]: + values: dict[ParameterName, float] = {} + cursor = 0 + for parameter in protocol.parameters: + if parameter.estimated: + values[parameter.name] = float(estimated_log_values[cursor]) + cursor += 1 + else: + values[parameter.name] = parameter.truth_log10 + if cursor != len(estimated_log_values): + raise ValueError("estimated coordinate vector has the wrong size") + return values + + +def _predict_interface_srh_observables( + protocol: InterfaceSRHIdentifiabilityProtocol, + estimated_log_values: np.ndarray, +) -> tuple[tuple[str, ...], tuple[str, ...], np.ndarray]: + log_values = _full_parameter_log_values(protocol, estimated_log_values) + trap_density_cm2 = 10.0 ** log_values["trap_density_cm2"] + capture_scale = 10.0 ** log_values["capture_cross_section_scale"] + calibration = 10.0 ** log_values["calibration_factor"] + common = protocol.thermal_velocity_cm_s * trap_density_cm2 * 1.0e-2 + velocity_n = protocol.base_sigma_n_cm2 * capture_scale * common * calibration + velocity_p = protocol.base_sigma_p_cm2 * capture_scale * common * calibration + if not ( + math.isfinite(velocity_n) + and math.isfinite(velocity_p) + and velocity_n > 0.0 + and velocity_p > 0.0 + ): + raise IdentifiabilityForwardError("synthetic capture velocities are invalid") + + labels: list[str] = [] + units: list[str] = [] + values: list[float] = [] + occupancies: list[float] = [] + for index, condition in enumerate(protocol.carrier_conditions): + n = condition.electron_density_m3 + p = condition.hole_density_m3 + rate = _interface_recombination_rate( + n, + p, + protocol.intrinsic_density_squared_m6, + protocol.trap_electron_density_m3, + protocol.trap_hole_density_m3, + velocity_n, + velocity_p, + ) + current = Q * float(rate) + denominator = velocity_n * (n + protocol.trap_electron_density_m3) + ( + velocity_p * (p + protocol.trap_hole_density_m3) + ) + occupancy = (velocity_n * n + velocity_p * protocol.trap_hole_density_m3) / denominator + if not ( + math.isfinite(current) + and current > 0.0 + and math.isfinite(occupancy) + and 0.0 <= occupancy <= 1.0 + ): + raise IdentifiabilityForwardError( + "production interface-SRH formula left its valid envelope" + ) + labels.append(f"interface_current_condition_{index}_A_m2") + units.append("A m-2") + values.append(current) + occupancies.append(occupancy) + + if protocol.observable_family == "recombination_plus_charge": + trap_density_m2 = trap_density_cm2 * 1.0e4 + charge = _equilibrium_referenced_interface_trap_charge( + np.asarray(occupancies), + protocol.equilibrium_occupancy, + trap_density_m2, + ) + for index, value in enumerate(np.asarray(charge, dtype=float)): + labels.append(f"incremental_sheet_charge_condition_{index}_C_m2") + units.append("C m-2") + values.append(float(value)) + predicted: NDArray[np.float64] = np.asarray(values, dtype=float) + if not np.all(np.isfinite(predicted)): + raise IdentifiabilityForwardError("synthetic observables are non-finite") + return tuple(labels), tuple(units), predicted + + +def _block_standard_deviations( + protocol: InterfaceSRHIdentifiabilityProtocol, + truth: np.ndarray, +) -> np.ndarray: + count = len(protocol.carrier_conditions) + standard_deviations = np.empty_like(truth) + blocks = [(slice(0, count), protocol.rate_relative_standard_deviation)] + if protocol.observable_family == "recombination_plus_charge": + blocks.append((slice(count, 2 * count), protocol.charge_relative_standard_deviation)) + for block, relative in blocks: + values = np.abs(truth[block]) + scale = float(np.max(values)) + if not math.isfinite(scale) or scale <= 0.0: + raise IdentifiabilityForwardError("observable block has no finite scale") + floor = protocol.standard_deviation_floor_fraction * scale + standard_deviations[block] = relative * np.maximum(values, floor) + return standard_deviations + + +class _ResidualEvaluator: + def __init__( + self, + forward_fn: Callable[[np.ndarray], np.ndarray], + observed: np.ndarray, + standard_deviations: np.ndarray, + *, + finite_difference_step_log10: float, + least_squares_max_nfev: int, + failure_standardized_residual: float, + ) -> None: + self.forward_fn = forward_fn + self.observed = observed + self.standard_deviations = standard_deviations + self.finite_difference_step_log10 = finite_difference_step_log10 + self.least_squares_max_nfev = least_squares_max_nfev + self.failure_standardized_residual = failure_standardized_residual + self.forward_failure_count = 0 + self.stage = "multistart" + self.failed_samples: list[FailedSampleRecord] = [] + + def residual(self, coordinates: np.ndarray) -> np.ndarray: + coords = np.asarray(coordinates, dtype=float) + try: + predicted = np.asarray(self.forward_fn(coords), dtype=float) + if predicted.shape != self.observed.shape or not np.all(np.isfinite(predicted)): + raise IdentifiabilityForwardError("forward observables are misaligned or non-finite") + except Exception as exc: + self.forward_failure_count += 1 + if np.all(np.isfinite(coords)) and coords.size > 0: + msg = str(exc).strip() or type(exc).__name__ + self.failed_samples.append( + FailedSampleRecord( + stage=self.stage, + coordinates_log10=tuple(float(v) for v in coords), + error_type=type(exc).__name__, + error_message=msg[:400], + ) + ) + return np.full( + self.observed.shape, + self.failure_standardized_residual, + dtype=float, + ) + return (predicted - self.observed) / self.standard_deviations + + def jacobian( + self, + coordinates: np.ndarray, + lower: np.ndarray, + upper: np.ndarray, + ) -> np.ndarray: + values = np.asarray(coordinates, dtype=float) + jacobian = np.empty((self.observed.size, values.size), dtype=float) + step = self.finite_difference_step_log10 + base = self.residual(values) + for column in range(values.size): + left = values.copy() + right = values.copy() + left[column] = max(lower[column], values[column] - step) + right[column] = min(upper[column], values[column] + step) + if left[column] < values[column] and right[column] > values[column]: + jacobian[:, column] = (self.residual(right) - self.residual(left)) / ( + right[column] - left[column] + ) + elif right[column] > values[column]: + jacobian[:, column] = (self.residual(right) - base) / ( + right[column] - values[column] + ) + elif left[column] < values[column]: + jacobian[:, column] = (base - self.residual(left)) / ( + values[column] - left[column] + ) + else: + raise IdentifiabilityForwardError( + "finite-difference coordinate is pinned at both bounds" + ) + return jacobian + + +def _fit( + evaluator: _ResidualEvaluator, + start: np.ndarray, + lower: np.ndarray, + upper: np.ndarray, +) -> IdentifiabilityFitAttempt: + result = least_squares( + evaluator.residual, + start, + jac=lambda values: evaluator.jacobian(values, lower, upper), + bounds=(lower, upper), + method="trf", + ftol=1.0e-12, + xtol=1.0e-12, + gtol=1.0e-12, + max_nfev=evaluator.least_squares_max_nfev, + ) + residual = evaluator.residual(result.x) + return IdentifiabilityFitAttempt( + start_log10=tuple(float(value) for value in start), + solution_log10=tuple(float(value) for value in result.x), + chi_square=float(np.dot(residual, residual)), + standardized_residual_linf=float(np.max(np.abs(residual))), + success=bool(result.success and np.all(np.isfinite(result.x))), + status=int(result.status), + function_evaluations=int(result.nfev), + ) + + +def _profile_parameter( + parameter_name: str, + profile_grid_count: int, + least_squares_max_nfev: int, + evaluator: _ResidualEvaluator, + best: np.ndarray, + lower: np.ndarray, + upper: np.ndarray, + index: int, +) -> IdentifiabilityProfile: + grid = np.linspace(lower[index], upper[index], profile_grid_count) + remaining = np.array([item for item in range(best.size) if item != index], dtype=int) + costs: list[float] = [] + successes: list[bool] = [] + for fixed in grid: + if remaining.size == 0: + candidate = np.array([fixed], dtype=float) + residual = evaluator.residual(candidate) + costs.append(float(np.dot(residual, residual))) + successes.append(bool(np.all(np.isfinite(residual)))) + continue + + reduced_lower = lower[remaining] + reduced_upper = upper[remaining] + reduced_start = np.clip(best[remaining], reduced_lower, reduced_upper) + + def expand(reduced: np.ndarray, _fixed: float = float(fixed)) -> np.ndarray: + candidate = best.copy() + candidate[index] = _fixed + candidate[remaining] = reduced + return candidate + + def residual_fn(reduced: np.ndarray) -> np.ndarray: + return evaluator.residual(expand(reduced)) + + def jacobian_fn(reduced: np.ndarray) -> np.ndarray: + expanded = expand(reduced) + full = evaluator.jacobian(expanded, lower, upper) + return full[:, remaining] + + result = least_squares( + residual_fn, + reduced_start, + jac=jacobian_fn, + bounds=(reduced_lower, reduced_upper), + method="trf", + ftol=1.0e-12, + xtol=1.0e-12, + gtol=1.0e-12, + max_nfev=least_squares_max_nfev, + ) + profile_residual = residual_fn(result.x) + costs.append(float(np.dot(profile_residual, profile_residual))) + successes.append(bool(result.success and np.all(np.isfinite(result.x)))) + return IdentifiabilityProfile( + parameter_name=parameter_name, + parameter_values_log10=tuple(float(value) for value in grid), + chi_square=tuple(costs), + successful=tuple(successes), + ) + + +def _canonical_nullspace(vectors: np.ndarray) -> tuple[tuple[float, ...], ...]: + canonical: list[tuple[float, ...]] = [] + for vector in vectors: + values = np.asarray(vector, dtype=float).copy() + pivot = int(np.argmax(np.abs(values))) + if values[pivot] < 0.0: + values *= -1.0 + canonical.append(tuple(float(value) for value in values)) + return tuple(canonical) + + +def _correlation_from_fisher(fisher: np.ndarray) -> np.ndarray: + covariance = np.linalg.pinv(fisher, rcond=1.0e-15, hermitian=True) + diagonal = np.maximum(np.diag(covariance), 0.0) + scale = np.sqrt(diagonal) + denominator = np.outer(scale, scale) + correlation = np.divide( + covariance, + denominator, + out=np.zeros_like(covariance), + where=denominator > 0.0, + ) + np.fill_diagonal(correlation, 1.0) + return correlation + + +def run_interface_srh_identifiability( + protocol: InterfaceSRHIdentifiabilityProtocol, +) -> InterfaceSRHIdentifiabilityResult: + """Run the frozen synthetic multi-start, Fisher/SVD, and profile analysis.""" + if not isinstance(protocol, InterfaceSRHIdentifiabilityProtocol): + raise TypeError("protocol must be InterfaceSRHIdentifiabilityProtocol") + estimated = protocol.estimated_parameters + truth_log: NDArray[np.float64] = np.asarray([item.truth_log10 for item in estimated], dtype=float) + labels, units, truth_prediction = _predict_interface_srh_observables( + protocol, + truth_log, + ) + standard_deviations = _block_standard_deviations(protocol, truth_prediction) + rng = np.random.default_rng(protocol.noise_seed) + observed = truth_prediction + ( + protocol.synthetic_noise_sigma_multiplier + * standard_deviations + * rng.standard_normal(truth_prediction.shape) + ) + evaluator = _ResidualEvaluator( + lambda coords: _predict_interface_srh_observables(protocol, coords)[2], + observed, + standard_deviations, + finite_difference_step_log10=protocol.finite_difference_step_log10, + least_squares_max_nfev=protocol.least_squares_max_nfev, + failure_standardized_residual=protocol.failure_standardized_residual, + ) + lower: NDArray[np.float64] = np.asarray([item.lower_log10 for item in estimated], dtype=float) + upper: NDArray[np.float64] = np.asarray([item.upper_log10 for item in estimated], dtype=float) + starts = tuple( + lower + np.asarray(fractions, dtype=float) * (upper - lower) + for fractions in protocol.multistart_fractions + ) + evaluator.stage = "multistart" + attempts = tuple(_fit(evaluator, start, lower, upper) for start in starts) + best_attempt = min( + attempts, + key=lambda item: (item.chi_square, item.standardized_residual_linf), + ) + best: NDArray[np.float64] = np.asarray(best_attempt.solution_log10, dtype=float) + evaluator.stage = "jacobian" + weighted_jacobian = evaluator.jacobian(best, lower, upper) + _u, singular_values, vh = np.linalg.svd(weighted_jacobian, full_matrices=True) + threshold = protocol.svd_relative_threshold * float(singular_values[0]) + rank = int(np.count_nonzero(singular_values > threshold)) + if rank < 1: + raise IdentifiabilityForwardError("weighted Jacobian has zero numerical rank") + fisher = weighted_jacobian.T @ weighted_jacobian + correlation = _correlation_from_fisher(fisher) + condition_number = ( + float(singular_values[0] / singular_values[-1]) if rank == len(estimated) else None + ) + nullspace = _canonical_nullspace(vh[rank:]) + evaluator.stage = "profile" + profiles = tuple( + _profile_parameter( + estimated[index].name, + protocol.profile_grid_count, + protocol.least_squares_max_nfev, + evaluator, + best, + lower, + upper, + index, + ) + for index in range(len(estimated)) + ) + truth_values = tuple(10.0**item.truth_log10 for item in estimated) + best_values = tuple(10.0**value for value in best) + parameters_identifiable = ( + rank == len(estimated) + and condition_number is not None + and condition_number <= protocol.condition_number_limit + ) + truth_error = float(np.max(np.abs(best - truth_log))) + truth_recovered = ( + parameters_identifiable and truth_error <= protocol.truth_recovery_tolerance_log10 + ) + rank_expectation_met = rank == protocol.expected_rank + all_multistarts_converged = all(item.success for item in attempts) + profiles_completed = all(all(item.successful) for item in profiles) + analysis_certified = ( + rank_expectation_met + and all_multistarts_converged + and profiles_completed + and evaluator.forward_failure_count == 0 + and (truth_recovered if rank == len(estimated) else True) + ) + + values: dict[str, Any] = { + "protocol": protocol, + "protocol_sha256": protocol.sha256, + "observable_labels": labels, + "observable_units": units, + "observed_values": tuple(float(value) for value in observed), + "standard_deviations": tuple(float(value) for value in standard_deviations), + "truth_values": truth_values, + "best_fit_log10": tuple(float(value) for value in best), + "best_fit_values": best_values, + "best_chi_square": best_attempt.chi_square, + "best_standardized_residual_linf": best_attempt.standardized_residual_linf, + "weighted_jacobian": tuple( + tuple(float(value) for value in row) for row in weighted_jacobian + ), + "fisher_information": tuple(tuple(float(value) for value in row) for row in fisher), + "fisher_correlation": tuple( + tuple(float(value) for value in row) for row in correlation + ), + "singular_values": tuple(float(value) for value in singular_values), + "numerical_rank": rank, + "condition_number": condition_number, + "nullspace_vectors": nullspace, + "fit_attempts": attempts, + "profiles": profiles, + "forward_failure_count": evaluator.forward_failure_count, + "rank_expectation_met": rank_expectation_met, + "truth_recovered": truth_recovered, + "all_multistarts_converged": all_multistarts_converged, + "profiles_completed": profiles_completed, + "parameters_identifiable": parameters_identifiable, + "analysis_certified": analysis_certified, + } + unsigned = _json_ready(values) + values["mapping_sha256"] = hashlib.sha256( + _canonical_json(unsigned).encode("ascii") + ).hexdigest() + result = InterfaceSRHIdentifiabilityResult(**values) + _FAILED_SAMPLES_REGISTRY[result] = tuple(evaluator.failed_samples) + return result + + +@dataclass(frozen=True, slots=True) +class GenericIdentifiabilityParameter: + """Bounded base-10 log parameter declaration for general protocol identifiability.""" + + name: str + lower_log10: float + upper_log10: float + reference_log10: float + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("parameter name must be a non-empty string") + lower = _finite(self.lower_log10, "lower_log10") + upper = _finite(self.upper_log10, "upper_log10") + ref = _finite(self.reference_log10, "reference_log10") + if not lower < ref < upper: + raise ValueError("reference_log10 must lie strictly inside (lower_log10, upper_log10)") + object.__setattr__(self, "lower_log10", lower) + object.__setattr__(self, "upper_log10", upper) + object.__setattr__(self, "reference_log10", ref) + + +@dataclass(frozen=True, slots=True) +class GenericIdentifiabilityProtocol: + """Protocol-agnostic identifiability specification for arbitrary ``solarlab`` observables.""" + + protocol_id: str + parameters: tuple[GenericIdentifiabilityParameter, ...] + observable_labels: tuple[str, ...] + observable_units: tuple[str, ...] + standard_deviations: tuple[float, ...] + finite_difference_step_log10: float = 1.0e-3 + svd_relative_threshold: float = 1.0e-7 + condition_number_limit: float = 1.0e8 + collinearity_limit: float = 1.0e6 + profile_grid_count: int = 7 + least_squares_max_nfev: int = 120 + failure_standardized_residual: float = 1.0e6 + + def __post_init__(self) -> None: + if not isinstance(self.protocol_id, str) or not self.protocol_id.strip(): + raise ValueError("protocol_id must be a non-empty string") + params = tuple(self.parameters) + if not params or len({p.name for p in params}) != len(params): + raise ValueError("parameters must be non-empty with unique names") + labels = tuple(self.observable_labels) + units = tuple(self.observable_units) + sds = tuple(_positive(v, "standard_deviations") for v in self.standard_deviations) + if not labels or len(set(labels)) != len(labels) or len(labels) != len(units) or len(labels) != len(sds): + raise ValueError("observable_labels, observable_units, and standard_deviations must align") + object.__setattr__(self, "parameters", params) + object.__setattr__(self, "observable_labels", labels) + object.__setattr__(self, "observable_units", units) + object.__setattr__(self, "standard_deviations", sds) + object.__setattr__( + self, + "finite_difference_step_log10", + _positive(self.finite_difference_step_log10, "finite_difference_step_log10"), + ) + object.__setattr__( + self, + "svd_relative_threshold", + _positive(self.svd_relative_threshold, "svd_relative_threshold"), + ) + object.__setattr__( + self, + "condition_number_limit", + _positive(self.condition_number_limit, "condition_number_limit"), + ) + object.__setattr__( + self, + "collinearity_limit", + _positive(self.collinearity_limit, "collinearity_limit"), + ) + grid_n = _integer(self.profile_grid_count, "profile_grid_count", minimum=5) + if grid_n % 2 == 0: + raise ValueError("profile_grid_count must be odd") + object.__setattr__(self, "profile_grid_count", grid_n) + object.__setattr__( + self, + "least_squares_max_nfev", + _integer(self.least_squares_max_nfev, "least_squares_max_nfev", minimum=10), + ) + object.__setattr__( + self, + "failure_standardized_residual", + _positive(self.failure_standardized_residual, "failure_standardized_residual"), + ) + + @property + def sha256(self) -> str: + return hashlib.sha256(_canonical_json(self).encode("ascii")).hexdigest() + + +@dataclass(frozen=True, slots=True) +class GenericIdentifiabilityResult: + """Protocol identifiability result retaining full Jacobian/Fisher/collinearity and failed samples.""" + + protocol: GenericIdentifiabilityProtocol + protocol_sha256: str + observed_values: tuple[float, ...] + best_fit_log10: tuple[float, ...] + best_chi_square: float + weighted_jacobian: tuple[tuple[float, ...], ...] + fisher_information: tuple[tuple[float, ...], ...] + fisher_correlation: tuple[tuple[float, ...], ...] + singular_values: tuple[float, ...] + numerical_rank: int + condition_number: float | None + collinearity_index: float | None + confounded_parameter_groups: tuple[tuple[str, ...], ...] + nullspace_vectors: tuple[tuple[float, ...], ...] + fit_attempts: tuple[IdentifiabilityFitAttempt, ...] + profiles: tuple[IdentifiabilityProfile, ...] + failed_samples: tuple[FailedSampleRecord, ...] + parameters_identifiable: bool + analysis_certified: bool + mapping_sha256: str + + +def run_protocol_identifiability( + protocol: GenericIdentifiabilityProtocol, + forward_fn: Callable[[np.ndarray], Sequence[float] | np.ndarray], + *, + observed_values: Sequence[float] | np.ndarray | None = None, + multistart_fractions: Sequence[Sequence[float]] | None = None, +) -> GenericIdentifiabilityResult: + """Run local sensitivity, Fisher/SVD, collinearity, and profile-likelihood over ``forward_fn``. + + Every forward failure during multistart fitting, Jacobian probing, or + profile-likelihood sweeps is explicitly retained in ``result.failed_samples`` + and invalidates ``analysis_certified`` without crashing or dropping evidence. + """ + ref_coords: NDArray[np.float64] = np.asarray([p.reference_log10 for p in protocol.parameters], dtype=float) + if observed_values is None: + observed: NDArray[np.float64] = np.asarray(forward_fn(ref_coords), dtype=float) + else: + observed = np.asarray(observed_values, dtype=float) + if observed.shape != (len(protocol.observable_labels),) or not np.all(np.isfinite(observed)): + raise IdentifiabilityForwardError("observed_values must be finite and match observable_labels") + + sds: NDArray[np.float64] = np.asarray(protocol.standard_deviations, dtype=float) + evaluator = _ResidualEvaluator( + lambda coords: np.asarray(forward_fn(coords), dtype=float), + observed, + sds, + finite_difference_step_log10=protocol.finite_difference_step_log10, + least_squares_max_nfev=protocol.least_squares_max_nfev, + failure_standardized_residual=protocol.failure_standardized_residual, + ) + dim = len(protocol.parameters) + lower: NDArray[np.float64] = np.asarray([p.lower_log10 for p in protocol.parameters], dtype=float) + upper: NDArray[np.float64] = np.asarray([p.upper_log10 for p in protocol.parameters], dtype=float) + fracs = ( + _default_multistarts(dim) + if multistart_fractions is None + else tuple(tuple(float(v) for v in row) for row in multistart_fractions) + ) + starts = tuple(lower + np.asarray(row, dtype=float) * (upper - lower) for row in fracs) + evaluator.stage = "multistart" + attempts = tuple(_fit(evaluator, start, lower, upper) for start in starts) + best_attempt = min( + attempts, + key=lambda item: (item.chi_square, item.standardized_residual_linf), + ) + best: NDArray[np.float64] = np.asarray(best_attempt.solution_log10, dtype=float) + evaluator.stage = "jacobian" + weighted_jacobian = evaluator.jacobian(best, lower, upper) + _u, singular_values, vh = np.linalg.svd(weighted_jacobian, full_matrices=True) + max_sv = float(singular_values[0]) if singular_values.size else 0.0 + threshold = protocol.svd_relative_threshold * max_sv + rank = int(np.count_nonzero(singular_values > threshold)) if max_sv > 0.0 else 0 + fisher = weighted_jacobian.T @ weighted_jacobian + correlation = _correlation_from_fisher(fisher) + condition_number = ( + float(singular_values[0] / singular_values[-1]) if rank == dim and dim > 0 else None + ) + coll_idx = collinearity_index( + weighted_jacobian, svd_relative_threshold=protocol.svd_relative_threshold + ) + param_names = [p.name for p in protocol.parameters] + confounded = confounded_parameter_groups( + weighted_jacobian, + param_names, + svd_relative_threshold=protocol.svd_relative_threshold, + collinearity_limit=protocol.collinearity_limit, + ) + nullspace = _canonical_nullspace(vh[rank:]) if rank < dim else () + evaluator.stage = "profile" + profiles = tuple( + _profile_parameter( + protocol.parameters[idx].name, + protocol.profile_grid_count, + protocol.least_squares_max_nfev, + evaluator, + best, + lower, + upper, + idx, + ) + for idx in range(dim) + ) + identifiable = ( + rank == dim + and condition_number is not None + and condition_number <= protocol.condition_number_limit + and coll_idx is not None + and coll_idx <= protocol.collinearity_limit + and not confounded + ) + certified = ( + all(item.success for item in attempts) + and all(all(item.successful) for item in profiles) + and len(evaluator.failed_samples) == 0 + ) + unsigned_fields: dict[str, Any] = { + "protocol": protocol, + "protocol_sha256": protocol.sha256, + "observed_values": tuple(float(v) for v in observed), + "best_fit_log10": tuple(float(v) for v in best), + "best_chi_square": best_attempt.chi_square, + "weighted_jacobian": tuple(tuple(float(v) for v in row) for row in weighted_jacobian), + "fisher_information": tuple(tuple(float(v) for v in row) for row in fisher), + "fisher_correlation": tuple(tuple(float(v) for v in row) for row in correlation), + "singular_values": tuple(float(v) for v in singular_values), + "numerical_rank": rank, + "condition_number": condition_number, + "collinearity_index": coll_idx, + "confounded_parameter_groups": confounded, + "nullspace_vectors": nullspace, + "fit_attempts": attempts, + "profiles": profiles, + "failed_samples": tuple(evaluator.failed_samples), + "parameters_identifiable": identifiable, + "analysis_certified": certified, + } + digest = hashlib.sha256(_canonical_json(unsigned_fields).encode("ascii")).hexdigest() + return GenericIdentifiabilityResult(**unsigned_fields, mapping_sha256=digest) + + +def identifiability_to_experiment_result( + result: InterfaceSRHIdentifiabilityResult | GenericIdentifiabilityResult, + *, + run_id: str, + attempt_id: str, + experiment_id: str = "parameter_identifiability", + evidence_label: str = "FIRST_SLICE", +) -> ExperimentResult: + """Export an identifiability analysis into a canonical ``ExperimentResult`` envelope.""" + if evidence_label not in EVIDENCE_LABELS: + raise ValueError(f"unsupported evidence_label: {evidence_label!r}") + if isinstance(result, InterfaceSRHIdentifiabilityResult): + param_names: list[str] = [str(p.name) for p in result.protocol.estimated_parameters] + failed_list = result.failed_samples + coll_idx = result.collinearity_index + confounded = result.confounded_parameter_groups + proto_id: str = str(result.protocol.model) + else: + param_names = [str(p.name) for p in result.protocol.parameters] + failed_list = result.failed_samples + coll_idx = result.collinearity_index + confounded = result.confounded_parameter_groups + proto_id = str(result.protocol.protocol_id) + + confounded_flat = {name for group in confounded for name in group} + metrics: dict[str, dict[str, Any]] = { + "numerical_rank": { + "status": "identified", + "value": int(result.numerical_rank), + "reason": None, + }, + "best_chi_square": { + "status": "identified", + "value": float(result.best_chi_square), + "reason": None, + }, + "collinearity_index": ( + {"status": "identified", "value": float(coll_idx), "reason": None} + if coll_idx is not None + else { + "status": "unidentified", + "value": None, + "reason": "rank_deficient_or_collinear_jacobian", + } + ), + } + for name, best_log in zip(param_names, result.best_fit_log10, strict=True): + if result.parameters_identifiable and name not in confounded_flat: + metrics[f"param_log10:{name}"] = { + "status": "identified", + "value": float(best_log), + "reason": None, + } + else: + reason = ( + f"confounded_in:{','.join( next((g for g in confounded if name in g), (name,)) )}" + if name in confounded_flat + else "parameter_set_not_identifiable" + ) + metrics[f"param_log10:{name}"] = { + "status": "unidentified", + "value": None, + "reason": reason, + } + + outcome: Literal["completed", "partial", "failed"] = ( + "completed" if len(failed_list) == 0 else "partial" + ) + reason_hdr = ( + None + if outcome == "completed" + else f"retained_{len(failed_list)}_failed_forward_samples" + ) + bindings = { + "source": {"id": proto_id, "sha256": result.protocol_sha256}, + "schema": { + "id": "solarlab.experiment-result.v1", + "sha256": hashlib.sha256(b"solarlab.experiment-result.v1").hexdigest(), + }, + "registry": { + "id": experiment_id, + "sha256": hashlib.sha256(experiment_id.encode()).hexdigest(), + }, + "physics": {"id": proto_id, "sha256": result.protocol_sha256}, + "protocol": {"id": proto_id, "sha256": result.protocol_sha256}, + "initial": {"id": "truth_or_reference_log10", "sha256": result.protocol_sha256}, + "numerics": {"id": "scipy_least_squares_trf", "sha256": result.mapping_sha256}, + "resources": {"id": "synthetic_or_bound_observables", "sha256": result.mapping_sha256}, + } + payload: dict[str, Any] = { + "parameter_names": list(param_names), + "observed_values": encode_array(np.asarray(result.observed_values, dtype=np.float64), unit="1"), + "weighted_jacobian": encode_array( + np.asarray(result.weighted_jacobian, dtype=np.float64), unit="1" + ), + "fisher_information": encode_array( + np.asarray(result.fisher_information, dtype=np.float64), unit="1" + ), + "singular_values": encode_array( + np.asarray(result.singular_values, dtype=np.float64), unit="1" + ), + "confounded_parameter_groups": [list(g) for g in confounded], + "failed_samples": [_json_ready(rec) for rec in failed_list], + "parameters_identifiable": bool(result.parameters_identifiable), + "analysis_certified": bool(result.analysis_certified), + "mapping_sha256": result.mapping_sha256, + } + doc: dict[str, Any] = { + "schema": "solarlab.experiment-result.v1", + "header": { + "run_id": run_id, + "attempt_id": attempt_id, + "experiment_id": experiment_id, + "engine": "solarlab", + "manifest_sha256": result.mapping_sha256, + "outcome": outcome, + "reason": reason_hdr, + "bindings": bindings, + "evidence": [ + { + "label": evidence_label, + "scope": [experiment_id], + "sources": ( + [] + if evidence_label in {"PARKED", "FIRST_SLICE"} + else [{"id": proto_id, "sha256": result.mapping_sha256}] + ), + "limitations": [ + "identifiability_certification_never_claims_confounded_parameters_are_identifiable" + ], + } + ], + }, + "payload_schema": "solarlab.identifiability-payload.v1", + "payload": payload, + "metrics": metrics, + } + return ExperimentResult.from_document(doc) + + +__all__ = [ + "FailedSampleRecord", + "GenericIdentifiabilityParameter", + "GenericIdentifiabilityProtocol", + "GenericIdentifiabilityResult", + "IdentifiabilityError", + "IdentifiabilityFitAttempt", + "IdentifiabilityForwardError", + "IdentifiabilityParameter", + "IdentifiabilityProfile", + "InterfaceCarrierCondition", + "InterfaceSRHIdentifiabilityProtocol", + "InterfaceSRHIdentifiabilityResult", + "OBSERVABLE_FAMILIES", + "PARAMETER_NAMES", + "build_interface_srh_identifiability_protocol", + "collinearity_index", + "confounded_parameter_groups", + "identifiability_to_experiment_result", + "run_interface_srh_identifiability", + "run_protocol_identifiability", + "subset_collinearity_indices", +] diff --git a/src/solarlab/experiments/solarscale.py b/src/solarlab/experiments/solarscale.py new file mode 100644 index 00000000..61dc9b56 --- /dev/null +++ b/src/solarlab/experiments/solarscale.py @@ -0,0 +1,2324 @@ +"""SolarScale MaterialRecord screening, sweep expansion, and native 1D evaluation. + +Ports the SolarScale -> SolarLab material-screening policy onto ``solarlab``'s +canonical configuration, device compilation, and steady 1D solver stack with: +- strict provenance-backed DFT/MD property filtering (rejecting ``missing`` or + ``swept`` provenance as fixed absorber inputs), +- deterministic import plans, generated YAML manifests, and multi-axis sweep + manifest expansion with canonical SHA-256 digests, +- native 1D execution via :func:`import_standard_device`, :func:`resolve_device`, + :func:`compile_device_1d` (with exact defect-free interface SRV local + tangents), and :func:`solve_steady_state` (or :func:`compile_ionic_device_1d` + + :func:`solve_ionic_steady_state` for single-domain ionic stacks), +- explicit per-candidate failure retention without silent physics fallbacks. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterator, Mapping, Sequence +import copy +import csv +from dataclasses import dataclass, field +from datetime import UTC, datetime +import hashlib +import itertools +import json +import math +from pathlib import Path +import re +import subprocess +from typing import Any, Literal + +import numpy as np +from numpy.typing import NDArray +import yaml + +from solarlab.config.device_import import import_standard_device +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import CapabilityError, CompiledDevice1D, compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import State1D +from solarlab.equations.ionic_1d import IonicState1D +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.physics.recombination.bulk import RecombinationRate +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + SteadyStateError, + solve_steady_state, +) + +BOLTZMANN_CONSTANT_J_K = 1.380649e-23 + +__all__ = [ + "CandidatePlan", + "DEFAULT_SWEEP_GRID", + "DEFAULT_SWEEP_POLICY", + "DEVICE_SWEEP_PROPERTY_MAP", + "DefectFreeInterfaceSRVModel1D", + "ImportPolicy", + "MAPPED_PROPERTY_SPECS", + "MaterialProperty", + "MaterialRecord", + "OPTIONAL_PHYSICAL_INPUTS", + "PropertyProvenance", + "REQUIRED_PHYSICAL_INPUTS", + "SCORE_FIELDS", + "SWEEP_DIMENSION_ORDER", + "SWEEP_POLICIES", + "SolarScaleJVMetrics", + "SolarScaleJVResult", + "SweepPolicyName", + "advance_electronic_steady_1d", + "compile_solarscale_electronic_1d", + "compute_solarscale_jv_metrics", + "expand_sweep_manifest", + "generate_solarlab_inputs", + "load_material_records", + "manifest_sha256", + "parse_material_records", + "plan_solarlab_import", + "prepare_solarscale_device", + "run_smoke_device_results", + "run_smoke_jv", + "solarscale_default_catalog", + "solve_solarscale_jv_1d", + "write_device_results", +] + +ImportPolicy = Literal["production", "exploratory"] +SweepPolicyName = Literal["quick", "exploratory", "production"] +SWEEP_DIMENSION_ORDER = ( + "absorber.thickness", + "absorber.tau_n", + "absorber.tau_p", + "absorber.trap_N_t_bulk", + "device.interfaces", +) + +_J_ZERO_FRACTION_OF_JSC = 1.0e-3 +_VOLATILE_MANIFEST_KEYS = frozenset({"timestamp", "git_commit"}) + + +@dataclass(frozen=True) +class PropertyProvenance: + kind: str = "missing" + source: str = "not_available" + notes: str = "" + + +@dataclass(frozen=True) +class MaterialProperty: + value: Any + unit: str = "" + provenance: PropertyProvenance = field(default_factory=PropertyProvenance) + + +@dataclass(frozen=True) +class MaterialRecord: + material_id: str + formula: str | None = None + schema_version: str | None = None + properties: dict[str, MaterialProperty] = field(default_factory=dict) + screening: dict[str, Any] = field(default_factory=dict) + stages: dict[str, Any] = field(default_factory=dict) + source: dict[str, Any] = field(default_factory=dict) + notes: list[str] = field(default_factory=list) + + +@dataclass(frozen=True) +class CandidatePlan: + material_id: str + rank: int + selected: bool + reason: str + readiness: str + ranking_score: float | None + ranking_score_source: str | None + ml_pv_score: float | None + final_fom_score: float | None + screening_evidence: dict[str, Any] + mapped_parameters: dict[str, Any] + material_metadata: dict[str, Any] + sweep_parameters: dict[str, Any] + missing_required: list[str] + missing_optional: list[str] + assumed_parameters: dict[str, Any] + diagnostics: list[str] + config: dict[str, Any] | None = None + config_path: str | None = None + + +@dataclass(frozen=True) +class SolarScaleJVMetrics: + """Photovoltaic metrics in the J_sc-positive 1D convention.""" + + V_oc: float + J_sc: float + FF: float + PCE: float + voc_bracketed: bool + + +@dataclass(frozen=True) +class SolarScaleJVResult: + """Forward/reverse 1D steady screening J-V result.""" + + V_fwd: NDArray[np.float64] + J_fwd: NDArray[np.float64] + V_rev: NDArray[np.float64] + J_rev: NDArray[np.float64] + metrics_fwd: SolarScaleJVMetrics + metrics_rev: SolarScaleJVMetrics + hysteresis_index: float + compiled_identity: str + scientific_qualification: bool = False + + +SWEEP_POLICIES: dict[SweepPolicyName, dict[str, list[float]]] = { + "quick": { + "absorber.thickness": [300.0e-9], + "absorber.tau_n": [1.0e-7], + "absorber.tau_p": [1.0e-7], + "absorber.trap_N_t_bulk": [1.0e22], + "device.interfaces": [1.0], + }, + "exploratory": { + "absorber.thickness": [300.0e-9, 500.0e-9, 800.0e-9], + "absorber.tau_n": [1.0e-9, 1.0e-7, 1.0e-6], + "absorber.tau_p": [1.0e-9, 1.0e-7, 1.0e-6], + "absorber.trap_N_t_bulk": [1.0e20, 1.0e22, 1.0e24], + "device.interfaces": [0.0, 1.0, 10.0], + }, + "production": { + "absorber.thickness": [400.0e-9, 600.0e-9], + "absorber.tau_n": [1.0e-8, 1.0e-7], + "absorber.tau_p": [1.0e-8, 1.0e-7], + "absorber.trap_N_t_bulk": [1.0e21, 1.0e22], + "device.interfaces": [0.1, 1.0], + }, +} +DEFAULT_SWEEP_POLICY: SweepPolicyName = "quick" +DEFAULT_SWEEP_GRID = SWEEP_POLICIES[DEFAULT_SWEEP_POLICY] + +DEVICE_SWEEP_PROPERTY_MAP: dict[str, str] = { + "absorber_thickness_m": "absorber.thickness", + "carrier_lifetime_s": "absorber.tau_n/tau_p", + "trap_density_m3": "absorber.trap_N_t_bulk", + "surface_recombination_velocity_m_s": "device.interfaces", + "contact_work_function_ev": "device.contact_work_function", +} + +MAPPED_PROPERTY_SPECS: dict[str, tuple[str, str | None, float]] = { + "dielectric_static_avg": ("absorber.eps_r", "eps_r", 1.0), + "electron_affinity_ev": ("absorber.chi", "chi", 1.0), + "electron_mobility_cm2_v_s": ("absorber.mu_n", "mu_n", 1.0e-4), + "hole_mobility_cm2_v_s": ("absorber.mu_p", "mu_p", 1.0e-4), + "ion_diffusion_coefficient_m2_s": ("absorber.D_ion", "D_ion", 1.0), + "ion_activation_energy_ev": ("absorber.E_a_ion", "E_a_ion", 1.0), +} + +REQUIRED_PHYSICAL_INPUTS = ( + "band_gap_hse_ev", + "dielectric_static_avg", +) + +OPTIONAL_PHYSICAL_INPUTS = ( + "electron_affinity_ev", + "electron_mobility_cm2_v_s", + "hole_mobility_cm2_v_s", + "ion_diffusion_coefficient_m2_s", + "ion_activation_energy_ev", +) + +SCORE_FIELDS = ("final_fom_score", "ml_pv_score") + +_ALLOWED_READINESS: dict[ImportPolicy, set[str]] = { + "production": {"promising"}, + "exploratory": {"phonon", "promising"}, +} + +_READY_FLAG_BY_POLICY: dict[ImportPolicy, str] = { + "production": "solarlab_production_ready", + "exploratory": "solarlab_provisional_ready", +} + + +@dataclass +class DefectFreeInterfaceSRVModel1D: + """Exact node-local 1D recombination model for defect-free ``[v_n, v_p]`` interfaces.""" + + interface_nodes: tuple[int, ...] + electron_velocities_m_s: tuple[float, ...] + hole_velocities_m_s: tuple[float, ...] + ni_sq_m6: tuple[float, ...] + n1_m3: tuple[float, ...] + p1_m3: tuple[float, ...] + cell_widths_m: tuple[float, ...] + node_count: int + model_id: str + + @classmethod + def from_interfaces( + cls, + base_device: CompiledDevice1D, + electrical_srv_pairs: Sequence[tuple[float, float]], + ) -> DefectFreeInterfaceSRVModel1D | None: + if not electrical_srv_pairs: + return None + thicknesses = [ + float(layer.thickness_m) for layer in base_device.parameters.layers + ] + if len(electrical_srv_pairs) != max(0, len(thicknesses) - 1): + raise ValueError("electrical_srv_pairs must align with internal electrical interfaces") + nodes = base_device.geometry.nodes_m + boundaries: NDArray[np.float64] = np.cumsum(np.asarray(thicknesses, dtype=np.float64))[:-1] + coeffs = base_device.recombination.coefficients + active_nodes: list[int] = [] + v_n_list: list[float] = [] + v_p_list: list[float] = [] + ni_sq_list: list[float] = [] + n1_list: list[float] = [] + p1_list: list[float] = [] + dx_list: list[float] = [] + for (v_n, v_p), x_iface in zip(electrical_srv_pairs, boundaries, strict=True): + if v_n < 0.0 or v_p < 0.0 or not (math.isfinite(v_n) and math.isfinite(v_p)): + raise CapabilityError("interface SRV must be finite and non-negative") + if v_n == 0.0 and v_p == 0.0: + continue + if v_n <= 0.0 or v_p <= 0.0: + # One zero velocity yields infinite denominator => zero SRH rate + continue + idx = int(np.argmin(np.abs(nodes - float(x_iface)))) + active_nodes.append(idx) + v_n_list.append(float(v_n)) + v_p_list.append(float(v_p)) + ni_sq_list.append(float(coeffs.ni_sq_m6[idx])) + n1_list.append(float(coeffs.n1_m3[idx])) + p1_list.append(float(coeffs.p1_m3[idx])) + dx_list.append(float(base_device.geometry.cell_measures_m[idx])) + if not active_nodes: + return None + payload = json.dumps( + { + "kind": "defect_free_interface_srv_1d_v1", + "nodes": active_nodes, + "v_n": v_n_list, + "v_p": v_p_list, + "ni_sq": ni_sq_list, + "n1": n1_list, + "p1": p1_list, + "dx": dx_list, + }, + sort_keys=True, + separators=(",", ":"), + ) + digest = hashlib.sha256(payload.encode("utf-8")).hexdigest() + return cls( + interface_nodes=tuple(active_nodes), + electron_velocities_m_s=tuple(v_n_list), + hole_velocities_m_s=tuple(v_p_list), + ni_sq_m6=tuple(ni_sq_list), + n1_m3=tuple(n1_list), + p1_m3=tuple(p1_list), + cell_widths_m=tuple(dx_list), + node_count=int(nodes.size), + model_id=f"defect_free_interface_srv_1d_v1:{digest}", + ) + + def evaluate(self, n: NDArray[np.float64], p: NDArray[np.float64]) -> RecombinationRate: + rate: NDArray[np.float64] = np.zeros(self.node_count, dtype=np.float64) + dn: NDArray[np.float64] = np.zeros(self.node_count, dtype=np.float64) + dp: NDArray[np.float64] = np.zeros(self.node_count, dtype=np.float64) + for idx, v_n, v_p, ni_sq, n1, p1, dx in zip( + self.interface_nodes, + self.electron_velocities_m_s, + self.hole_velocities_m_s, + self.ni_sq_m6, + self.n1_m3, + self.p1_m3, + self.cell_widths_m, + strict=True, + ): + n_i = float(n[idx]) + p_i = float(p[idx]) + denom = (n_i + n1) / v_p + (p_i + p1) / v_n + numer = n_i * p_i - ni_sq + inv_denom = 1.0 / denom + r_surf = numer * inv_denom + dr_dn = (p_i * denom - numer / v_p) * inv_denom * inv_denom + dr_dp = (n_i * denom - numer / v_n) * inv_denom * inv_denom + inv_dx = 1.0 / dx + rate[idx] += r_surf * inv_dx + dn[idx] += dr_dn * inv_dx + dp[idx] += dr_dp * inv_dx + return RecombinationRate(rate=rate, d_rate_dn=dn, d_rate_dp=dp) + + +def solarscale_default_catalog() -> DefaultCatalog: + """Return the explicit SI ``DefaultCatalog`` for SolarScale 1D screening.""" + vt_300 = BOLTZMANN_CONSTANT_J_K * 300.0 / ELEMENTARY_CHARGE_C + ni_default = 1.0e25 * math.exp(-1.6 / (2.0 * vt_300)) + catalog_doc: dict[str, Any] = { + "schema": "solarlab.default-catalog.v1", + "material": { + "eps_r": 25.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_default, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_default, + "p1": ni_default, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "N_A": 0.0, + "N_D": 0.0, + "chi": 0.0, + "Eg": 0.0, + "A_star_n": 1.2017e6, + "A_star_p": 1.2017e6, + "v_th": 1.0e5, + "D_ion_neg": 0.0, + "P0_neg": 0.0, + "P_lim_neg": 1.0e30, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "carrier_statistics": "maxwell_boltzmann", + "dopant_ionization_model": "fully_ionized", + "donor_binding_energy_eV": None, + "acceptor_binding_energy_eV": None, + "donor_degeneracy": 2.0, + "acceptor_degeneracy": 4.0, + "band_gap_narrowing_model": "off", + "bgn_reference_energy_eV": 0.009, + "bgn_reference_density_m3": 1.0e23, + "bgn_log_shape": 0.5, + "bgn_conduction_band_fraction": 0.5, + "mu_T_gamma": -1.5, + "E_a_ion": 0.58, + "B_rad_T_gamma": 0.0, + "varshni_alpha": 0.0, + "varshni_beta": 0.0, + "trap_N_t_interface": None, + "trap_N_t_bulk": None, + "trap_decay_length": None, + "trap_profile_shape": "exponential", + "trap_edge": "both", + "optical_material": None, + "n_optical": None, + "incoherent": False, + "v_sat_n": 0.0, + "v_sat_p": 0.0, + "ct_beta_n": 2.0, + "ct_beta_p": 2.0, + "pf_gamma_n": 0.0, + "pf_gamma_p": 0.0, + "Eg_back": None, + "chi_back": None, + "grading_profile": "linear", + "grading_direction": "front_to_back", + "grading_bowing": 0.0, + "grading_char_length": None, + "grading_N_mult": 1, + "N_A_bulk": None, + "N_D_bulk": None, + "doping_profile_shape": None, + "doping_decay_length": None, + "doping_edge": "front", + }, + "device": { + "phi_left": 0.0, + "V_bi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "work_function_left_eV": None, + "work_function_right_eV": None, + "Phi": 2.5e21, + "T": 300.0, + "mode": "fast", + "interface_plane_projection": False, + "dos_band_potentials": True, + "te_physical_norm": False, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "flat_band_contacts": False, + "flat_band_metal_contacts": False, + "contact_phi_B_eV": 0.0, + "interface_two_sided": False, + "interface_shared_occupancy": False, + "interface_plane_closure": False, + "interface_plane_generation": False, + "het_recomb_despike": 0.0, + "band_grading": False, + "graded_optics": False, + "interface_tunneling": False, + "tunnel_mass_eff": 0.2, + "jv_solver_policy": "general", + "interface_charge_closure": "off", + "interface_charge_rebaseline_acknowledged": False, + }, + "scaps": { + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + }, + "interface": { + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0, + }, + "constants": { + "Q": ELEMENTARY_CHARGE_C, + "K_B": BOLTZMANN_CONSTANT_J_K, + "T": 300.0, + }, + "contacts": { + "S_n_left": None, + "S_p_left": None, + "S_n_right": None, + "S_p_right": None, + }, + "structural": { + "grain_boundary_layer_role": "absorber", + "tandem_light_direction": "top_first", + "junction_incoherent": False, + }, + "defect_model": "effective_lifetime", + "defect_schema_version": None, + "defect_degeneracy": 1.0, + "distribution_width_convention": "not_applicable", + } + evidence_sha = hashlib.sha256( + json.dumps(catalog_doc, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + catalog_doc["evidence"] = [["solarscale_screening_defaults_v1", evidence_sha]] + return DefaultCatalog.from_mapping(catalog_doc) + + +def manifest_sha256(manifest: Mapping[str, Any], *, ignore_volatile: bool = True) -> str: + """Compute a canonical SHA-256 digest for a SolarScale plan, sweep, or result manifest.""" + + def _strip(obj: Any) -> Any: + if isinstance(obj, Mapping): + return { + str(k): _strip(v) + for k, v in obj.items() + if not (ignore_volatile and str(k) in _VOLATILE_MANIFEST_KEYS) + } + if isinstance(obj, list): + return [_strip(item) for item in obj] + if isinstance(obj, tuple): + return [_strip(item) for item in obj] + return obj + + cleaned = _strip(manifest) + canonical = json.dumps(cleaned, sort_keys=True, separators=(",", ":"), allow_nan=False) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def prepare_solarscale_device( + config_or_path: str | Path | Mapping[str, Any], + *, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> tuple[PreparedDevice, tuple[tuple[float, float], ...]]: + """Resolve a SolarScale YAML config into a ``PreparedDevice`` and defect-free SRVs. + + Strips only SolarScale envelope metadata (``source``, ``notes``) and inactive + sweep placeholders (``trap_N_t_bulk`` when ``trap_N_t_interface`` and + ``trap_decay_length`` are both absent; ``D_ion`` when ``P0 == 0``) while + binding the original YAML bytes as an immutable ``SourceDocument``. + """ + catalog = solarscale_default_catalog() if defaults is None else defaults + res_lib = ResourceLibrary() if resources is None else resources + if isinstance(config_or_path, (str, Path)): + cfg_path = Path(config_or_path) + raw_bytes = cfg_path.read_bytes() + raw_doc = yaml.safe_load(raw_bytes.decode("utf-8")) or {} + source_id = f"solarscale:{cfg_path.name}" + elif isinstance(config_or_path, Mapping): + raw_doc = copy.deepcopy(dict(config_or_path)) + raw_bytes = yaml.safe_dump(raw_doc, sort_keys=False).encode("utf-8") + source_id = "solarscale:inline_config" + else: + raise TypeError("config_or_path must be a path or mapping") + + if not isinstance(raw_doc, Mapping) or "device" not in raw_doc or "layers" not in raw_doc: + raise ValueError("SolarScale config must contain 'device' and 'layers'") + + doc = copy.deepcopy(dict(raw_doc)) + source_meta = doc.pop("source", None) + doc.pop("notes", None) + sim_hints = doc.get("simulation_hints") + if isinstance(sim_hints, Mapping): + cleaned_hints = { + k: v + for k, v in sim_hints.items() + if k not in {"N_grid", "n_points", "v_rate", "V_max", "notes"} + } + if cleaned_hints: + doc["simulation_hints"] = cleaned_hints + else: + doc.pop("simulation_hints", None) + + layers = doc.get("layers") + if not isinstance(layers, list): + raise ValueError("SolarScale config layers must be a list") + + elec_indices = [ + i for i, layer in enumerate(layers) if isinstance(layer, Mapping) and layer.get("role") != "substrate" + ] + dev_block = doc.get("device") + optical_model = ( + str(dev_block.get("optical_model") or "beer_lambert") + if isinstance(dev_block, Mapping) + else "beer_lambert" + ) + for layer in layers: + if not isinstance(layer, dict): + continue + # Under Beer-Lambert optics without supplied n/k tables, optical_material is + # inactive provenance metadata (preserved verbatim in raw_source). + if optical_model == "beer_lambert" and resources is None: + layer.pop("optical_material", None) + # When spatial trap profile is not configured (interface + decay length absent), + # trap_N_t_bulk is inactive sweep metadata in SolarScale templates. + if layer.get("trap_N_t_interface") is None and layer.get("trap_decay_length") is None: + layer.pop("trap_N_t_bulk", None) + layer.pop("trap_profile_shape", None) + # On ion-free layers (P0 == 0), D_ion has zero physical population to transport. + p0_val = float(layer.get("P0", 0.0) or 0.0) + p0_neg_val = float(layer.get("P0_neg", 0.0) or 0.0) + if p0_val == 0.0 and p0_neg_val == 0.0: + if "D_ion" in layer and float(layer["D_ion"] or 0.0) != 0.0: + layer["D_ion"] = 0.0 + + electrical_srvs: list[tuple[float, float]] = [] + if isinstance(dev_block, dict): + has_defects = bool(dev_block.get("interface_defects")) + raw_ifaces = dev_block.get("interfaces") + if not has_defects and isinstance(raw_ifaces, list) and len(elec_indices) >= 2: + # Extract defect-free electrical interface SRVs aligned with full-stack slots + first_elec = elec_indices[0] + n_elec_ifaces = len(elec_indices) - 1 + all_pairs: list[tuple[float, float]] = [] + for k in range(max(0, len(layers) - 1)): + if k < len(raw_ifaces) and isinstance(raw_ifaces[k], (list, tuple)) and len(raw_ifaces[k]) == 2: + all_pairs.append((float(raw_ifaces[k][0]), float(raw_ifaces[k][1]))) + else: + all_pairs.append((0.0, 0.0)) + electrical_srvs = all_pairs[first_elec : first_elec + n_elec_ifaces] + dev_block["interfaces"] = [[0.0, 0.0] for _ in range(max(0, len(layers) - 1))] + + mat_id = ( + str(source_meta.get("material_id")) + if isinstance(source_meta, Mapping) and source_meta.get("material_id") + else "solarscale_device" + ) + dev_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", mat_id).strip("_") or "solarscale_device" + normalized_yaml = yaml.safe_dump(doc, sort_keys=False).encode("utf-8") + norm_source = SourceDocument(f"{source_id}:standard", normalized_yaml) + raw_source = SourceDocument(source_id, raw_bytes) + device_input = import_standard_device(norm_source, id=dev_id, defaults=catalog) + prepared = resolve_device( + device_input, + catalog, + res_lib, + sources=(norm_source, raw_source), + ) + return prepared, tuple(electrical_srvs) + + +def compute_solarscale_jv_metrics( + voltages_V: NDArray[np.float64], + output_current_A_m2: NDArray[np.float64], + *, + incident_power_W_m2: float = 1000.0, + voc_ceiling_V: float | None = None, +) -> SolarScaleJVMetrics: + """Compute sampled ``(V_oc, J_sc, FF, PCE, voc_bracketed)`` metrics.""" + v = np.asarray(voltages_V, dtype=np.float64) + j = np.asarray(output_current_A_m2, dtype=np.float64) + if v.ndim != 1 or j.ndim != 1 or v.shape != j.shape or v.size < 2: + raise ValueError("V and J must be 1D arrays of equal length >= 2") + if not (np.all(np.isfinite(v)) and np.all(np.isfinite(j))): + raise ValueError("J-V metrics require finite voltage and current samples") + order = np.argsort(v) + v_s = v[order] + j_s = j[order] + j_sc = float(np.interp(0.0, v_s, j_s)) + j_tol = _J_ZERO_FRACTION_OF_JSC * abs(j_sc) + crossings = np.where((j_s[:-1] > j_tol) & (j_s[1:] <= j_tol))[0] + if crossings.size == 0: + return SolarScaleJVMetrics(V_oc=0.0, J_sc=j_sc, FF=0.0, PCE=0.0, voc_bracketed=False) + idx = int(crossings[0]) + dv = float(v_s[idx + 1] - v_s[idx]) + dj = float(j_s[idx + 1] - j_s[idx]) + v_oc = float(v_s[idx] - j_s[idx] * dv / dj) if dj != 0.0 else float(v_s[idx]) + v_oc = min(max(v_oc, float(v_s[idx])), float(v_s[idx + 1])) + if voc_ceiling_V is not None and v_oc > voc_ceiling_V: + return SolarScaleJVMetrics(V_oc=0.0, J_sc=j_sc, FF=0.0, PCE=0.0, voc_bracketed=False) + mask = (v_s >= 0.0) & (v_s <= v_oc) + op_power = v_s[mask] * j_s[mask] + p_mpp = float(np.max(op_power)) if op_power.size else 0.0 + ff = p_mpp / (v_oc * j_sc) if (v_oc * j_sc) > 0.0 else 0.0 + pce = p_mpp / incident_power_W_m2 if incident_power_W_m2 > 0.0 else 0.0 + return SolarScaleJVMetrics(V_oc=v_oc, J_sc=j_sc, FF=ff, PCE=pce, voc_bracketed=True) + + +def _intervals_for_n_grid(prepared: PreparedDevice, n_grid: int) -> int | tuple[int, ...]: + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + n_elec = max(1, len(elec_layers)) + data = prepared.to_mapping() + if data["electrical_grid"]: + return max(2, int(round(float(n_grid) / n_elec))) + per_layer = max(2, int(n_grid) // n_elec) + return (per_layer,) * n_elec + + +def compile_solarscale_electronic_1d( + config_or_path: str | Path | Mapping[str, Any], + *, + N_grid: int = 20, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> tuple[PreparedDevice, CompiledDevice1D]: + """Compile an ion-free 1D SolarScale config into a ``CompiledDevice1D``.""" + prepared, electrical_srvs = prepare_solarscale_device( + config_or_path, defaults=defaults, resources=resources + ) + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + ion_layers = [ + layer.id + for layer in elec_layers + if float(dict(layer.parameters)["P0"] or 0.0) > 0.0 + or float(dict(layer.parameters)["P0_neg"] or 0.0) > 0.0 + ] + if ion_layers: + raise CapabilityError( + "electronic_only_1d_refused_mobile_ions: config declares mobile ions and cannot use carrier-only 1D compile" + ) + intervals = _intervals_for_n_grid(prepared, int(N_grid)) + base_dev = compile_device_1d(prepared, intervals_per_layer=intervals) + srv_model = DefectFreeInterfaceSRVModel1D.from_interfaces(base_dev, electrical_srvs) + device = ( + compile_device_1d( + prepared, + intervals_per_layer=intervals, + additional_recombination=srv_model, + ) + if srv_model is not None + else base_dev + ) + return prepared, device + + +def advance_electronic_steady_1d( + device: CompiledDevice1D, + seed: State1D, + v_target: float, + *, + generation_scale: float, + options: SteadyOptions, + initial_step_V: float = 0.025, + min_step_V: float = 0.0125, +) -> SteadyState1D: + """Advance an electronic 1D steady state to ``v_target`` with adaptive bias halving.""" + cur_state = seed + cur_v = float(seed.voltage_V) + active_opts = options + if cur_v == v_target: + return solve_steady_state( + device, + initial_state=cur_state, + voltage_V=v_target, + generation_scale=generation_scale, + options=active_opts, + ) + step = min(initial_step_V, abs(v_target - cur_v)) + last_sol: SteadyState1D | None = None + while True: + rem = v_target - cur_v + if abs(rem) <= 1.0e-14: + assert last_sol is not None + return last_sol + d_try = math.copysign(min(step, abs(rem)), rem) + v_try = v_target if abs(d_try) >= abs(rem) - 1.0e-14 else cur_v + d_try + try: + sol = solve_steady_state( + device, + initial_state=cur_state, + voltage_V=v_try, + generation_scale=generation_scale, + options=active_opts, + ) + except SteadyStateError: + if step > min_step_V: + step = max(min_step_V, 0.5 * step) + continue + if v_try > 1.0 and active_opts.continuity_tolerance_A_m2 < 1.0e-5: + active_opts = SteadyOptions( + poisson_tolerance=max(active_opts.poisson_tolerance, 1.0e-9), + continuity_tolerance_A_m2=1.0e-5, + current_spread_tolerance_A_m2=1.0e-5, + max_iterations=active_opts.max_iterations, + max_bias_step_V=active_opts.max_bias_step_V, + ) + sol = solve_steady_state( + device, + initial_state=cur_state, + voltage_V=v_try, + generation_scale=generation_scale, + options=active_opts, + ) + step = initial_step_V + else: + raise + cur_state = sol.state + cur_v = v_try + last_sol = sol + if v_try == v_target: + return sol + step = min(initial_step_V, step * 1.5) + + +def solve_solarscale_jv_1d( + config_or_path: str | Path | Mapping[str, Any], + *, + N_grid: int = 12, + n_points: int = 4, + v_rate: float = 5.0, + V_max: float = 0.2, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> SolarScaleJVResult: + """Compile and solve a 1D SolarScale J-V sweep natively in ``solarlab``.""" + _ = v_rate + if int(n_points) < 2: + raise ValueError("n_points must be >= 2") + if not math.isfinite(V_max) or V_max <= 0.0: + raise ValueError("V_max must be finite and positive") + + prepared, electrical_srvs = prepare_solarscale_device( + config_or_path, defaults=defaults, resources=resources + ) + intervals = _intervals_for_n_grid(prepared, int(N_grid)) + voltages_fwd: NDArray[np.float64] = np.linspace(0.0, float(V_max), int(n_points), dtype=np.float64) + + elec_layers = [layer for layer in prepared.layers if layer.role != "substrate"] + ion_layers = [ + layer.id + for layer in elec_layers + if float(dict(layer.parameters)["P0"] or 0.0) > 0.0 + or float(dict(layer.parameters)["P0_neg"] or 0.0) > 0.0 + ] + + if ion_layers: + if any(v_n != 0.0 or v_p != 0.0 for v_n, v_p in electrical_srvs): + raise CapabilityError( + "ionic_interface_srv_1d_unbound: nonzero interface SRV with mobile ions is not bound in 1D steady screening" + ) + if len(ion_layers) != 1: + raise CapabilityError("multiple_ion_domains_1d_unbound: SolarScale 1D screening supports one ion domain") + ionic_dev = compile_ionic_device_1d( + prepared, + intervals_per_layer=intervals, + ion_domain_layer=ion_layers[0], + ion_domain_endpoints=("blocking", "blocking"), + ) + ion_opts = IonicSteadyOptions( + SteadyOptions(), + 1.0e-11, + 1.0e6, + 1.0e6, + 1.0, + ionic_dev.ion_node_count - 1, + SolveBudget(65, 650, 65, 24), + 30.0, + ) + polarity = float(ionic_dev.electronic_component.voltage_polarity) + j_out_list: list[float] = [] + prev_ion: IonicState1D | None = None + elec_dim = 3 * ionic_dev.node_count + for idx, v_app in enumerate(voltages_fwd): + v_target = float(v_app) + if prev_ion is None: + seed_ion = ionic_dev.initial_state(voltage_V=v_target) + elif prev_ion.voltage_V == v_target: + seed_ion = prev_ion + else: + u_rebased = prev_ion.u.copy() + u_rebased[:elec_dim] = ionic_dev.electronic_component.rebase_coordinates( + u_rebased[:elec_dim], prev_ion.voltage_V, v_target + ) + seed_ion = ionic_dev.state(u_rebased, voltage_V=v_target) + res_i = solve_ionic_steady_state( + ionic_dev, + voltage_V=v_target, + generation_scale=1.0, + initial_state=seed_ion, + options=ion_opts, + ) + if not res_i.accepted or res_i.state is None or res_i.diagnostics is None: + raise RuntimeError( + f"1D ionic steady J-V point {idx} at V={v_target:.4f} V failed: {res_i.error or res_i.termination}" + ) + prev_ion = res_i.state + tot_cur = np.asarray(res_i.diagnostics["total_current_density_A_m2"], dtype=np.float64) + j_out_list.append(-polarity * float(tot_cur[0])) + j_fwd: NDArray[np.float64] = np.asarray(j_out_list, dtype=np.float64) + compiled_id = ionic_dev.identity + eg_ceiling = float(np.min(ionic_dev.electronic_component.parameters.band_structure.physical_band_gap_eV)) + else: + _, device = compile_solarscale_electronic_1d( + config_or_path, N_grid=int(N_grid), defaults=defaults, resources=resources + ) + polarity = float(device.voltage_polarity) + steady_opts = SteadyOptions(max_iterations=250, max_bias_step_V=0.025) + j_out_list = [] + seed_elec: State1D | None = None + for idx, v_app in enumerate(voltages_fwd): + v_target = float(v_app) + if seed_elec is None: + sol = solve_steady_state( + device, + voltage_V=v_target, + generation_scale=1.0, + options=steady_opts, + ) + else: + sol = advance_electronic_steady_1d( + device, + seed_elec, + v_target, + generation_scale=1.0, + options=steady_opts, + ) + if not sol.converged: + raise RuntimeError(f"1D steady J-V point {idx} at V={v_target:.4f} V failed to converge") + seed_elec = sol.state + j_out_list.append(-polarity * float(sol.current_density_A_m2[0])) + j_fwd = np.asarray(j_out_list, dtype=np.float64) + compiled_id = device.identity + eg_ceiling = float(np.min(device.parameters.band_structure.physical_band_gap_eV)) + + v_rev = voltages_fwd[::-1].copy() + j_rev = j_fwd[::-1].copy() + metrics_fwd = compute_solarscale_jv_metrics(voltages_fwd, j_fwd, voc_ceiling_V=eg_ceiling) + metrics_rev = compute_solarscale_jv_metrics(v_rev, j_rev, voc_ceiling_V=eg_ceiling) + return SolarScaleJVResult( + V_fwd=voltages_fwd, + J_fwd=j_fwd, + V_rev=v_rev, + J_rev=j_rev, + metrics_fwd=metrics_fwd, + metrics_rev=metrics_rev, + hysteresis_index=0.0, + compiled_identity=compiled_id, + scientific_qualification=False, + ) + + +def load_material_records(path: str | Path) -> list[dict[str, Any]]: + """Load raw SolarScale ``MaterialRecord`` dictionaries from JSON.""" + payload = json.loads(Path(path).read_text(encoding="utf-8")) + records = payload.get("records") + if not isinstance(records, list): + raise ValueError("MaterialRecord payload must contain a records list") + return records + + +def parse_material_records(path: str | Path) -> list[MaterialRecord]: + """Load and normalize SolarScale ``MaterialRecord`` JSON.""" + return [_parse_record(record) for record in load_material_records(path)] + + +def plan_solarlab_import( + records_path: str | Path, + *, + template_path: str | Path, + import_policy: ImportPolicy = "exploratory", + limit: int | None = None, + sweep_grid: Mapping[str, list[float]] | None = None, + sweep_policy: SweepPolicyName = DEFAULT_SWEEP_POLICY, + include_configs: bool = True, + activate_bandgap: bool = False, +) -> dict[str, Any]: + """Return a dry-run SolarScale import manifest without writing files.""" + if import_policy not in _ALLOWED_READINESS: + raise ValueError(f"Unknown import_policy {import_policy!r}") + + records = parse_material_records(records_path) + template = _load_yaml(template_path) + if activate_bandgap: + _validate_band_aligned_template(template) + sweeps = _resolve_sweep_grid(sweep_policy=sweep_policy, sweep_grid=sweep_grid) + + candidates = sorted( + ( + _candidate_plan( + record, + template, + sweeps, + import_policy, + activate_bandgap=activate_bandgap, + sweep_policy=sweep_policy, + ) + for record in records + ), + key=_candidate_sort_key, + ) + selected_count = 0 + limited_candidates: list[CandidatePlan] = [] + for rank, candidate in enumerate(candidates, start=1): + candidate = _replace_candidate(candidate, rank=rank) + if candidate.selected: + if limit is not None and selected_count >= limit: + candidate = _replace_candidate( + candidate, + selected=False, + reason="limit reached", + config=None, + ) + else: + selected_count += 1 + if not include_configs: + candidate = _replace_candidate(candidate, config=None) + limited_candidates.append(candidate) + + selected = [candidate for candidate in limited_candidates if candidate.selected] + skipped = [candidate for candidate in limited_candidates if not candidate.selected] + return { + "schema": "solarlab.solarscale_import_plan", + "schema_version": "0.4", + "records_path": str(records_path), + "template_path": str(template_path), + "import_policy": import_policy, + "allowed_readiness": sorted(_ALLOWED_READINESS[import_policy]), + "activate_bandgap": activate_bandgap, + "sweep_policy": sweep_policy, + "sweep_grid": sweeps, + "sweep_dimensions": _sweep_dimensions(sweeps), + "dry_run": True, + "selected_count": len(selected), + "skipped_count": len(skipped), + "summary": _screening_summary(limited_candidates), + "selected": [_candidate_to_dict(candidate) for candidate in selected], + "skipped": [_candidate_to_dict(candidate, include_config=False) for candidate in skipped], + } + + +def generate_solarlab_inputs( + records_path: str | Path, + *, + template_path: str | Path, + out_dir: str | Path, + limit: int | None = None, + sweep_grid: Mapping[str, list[float]] | None = None, + sweep_policy: SweepPolicyName = DEFAULT_SWEEP_POLICY, + import_policy: ImportPolicy = "production", + activate_bandgap: bool = False, +) -> dict[str, Any]: + """Generate SolarLab YAML configs and an import manifest from SolarScale records.""" + plan = plan_solarlab_import( + records_path, + template_path=template_path, + import_policy=import_policy, + limit=limit, + sweep_grid=sweep_grid, + sweep_policy=sweep_policy, + include_configs=True, + activate_bandgap=activate_bandgap, + ) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + + generated: list[dict[str, Any]] = [] + for item in plan["selected"]: + config = item.pop("config") + config_path = out / f"{_safe_name(item['material_id'])}.yaml" + _write_yaml(config_path, config) + item["config_path"] = str(config_path) + generated.append(item) + + manifest: dict[str, Any] = { + "schema": "solarlab.solarscale_import_manifest", + "schema_version": "0.4", + "records_path": plan["records_path"], + "template_path": plan["template_path"], + "out_dir": str(out), + "import_policy": import_policy, + "allowed_readiness": plan["allowed_readiness"], + "activate_bandgap": activate_bandgap, + "sweep_policy": sweep_policy, + "sweep_grid": plan["sweep_grid"], + "sweep_dimensions": plan["sweep_dimensions"], + "summary": plan["summary"], + "generated": generated, + "skipped": plan["skipped"], + } + (out / "manifest.json").write_text( + json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8" + ) + return manifest + + +def expand_sweep_manifest( + manifest: Mapping[str, Any], + *, + out_dir: str | Path | None = None, + max_points: int | None = None, +) -> dict[str, Any]: + """Expand selected candidates into one YAML config per sweep-grid point.""" + if max_points is not None and max_points < 0: + raise ValueError("max_points must be non-negative") + sweeps = _manifest_sweep_grid(manifest) + root = Path(out_dir or manifest.get("out_dir") or ".") + root.mkdir(parents=True, exist_ok=True) + config_dir = root / "sweep_configs" + config_dir.mkdir(parents=True, exist_ok=True) + + generated: list[dict[str, Any]] = [] + stopped_by_limit = False + for candidate in manifest.get("generated", []) or []: + parent_config_path = candidate.get("config_path") + if not parent_config_path: + raise ValueError( + f"Generated candidate {candidate.get('material_id')!r} is missing config_path" + ) + parent_config = _load_yaml(parent_config_path) + material_name = _safe_name(str(candidate.get("material_id", "material"))) + material_dir = config_dir / material_name + material_dir.mkdir(parents=True, exist_ok=True) + for candidate_index, sweep_values in enumerate(_iter_sweep_values(sweeps), start=1): + if max_points is not None and len(generated) >= max_points: + stopped_by_limit = True + break + sweep_point_id = f"{material_name}__sweep_{candidate_index:04d}" + config = copy.deepcopy(parent_config) + _apply_sweep_values( + config, + sweep_values, + sweep_point_id=sweep_point_id, + candidate_sweep_index=candidate_index, + parent_config_path=str(parent_config_path), + ) + config_path = material_dir / f"{sweep_point_id}.yaml" + _write_yaml(config_path, config) + sweep_item = copy.deepcopy(dict(candidate)) + sweep_item.update( + { + "parent_config_path": str(parent_config_path), + "config_path": str(config_path), + "sweep_point_id": sweep_point_id, + "sweep_index": candidate_index, + "global_sweep_index": len(generated) + 1, + "sweep_values": dict(sweep_values), + "sweep_policy": manifest.get("sweep_policy"), + } + ) + generated.append(sweep_item) + if stopped_by_limit: + break + + per_candidate = _sweep_dimensions(sweeps) + total_requested = per_candidate["total_points"] * len(manifest.get("generated", []) or []) + sweep_manifest: dict[str, Any] = { + "schema": "solarlab.solarscale_sweep_manifest", + "schema_version": "0.1", + "parent_schema": manifest.get("schema"), + "parent_schema_version": manifest.get("schema_version"), + "records_path": manifest.get("records_path"), + "template_path": manifest.get("template_path"), + "out_dir": str(root), + "sweep_config_dir": str(config_dir), + "import_policy": manifest.get("import_policy"), + "allowed_readiness": manifest.get("allowed_readiness", []), + "activate_bandgap": manifest.get("activate_bandgap"), + "sweep_policy": manifest.get("sweep_policy"), + "sweep_grid": sweeps, + "sweep_dimensions": { + **per_candidate, + "generated_configs_per_candidate": per_candidate["total_points"], + "candidate_count": len(manifest.get("generated", []) or []), + "total_requested_points": total_requested, + "total_generated_points": len(generated), + "max_points": max_points, + "truncated": stopped_by_limit, + }, + "summary": manifest.get("summary", {}), + "generated": generated, + "skipped": manifest.get("skipped", []), + } + (root / "sweep_plan.json").write_text( + json.dumps(sweep_manifest, indent=2, sort_keys=True), encoding="utf-8" + ) + return sweep_manifest + + +def run_smoke_jv( + config_path: str | Path, + *, + N_grid: int = 12, + n_points: int = 4, + v_rate: float = 5.0, + V_max: float = 0.2, + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> dict[str, Any]: + """Run a native 1D JV smoke check for one generated SolarScale config.""" + result = solve_solarscale_jv_1d( + config_path, + N_grid=N_grid, + n_points=n_points, + v_rate=v_rate, + V_max=V_max, + defaults=defaults, + resources=resources, + ) + return { + "config_path": str(config_path), + "N_grid": N_grid, + "n_points": n_points, + "v_rate": v_rate, + "V_max": V_max, + "metrics_fwd": { + "V_oc": result.metrics_fwd.V_oc, + "J_sc": result.metrics_fwd.J_sc, + "FF": result.metrics_fwd.FF, + "PCE": result.metrics_fwd.PCE, + "voc_bracketed": result.metrics_fwd.voc_bracketed, + }, + "metrics_rev": { + "V_oc": result.metrics_rev.V_oc, + "J_sc": result.metrics_rev.J_sc, + "FF": result.metrics_rev.FF, + "PCE": result.metrics_rev.PCE, + "voc_bracketed": result.metrics_rev.voc_bracketed, + }, + "hysteresis_index": result.hysteresis_index, + } + + +def run_smoke_device_results( + manifest: Mapping[str, Any], + *, + N_grid: int = 12, + n_points: int = 4, + v_rate: float = 5.0, + V_max: float = 0.2, + max_configs: int | None = 1, + result_type: str = "smoke_jv", + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> dict[str, Any]: + """Run native 1D JV smoke checks and return SolarScale-ingestible device results.""" + generated = list(manifest.get("generated", []) or []) + if max_configs is not None: + generated = generated[:max_configs] + timestamp = _utc_timestamp() + git_commit = _git_commit(Path(__file__).resolve()) + records = [ + _device_result_record( + item, + manifest, + timestamp=timestamp, + git_commit=git_commit, + smoke_settings={ + "N_grid": N_grid, + "n_points": n_points, + "v_rate": v_rate, + "V_max": V_max, + }, + defaults=defaults, + resources=resources, + ) + for item in generated + ] + return { + "schema": "solarlab.device_results", + "schema_version": "0.2", + "result_type": result_type, + "timestamp": timestamp, + "git_commit": git_commit, + "records_path": manifest.get("records_path"), + "template_path": manifest.get("template_path"), + "import_policy": manifest.get("import_policy"), + "activate_bandgap": manifest.get("activate_bandgap"), + "sweep_policy": manifest.get("sweep_policy"), + "sweep_dimensions": manifest.get("sweep_dimensions", {}), + "jv_settings": { + "N_grid": N_grid, + "n_points": n_points, + "v_rate": v_rate, + "V_max": V_max, + "max_configs": max_configs, + }, + "smoke_settings": { + "N_grid": N_grid, + "n_points": n_points, + "v_rate": v_rate, + "V_max": V_max, + "max_configs": max_configs, + }, + "records": records, + "summary": _device_results_summary(records), + } + + +def write_device_results( + results: Mapping[str, Any], + *, + json_path: str | Path, + csv_path: str | Path | None = None, +) -> None: + """Write device results as JSON plus an optional flat CSV table.""" + json_out = Path(json_path) + json_out.write_text(json.dumps(results, indent=2, sort_keys=True), encoding="utf-8") + if csv_path is None: + return + csv_out = Path(csv_path) + rows = [_device_result_csv_row(record) for record in results.get("records", []) or []] + fieldnames = [ + "material_id", + "config_path", + "template_path", + "import_policy", + "activate_bandgap", + "sweep_policy", + "sweep_point_id", + "sweep_index", + "global_sweep_index", + "sweep_values_json", + "parent_config_path", + "simulation_status", + "Voc", + "Jsc", + "FF", + "PCE", + "hysteresis_index", + "voc_bracketed_fwd", + "voc_bracketed_rev", + "error_type", + "error_message", + "git_commit", + "timestamp", + ] + with csv_out.open("w", encoding="utf-8", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def _device_result_record( + item: Mapping[str, Any], + manifest: Mapping[str, Any], + *, + timestamp: str, + git_commit: str | None, + smoke_settings: Mapping[str, Any], + defaults: DefaultCatalog | None = None, + resources: ResourceLibrary | None = None, +) -> dict[str, Any]: + warnings = list(item.get("diagnostics", []) or []) + config_path = item.get("config_path") + if not config_path: + return _failed_device_result_record( + item, + manifest, + timestamp=timestamp, + git_commit=git_commit, + smoke_settings=smoke_settings, + error=ValueError("generated manifest item is missing config_path"), + warnings=warnings, + ) + try: + smoke = run_smoke_jv( + config_path, + N_grid=int(smoke_settings["N_grid"]), + n_points=int(smoke_settings["n_points"]), + v_rate=float(smoke_settings["v_rate"]), + V_max=float(smoke_settings["V_max"]), + defaults=defaults, + resources=resources, + ) + except Exception as exc: # noqa: BLE001 + return _failed_device_result_record( + item, + manifest, + timestamp=timestamp, + git_commit=git_commit, + smoke_settings=smoke_settings, + error=exc, + warnings=warnings, + ) + + metrics_fwd = dict(smoke.get("metrics_fwd", {}) or {}) + metrics_rev = dict(smoke.get("metrics_rev", {}) or {}) + if metrics_fwd.get("voc_bracketed") is False: + warnings.append("forward JV did not bracket Voc; increase smoke V_max for physical metrics") + if metrics_rev.get("voc_bracketed") is False: + warnings.append("reverse JV did not bracket Voc; increase smoke V_max for physical metrics") + return { + **_device_result_base( + item, + manifest, + timestamp=timestamp, + git_commit=git_commit, + smoke_settings=smoke_settings, + warnings=warnings, + ), + "simulation_status": "completed", + "JV_metrics": { + "forward": metrics_fwd, + "reverse": metrics_rev, + "hysteresis_index": smoke.get("hysteresis_index"), + }, + "smoke_result": smoke, + "error": None, + } + + +def _failed_device_result_record( + item: Mapping[str, Any], + manifest: Mapping[str, Any], + *, + timestamp: str, + git_commit: str | None, + smoke_settings: Mapping[str, Any], + error: Exception, + warnings: list[str], +) -> dict[str, Any]: + return { + **_device_result_base( + item, + manifest, + timestamp=timestamp, + git_commit=git_commit, + smoke_settings=smoke_settings, + warnings=warnings, + ), + "simulation_status": "failed", + "JV_metrics": { + "forward": None, + "reverse": None, + "hysteresis_index": None, + }, + "smoke_result": None, + "error": { + "error_type": type(error).__name__, + "error_message": str(error), + }, + } + + +def _device_result_base( + item: Mapping[str, Any], + manifest: Mapping[str, Any], + *, + timestamp: str, + git_commit: str | None, + smoke_settings: Mapping[str, Any], + warnings: list[str], +) -> dict[str, Any]: + return { + "material_id": item.get("material_id"), + "config_path": item.get("config_path"), + "template_path": manifest.get("template_path"), + "records_path": manifest.get("records_path"), + "import_policy": manifest.get("import_policy"), + "activate_bandgap": manifest.get("activate_bandgap"), + "sweep_policy": manifest.get("sweep_policy") or item.get("sweep_policy"), + "sweep_point_id": item.get("sweep_point_id"), + "sweep_index": item.get("sweep_index"), + "global_sweep_index": item.get("global_sweep_index"), + "parent_config_path": item.get("parent_config_path"), + "sweep_values": item.get("sweep_values", {}), + "mapped_parameters": item.get("mapped_parameters", {}), + "material_metadata": item.get("material_metadata", {}), + "screening_evidence": item.get("screening_evidence", {}), + "ranking": { + "ranking_score": item.get("ranking_score"), + "ranking_score_source": item.get("ranking_score_source"), + "ml_pv_score": item.get("ml_pv_score"), + "final_fom_score": item.get("final_fom_score"), + }, + "missing_required": item.get("missing_required", []), + "missing_optional": item.get("missing_optional", []), + "sweep_parameters": item.get("sweep_parameters", {}), + "warnings": warnings, + "jv_settings": dict(smoke_settings), + "smoke_settings": dict(smoke_settings), + "git_commit": git_commit, + "timestamp": timestamp, + } + + +def _device_results_summary(records: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + status_counts = Counter(str(record.get("simulation_status", "unknown")) for record in records) + completed = [record for record in records if record.get("simulation_status") == "completed"] + failed = [record for record in records if record.get("simulation_status") == "failed"] + best = sorted( + completed, + key=lambda record: _metric_value(record, "PCE") or float("-inf"), + reverse=True, + ) + return { + "total_records": len(records), + "status_counts": dict(sorted(status_counts.items())), + "failed_materials": [record.get("material_id") for record in failed], + "best_by_pce": [ + { + "material_id": record.get("material_id"), + "sweep_point_id": record.get("sweep_point_id"), + "sweep_index": record.get("sweep_index"), + "PCE": _metric_value(record, "PCE"), + "Voc": _metric_value(record, "V_oc"), + "Jsc": _metric_value(record, "J_sc"), + "FF": _metric_value(record, "FF"), + } + for record in best[:10] + ], + } + + +def _metric_value(record: Mapping[str, Any], field_name: str) -> float | None: + metrics = record.get("JV_metrics", {}) + if not isinstance(metrics, Mapping): + return None + forward = metrics.get("forward") + if not isinstance(forward, Mapping): + return None + value = forward.get(field_name) + return None if value is None else float(value) + + +def _device_result_csv_row(record: Mapping[str, Any]) -> dict[str, Any]: + metrics = record.get("JV_metrics", {}) + forward = metrics.get("forward") if isinstance(metrics, Mapping) else None + reverse = metrics.get("reverse") if isinstance(metrics, Mapping) else None + error = record.get("error") or {} + return { + "material_id": record.get("material_id"), + "config_path": record.get("config_path"), + "template_path": record.get("template_path"), + "import_policy": record.get("import_policy"), + "activate_bandgap": record.get("activate_bandgap"), + "sweep_policy": record.get("sweep_policy"), + "sweep_point_id": record.get("sweep_point_id"), + "sweep_index": record.get("sweep_index"), + "global_sweep_index": record.get("global_sweep_index"), + "sweep_values_json": json.dumps(record.get("sweep_values", {}) or {}, sort_keys=True), + "parent_config_path": record.get("parent_config_path"), + "simulation_status": record.get("simulation_status"), + "Voc": _dict_get(forward, "V_oc"), + "Jsc": _dict_get(forward, "J_sc"), + "FF": _dict_get(forward, "FF"), + "PCE": _dict_get(forward, "PCE"), + "hysteresis_index": _dict_get(metrics, "hysteresis_index"), + "voc_bracketed_fwd": _dict_get(forward, "voc_bracketed"), + "voc_bracketed_rev": _dict_get(reverse, "voc_bracketed"), + "error_type": error.get("error_type"), + "error_message": error.get("error_message"), + "git_commit": record.get("git_commit"), + "timestamp": record.get("timestamp"), + } + + +def _dict_get(value: Any, key: str) -> Any: + if not isinstance(value, Mapping): + return None + return value.get(key) + + +def _utc_timestamp() -> str: + return datetime.now(UTC).isoformat().replace("+00:00", "Z") + + +def _git_commit(anchor: Path) -> str | None: + try: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=anchor if anchor.is_dir() else anchor.parent, + check=True, + text=True, + capture_output=True, + ) + except Exception: # noqa: BLE001 + return None + return result.stdout.strip() or None + + +def _parse_record(record: Mapping[str, Any]) -> MaterialRecord: + material_id = str(record.get("material_id", "")).strip() + properties_raw = record.get("properties", {}) + properties: dict[str, MaterialProperty] = {} + if isinstance(properties_raw, Mapping): + for name, prop in properties_raw.items(): + properties[str(name)] = _parse_property(prop) + notes = record.get("notes", []) + return MaterialRecord( + material_id=material_id, + formula=record.get("formula"), + schema_version=record.get("schema_version"), + properties=properties, + screening=dict(record.get("screening", {}) or {}), + stages=dict(record.get("stages", {}) or {}), + source=dict(record.get("source", {}) or {}), + notes=[str(note) for note in notes] if isinstance(notes, list) else [str(notes)], + ) + + +def _parse_property(prop: Any) -> MaterialProperty: + if not isinstance(prop, Mapping): + return MaterialProperty(value=prop) + provenance = prop.get("provenance", {}) + if not isinstance(provenance, Mapping): + provenance = {} + return MaterialProperty( + value=prop.get("value"), + unit=str(prop.get("unit", "") or ""), + provenance=PropertyProvenance( + kind=str(provenance.get("kind", "missing") or "missing"), + source=str(provenance.get("source", "not_available") or "not_available"), + notes=str(provenance.get("notes", "") or ""), + ), + ) + + +def _resolve_sweep_grid( + *, + sweep_policy: SweepPolicyName, + sweep_grid: Mapping[str, list[float]] | None, +) -> dict[str, list[float]]: + if sweep_policy not in SWEEP_POLICIES: + raise ValueError( + f"Unknown sweep_policy {sweep_policy!r}; expected one of " + + ", ".join(sorted(SWEEP_POLICIES)) + ) + grid = {name: list(values) for name, values in SWEEP_POLICIES[sweep_policy].items()} + if sweep_grid: + for name, values in sweep_grid.items(): + grid[str(name)] = list(values) + _validate_sweep_grid(grid) + return grid + + +def _validate_sweep_grid(grid: Mapping[str, list[float]]) -> None: + required = { + "absorber.thickness", + "absorber.tau_n", + "absorber.tau_p", + "absorber.trap_N_t_bulk", + "device.interfaces", + } + missing = sorted(required - set(grid)) + if missing: + raise ValueError("sweep grid is missing required dimensions: " + ", ".join(missing)) + empty = [name for name, values in grid.items() if not values] + if empty: + raise ValueError("sweep grid dimensions must not be empty: " + ", ".join(sorted(empty))) + + +def _sweep_dimensions(sweeps: Mapping[str, list[float]]) -> dict[str, Any]: + sizes = {name: len(values) for name, values in sweeps.items()} + total = 1 + for size in sizes.values(): + total *= size + return { + "dimensions": sizes, + "total_points": total, + "generated_configs_per_candidate": 1, + "note": ( + "Sweep-grid size per selected candidate. Baseline imports generate one config; " + "expand_sweep_manifest generates the full matrix or a capped subset." + ), + } + + +def _candidate_plan( + record: MaterialRecord, + template: Mapping[str, Any], + sweeps: Mapping[str, list[float]], + import_policy: ImportPolicy, + *, + activate_bandgap: bool, + sweep_policy: SweepPolicyName, +) -> CandidatePlan: + material_id = record.material_id + if not material_id: + return CandidatePlan( + material_id="", + rank=0, + selected=False, + reason="missing material_id", + readiness="", + ranking_score=None, + ranking_score_source=None, + ml_pv_score=None, + final_fom_score=None, + screening_evidence={ + "readiness": None, + "resolved_readiness": "", + "gates": {}, + "thresholds": {}, + "raw_screening": {}, + }, + mapped_parameters={}, + material_metadata={}, + sweep_parameters={}, + missing_required=list(REQUIRED_PHYSICAL_INPUTS), + missing_optional=list(OPTIONAL_PHYSICAL_INPUTS), + assumed_parameters={}, + diagnostics=[], + ) + + readiness = str( + record.screening.get("readiness", "") or _property_value(record, "screening_readiness") or "" + ) + ready, reason = _is_device_ready(record, import_policy=import_policy) + mapped, missing_required, missing_optional, diagnostics = _mapped_parameters( + record, + activate_bandgap=activate_bandgap, + ) + material_metadata = _material_metadata(record) + sweep_parameters = _sweep_parameters(record, sweeps) + assumed = _template_assumptions(template, mapped, sweeps) + ranking_score, ranking_source = _ranking_score(record) + ml_score = _numeric_property(record, "ml_pv_score") + fom_score = _numeric_property(record, "final_fom_score") + screening_evidence = _screening_evidence(record, resolved_readiness=readiness) + selected = ready and not missing_required + if ready and missing_required: + reason = "missing required SolarLab physical inputs: " + ", ".join(missing_required) + + config = None + if selected: + config = _build_config( + template, + record, + mapped, + sweeps, + missing_optional, + diagnostics, + import_policy=import_policy, + activate_bandgap=activate_bandgap, + sweep_policy=sweep_policy, + ) + + return CandidatePlan( + material_id=material_id, + rank=0, + selected=selected, + reason=reason, + readiness=readiness, + ranking_score=ranking_score, + ranking_score_source=ranking_source, + ml_pv_score=ml_score, + final_fom_score=fom_score, + screening_evidence=screening_evidence, + mapped_parameters=mapped, + material_metadata=material_metadata, + sweep_parameters=sweep_parameters, + missing_required=missing_required, + missing_optional=missing_optional, + assumed_parameters=assumed, + diagnostics=diagnostics, + config=config, + ) + + +def _is_device_ready(record: MaterialRecord, *, import_policy: ImportPolicy) -> tuple[bool, str]: + if import_policy not in _ALLOWED_READINESS: + raise ValueError(f"Unknown import_policy {import_policy!r}") + + flag_name = _READY_FLAG_BY_POLICY[import_policy] + flag_value = _property_value(record, flag_name) + if flag_value is None: + flag_value = record.screening.get( + "production_solarlab_ready" + if import_policy == "production" + else "provisional_solarlab_ready" + ) + if flag_value is True: + return True, f"{flag_name}=true" + if import_policy == "production": + return False, f"{flag_name} is not true" + + readiness = str( + record.screening.get("readiness", "") or _property_value(record, "screening_readiness") or "" + ) + if readiness: + if readiness in _ALLOWED_READINESS[import_policy]: + return True, f"screening.readiness={readiness!r}" + return False, f"screening.readiness={readiness!r} not allowed by {import_policy} policy" + + dft_flag = _property_value(record, "dft_result_available") + if import_policy == "exploratory" and dft_flag is True: + return True, "dft_result_available=true" + return False, f"{flag_name} is not true and screening.readiness is unavailable" + + +def _mapped_parameters( + record: MaterialRecord, + *, + activate_bandgap: bool, +) -> tuple[dict[str, Any], list[str], list[str], list[str]]: + mapped: dict[str, Any] = {} + missing_required: list[str] = [] + missing_optional: list[str] = [] + diagnostics: list[str] = [] + + band_gap = record.properties.get("band_gap_hse_ev") + if band_gap is None or band_gap.value is None or band_gap.provenance.kind == "missing": + missing_required.append("band_gap_hse_ev") + elif band_gap.provenance.kind not in {"computed", "derived"}: + missing_required.append("band_gap_hse_ev") + diagnostics.append( + f"band_gap_hse_ev provenance kind {band_gap.provenance.kind!r} is not accepted as a fixed input" + ) + elif activate_bandgap: + mapped["absorber.Eg"] = _coerce_numeric(band_gap.value) + diagnostics.append("band_gap_hse_ev activated as absorber Eg") + else: + diagnostics.append("band_gap_hse_ev kept as metadata; absorber Eg follows the template") + + for prop_name, (target, _field, scale) in MAPPED_PROPERTY_SPECS.items(): + prop = record.properties.get(prop_name) + if prop is None or prop.value is None or prop.provenance.kind == "missing": + if prop_name in REQUIRED_PHYSICAL_INPUTS: + missing_required.append(prop_name) + else: + missing_optional.append(prop_name) + continue + if prop.provenance.kind == "swept": + missing_optional.append(prop_name) + diagnostics.append(f"{prop_name} is swept and was not mapped as a fixed absorber input") + continue + if prop.provenance.kind not in {"computed", "derived"}: + if prop_name in REQUIRED_PHYSICAL_INPUTS: + missing_required.append(prop_name) + else: + missing_optional.append(prop_name) + diagnostics.append( + f"{prop_name} provenance kind {prop.provenance.kind!r} is not accepted as a fixed input" + ) + continue + mapped[target] = _coerce_numeric(prop.value) * scale + + for score_field in SCORE_FIELDS: + if score_field in record.properties: + diagnostics.append(f"{score_field} imported as ranking metadata only") + if _property_value(record, "slme_0p5um") is not None or _property_value(record, "slme_2um") is not None: + diagnostics.append("SLME is preserved as ranking metadata; it is not converted to absorber alpha") + if _property_value(record, "absorption_edge_ev") is not None: + diagnostics.append("absorption_edge_ev is not converted to a scalar absorption coefficient") + return mapped, missing_required, missing_optional, diagnostics + + +def _sweep_parameters( + record: MaterialRecord, + sweeps: Mapping[str, list[float]], +) -> dict[str, Any]: + sweep_parameters: dict[str, Any] = {name: list(values) for name, values in sweeps.items()} + for prop_name, target_name in DEVICE_SWEEP_PROPERTY_MAP.items(): + prop = record.properties.get(prop_name) + if prop is None: + continue + value = prop.value + kind = prop.provenance.kind + if kind == "swept": + if target_name in sweeps: + sweep_parameters.setdefault(target_name, list(sweeps[target_name])) + elif value is not None: + sweep_parameters[target_name] = value + return sweep_parameters + + +def _template_assumptions( + template: Mapping[str, Any], + mapped: Mapping[str, Any], + sweeps: Mapping[str, list[float]], +) -> dict[str, Any]: + layers = template.get("layers") + if not isinstance(layers, list): + return {} + absorber = _absorber_layer(copy.deepcopy(layers)) + assumptions: dict[str, Any] = {} + if "absorber.Eg" not in mapped: + assumptions["absorber.Eg"] = absorber.get("Eg", 0.0) + for _prop_name, (target, field_name, _scale) in MAPPED_PROPERTY_SPECS.items(): + if field_name is None or target in mapped: + continue + if field_name in absorber: + assumptions[f"absorber.{field_name}"] = absorber[field_name] + assumptions["absorber.thickness"] = sweeps["absorber.thickness"][0] + assumptions["absorber.tau_n"] = sweeps["absorber.tau_n"][0] + assumptions["absorber.tau_p"] = sweeps["absorber.tau_p"][0] + assumptions["absorber.trap_N_t_bulk"] = sweeps["absorber.trap_N_t_bulk"][0] + assumptions["device.interfaces"] = sweeps["device.interfaces"][0] + return assumptions + + +def _build_config( + template: Mapping[str, Any], + record: MaterialRecord, + mapped: Mapping[str, Any], + sweeps: Mapping[str, list[float]], + missing_optional: list[str], + diagnostics: list[str], + *, + import_policy: ImportPolicy, + activate_bandgap: bool, + sweep_policy: SweepPolicyName, +) -> dict[str, Any]: + config = copy.deepcopy(dict(template)) + layers = config.get("layers") + if not isinstance(layers, list): + raise ValueError("Template layers must be a list") + + absorber = _absorber_layer(layers) + material_id = record.material_id + absorber["name"] = f"SolarScale_{material_id}" + activate_material_specific_device_evidence = bool( + activate_bandgap and "absorber.Eg" in mapped and "absorber.chi" in mapped + ) + for target, value in mapped.items(): + if target == "absorber.chi" and not activate_material_specific_device_evidence: + continue + field_name = target.split(".", 1)[1] + absorber[field_name] = value + optical_material = _text_property(record, "optical_material") + if activate_material_specific_device_evidence and optical_material and optical_material != "MAPbI3": + absorber["optical_material"] = optical_material + + absorber["thickness"] = sweeps["absorber.thickness"][0] + absorber["tau_n"] = sweeps["absorber.tau_n"][0] + absorber["tau_p"] = sweeps["absorber.tau_p"][0] + absorber["trap_N_t_bulk"] = sweeps["absorber.trap_N_t_bulk"][0] + absorber["trap_profile_shape"] = "exponential" + + device = config.setdefault("device", {}) + interface_s = sweeps["device.interfaces"][0] + device["interfaces"] = [[interface_s, interface_s] for _ in range(max(0, len(layers) - 1))] + device.setdefault("mode", "fast") + + notes = list(config.get("notes", []) or []) + notes.append( + "Generated from SolarScale MaterialRecord. Only computed/derived DFT/MD absorber inputs are fixed; device-only unknowns remain sweep dimensions." + ) + if import_policy == "exploratory": + notes.append( + "Exploratory import may include records whose MD/ion gate is missing; do not treat those as publication-grade candidates." + ) + if "absorber.Eg" in mapped: + notes.append( + "HSE band gap is explicitly activated as absorber Eg. Use only with a fully band-aligned template." + ) + else: + notes.append( + "HSE band gap is preserved as metadata; absorber Eg follows the template to avoid partial band-alignment activation." + ) + material_metadata = _material_metadata(record) + screening_evidence = _screening_evidence( + record, + resolved_readiness=str( + record.screening.get("readiness", "") or _property_value(record, "screening_readiness") or "" + ), + ) + config["notes"] = notes + config["source"] = { + "schema": "solarlab.solarscale_import_config", + "schema_version": "0.4", + "material_id": material_id, + "import_policy": import_policy, + "activate_bandgap": activate_bandgap, + "sweep_policy": sweep_policy, + "sweep_grid": {name: list(values) for name, values in sweeps.items()}, + "sweep_dimensions": _sweep_dimensions(sweeps), + "screening": record.screening, + "screening_evidence": screening_evidence, + "ranking": { + "ranking_score": _ranking_score(record)[0], + "ranking_score_source": _ranking_score(record)[1], + "ml_pv_score": _numeric_property(record, "ml_pv_score"), + "final_fom_score": _numeric_property(record, "final_fom_score"), + }, + "material_metadata": material_metadata, + "mapped_parameters": dict(mapped), + "optical_material": optical_material, + "nk_provenance": _text_property(record, "nk_provenance"), + "nk_csv_path": _text_property(record, "nk_csv_path"), + "nk_source_path": _text_property(record, "nk_source_path"), + "band_alignment_provenance": _text_property(record, "band_alignment_provenance"), + "band_alignment_source_path": _text_property(record, "band_alignment_source_path"), + "missing_optional": list(missing_optional), + "sweep_parameters": _sweep_parameters(record, sweeps), + "diagnostics": list(diagnostics), + } + config["simulation_hints"] = { + "N_grid": 30, + "n_points": 8, + "v_rate": 5.0, + "V_max": 1.4, + "notes": ( + "First-pass SolarScale imports should run low-resolution screening " + "before production sweeps." + ), + } + return config + + +def _load_yaml(path: str | Path) -> dict[str, Any]: + with Path(path).open(encoding="utf-8") as fh: + data = yaml.safe_load(fh) or {} + if "device" not in data or "layers" not in data: + raise ValueError(f"Template is not a SolarLab device config: {path}") + return dict(data) + + +def _write_yaml(path: Path, config: Mapping[str, Any]) -> None: + path.write_text( + yaml.safe_dump(dict(config), sort_keys=False, default_flow_style=False), + encoding="utf-8", + ) + + +def _manifest_sweep_grid(manifest: Mapping[str, Any]) -> dict[str, list[float]]: + raw = manifest.get("sweep_grid") + if not isinstance(raw, Mapping): + raise ValueError("Manifest is missing sweep_grid") + sweeps = {str(name): [float(value) for value in values] for name, values in raw.items()} + _validate_sweep_grid(sweeps) + return {name: sweeps[name] for name in _sweep_dimension_names(sweeps)} + + +def _sweep_dimension_names(sweeps: Mapping[str, list[float]]) -> list[str]: + ordered = [name for name in SWEEP_DIMENSION_ORDER if name in sweeps] + ordered.extend(sorted(name for name in sweeps if name not in set(ordered))) + return ordered + + +def _iter_sweep_values(sweeps: Mapping[str, list[float]]) -> Iterator[dict[str, float]]: + names = _sweep_dimension_names(sweeps) + for values in itertools.product(*(sweeps[name] for name in names)): + yield dict(zip(names, values, strict=True)) + + +def _apply_sweep_values( + config: dict[str, Any], + sweep_values: Mapping[str, float], + *, + sweep_point_id: str, + candidate_sweep_index: int, + parent_config_path: str, +) -> None: + layers = config.get("layers") + if not isinstance(layers, list): + raise ValueError("Sweep config layers must be a list") + absorber = _absorber_layer(layers) + for target, value in sweep_values.items(): + if target.startswith("absorber."): + absorber[target.split(".", 1)[1]] = float(value) + elif target == "device.interfaces": + device = config.setdefault("device", {}) + interface_s = float(value) + device["interfaces"] = [[interface_s, interface_s] for _ in range(max(0, len(layers) - 1))] + else: + raise ValueError(f"Unsupported sweep target {target!r}") + source = config.setdefault("source", {}) + source["sweep_point_id"] = sweep_point_id + source["sweep_index"] = candidate_sweep_index + source["parent_config_path"] = parent_config_path + source["sweep_values"] = {name: float(value) for name, value in sweep_values.items()} + + +def _absorber_layer(layers: list[dict[str, Any]]) -> dict[str, Any]: + absorbers = [layer for layer in layers if layer.get("role") == "absorber"] + if len(absorbers) != 1: + raise ValueError("Template must contain exactly one absorber layer") + return absorbers[0] + + +def _ranking_score(record: MaterialRecord) -> tuple[float | None, str | None]: + for score_name in SCORE_FIELDS: + score = _numeric_property(record, score_name) + if score is not None: + return score, score_name + return None, None + + +def _candidate_sort_key(candidate: CandidatePlan) -> tuple[int, float, str]: + selected_bucket = 0 if candidate.selected else 1 + score = candidate.ranking_score if candidate.ranking_score is not None else float("-inf") + return selected_bucket, -score, candidate.material_id + + +def _candidate_to_dict(candidate: CandidatePlan, *, include_config: bool = True) -> dict[str, Any]: + data: dict[str, Any] = { + "material_id": candidate.material_id, + "rank": candidate.rank, + "selected": candidate.selected, + "reason": candidate.reason, + "readiness": candidate.readiness, + "ranking_score": candidate.ranking_score, + "ranking_score_source": candidate.ranking_score_source, + "ml_pv_score": candidate.ml_pv_score, + "final_fom_score": candidate.final_fom_score, + "screening_evidence": candidate.screening_evidence, + "mapped_parameters": candidate.mapped_parameters, + "material_metadata": candidate.material_metadata, + "dft_properties": _legacy_dft_properties(candidate.mapped_parameters, candidate.material_metadata), + "md_properties": _legacy_md_properties(candidate.mapped_parameters), + "sweep_parameters": candidate.sweep_parameters, + "missing_required": candidate.missing_required, + "missing_optional": candidate.missing_optional, + "assumed_parameters": candidate.assumed_parameters, + "diagnostics": candidate.diagnostics, + } + if candidate.config_path is not None: + data["config_path"] = candidate.config_path + if include_config and candidate.config is not None: + data["config"] = candidate.config + return data + + +def _replace_candidate(candidate: CandidatePlan, **changes: Any) -> CandidatePlan: + data: dict[str, Any] = { + "material_id": candidate.material_id, + "rank": candidate.rank, + "selected": candidate.selected, + "reason": candidate.reason, + "readiness": candidate.readiness, + "ranking_score": candidate.ranking_score, + "ranking_score_source": candidate.ranking_score_source, + "ml_pv_score": candidate.ml_pv_score, + "final_fom_score": candidate.final_fom_score, + "screening_evidence": candidate.screening_evidence, + "mapped_parameters": candidate.mapped_parameters, + "material_metadata": candidate.material_metadata, + "sweep_parameters": candidate.sweep_parameters, + "missing_required": candidate.missing_required, + "missing_optional": candidate.missing_optional, + "assumed_parameters": candidate.assumed_parameters, + "diagnostics": candidate.diagnostics, + "config": candidate.config, + "config_path": candidate.config_path, + } + data.update(changes) + return CandidatePlan(**data) + + +def _screening_summary(candidates: list[CandidatePlan]) -> dict[str, Any]: + readiness_counts = Counter(candidate.readiness or "" for candidate in candidates) + skipped_reason_counts = Counter(candidate.reason for candidate in candidates if not candidate.selected) + selected_candidates = [candidate for candidate in candidates if candidate.selected] + return { + "readiness_distribution": dict(sorted(readiness_counts.items())), + "gate_summary": _gate_summary(candidates), + "skipped_reason_counts": dict(sorted(skipped_reason_counts.items())), + "top_selected_candidates": [ + { + "material_id": candidate.material_id, + "rank": candidate.rank, + "readiness": candidate.readiness, + "ranking_score": candidate.ranking_score, + "ranking_score_source": candidate.ranking_score_source, + } + for candidate in selected_candidates[:10] + ], + } + + +def _gate_summary(candidates: list[CandidatePlan]) -> dict[str, Any]: + statuses = ("pass", "fail", "missing", "unknown") + totals: Counter[str] = Counter() + by_gate: dict[str, Counter[str]] = {} + records_with_gate_data = 0 + for candidate in candidates: + gates = candidate.screening_evidence.get("gates", {}) + if not isinstance(gates, Mapping) or not gates: + continue + records_with_gate_data += 1 + for gate_name, gate_value in gates.items(): + status = _gate_status(gate_value) + gate_counts = by_gate.setdefault(str(gate_name), Counter()) + gate_counts[status] += 1 + totals[status] += 1 + return { + "records_with_gate_data": records_with_gate_data, + "totals": {status: totals.get(status, 0) for status in statuses}, + "by_gate": { + gate_name: {status: counts.get(status, 0) for status in statuses} + for gate_name, counts in sorted(by_gate.items()) + }, + } + + +def _gate_status(value: Any) -> str: + if isinstance(value, Mapping): + for key in ("status", "state", "outcome", "result"): + if key in value: + return _gate_status(value[key]) + for key in ("passed", "pass", "is_passed"): + if key in value: + return "pass" if bool(value[key]) else "fail" + if value.get("missing") is True or value.get("available") is False: + return "missing" + return "unknown" + if value is True: + return "pass" + if value is False: + return "fail" + if value is None: + return "missing" + text = str(value).strip().lower().replace("-", "_") + if text in {"pass", "passed", "ok", "true", "yes", "accepted"}: + return "pass" + if text in {"fail", "failed", "false", "no", "blocked", "rejected", "reject"}: + return "fail" + if text in {"missing", "not_run", "not_available", "none", ""}: + return "missing" + if text in {"unknown", "pending", "inconclusive"}: + return "unknown" + return "unknown" + + +def _screening_evidence(record: MaterialRecord, *, resolved_readiness: str) -> dict[str, Any]: + raw_screening = copy.deepcopy(record.screening) + return { + "readiness": raw_screening.get("readiness"), + "resolved_readiness": resolved_readiness, + "gates": copy.deepcopy(raw_screening.get("gates", {})), + "thresholds": copy.deepcopy(raw_screening.get("thresholds", {})), + "raw_screening": raw_screening, + } + + +def _property_value(record: MaterialRecord, name: str) -> Any: + prop = record.properties.get(name) + if prop is None: + return None + return prop.value + + +def _material_metadata(record: MaterialRecord) -> dict[str, Any]: + return { + "band_gap_hse_ev": _numeric_property(record, "band_gap_hse_ev"), + "electron_effective_mass_m0": _numeric_property(record, "electron_effective_mass_m0"), + "hole_effective_mass_m0": _numeric_property(record, "hole_effective_mass_m0"), + "electron_affinity_ev": _numeric_property(record, "electron_affinity_ev"), + "cbm_vs_vacuum_ev": _numeric_property(record, "cbm_vs_vacuum_ev"), + "vbm_vs_vacuum_ev": _numeric_property(record, "vbm_vs_vacuum_ev"), + "optical_material": _text_property(record, "optical_material"), + "nk_csv_path": _text_property(record, "nk_csv_path"), + "nk_provenance": _text_property(record, "nk_provenance"), + "nk_source_path": _text_property(record, "nk_source_path"), + "nk_wavelength_min_nm": _numeric_property(record, "nk_wavelength_min_nm"), + "nk_wavelength_max_nm": _numeric_property(record, "nk_wavelength_max_nm"), + "band_alignment_provenance": _text_property(record, "band_alignment_provenance"), + "band_alignment_source_path": _text_property(record, "band_alignment_source_path"), + "slme_0p5um": _numeric_property(record, "slme_0p5um"), + "slme_2um": _numeric_property(record, "slme_2um"), + "absorption_edge_ev": _numeric_property(record, "absorption_edge_ev"), + } + + +def _validate_band_aligned_template(template: Mapping[str, Any]) -> None: + layers = template.get("layers") + if not isinstance(layers, list): + raise ValueError("Template layers must be a list") + invalid: list[str] = [] + for layer in layers: + if layer.get("role") == "substrate": + continue + name = str(layer.get("name", "")) + chi = _optional_float(layer.get("chi")) + eg = _optional_float(layer.get("Eg")) + if chi is None or eg is None or eg <= 0.0: + invalid.append(name) + if invalid: + raise ValueError( + "--activate-bandgap requires a fully band-aligned template with " + "chi and positive Eg on every electrical layer; invalid layers: " + + ", ".join(invalid) + ) + + +def _optional_float(value: Any) -> float | None: + if value is None: + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _legacy_dft_properties( + mapped: Mapping[str, Any], + material_metadata: Mapping[str, Any], +) -> dict[str, Any]: + return { + "band_gap_hse_ev": mapped.get("absorber.Eg", material_metadata.get("band_gap_hse_ev")), + "dielectric_static_avg": mapped.get("absorber.eps_r"), + "electron_mobility_cm2_v_s": _inverse_scaled(mapped.get("absorber.mu_n"), 1.0e-4), + "hole_mobility_cm2_v_s": _inverse_scaled(mapped.get("absorber.mu_p"), 1.0e-4), + } + + +def _legacy_md_properties(mapped: Mapping[str, Any]) -> dict[str, Any]: + return { + "ion_diffusion_coefficient_m2_s": mapped.get("absorber.D_ion"), + "ion_activation_energy_ev": mapped.get("absorber.E_a_ion"), + } + + +def _inverse_scaled(value: Any, scale: float) -> float | None: + if value is None: + return None + return float(value) / scale + + +def _numeric_property(record: MaterialRecord, name: str) -> float | None: + prop = record.properties.get(name) + if prop is None or prop.value is None or prop.provenance.kind == "missing": + return None + try: + return float(prop.value) + except (TypeError, ValueError): + return None + + +def _text_property(record: MaterialRecord, name: str) -> str | None: + prop = record.properties.get(name) + if prop is None or prop.value is None or prop.provenance.kind == "missing": + return None + text = str(prop.value).strip() + return text or None + + +def _coerce_numeric(value: Any) -> float: + if isinstance(value, np.generic): + return float(value.item()) + return float(value) + + +def _safe_name(material_id: str) -> str: + return re.sub(r"[^A-Za-z0-9_.-]+", "_", material_id) diff --git a/src/solarlab/experiments/working_point_transfer.py b/src/solarlab/experiments/working_point_transfer.py new file mode 100644 index 00000000..dab7c072 --- /dev/null +++ b/src/solarlab/experiments/working_point_transfer.py @@ -0,0 +1,1914 @@ +"""P05-01b multi-stage working-point state transfer and paired perturbation runner. + +Implements lossless ``WorkingPoint`` bundle serialization/reconstruction across +1D electronic (``CompiledDevice1D`` / ``State1D``) and coupled 1D ionic +(``CompiledIonicDevice1D`` / ``IonicState1D``) representations, explicit +stage-left (``t^-``) and stage-right (``t^+``) boundary states, strict +``Protocol.transfers`` preservation enforcement, damage-gated material +rebinding, and matched pulsed + unpulsed-control perturbation execution with +step-to-step Maxwell displacement + conduction current accounting. + +Original NumericsHardening §0.2 ``EVIDENCE_LABELS`` scopes remain untouched; +run completion never promotes evidence labels or confers scientific +qualification. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +import hashlib +import json +import math +import time +from typing import Any, Literal, cast + +import numpy as np +from numpy.typing import NDArray + +from solarlab.contracts import ELEMENTARY_CHARGE_C, frozen_array +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem, classical_dc_1d +from solarlab.equations.assembly.ionic_1d import AssembledIonic1DProblem +from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem, State1D +from solarlab.equations.implementation import use_assembled +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, Ionic1DProblem, IonicState1D +from solarlab.experiments.ionic_transient import IonicTransientAttempt, IonicTransientOptions +from solarlab.experiments.protocol import Protocol, WorkingPoint +from solarlab.experiments.results import ( + EVIDENCE_LABELS, + ExperimentResult, + decode_array, + encode_array, +) +from solarlab.experiments.transient import TransientAttempt, TransientOptions, TransientProtocol +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import CallableProblem, Matrix, ResidualScaling, StepControl +from solarlab.solvers.nonlinear.production import ( + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.time import BackwardEuler1DStep, step_accounting as electronic_step_accounting +from solarlab.solvers.time.assembled_ionic_backward_euler import AssembledIonicBackwardEuler1DStep +from solarlab.solvers.time.assembled_storage import AssembledStorage1D +from solarlab.solvers.time.ionic_backward_euler import ( + IonicBackwardEuler1DStep, + step_accounting as ionic_step_accounting, +) + +__all__ = [ + "COORDINATE_ENCODING_1D", + "COORDINATE_ENCODING_IONIC_1D", + "PHYSICAL_FIELD_ENCODING_1D", + "PHYSICAL_FIELD_ENCODING_IONIC_1D", + "PairedStageRunResult", + "StageBoundaryState", + "StageIntegrationTrace", + "StageTransferResult", + "WorkingPointBundle", + "WorkingPointTransferError", + "build_stage_experiment_result", + "capture_working_point", + "compute_physical_identity", + "coordinates_from_physical_fields_1d", + "integrate_stage_from_working_point", + "ion_coordinates_from_physical_densities_1d", + "physical_state_equivalent", + "reconstruct_ionic_state_1d", + "reconstruct_state_1d", + "run_paired_perturbation_stages", + "transfer_working_point", +] + +Q = ELEMENTARY_CHARGE_C + +COORDINATE_ENCODING_1D = "solarlab.coordinates.1d.v1" +PHYSICAL_FIELD_ENCODING_1D = "solarlab.physical_fields.1d.v1" +COORDINATE_ENCODING_IONIC_1D = "solarlab.coordinates.ionic_1d.v1" +PHYSICAL_FIELD_ENCODING_IONIC_1D = "solarlab.physical_fields.ionic_1d.v1" + +_ELECTRONIC_ENCODINGS = frozenset({COORDINATE_ENCODING_1D, PHYSICAL_FIELD_ENCODING_1D}) +_IONIC_ENCODINGS = frozenset({COORDINATE_ENCODING_IONIC_1D, PHYSICAL_FIELD_ENCODING_IONIC_1D}) +_SUPPORTED_ENCODINGS = _ELECTRONIC_ENCODINGS | _IONIC_ENCODINGS +_POINT_SECTION_NAMES = ( + "state", + "inventories", + "coordinate_reference", + "materials", + "damage", + "grid", + "history", + "qualification", +) +_BUNDLE_SCHEMA = "solarlab.working-point-bundle.v1" + + +class WorkingPointTransferError(ValueError): + """Raised when a working-point bundle or multi-stage transfer violates invariants.""" + + +def _json_document(value: Any) -> str: + def check(item: Any, depth: int) -> None: + if depth > 32: + raise ValueError("metadata exceeds the supported nesting depth") + if item is None or type(item) in {bool, int}: + return + if type(item) is str: + item.encode("utf-8") + return + if type(item) is float and math.isfinite(item): + return + if type(item) is list: + for child in item: + check(child, depth + 1) + return + if type(item) is dict and all(type(key) is str for key in item): + for key, child in item.items(): + check(key, depth + 1) + check(child, depth + 1) + return + raise ValueError(f"unsupported metadata type/value: {type(item).__name__}") + + check(value, 0) + encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + if len(encoded.encode("utf-8")) > 2**20: + raise ValueError("metadata exceeds 1 MiB; use an independent artifact") + return encoded + + +def _parse_document(text: str) -> Any: + def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]: + if len({key for key, _ in items}) != len(items): + raise ValueError("duplicate metadata key") + return dict(items) + + value = json.loads(text, object_pairs_hook=pairs) + _json_document(value) + return value + + +def _section_sha256(document: Mapping[str, Any]) -> str: + canonical = _json_document(dict(document)) + return hashlib.sha256(canonical.encode()).hexdigest() + + +def _ref(identifier: str, sha256: str) -> dict[str, str]: + return {"id": identifier, "sha256": sha256} + + +def _canonical_f64_array(values: np.ndarray, *, name: str, positive: bool = False) -> np.ndarray: + arr = np.asarray(values, dtype=np.float64) + if arr.ndim != 1 or arr.size == 0 or not np.all(np.isfinite(arr)): + raise WorkingPointTransferError(f"{name} must be a non-empty finite 1D float64 vector") + if positive and np.any(arr <= 0.0): + raise WorkingPointTransferError(f"{name} must be strictly positive") + # Normalize -0.0 -> +0.0 so canonical byte digests do not depend on signed zero. + normalized = np.where(arr == 0.0, 0.0, arr) + return np.ascontiguousarray(normalized, dtype=" str: + """Compute canonical encoding-independent SHA-256 of a 1D physical state.""" + x_e = _canonical_f64_array(nodes_m, name="nodes_m") + phi = _canonical_f64_array(potential_V, name="potential_V") + n = _canonical_f64_array(electron_density_m3, name="electron_density_m3", positive=True) + p = _canonical_f64_array(hole_density_m3, name="hole_density_m3", positive=True) + if not (x_e.shape == phi.shape == n.shape == p.shape): + raise WorkingPointTransferError("electronic physical arrays must share identical 1D node shape") + + hasher = hashlib.sha256() + hasher.update(b"solarlab.physical-state.1d.v1\x00") + hasher.update(np.int64(x_e.size).astype(" 0: + p_neg = _canonical_f64_array( + negative_ion_density_m3, name="negative_ion_density_m3", positive=True + ) + if p_neg.shape != x_i.shape: + raise WorkingPointTransferError("negative_ion_density_m3 must match ion_nodes_m shape") + hasher.update(b"dual_neg.v1\x00") + hasher.update(p_neg.tobytes()) + else: + hasher.update(b"single_pos.v1\x00") + else: + if negative_ion_density_m3 is not None and np.asarray(negative_ion_density_m3).size > 0: + raise WorkingPointTransferError("negative_ion_density_m3 cannot be supplied without positive ions") + hasher.update(b"electronic_only.v1\x00") + + return hasher.hexdigest() + + +def coordinates_from_physical_fields_1d( + device: CompiledDevice1D, + *, + potential_V: np.ndarray, + electron_density_m3: np.ndarray, + hole_density_m3: np.ndarray, + voltage_V: float, +) -> np.ndarray: + """Invert ``device.fields(u, voltage_V)`` from physical ``(phi, n, p)`` to ``u``.""" + if not isinstance(device, CompiledDevice1D): + raise TypeError("device must be a CompiledDevice1D") + if not math.isfinite(voltage_V): + raise WorkingPointTransferError("voltage_V must be finite") + phi = _canonical_f64_array(potential_V, name="potential_V") + n = _canonical_f64_array(electron_density_m3, name="electron_density_m3", positive=True) + p = _canonical_f64_array(hole_density_m3, name="hole_density_m3", positive=True) + if phi.shape != (device.node_count,) or n.shape != (device.node_count,) or p.shape != (device.node_count,): + raise WorkingPointTransferError("physical field lengths do not match CompiledDevice1D.node_count") + ref_n, ref_p = device.carrier_reference_potentials(float(voltage_V)) + shift_n = (phi - ref_n) / device.thermal_voltage_V + shift_p = (phi - ref_p) / device.thermal_voltage_V + z_n = np.log(n / device.reference_electron_density_m3) - shift_n + z_p = -np.log(p / device.reference_hole_density_m3) - shift_p + u = np.concatenate((phi, z_n, z_p)) + if not np.all(np.isfinite(u)): + raise WorkingPointTransferError("reconstructed electronic coordinates contain non-finite entries") + return u + + +def _log_ratio_no_cancel(num: np.ndarray, den: np.ndarray) -> np.ndarray: + """Compute ``log(num / den)`` for positive arrays without near-unity or deep-depletion cancellation.""" + delta = num - den + near = np.abs(delta) <= 0.25 * den + safe_delta_over_den = np.where(near, delta / den, 0.0) + return np.where(near, np.log1p(safe_delta_over_den), np.log(num / den)) + + +def ion_coordinates_from_physical_densities_1d( + device: CompiledIonicDevice1D, + *, + positive_ion_density_m3: np.ndarray, + negative_ion_density_m3: np.ndarray | None = None, +) -> np.ndarray: + """Invert finite-site ion density maps (independent or shared-site) without cancellation.""" + if not isinstance(device, CompiledIonicDevice1D): + raise TypeError("device must be a CompiledIonicDevice1D") + ion_count = device.ion_geometry.node_count + p_pos = _canonical_f64_array( + positive_ion_density_m3, name="positive_ion_density_m3", positive=True + ) + if p_pos.shape != (ion_count,): + raise WorkingPointTransferError("positive_ion_density_m3 shape does not match ion_geometry.node_count") + p0_pos = device.positive_ion_reference_m3 + plim_pos = device.positive_ion_site_limit_m3 + if np.any(p_pos >= plim_pos): + raise WorkingPointTransferError("positive_ion_density_m3 exceeds or saturates positive_ion_site_limit_m3") + + if device.ion_species_count == 1: + if negative_ion_density_m3 is not None and np.asarray(negative_ion_density_m3).size > 0: + raise WorkingPointTransferError("single-ion device cannot accept negative_ion_density_m3") + y_pos = _log_ratio_no_cancel(p_pos, p0_pos) - _log_ratio_no_cancel( + plim_pos - p_pos, plim_pos - p0_pos + ) + if not np.all(np.isfinite(y_pos)): + raise WorkingPointTransferError("non-finite single-ion logit coordinate") + return y_pos + + if negative_ion_density_m3 is None or np.asarray(negative_ion_density_m3).size == 0: + raise WorkingPointTransferError("dual-ion device requires negative_ion_density_m3") + p_neg = _canonical_f64_array( + negative_ion_density_m3, name="negative_ion_density_m3", positive=True + ) + if p_neg.shape != (ion_count,): + raise WorkingPointTransferError("negative_ion_density_m3 shape does not match ion_geometry.node_count") + p0_neg = device.negative_ion_reference_m3 + plim_neg = device.negative_ion_site_limit_m3 + if np.any(p_neg >= plim_neg): + raise WorkingPointTransferError("negative_ion_density_m3 exceeds or saturates negative_ion_site_limit_m3") + + if device.ion_site_contract == "shared_finite_sites": + if np.any(p_pos + p_neg >= plim_pos): + raise WorkingPointTransferError("shared-site ion densities saturate common site capacity") + vac_term = _log_ratio_no_cancel(plim_pos - p_pos - p_neg, plim_pos - p0_pos - p0_neg) + y_pos = _log_ratio_no_cancel(p_pos, p0_pos) - vac_term + y_neg = _log_ratio_no_cancel(p_neg, p0_neg) - vac_term + else: + y_pos = _log_ratio_no_cancel(p_pos, p0_pos) - _log_ratio_no_cancel( + plim_pos - p_pos, plim_pos - p0_pos + ) + y_neg = _log_ratio_no_cancel(p_neg, p0_neg) - _log_ratio_no_cancel( + plim_neg - p_neg, plim_neg - p0_neg + ) + coords = np.concatenate((y_pos, y_neg)) + if not np.all(np.isfinite(coords)): + raise WorkingPointTransferError("non-finite dual-ion logit coordinates") + return coords + + +def physical_state_equivalent( + left: State1D | IonicState1D, + right: State1D | IonicState1D, + *, + rtol: float = 1e-13, + atol: float = 0.0, +) -> bool: + """Check whether two reconstructed states represent the same physical state.""" + if isinstance(left, State1D) and isinstance(right, State1D): + return bool( + np.allclose(left.potential_V, right.potential_V, rtol=rtol, atol=max(atol, 1e-15)) + and np.allclose(left.electron_density_m3, right.electron_density_m3, rtol=rtol, atol=atol) + and np.allclose(left.hole_density_m3, right.hole_density_m3, rtol=rtol, atol=atol) + ) + if isinstance(left, IonicState1D) and isinstance(right, IonicState1D): + if not physical_state_equivalent( + left.electronic_state, right.electronic_state, rtol=rtol, atol=atol + ): + return False + if not np.allclose(left.positive_ion_density_m3, right.positive_ion_density_m3, rtol=rtol, atol=atol): + return False + if left.negative_ion_density_m3.size != right.negative_ion_density_m3.size: + return False + if left.negative_ion_density_m3.size > 0 and not np.allclose( + left.negative_ion_density_m3, right.negative_ion_density_m3, rtol=rtol, atol=atol + ): + return False + return True + return False + + +@dataclass(frozen=True, slots=True) +class WorkingPointBundle: + """Complete self-verifying working-point document pairing ``WorkingPoint`` + section payloads.""" + + working_point: WorkingPoint + sections: dict[str, dict[str, Any]] + + def __post_init__(self) -> None: + if not isinstance(self.working_point, WorkingPoint): + raise TypeError("working_point must be a WorkingPoint instance") + if not isinstance(self.sections, Mapping) or set(self.sections) != set(_POINT_SECTION_NAMES): + raise WorkingPointTransferError("WorkingPointBundle requires all 8 working-point sections") + wp_doc = self.working_point.export() + encoding = wp_doc["state_encoding"] + if encoding not in _SUPPORTED_ENCODINGS: + raise WorkingPointTransferError(f"unsupported state_encoding: {encoding!r}") + normalized_sections: dict[str, dict[str, Any]] = {} + for name in _POINT_SECTION_NAMES: + raw_section = self.sections[name] + if not isinstance(raw_section, Mapping): + raise WorkingPointTransferError(f"section {name!r} must be a JSON object") + canonical_str = _json_document(dict(raw_section)) + digest = hashlib.sha256(canonical_str.encode()).hexdigest() + expected_digest = wp_doc[name]["sha256"] + if digest != expected_digest: + raise WorkingPointTransferError( + f"section {name!r} SHA-256 mismatch ({digest} != {expected_digest})" + ) + normalized_sections[name] = _parse_document(canonical_str) + + # Verify qualification invariants (7-tier labels, scientific_qualification never auto-true). + qual = normalized_sections["qualification"] + if qual.get("scientific_qualification") is not False: + raise WorkingPointTransferError( + "WorkingPoint qualification cannot assert scientific_qualification=True via runtime transfer" + ) + labels = qual.get("evidence_labels", []) + if not isinstance(labels, list) or not labels or any(lbl not in EVIDENCE_LABELS for lbl in labels): + raise WorkingPointTransferError("qualification.evidence_labels must contain valid EVIDENCE_LABELS") + + # Verify physical_identity directly when physical fields are inline. + state_sec = normalized_sections["state"] + grid_sec = normalized_sections["grid"] + if encoding in {PHYSICAL_FIELD_ENCODING_1D, PHYSICAL_FIELD_ENCODING_IONIC_1D}: + nodes_m = decode_array(grid_sec["electronic_nodes_m"]) + phi = decode_array(state_sec["potential_V"]) + n = decode_array(state_sec["electron_density_m3"]) + p = decode_array(state_sec["hole_density_m3"]) + ion_nodes = ( + decode_array(grid_sec["ion_nodes_m"]) + if encoding == PHYSICAL_FIELD_ENCODING_IONIC_1D + else None + ) + p_pos = ( + decode_array(state_sec["positive_ion_density_m3"]) + if encoding == PHYSICAL_FIELD_ENCODING_IONIC_1D + else None + ) + p_neg = ( + decode_array(state_sec["negative_ion_density_m3"]) + if encoding == PHYSICAL_FIELD_ENCODING_IONIC_1D + and state_sec.get("negative_ion_density_m3") is not None + else None + ) + computed_pid = compute_physical_identity( + nodes_m=nodes_m, + potential_V=phi, + electron_density_m3=n, + hole_density_m3=p, + ion_nodes_m=ion_nodes, + positive_ion_density_m3=p_pos, + negative_ion_density_m3=p_neg, + ) + if computed_pid != wp_doc["physical_identity"]: + raise WorkingPointTransferError( + "physical_identity mismatch against inline physical-field state arrays" + ) + object.__setattr__(self, "sections", normalized_sections) + + @property + def id(self) -> str: + return str(self.working_point.export()["id"]) + + @property + def sha256(self) -> str: + return self.working_point.sha256 + + @property + def physical_identity(self) -> str: + return str(self.working_point.export()["physical_identity"]) + + @property + def state_encoding(self) -> str: + return str(self.working_point.export()["state_encoding"]) + + def to_document(self) -> dict[str, Any]: + return { + "schema": _BUNDLE_SCHEMA, + "working_point": self.working_point.export(), + "sections": _parse_document(_json_document(self.sections)), + } + + def to_json(self) -> str: + return _json_document(self.to_document()) + + @classmethod + def from_document(cls, document: Mapping[str, Any]) -> WorkingPointBundle: + if not isinstance(document, Mapping) or set(document) != {"schema", "working_point", "sections"}: + raise WorkingPointTransferError("invalid WorkingPointBundle document structure") + if document["schema"] != _BUNDLE_SCHEMA: + raise WorkingPointTransferError(f"unsupported bundle schema: {document['schema']!r}") + wp_raw = document["working_point"] + if not isinstance(wp_raw, Mapping): + raise WorkingPointTransferError("working_point must be a JSON object") + wp = WorkingPoint.from_document(dict(wp_raw)) + sections_raw = document["sections"] + if not isinstance(sections_raw, Mapping): + raise WorkingPointTransferError("sections must be a JSON object") + return cls(working_point=wp, sections={str(k): dict(v) for k, v in sections_raw.items()}) + + @classmethod + def from_json(cls, text: str) -> WorkingPointBundle: + parsed = _parse_document(text) + if not isinstance(parsed, dict): + raise WorkingPointTransferError("WorkingPointBundle JSON must decode to an object") + return cls.from_document(parsed) + + +def _carrier_inventories(device: CompiledDevice1D, state: State1D) -> tuple[float, float]: + widths = device.geometry.cell_measures_m + elec_inv = math.fsum((widths * state.electron_density_m3).tolist()) + hole_inv = math.fsum((widths * state.hole_density_m3).tolist()) + return elec_inv, hole_inv + + +def capture_working_point( + device: CompiledDevice1D | CompiledIonicDevice1D, + state: State1D | IonicState1D, + *, + point_id: str, + owner_epoch: str, + stage_id: str, + time_s: float, + generation_scale: float, + is_equilibrium: bool, + encoding: Literal["coordinates", "physical_fields"] = "coordinates", + reference_voltage_V: float | None = None, + prepared: PreparedDevice | None = None, + damage_state: Mapping[str, Any] | None = None, + switch_state: Mapping[str, Any] | None = None, + prior_history: Mapping[str, Any] | None = None, + evidence_labels: Sequence[str] = ("FIRST_SLICE",), + limitations: Sequence[str] = (), +) -> WorkingPointBundle: + """Capture a lossless ``WorkingPointBundle`` from an electronic or ionic 1D state.""" + if not isinstance(point_id, str) or not point_id.strip(): + raise WorkingPointTransferError("point_id must be a non-empty string") + if not isinstance(owner_epoch, str) or not owner_epoch.strip(): + raise WorkingPointTransferError("owner_epoch must be a non-empty string") + if not isinstance(stage_id, str) or not stage_id.strip(): + raise WorkingPointTransferError("stage_id must be a non-empty string") + if not math.isfinite(time_s) or not math.isfinite(generation_scale) or generation_scale < 0.0: + raise WorkingPointTransferError("time_s must be finite and generation_scale finite non-negative") + if encoding not in {"coordinates", "physical_fields"}: + raise WorkingPointTransferError("encoding must be 'coordinates' or 'physical_fields'") + if not evidence_labels or any(lbl not in EVIDENCE_LABELS for lbl in evidence_labels): + raise WorkingPointTransferError("evidence_labels must be non-empty valid EVIDENCE_LABELS") + + is_ionic = isinstance(device, CompiledIonicDevice1D) + if isinstance(device, CompiledIonicDevice1D): + if not isinstance(state, IonicState1D): + raise WorkingPointTransferError("CompiledIonicDevice1D requires an IonicState1D") + if state.device_sha256 != device.identity: + raise WorkingPointTransferError("IonicState1D belongs to a different CompiledIonicDevice1D") + elec_device: CompiledDevice1D = device.electronic_component + elec_state: State1D = state.electronic_state + else: + if not isinstance(device, CompiledDevice1D) or not isinstance(state, State1D): + raise WorkingPointTransferError("CompiledDevice1D requires a State1D") + if state.device_sha256 != device.identity: + raise WorkingPointTransferError("State1D belongs to a different CompiledDevice1D") + elec_device = device + elec_state = state + + applied_voltage_V = float(state.voltage_V) + ref_voltage_V = applied_voltage_V if reference_voltage_V is None else float(reference_voltage_V) + if not math.isfinite(ref_voltage_V): + raise WorkingPointTransferError("reference_voltage_V must be finite") + + ion_nodes = device.ion_geometry.nodes_m if isinstance(device, CompiledIonicDevice1D) else None + p_pos = state.positive_ion_density_m3 if isinstance(state, IonicState1D) else None + p_neg = ( + state.negative_ion_density_m3 + if isinstance(state, IonicState1D) and state.negative_ion_density_m3.size > 0 + else None + ) + physical_id = compute_physical_identity( + nodes_m=elec_device.nodes_m, + potential_V=elec_state.potential_V, + electron_density_m3=elec_state.electron_density_m3, + hole_density_m3=elec_state.hole_density_m3, + ion_nodes_m=ion_nodes, + positive_ion_density_m3=p_pos, + negative_ion_density_m3=p_neg, + ) + + if encoding == "coordinates": + state_encoding = COORDINATE_ENCODING_IONIC_1D if is_ionic else COORDINATE_ENCODING_1D + if ref_voltage_V == applied_voltage_V: + u_elec = np.asarray(elec_state.u, dtype=np.float64) + else: + u_elec = coordinates_from_physical_fields_1d( + elec_device, + potential_V=elec_state.potential_V, + electron_density_m3=elec_state.electron_density_m3, + hole_density_m3=elec_state.hole_density_m3, + voltage_V=ref_voltage_V, + ) + if isinstance(device, CompiledIonicDevice1D) and isinstance(state, IonicState1D): + u_ion = np.asarray(state.u[3 * device.node_count :], dtype=np.float64) + u_full = np.concatenate((u_elec, u_ion)) + state_section: dict[str, Any] = { + "schema": state_encoding, + "u": encode_array(np.ascontiguousarray(u_full, dtype=np.float64), unit="1"), + "applied_voltage_V": applied_voltage_V, + "reference_voltage_V": ref_voltage_V, + "ion_species_count": int(device.ion_species_count), + "ion_site_contract": device.ion_site_contract, + } + else: + state_section = { + "schema": state_encoding, + "u": encode_array(np.ascontiguousarray(u_elec, dtype=np.float64), unit="1"), + "applied_voltage_V": applied_voltage_V, + "reference_voltage_V": ref_voltage_V, + } + coord_ref_section: dict[str, Any] = { + "schema": "solarlab.coordinate-reference.v1", + "representation": "coordinates", + "reference_voltage_V": ref_voltage_V, + "thermal_voltage_V": float(elec_device.thermal_voltage_V), + "voltage_polarity": float(elec_device.voltage_polarity), + "ion_site_contract": ( + device.ion_site_contract if isinstance(device, CompiledIonicDevice1D) else "none" + ), + } + else: + state_encoding = PHYSICAL_FIELD_ENCODING_IONIC_1D if is_ionic else PHYSICAL_FIELD_ENCODING_1D + state_section = { + "schema": state_encoding, + "applied_voltage_V": applied_voltage_V, + "potential_V": encode_array( + np.ascontiguousarray(elec_state.potential_V, dtype=np.float64), unit="V" + ), + "electron_density_m3": encode_array( + np.ascontiguousarray(elec_state.electron_density_m3, dtype=np.float64), unit="m^-3" + ), + "hole_density_m3": encode_array( + np.ascontiguousarray(elec_state.hole_density_m3, dtype=np.float64), unit="m^-3" + ), + } + if isinstance(device, CompiledIonicDevice1D) and isinstance(state, IonicState1D): + state_section["positive_ion_density_m3"] = encode_array( + np.ascontiguousarray(state.positive_ion_density_m3, dtype=np.float64), unit="m^-3" + ) + state_section["negative_ion_density_m3"] = ( + encode_array( + np.ascontiguousarray(state.negative_ion_density_m3, dtype=np.float64), unit="m^-3" + ) + if state.negative_ion_density_m3.size > 0 + else None + ) + state_section["ion_species_count"] = int(device.ion_species_count) + state_section["ion_site_contract"] = device.ion_site_contract + coord_ref_section = { + "schema": "solarlab.coordinate-reference.v1", + "representation": "physical_fields", + "reference_voltage_V": None, + "thermal_voltage_V": float(elec_device.thermal_voltage_V), + "voltage_polarity": float(elec_device.voltage_polarity), + "ion_site_contract": ( + device.ion_site_contract if isinstance(device, CompiledIonicDevice1D) else "none" + ), + } + + elec_inv, hole_inv = _carrier_inventories(elec_device, elec_state) + inventories_section: dict[str, Any] = { + "schema": "solarlab.inventories.v1", + "electron_inventory_m2": elec_inv, + "hole_inventory_m2": hole_inv, + "positive_ion_inventory_m2": ( + float(state.domain_inventory_m2) if isinstance(state, IonicState1D) else 0.0 + ), + "negative_ion_inventory_m2": ( + float(state.negative_domain_inventory_m2) if isinstance(state, IonicState1D) else 0.0 + ), + } + + prepared_sha = ( + prepared.content_sha256 + if prepared is not None + else ( + device.original_prepared_sha256 + if isinstance(device, CompiledIonicDevice1D) + else elec_device.parameters.sha256 + ) + ) + materials_section: dict[str, Any] = { + "schema": "solarlab.materials-binding.v1", + "device_id": device.device_id, + "compiled_identity": device.identity, + "prepared_sha256": prepared_sha, + "family": "ionic_1d" if is_ionic else "electronic_1d", + } + + damage_payload = ( + {"schema": "solarlab.damage-state.v1", "status": "undamaged", "parameters": {}} + if damage_state is None + else { + "schema": "solarlab.damage-state.v1", + **{k: v for k, v in damage_state.items() if k != "schema"}, + } + ) + + grid_section: dict[str, Any] = { + "schema": "solarlab.grid-binding.v1", + "geometry_name": elec_device.geometry.name, + "node_count": int(elec_device.node_count), + "electronic_nodes_m": encode_array( + np.ascontiguousarray(elec_device.nodes_m, dtype=np.float64), unit="m" + ), + "electronic_cell_measures_m": encode_array( + np.ascontiguousarray(elec_device.geometry.cell_measures_m, dtype=np.float64), unit="m" + ), + } + if isinstance(device, CompiledIonicDevice1D): + grid_section["ion_domain_layer"] = device.domain_layer_id + grid_section["ion_node_indices"] = [int(i) for i in device.ion_node_indices.tolist()] + grid_section["ion_nodes_m"] = encode_array( + np.ascontiguousarray(device.ion_geometry.nodes_m, dtype=np.float64), unit="m" + ) + grid_section["ion_cell_measures_m"] = encode_array( + np.ascontiguousarray(device.ion_geometry.cell_measures_m, dtype=np.float64), unit="m" + ) + + switches_doc = ( + {"illumination": "on" if generation_scale > 0.0 else "dark", "circuit": "voltage_source"} + if switch_state is None + else dict(switch_state) + ) + prior_stages = ( + list(prior_history.get("prior_stages", [])) + if prior_history is not None and isinstance(prior_history.get("prior_stages"), list) + else [] + ) + history_section: dict[str, Any] = { + "schema": "solarlab.stage-history.v1", + "stage_id": stage_id, + "boundary_side": str(prior_history.get("boundary_side", "interior")) + if prior_history is not None + else "interior", + "time_s": float(time_s), + "applied_voltage_V": applied_voltage_V, + "generation_scale": float(generation_scale), + "switches": switches_doc, + "is_equilibrium": bool(is_equilibrium), + "declared_state_reset": bool( + prior_history.get("declared_state_reset", False) if prior_history is not None else False + ), + "prior_stages": prior_stages, + } + + qualification_section: dict[str, Any] = { + "schema": "solarlab.qualification-record.v1", + "scientific_qualification": False, + "evidence_labels": list(dict.fromkeys(evidence_labels)), + "limitations": list(dict.fromkeys(limitations)), + } + + sections: dict[str, dict[str, Any]] = { + "state": state_section, + "inventories": inventories_section, + "coordinate_reference": coord_ref_section, + "materials": materials_section, + "damage": damage_payload, + "grid": grid_section, + "history": history_section, + "qualification": qualification_section, + } + wp_doc: dict[str, Any] = { + "schema": "solarlab.working-point.v1", + "id": point_id, + "engine": "solarlab", + "owner_epoch": owner_epoch, + "physical_identity": physical_id, + "state_encoding": state_encoding, + **{name: _ref(f"{point_id}:{name}", _section_sha256(sections[name])) for name in _POINT_SECTION_NAMES}, + } + wp = WorkingPoint.from_document(wp_doc) + return WorkingPointBundle(working_point=wp, sections=sections) + + +def _verify_grid_against_device( + bundle: WorkingPointBundle, device: CompiledDevice1D | CompiledIonicDevice1D +) -> None: + grid_sec = bundle.sections["grid"] + elec_device = device.electronic_component if isinstance(device, CompiledIonicDevice1D) else device + nodes = decode_array(grid_sec["electronic_nodes_m"]) + measures = decode_array(grid_sec["electronic_cell_measures_m"]) + if nodes.shape != elec_device.nodes_m.shape or not np.array_equal(nodes, elec_device.nodes_m): + raise WorkingPointTransferError("electronic grid nodes disagree between WorkingPointBundle and device") + if measures.shape != elec_device.geometry.cell_measures_m.shape or not np.array_equal( + measures, elec_device.geometry.cell_measures_m + ): + raise WorkingPointTransferError("electronic control volumes disagree between WorkingPointBundle and device") + if isinstance(device, CompiledIonicDevice1D): + if "ion_nodes_m" not in grid_sec: + raise WorkingPointTransferError("ionic device reconstruction requires ion_nodes_m in grid section") + ion_nodes = decode_array(grid_sec["ion_nodes_m"]) + if ion_nodes.shape != device.ion_geometry.nodes_m.shape or not np.array_equal( + ion_nodes, device.ion_geometry.nodes_m + ): + raise WorkingPointTransferError("ionic grid nodes disagree between WorkingPointBundle and device") + + +def reconstruct_state_1d( + bundle: WorkingPointBundle, + device: CompiledDevice1D, + *, + target_voltage_V: float | None = None, + require_same_materials: bool = True, + inventory_rtol: float = 1e-12, +) -> State1D: + """Reconstruct a ``State1D`` from either coordinate-encoded or physical-field-encoded bundle.""" + if not isinstance(bundle, WorkingPointBundle) or not isinstance(device, CompiledDevice1D): + raise TypeError("reconstruct_state_1d requires WorkingPointBundle and CompiledDevice1D") + if bundle.state_encoding not in _ELECTRONIC_ENCODINGS: + raise WorkingPointTransferError( + f"reconstruct_state_1d expects electronic 1D encoding, got {bundle.state_encoding!r}" + ) + if require_same_materials and bundle.sections["materials"]["compiled_identity"] != device.identity: + raise WorkingPointTransferError( + "WorkingPointBundle materials.compiled_identity disagrees with CompiledDevice1D.identity" + ) + _verify_grid_against_device(bundle, device) + state_sec = bundle.sections["state"] + applied_v = float(state_sec["applied_voltage_V"]) if target_voltage_V is None else float(target_voltage_V) + if not math.isfinite(applied_v): + raise WorkingPointTransferError("target_voltage_V must be finite") + + if bundle.state_encoding == COORDINATE_ENCODING_1D: + u_raw = decode_array(state_sec["u"]) + ref_v = float(state_sec["reference_voltage_V"]) + if u_raw.shape != (3 * device.node_count,): + raise WorkingPointTransferError("encoded u shape does not match 3 * device.node_count") + u = u_raw if ref_v == applied_v else device.rebase_coordinates(u_raw, ref_v, applied_v) + else: + phi = decode_array(state_sec["potential_V"]) + n = decode_array(state_sec["electron_density_m3"]) + p = decode_array(state_sec["hole_density_m3"]) + u = coordinates_from_physical_fields_1d( + device, + potential_V=phi, + electron_density_m3=n, + hole_density_m3=p, + voltage_V=applied_v, + ) + + reconstructed = device.state(u, voltage_V=applied_v) + elec_inv, hole_inv = _carrier_inventories(device, reconstructed) + inv_sec = bundle.sections["inventories"] + if not math.isclose(elec_inv, float(inv_sec["electron_inventory_m2"]), rel_tol=inventory_rtol, abs_tol=1e-18): + raise WorkingPointTransferError("reconstructed electron inventory diverges from recorded inventory") + if not math.isclose(hole_inv, float(inv_sec["hole_inventory_m2"]), rel_tol=inventory_rtol, abs_tol=1e-18): + raise WorkingPointTransferError("reconstructed hole inventory diverges from recorded inventory") + return reconstructed + + +def reconstruct_ionic_state_1d( + bundle: WorkingPointBundle, + device: CompiledIonicDevice1D, + *, + target_voltage_V: float | None = None, + require_same_materials: bool = True, + inventory_rtol: float = 1e-12, +) -> IonicState1D: + """Reconstruct an ``IonicState1D`` from coordinate-encoded or physical-field-encoded bundle.""" + if not isinstance(bundle, WorkingPointBundle) or not isinstance(device, CompiledIonicDevice1D): + raise TypeError("reconstruct_ionic_state_1d requires WorkingPointBundle and CompiledIonicDevice1D") + if bundle.state_encoding not in _IONIC_ENCODINGS: + raise WorkingPointTransferError( + f"reconstruct_ionic_state_1d expects ionic 1D encoding, got {bundle.state_encoding!r}" + ) + if require_same_materials and bundle.sections["materials"]["compiled_identity"] != device.identity: + raise WorkingPointTransferError( + "WorkingPointBundle materials.compiled_identity disagrees with CompiledIonicDevice1D.identity" + ) + _verify_grid_against_device(bundle, device) + state_sec = bundle.sections["state"] + applied_v = float(state_sec["applied_voltage_V"]) if target_voltage_V is None else float(target_voltage_V) + if not math.isfinite(applied_v): + raise WorkingPointTransferError("target_voltage_V must be finite") + + elec_count = 3 * device.node_count + if bundle.state_encoding == COORDINATE_ENCODING_IONIC_1D: + u_raw = decode_array(state_sec["u"]) + if u_raw.shape != (device.state_size,): + raise WorkingPointTransferError("encoded ionic u shape does not match device.state_size") + ref_v = float(state_sec["reference_voltage_V"]) + u_elec = ( + u_raw[:elec_count] + if ref_v == applied_v + else device.electronic_component.rebase_coordinates(u_raw[:elec_count], ref_v, applied_v) + ) + u_full = np.concatenate((u_elec, u_raw[elec_count:])) + else: + phi = decode_array(state_sec["potential_V"]) + n = decode_array(state_sec["electron_density_m3"]) + p = decode_array(state_sec["hole_density_m3"]) + p_pos = decode_array(state_sec["positive_ion_density_m3"]) + p_neg = ( + decode_array(state_sec["negative_ion_density_m3"]) + if state_sec.get("negative_ion_density_m3") is not None + else None + ) + u_elec = coordinates_from_physical_fields_1d( + device.electronic_component, + potential_V=phi, + electron_density_m3=n, + hole_density_m3=p, + voltage_V=applied_v, + ) + u_ion = ion_coordinates_from_physical_densities_1d( + device, + positive_ion_density_m3=p_pos, + negative_ion_density_m3=p_neg, + ) + u_full = np.concatenate((u_elec, u_ion)) + + reconstructed = device.state(u_full, voltage_V=applied_v) + elec_inv, hole_inv = _carrier_inventories(device.electronic_component, reconstructed.electronic_state) + inv_sec = bundle.sections["inventories"] + if not math.isclose(elec_inv, float(inv_sec["electron_inventory_m2"]), rel_tol=inventory_rtol, abs_tol=1e-18): + raise WorkingPointTransferError("reconstructed electron inventory diverges from recorded inventory") + if not math.isclose(hole_inv, float(inv_sec["hole_inventory_m2"]), rel_tol=inventory_rtol, abs_tol=1e-18): + raise WorkingPointTransferError("reconstructed hole inventory diverges from recorded inventory") + if not math.isclose( + reconstructed.domain_inventory_m2, + float(inv_sec["positive_ion_inventory_m2"]), + rel_tol=inventory_rtol, + abs_tol=1e-18, + ): + raise WorkingPointTransferError("reconstructed positive ion inventory diverges from recorded inventory") + if device.ion_species_count == 2 and not math.isclose( + reconstructed.negative_domain_inventory_m2, + float(inv_sec["negative_ion_inventory_m2"]), + rel_tol=inventory_rtol, + abs_tol=1e-18, + ): + raise WorkingPointTransferError("reconstructed negative ion inventory diverges from recorded inventory") + return reconstructed + + +@dataclass(frozen=True, slots=True) +class StageBoundaryState: + """Explicit stage-left (``t^-``) and stage-right (``t^+``) boundary states.""" + + from_stage: str + to_stage: str + boundary_time_s: float + preserved_quantities: tuple[str, ...] + left_bundle: WorkingPointBundle + right_bundle: WorkingPointBundle + + +@dataclass(frozen=True, slots=True) +class StageTransferResult: + """Validated stage-to-stage transfer outcome with rebound device and right-boundary state.""" + + boundary: StageBoundaryState + compiled_device: CompiledDevice1D | CompiledIonicDevice1D + right_state: State1D | IonicState1D + rebound_materials: bool + + +def transfer_working_point( + protocol: Protocol, + source_bundle: WorkingPointBundle, + compiled_device: CompiledDevice1D | CompiledIonicDevice1D, + *, + from_stage: str, + to_stage: str, + boundary_time_s: float, + right_voltage_V: float, + right_generation_scale: float, + right_point_id: str, + owner_epoch: str, + right_encoding: Literal["coordinates", "physical_fields"] | None = None, + right_switches: Mapping[str, Any] | None = None, + next_damage_state: Mapping[str, Any] | None = None, + rebind_damaged_device: Callable[ + [Mapping[str, Any]], CompiledDevice1D | CompiledIonicDevice1D + ] + | None = None, + declared_reset_state: State1D | IonicState1D | None = None, + allow_declared_reset: bool = False, +) -> StageTransferResult: + """Execute a protocol-governed ``t^- -> t^+`` stage boundary transfer. + + Enforces ``preserve`` invariants strictly: + - Never silently resets state to steady state; state reset requires both + ``"state"`` omitted from ``preserve`` AND explicit ``declared_reset_state`` + with ``allow_declared_reset=True``. + - Rebinds ``CompiledDevice1D`` / ``CompiledIonicDevice1D`` if and only if + ``damage`` digest changes across the stage boundary. + """ + if not isinstance(protocol, Protocol) or not isinstance(source_bundle, WorkingPointBundle): + raise TypeError("transfer_working_point requires Protocol and WorkingPointBundle") + proto_doc = protocol.export() + matching = [ + entry + for entry in proto_doc["transfers"] + if entry["from"] == from_stage and entry["to"] == to_stage + ] + if len(matching) != 1: + raise WorkingPointTransferError( + f"protocol must declare exactly one transfer for {from_stage!r} -> {to_stage!r}" + ) + transfer_decl = matching[0] + expected_wp = transfer_decl["working_point"] + if expected_wp["id"] != source_bundle.id or expected_wp["sha256"] != source_bundle.sha256: + raise WorkingPointTransferError( + "source_bundle working_point id/sha256 disagrees with Protocol.transfers declaration" + ) + preserve = tuple(str(item) for item in transfer_decl["preserve"]) + preserve_set = set(preserve) + + # Damage & material rebinding rule: rebind ONLY when damage digest changes. + old_damage_doc = source_bundle.sections["damage"] + new_damage_doc = ( + old_damage_doc + if next_damage_state is None + else { + "schema": "solarlab.damage-state.v1", + **{k: v for k, v in next_damage_state.items() if k != "schema"}, + } + ) + damage_changed = _section_sha256(new_damage_doc) != _section_sha256(old_damage_doc) + + if damage_changed: + if "damage" in preserve_set or "materials" in preserve_set: + raise WorkingPointTransferError( + "damage state changed across boundary while protocol preserves 'damage'/'materials'" + ) + if rebind_damaged_device is None: + raise WorkingPointTransferError( + "damage state changed across boundary; explicit rebind_damaged_device callback is required" + ) + target_device = rebind_damaged_device(new_damage_doc) + rebound_materials = True + else: + if rebind_damaged_device is not None and "materials" in preserve_set: + # Even if a callback was passed, unchanged damage MUST NOT trigger material rebinding. + target_device = compiled_device + else: + target_device = compiled_device + rebound_materials = False + if source_bundle.sections["materials"]["compiled_identity"] != target_device.identity: + raise WorkingPointTransferError( + "compiled_device identity differs from source_bundle without a damage transition" + ) + + if "grid" in preserve_set: + _verify_grid_against_device(source_bundle, target_device) + + target_encoding: Literal["coordinates", "physical_fields"] + if right_encoding is None: + target_encoding = ( + "coordinates" + if source_bundle.state_encoding in {COORDINATE_ENCODING_1D, COORDINATE_ENCODING_IONIC_1D} + else "physical_fields" + ) + else: + target_encoding = right_encoding + + left_coord_ref = source_bundle.sections["coordinate_reference"] + if "coordinate_reference" in preserve_set: + expected_repr = str(left_coord_ref["representation"]) + if target_encoding != expected_repr: + raise WorkingPointTransferError( + "protocol preserves 'coordinate_reference'; representation encoding cannot change" + ) + if target_encoding == "coordinates" and float(right_voltage_V) != float( + left_coord_ref["reference_voltage_V"] + ): + raise WorkingPointTransferError( + "protocol preserves 'coordinate_reference'; coordinate reference voltage cannot jump" + ) + + # Reconstruct left physical state on source device first so t^- is verified intact. + if isinstance(compiled_device, CompiledIonicDevice1D): + left_state: State1D | IonicState1D = reconstruct_ionic_state_1d(source_bundle, compiled_device) + else: + left_state = reconstruct_state_1d(source_bundle, compiled_device) + + # Enforce strict state preservation vs explicitly declared reset. + if declared_reset_state is not None: + if "state" in preserve_set: + raise WorkingPointTransferError( + "protocol preserves 'state'; silent or declared reset to equilibrium is forbidden" + ) + if not allow_declared_reset: + raise WorkingPointTransferError( + "declared_reset_state requires allow_declared_reset=True and 'state' omitted from preserve" + ) + right_state = declared_reset_state + was_reset = True + else: + if "state" not in preserve_set and not allow_declared_reset: + raise WorkingPointTransferError( + "protocol omits 'state' from preserve without an explicit authorized declared_reset_state" + ) + was_reset = False + if rebound_materials: + if isinstance(target_device, CompiledIonicDevice1D): + if not isinstance(left_state, IonicState1D): + raise WorkingPointTransferError("ionic target_device requires ionic left_state") + u_elec_reb = coordinates_from_physical_fields_1d( + target_device.electronic_component, + potential_V=left_state.electronic_state.potential_V, + electron_density_m3=left_state.electronic_state.electron_density_m3, + hole_density_m3=left_state.electronic_state.hole_density_m3, + voltage_V=right_voltage_V, + ) + u_ion_reb = ion_coordinates_from_physical_densities_1d( + target_device, + positive_ion_density_m3=left_state.positive_ion_density_m3, + negative_ion_density_m3=( + left_state.negative_ion_density_m3 + if left_state.negative_ion_density_m3.size > 0 + else None + ), + ) + right_state = target_device.state( + np.concatenate((u_elec_reb, u_ion_reb)), voltage_V=right_voltage_V + ) + else: + if not isinstance(left_state, State1D): + raise WorkingPointTransferError("electronic target_device requires electronic left_state") + u_reb = coordinates_from_physical_fields_1d( + target_device, + potential_V=left_state.potential_V, + electron_density_m3=left_state.electron_density_m3, + hole_density_m3=left_state.hole_density_m3, + voltage_V=right_voltage_V, + ) + right_state = target_device.state(u_reb, voltage_V=right_voltage_V) + elif isinstance(target_device, CompiledIonicDevice1D): + right_state = reconstruct_ionic_state_1d( + source_bundle, + target_device, + target_voltage_V=right_voltage_V, + require_same_materials=True, + ) + else: + right_state = reconstruct_state_1d( + source_bundle, + target_device, + target_voltage_V=right_voltage_V, + require_same_materials=True, + ) + if not physical_state_equivalent(left_state, right_state, rtol=1e-13): + raise WorkingPointTransferError("t^- and t^+ physical densities diverged across transfer") + + left_history = source_bundle.sections["history"] + if "history" in preserve_set and not math.isclose( + float(boundary_time_s), float(left_history["time_s"]), rel_tol=0.0, abs_tol=1e-15 + ): + raise WorkingPointTransferError( + f"boundary_time_s ({boundary_time_s}) disagrees with t^- history time_s ({left_history['time_s']})" + ) + + prior_chain = list(left_history.get("prior_stages", [])) + prior_chain.append( + { + "stage_id": str(left_history["stage_id"]), + "end_time_s": float(left_history["time_s"]), + "left_working_point_sha256": source_bundle.sha256, + "rebound_materials": rebound_materials, + "declared_state_reset": was_reset, + } + ) + qual_sec = source_bundle.sections["qualification"] + right_bundle = capture_working_point( + target_device, + right_state, + point_id=right_point_id, + owner_epoch=owner_epoch, + stage_id=to_stage, + time_s=boundary_time_s, + generation_scale=right_generation_scale, + is_equilibrium=bool(left_history["is_equilibrium"]) and not was_reset + and float(right_voltage_V) == float(left_history["applied_voltage_V"]) + and float(right_generation_scale) == float(left_history["generation_scale"]) + and not rebound_materials, + encoding=target_encoding, + reference_voltage_V=right_voltage_V if target_encoding == "coordinates" else None, + damage_state=new_damage_doc, + switch_state=right_switches, + prior_history={ + "boundary_side": "right", + "declared_state_reset": was_reset, + "prior_stages": prior_chain, + }, + evidence_labels=tuple(qual_sec["evidence_labels"]), + limitations=tuple(qual_sec["limitations"]), + ) + + if "inventories" in preserve_set: + for key in ( + "electron_inventory_m2", + "hole_inventory_m2", + "positive_ion_inventory_m2", + "negative_ion_inventory_m2", + ): + if not math.isclose( + float(source_bundle.sections["inventories"][key]), + float(right_bundle.sections["inventories"][key]), + rel_tol=1e-13, + abs_tol=1e-18, + ): + raise WorkingPointTransferError(f"preserved inventory {key!r} drifted across boundary") + + if "state" in preserve_set and right_bundle.physical_identity != source_bundle.physical_identity: + # When rebinding or voltage-rebasing shifts float64 by 1 ULP, verify 1e-13 equivalence; + # when capture uses identical physical arrays (same device, physical_fields or exact state), + # physical_identity matches bit-for-bit as well. + if not physical_state_equivalent(left_state, right_state, rtol=1e-13): + raise WorkingPointTransferError("physical state identity violated across preserved transfer") + + boundary = StageBoundaryState( + from_stage=from_stage, + to_stage=to_stage, + boundary_time_s=float(boundary_time_s), + preserved_quantities=preserve, + left_bundle=source_bundle, + right_bundle=right_bundle, + ) + return StageTransferResult( + boundary=boundary, + compiled_device=target_device, + right_state=right_state, + rebound_materials=rebound_materials, + ) + + +@dataclass(frozen=True, slots=True) +class StageIntegrationTrace: + """Step-by-step Backward Euler stage trace starting from an arbitrary ``WorkingPointBundle``.""" + + initial_bundle: WorkingPointBundle + final_bundle: WorkingPointBundle | None + protocol: TransientProtocol + accepted_times_s: np.ndarray + states: tuple[State1D | IonicState1D, ...] + attempts: tuple[TransientAttempt | IonicTransientAttempt, ...] + terminal_conduction_current_A_m2: np.ndarray + terminal_displacement_current_A_m2: np.ndarray + terminal_total_current_A_m2: np.ndarray + maxwell_spread_A_m2: np.ndarray + outcome: Literal["completed", "partial", "failed"] + failure_reason: str | None + wall_s: float + + +def _ionic_newton_settings( + compiled: CompiledIonicDevice1D, options: IonicTransientOptions +) -> tuple[NewtonSettings, Callable[[np.ndarray], float]]: + electronic = options.electronic + count, ion_count = compiled.node_count, compiled.ion_geometry.node_count + weights = np.r_[ + production_residual_scaling( + compiled.electronic_component, + poisson_tolerance=electronic.poisson_tolerance, + continuity_tolerance_A_m2=electronic.continuity_tolerance_A_m2, + contact_log_tolerance=electronic.contact_log_tolerance, + ).row_weights, + np.full( + ion_count * compiled.ion_species_count, + ion_count / options.ion_balance_tolerance_m2_s, + ), + ] + steps = np.r_[ + production_coordinates( + compiled.electronic_component, + potential_step_V=electronic.potential_step_V, + quasi_fermi_step=electronic.quasi_fermi_step, + ).max_step, + np.full(ion_count * compiled.ion_species_count, options.ion_logit_step), + ] + settings = NewtonSettings( + ResidualScaling(weights), + 1.0, + StepControl(steps), + electronic.newton_budget, + (), + False, + ) + electronic_norm = production_convergence_norm( + compiled.electronic_component, + convergence_policy=electronic.convergence_policy, + ) + assert electronic_norm is not None + + def convergence_norm(scaled: np.ndarray) -> float: + if scaled.shape != (compiled.state_size,) or not np.all(np.isfinite(scaled)): + return math.inf + return max( + electronic_norm(scaled[: 3 * count]), + *( + math.fsum(abs(scaled[block]).tolist()) / ion_count + for block in compiled.ion_species_slices + ), + ) + + return settings, convergence_norm + + +def integrate_stage_from_working_point( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + initial_bundle: WorkingPointBundle, + stage_protocol: TransientProtocol, + *, + options: TransientOptions | IonicTransientOptions, + stage_id: str, + final_point_id: str, + owner_epoch: str, + final_encoding: Literal["coordinates", "physical_fields"] = "coordinates", +) -> StageIntegrationTrace: + """Integrate a transient stage directly from ``initial_bundle`` without steady-state reset. + + Computes conduction, displacement, and total Maxwell terminal currents from + step-to-step Backward Euler state differences (never single-snapshot DC + postprocessing). Unreached steps on partial/failed runs carry IEEE-754 + ``NaN`` so ``encode_array`` masks them losslessly. + """ + started = time.monotonic() + step_count = int(stage_protocol.times_s.size - 1) + cond_arr: NDArray[np.float64] = np.full(step_count, np.nan, dtype=np.float64) + disp_arr: NDArray[np.float64] = np.full(step_count, np.nan, dtype=np.float64) + tot_arr: NDArray[np.float64] = np.full(step_count, np.nan, dtype=np.float64) + spread_arr: NDArray[np.float64] = np.full(step_count, np.nan, dtype=np.float64) + + hist = initial_bundle.sections["history"] + v0 = float(stage_protocol.voltage_V[0]) + g0 = float(stage_protocol.generation_scale[0]) + if not math.isclose(v0, float(hist["applied_voltage_V"]), rel_tol=0.0, abs_tol=1e-15): + raise WorkingPointTransferError( + "stage_protocol.voltage_V[0] must match initial_bundle history applied_voltage_V; " + "use transfer_working_point for stage boundary voltage jumps" + ) + if not math.isclose(g0, float(hist["generation_scale"]), rel_tol=0.0, abs_tol=1e-15): + raise WorkingPointTransferError( + "stage_protocol.generation_scale[0] must match initial_bundle history generation_scale; " + "use transfer_working_point for stage boundary illumination switches" + ) + + if isinstance(compiled, CompiledIonicDevice1D): + if not isinstance(options, IonicTransientOptions): + raise TypeError("CompiledIonicDevice1D requires IonicTransientOptions") + elec_opts = options.electronic + if step_count > elec_opts.max_steps: + raise ValueError("requested timepoints exceed max_steps") + state0_ion = reconstruct_ionic_state_1d(initial_bundle, compiled, target_voltage_V=v0) + settings, conv_norm = _ionic_newton_settings(compiled, options) + deadline = started + elec_opts.wall_s + assembled = use_assembled() + states_ion: list[State1D | IonicState1D] = [state0_ion] + accepted_times = [float(stage_protocol.times_s[0])] + attempts_ion: list[TransientAttempt | IonicTransientAttempt] = [] + failure_reason: str | None = None + + for idx in range(1, stage_protocol.times_s.size): + t_start = float(stage_protocol.times_s[idx - 1]) + t_end = float(stage_protocol.times_s[idx]) + v_end = float(stage_protocol.voltage_V[idx]) + g_end = float(stage_protocol.generation_scale[idx]) + attempt_t0 = time.monotonic() + prev_ion = cast(IonicState1D, states_ion[-1]) + candidate = np.array(prev_ion.u, copy=True) + seed = candidate.copy() + counts = {"residual": 0, "jacobian": 0, "accounting": 0} + newton_res = None + accounting: dict[str, object] | None = None + err_msg: str | None = None + next_ion: IonicState1D | None = None + + def eval_ion( + kind: str, + fn: Callable[[np.ndarray], Matrix], + y: np.ndarray, + _counts: dict[str, int] = counts, + ) -> Matrix: + nonlocal candidate + candidate = np.array(y, copy=True) + if time.monotonic() >= deadline: + raise RuntimeError("wall_budget_exhausted") + _counts[kind] += 1 + out = fn(y) + if time.monotonic() >= deadline: + raise RuntimeError("wall_budget_exhausted") + return out + + try: + step_ion = ( + cast( + IonicBackwardEuler1DStep, + AssembledIonicBackwardEuler1DStep( + AssembledIonic1DProblem(compiled, v_end, g_end), + prev_ion, + t_end - t_start, + ), + ) + if assembled + else IonicBackwardEuler1DStep( + Ionic1DProblem(compiled, v_end, g_end), + prev_ion, + t_end - t_start, + ) + ) + candidate = step_ion.initial_coordinates(elec_opts.predictor, voltage_lift=True) + seed = candidate.copy() + def _ion_res(y: np.ndarray) -> np.ndarray: + return np.asarray(eval_ion("residual", step_ion.residual, y), dtype=np.float64) + + def _ion_jac(y: np.ndarray) -> Matrix: + return eval_ion("jacobian", step_ion.jacobian, y) + + newton_res = solve_newton( + CallableProblem(_ion_res, _ion_jac), + candidate, + settings, + convergence_norm=conv_norm, + ) + candidate = newton_res.state + if np.all(np.isfinite(candidate)): + next_ion = compiled.state(candidate, voltage_V=v_end) + counts["accounting"] += 1 + accounting = ionic_step_accounting(step_ion, candidate) + accepted = bool(newton_res.accepted) + termination = newton_res.termination.value + if accepted and accounting is None: + accepted, termination = False, "nonfinite_accounting" + except Exception as exc: + accepted = False + termination = ( + "wall_budget_exhausted" + if str(exc) == "wall_budget_exhausted" + else "evaluation_error" + ) + err_msg = f"{type(exc).__name__}: {str(exc)[:300]}" + + attempts_ion.append( + IonicTransientAttempt( + t_start, + t_end, + v_end, + g_end, + accepted, + termination, + seed, + candidate, + newton_res, + accounting, + counts, + time.monotonic() - attempt_t0, + err_msg, + ) + ) + if not accepted or next_ion is None or accounting is None: + failure_reason = err_msg or f"step_{idx}_failed:{termination}" + break + + cond_faces = np.asarray(accounting["conduction_current_density_A_m2"], dtype=float) + disp_faces = np.asarray(accounting["displacement_current_density_A_m2"], dtype=float) + tot_term = np.asarray(accounting["terminal_total_current_density_A_m2"], dtype=float) + cond_arr[idx - 1] = float(cond_faces[0]) + disp_arr[idx - 1] = float(disp_faces[0]) + tot_arr[idx - 1] = float(tot_term[0]) + spread_arr[idx - 1] = float(cast(float, accounting["maxwell_spread_A_m2"])) + states_ion.append(next_ion) + accepted_times.append(t_end) + + states_out = tuple(states_ion) + attempts_out = tuple(attempts_ion) + else: + if not isinstance(options, TransientOptions): + raise TypeError("CompiledDevice1D requires TransientOptions") + if step_count > options.max_steps: + raise ValueError("requested timepoints exceed max_steps") + state0_elec = reconstruct_state_1d(initial_bundle, compiled, target_voltage_V=v0) + settings = NewtonSettings( + production_residual_scaling( + compiled, + poisson_tolerance=options.poisson_tolerance, + continuity_tolerance_A_m2=options.continuity_tolerance_A_m2, + contact_log_tolerance=options.contact_log_tolerance, + ), + 1.0, + production_coordinates( + compiled, + potential_step_V=options.potential_step_V, + quasi_fermi_step=options.quasi_fermi_step, + ), + options.newton_budget, + (), + False, + ) + conv_norm_e = production_convergence_norm( + compiled, convergence_policy=options.convergence_policy + ) + deadline = started + options.wall_s + binding = classical_dc_1d(compiled) if use_assembled() else None + states_e: list[State1D | IonicState1D] = [state0_elec] + accepted_times = [float(stage_protocol.times_s[0])] + attempts_e: list[TransientAttempt | IonicTransientAttempt] = [] + failure_reason = None + + for idx in range(1, stage_protocol.times_s.size): + t_start = float(stage_protocol.times_s[idx - 1]) + t_end = float(stage_protocol.times_s[idx]) + v_end = float(stage_protocol.voltage_V[idx]) + g_end = float(stage_protocol.generation_scale[idx]) + attempt_t0 = time.monotonic() + prev_e = cast(State1D, states_e[-1]) + endpoint = ( + DC1DProblem(compiled, v_end, g_end) + if binding is None + else cast( + DC1DProblem, + AssembledStorage1D(AssembledDC1DProblem(compiled, v_end, g_end, binding)), + ) + ) + step_e = BackwardEuler1DStep(endpoint, prev_e, t_end - t_start) + candidate = step_e.initial_coordinates(voltage_lift=True) + seed = candidate.copy() + newton_res = None + accounting = None + err_msg = None + + def eval_e(fn: Callable[[np.ndarray], Matrix], u: np.ndarray) -> Matrix: + nonlocal candidate + candidate = np.array(u, copy=True) + if time.monotonic() >= deadline: + raise RuntimeError("wall_budget_exhausted") + out = fn(u) + if time.monotonic() >= deadline: + raise RuntimeError("wall_budget_exhausted") + return out + + try: + candidate = step_e.initial_coordinates(options.predictor, voltage_lift=True) + seed = candidate.copy() + def _elec_res(u: np.ndarray) -> np.ndarray: + return np.asarray(eval_e(step_e.residual, u), dtype=np.float64) + + def _elec_jac(u: np.ndarray) -> Matrix: + return eval_e(step_e.jacobian, u) + + newton_res = solve_newton( + CallableProblem(_elec_res, _elec_jac), + candidate, + settings, + convergence_norm=conv_norm_e, + ) + candidate = newton_res.state + if np.all(np.isfinite(candidate)): + _, n_chk, p_chk = compiled.fields(candidate, voltage_V=v_end) + if ( + np.all(np.isfinite(n_chk)) + and np.all(np.isfinite(p_chk)) + and np.all(n_chk > 0.0) + and np.all(p_chk > 0.0) + ): + accounting = electronic_step_accounting(step_e, candidate) + accepted = bool(newton_res.accepted) + termination = newton_res.termination.value + if accepted and accounting is None: + accepted, termination = False, "nonfinite_accounting" + except Exception as exc: + accepted = False + termination = ( + "wall_budget_exhausted" + if str(exc) == "wall_budget_exhausted" + else "evaluation_error" + ) + err_msg = f"{type(exc).__name__}: {str(exc)[:300]}" + + attempts_e.append( + TransientAttempt( + t_start, + t_end, + v_end, + g_end, + accepted, + termination, + seed, + candidate, + newton_res, + accounting, + time.monotonic() - attempt_t0, + err_msg, + ) + ) + if not accepted or accounting is None: + failure_reason = err_msg or f"step_{idx}_failed:{termination}" + break + + cond_term = np.asarray( + accounting["terminal_conduction_current_density_A_m2"], dtype=float + ) + disp_term = np.asarray( + accounting["terminal_displacement_current_density_A_m2"], dtype=float + ) + tot_term = np.asarray(accounting["terminal_total_current_density_A_m2"], dtype=float) + cond_arr[idx - 1] = float(cond_term[0]) + disp_arr[idx - 1] = float(disp_term[0]) + tot_arr[idx - 1] = float(tot_term[0]) + spread_arr[idx - 1] = float(cast(float, accounting["maxwell_spread_A_m2"])) + states_e.append(compiled.state(candidate, voltage_V=v_end)) + accepted_times.append(t_end) + + states_out = tuple(states_e) + attempts_out = tuple(attempts_e) + + n_accepted_steps = len(states_out) - 1 + if n_accepted_steps == step_count and failure_reason is None: + outcome: Literal["completed", "partial", "failed"] = "completed" + elif n_accepted_steps > 0: + outcome = "partial" + else: + outcome = "failed" + + qual = initial_bundle.sections["qualification"] + final_bundle: WorkingPointBundle | None = None + if n_accepted_steps > 0: + last_idx = n_accepted_steps + prior_stages = list(hist.get("prior_stages", [])) + prior_stages.append( + { + "stage_id": str(hist["stage_id"]), + "start_time_s": float(stage_protocol.times_s[0]), + "end_time_s": float(accepted_times[-1]), + "initial_working_point_sha256": initial_bundle.sha256, + "accepted_steps": n_accepted_steps, + } + ) + final_bundle = capture_working_point( + compiled, + states_out[-1], + point_id=final_point_id, + owner_epoch=owner_epoch, + stage_id=stage_id, + time_s=float(accepted_times[-1]), + generation_scale=float(stage_protocol.generation_scale[last_idx]), + is_equilibrium=False, + encoding=final_encoding, + damage_state=initial_bundle.sections["damage"], + switch_state=hist.get("switches"), + prior_history={"boundary_side": "left", "prior_stages": prior_stages}, + evidence_labels=tuple(qual["evidence_labels"]), + limitations=tuple(qual["limitations"]), + ) + + def _readonly_float64(values: np.ndarray) -> np.ndarray: + arr = np.array(values, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + return StageIntegrationTrace( + initial_bundle=initial_bundle, + final_bundle=final_bundle, + protocol=stage_protocol, + accepted_times_s=frozen_array(np.asarray(accepted_times, dtype=np.float64)), + states=states_out, + attempts=attempts_out, + terminal_conduction_current_A_m2=_readonly_float64(cond_arr), + terminal_displacement_current_A_m2=_readonly_float64(disp_arr), + terminal_total_current_A_m2=_readonly_float64(tot_arr), + maxwell_spread_A_m2=_readonly_float64(spread_arr), + outcome=outcome, + failure_reason=failure_reason, + wall_s=time.monotonic() - started, + ) + + +def build_stage_experiment_result( + trace: StageIntegrationTrace, + *, + protocol: Protocol, + run_id: str, + attempt_id: str, + experiment_id: str, + bindings_override: Mapping[str, Mapping[str, str]] | None = None, + evidence: Sequence[Mapping[str, Any]] | None = None, +) -> ExperimentResult: + """Wrap a ``StageIntegrationTrace`` into a validated ``ExperimentResult`` envelope.""" + wp = trace.initial_bundle.working_point + mat_sec = trace.initial_bundle.sections["materials"] + qual_sec = trace.initial_bundle.sections["qualification"] + proto_sha = protocol.sha256 + + numerics_doc = { + "step_count": int(trace.protocol.times_s.size - 1), + "accepted_steps": int(len(trace.states) - 1), + } + numerics_sha = _section_sha256(numerics_doc) + default_bindings: dict[str, dict[str, str]] = { + "source": _ref(str(mat_sec["device_id"]), str(mat_sec["prepared_sha256"])), + "schema": _ref("solarlab.experiment-result.v1", hashlib.sha256(b"solarlab.experiment-result.v1").hexdigest()), + "registry": _ref(experiment_id, hashlib.sha256(experiment_id.encode()).hexdigest()), + "physics": _ref(str(mat_sec["family"]), str(mat_sec["compiled_identity"])), + "protocol": _ref(str(protocol.export()["id"]), proto_sha), + "initial": _ref(trace.initial_bundle.id, wp.sha256), + "numerics": _ref("backward_euler_1d", numerics_sha), + "resources": _ref("inline_stage_resources", _section_sha256(trace.initial_bundle.sections["grid"])), + } + if bindings_override is not None: + for key, val in bindings_override.items(): + default_bindings[str(key)] = {"id": str(val["id"]), "sha256": str(val["sha256"])} + # Always pin 'initial' to the exact WorkingPoint binding of trace.initial_bundle. + default_bindings["initial"] = _ref(trace.initial_bundle.id, wp.sha256) + + evidence_list = ( + [dict(item) for item in evidence] + if evidence is not None + else [ + { + "label": str(qual_sec["evidence_labels"][0]), + "scope": [experiment_id], + "sources": ( + [] + if str(qual_sec["evidence_labels"][0]) in {"PARKED", "FIRST_SLICE"} + else [_ref(trace.initial_bundle.id, wp.sha256)] + ), + "limitations": list(qual_sec["limitations"]), + } + ] + ) + + payload: dict[str, Any] = { + "times_s": encode_array(np.asarray(trace.protocol.times_s, dtype=np.float64), unit="s"), + "accepted_times_s": encode_array(np.asarray(trace.accepted_times_s, dtype=np.float64), unit="s"), + "terminal_conduction_current_A_m2": encode_array( + np.asarray(trace.terminal_conduction_current_A_m2, dtype=np.float64), unit="A/m^2" + ), + "terminal_displacement_current_A_m2": encode_array( + np.asarray(trace.terminal_displacement_current_A_m2, dtype=np.float64), unit="A/m^2" + ), + "terminal_total_current_A_m2": encode_array( + np.asarray(trace.terminal_total_current_A_m2, dtype=np.float64), unit="A/m^2" + ), + "maxwell_spread_A_m2": encode_array( + np.asarray(trace.maxwell_spread_A_m2, dtype=np.float64), unit="A/m^2" + ), + "final_working_point": ( + _ref(trace.final_bundle.id, trace.final_bundle.sha256) + if trace.final_bundle is not None + else None + ), + } + + if trace.outcome == "completed": + peak_disp = float(np.max(np.abs(trace.terminal_displacement_current_A_m2))) + final_total = float(trace.terminal_total_current_A_m2[-1]) + max_spread = float(np.max(trace.maxwell_spread_A_m2)) + metrics: dict[str, dict[str, Any]] = { + "peak_abs_displacement_current_A_m2": { + "status": "identified", + "value": peak_disp, + "reason": None, + }, + "final_terminal_total_current_A_m2": { + "status": "identified", + "value": final_total, + "reason": None, + }, + "max_maxwell_spread_A_m2": { + "status": "identified", + "value": max_spread, + "reason": None, + }, + } + else: + unid_reason = trace.failure_reason or "incomplete_stage_trajectory" + metrics = { + "peak_abs_displacement_current_A_m2": { + "status": "unidentified", + "value": None, + "reason": unid_reason, + }, + "final_terminal_total_current_A_m2": { + "status": "unidentified", + "value": None, + "reason": unid_reason, + }, + "max_maxwell_spread_A_m2": { + "status": "unidentified", + "value": None, + "reason": unid_reason, + }, + } + + manifest_doc = { + "run_id": run_id, + "attempt_id": attempt_id, + "experiment_id": experiment_id, + "bindings": default_bindings, + } + manifest_sha = _section_sha256(manifest_doc) + doc: dict[str, Any] = { + "schema": "solarlab.experiment-result.v1", + "header": { + "run_id": run_id, + "attempt_id": attempt_id, + "experiment_id": experiment_id, + "engine": "solarlab", + "manifest_sha256": manifest_sha, + "outcome": trace.outcome, + "reason": None if trace.outcome == "completed" else (trace.failure_reason or "stage_incomplete"), + "bindings": default_bindings, + "evidence": evidence_list, + }, + "payload_schema": "solarlab.stage-transient-payload.v1", + "payload": payload, + "metrics": metrics, + } + return ExperimentResult.from_document(doc) + + +@dataclass(frozen=True, slots=True) +class PairedStageRunResult: + """Matched pulsed + unpulsed control perturbation stage results from one ``WorkingPointBundle``.""" + + initial_bundle: WorkingPointBundle + pulsed_trace: StageIntegrationTrace + control_trace: StageIntegrationTrace + pulsed_result: ExperimentResult + control_result: ExperimentResult + differential_conduction_current_A_m2: np.ndarray + differential_displacement_current_A_m2: np.ndarray + differential_total_current_A_m2: np.ndarray + + +def run_paired_perturbation_stages( + compiled: CompiledDevice1D | CompiledIonicDevice1D, + initial_bundle: WorkingPointBundle, + pulsed_protocol: TransientProtocol, + *, + options: TransientOptions | IonicTransientOptions, + protocol: Protocol, + run_id: str, + experiment_id: str, + owner_epoch: str, + control_protocol: TransientProtocol | None = None, + stage_id: str = "perturbation", +) -> PairedStageRunResult: + """Run pulsed and matched unpulsed-control perturbation stages from identical ``initial_bundle``. + + When ``control_protocol`` is omitted, constructs the matched constant-drive + unpulsed baseline on the exact ``pulsed_protocol.times_s`` grid holding + ``(voltage_V[0], generation_scale[0])`` fixed so background non-equilibrium + drift is subtracted cleanly step-by-step. + """ + if control_protocol is None: + v_hold = np.full_like(pulsed_protocol.times_s, float(pulsed_protocol.voltage_V[0])) + g_hold = np.full_like(pulsed_protocol.times_s, float(pulsed_protocol.generation_scale[0])) + control_protocol = TransientProtocol( + times_s=np.array(pulsed_protocol.times_s, copy=True), + voltage_V=v_hold, + generation_scale=g_hold, + ) + else: + if not np.array_equal(pulsed_protocol.times_s, control_protocol.times_s): + raise WorkingPointTransferError( + "pulsed_protocol and control_protocol must share identical times_s sample grids" + ) + if float(pulsed_protocol.voltage_V[0]) != float(control_protocol.voltage_V[0]) or float( + pulsed_protocol.generation_scale[0] + ) != float(control_protocol.generation_scale[0]): + raise WorkingPointTransferError( + "pulsed_protocol and control_protocol must start at identical initial drive" + ) + + pulsed_trace = integrate_stage_from_working_point( + compiled, + initial_bundle, + pulsed_protocol, + options=options, + stage_id=f"{stage_id}_pulsed", + final_point_id=f"{initial_bundle.id}:{stage_id}_pulsed_end", + owner_epoch=owner_epoch, + ) + control_trace = integrate_stage_from_working_point( + compiled, + initial_bundle, + control_protocol, + options=options, + stage_id=f"{stage_id}_control", + final_point_id=f"{initial_bundle.id}:{stage_id}_control_end", + owner_epoch=owner_epoch, + ) + + pulsed_res = build_stage_experiment_result( + pulsed_trace, + protocol=protocol, + run_id=run_id, + attempt_id=f"{run_id}:pulsed", + experiment_id=experiment_id, + ) + control_res = build_stage_experiment_result( + control_trace, + protocol=protocol, + run_id=run_id, + attempt_id=f"{run_id}:control", + experiment_id=f"{experiment_id}.unpulsed_control", + ) + + # Assert identical initial WorkingPoint binding across pulsed and control envelopes. + if pulsed_res.export()["header"]["bindings"]["initial"] != control_res.export()["header"]["bindings"]["initial"]: + raise WorkingPointTransferError("pulsed and unpulsed control initial WorkingPoint bindings diverged") + + def _ro(arr: np.ndarray) -> np.ndarray: + out = np.array(arr, dtype=np.float64, copy=True) + out.setflags(write=False) + return out + + diff_cond = _ro( + pulsed_trace.terminal_conduction_current_A_m2 - control_trace.terminal_conduction_current_A_m2 + ) + diff_disp = _ro( + pulsed_trace.terminal_displacement_current_A_m2 + - control_trace.terminal_displacement_current_A_m2 + ) + diff_tot = _ro( + pulsed_trace.terminal_total_current_A_m2 - control_trace.terminal_total_current_A_m2 + ) + return PairedStageRunResult( + initial_bundle=initial_bundle, + pulsed_trace=pulsed_trace, + control_trace=control_trace, + pulsed_result=pulsed_res, + control_result=control_res, + differential_conduction_current_A_m2=diff_cond, + differential_displacement_current_A_m2=diff_disp, + differential_total_current_A_m2=diff_tot, + ) diff --git a/tests/integration/test_identifiability_parity.py b/tests/integration/test_identifiability_parity.py new file mode 100644 index 00000000..96f103cf --- /dev/null +++ b/tests/integration/test_identifiability_parity.py @@ -0,0 +1,267 @@ +"""Integration and M-class parity tests for solarlab.experiments.identifiability.""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np +import pytest + +from perovskite_sim.experiments import identifiability as legacy_id +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.experiments import identifiability as new_id +from solarlab.experiments.solarscale import ( + BOLTZMANN_CONSTANT_J_K, + prepare_solarscale_device, +) +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state + + +@pytest.mark.parametrize( + ("family", "estimated", "expect_identifiable", "expect_rank"), + [ + ( + "recombination_only", + ("trap_density_cm2", "capture_cross_section_scale", "calibration_factor"), + False, + 1, + ), + ( + "recombination_plus_charge", + ("trap_density_cm2", "capture_cross_section_scale", "calibration_factor"), + False, + 2, + ), + ( + "recombination_plus_charge", + ("trap_density_cm2", "capture_cross_section_scale"), + True, + 2, + ), + ], +) +def test_interface_srh_identifiability_m_class_parity( + family: new_id.ObservableFamily, + estimated: tuple[new_id.ParameterName, ...], + expect_identifiable: bool, + expect_rank: int, +) -> None: + proto_old = legacy_id.build_interface_srh_identifiability_protocol( + observable_family=family, + estimated_parameters=estimated, + carrier_condition_count=5, + synthetic_noise_sigma_multiplier=0.1, + noise_seed=1729, + ) + proto_new = new_id.build_interface_srh_identifiability_protocol( + observable_family=family, + estimated_parameters=estimated, + carrier_condition_count=5, + synthetic_noise_sigma_multiplier=0.1, + noise_seed=1729, + ) + assert proto_new.sha256 == proto_old.sha256 + + res_old = legacy_id.run_interface_srh_identifiability(proto_old) + res_new = new_id.run_interface_srh_identifiability(proto_new) + + assert res_new.protocol_sha256 == res_old.protocol_sha256 + assert res_new.mapping_sha256 == res_old.mapping_sha256 + assert res_new.singular_values == res_old.singular_values + assert res_new.fisher_information == res_old.fisher_information + assert res_new.numerical_rank == expect_rank == res_old.numerical_rank + assert res_new.parameters_identifiable is expect_identifiable + assert res_new.parameters_identifiable == res_old.parameters_identifiable + assert res_new.analysis_certified == res_old.analysis_certified + assert len(res_new.profiles) == len(res_old.profiles) + for p_new, p_old in zip(res_new.profiles, res_old.profiles, strict=True): + assert p_new.chi_square == p_old.chi_square + assert p_new.parameter_values_log10 == p_old.parameter_values_log10 + + # JSON round-trip preserves mapping_sha256 bit-identically. + reloaded = new_id.InterfaceSRHIdentifiabilityResult.from_json(res_new.to_json()) + assert reloaded.mapping_sha256 == res_new.mapping_sha256 + + if expect_identifiable: + assert res_new.collinearity_index is not None and res_new.collinearity_index < 50.0 + assert res_new.confounded_parameter_groups == () + else: + assert len(res_new.confounded_parameter_groups) >= 1 + + +_OBS_CACHE: dict[tuple[float, float], np.ndarray] = {} + + +def _solve_1d_observables(*, alpha_m_inv: float, tau_s: float) -> np.ndarray: + key = (float(alpha_m_inv), float(tau_s)) + cached = _OBS_CACHE.get(key) + if cached is not None: + return cached.copy() + vt = BOLTZMANN_CONSTANT_J_K * 300.0 / ELEMENTARY_CHARGE_C + + def _ni(eg: float, nc: float, nv: float) -> float: + return math.sqrt(nc * nv) * math.exp(-eg / (2.0 * vt)) + + doc: dict[str, Any] = { + "device": { + "T": 300.0, + "Phi": 2.0e21, + "built_in_potential_mode": "semiconductor_work_function", + }, + "layers": [ + { + "name": "HTL", + "role": "HTL", + "thickness": 80.0e-9, + "eps_r": 3.0, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "chi": 3.6, + "Eg": 1.8, + "Nc300": 2.0e25, + "Nv300": 3.0e25, + "ni": _ni(1.8, 2.0e25, 3.0e25), + "n1": _ni(1.8, 2.0e25, 3.0e25), + "p1": _ni(1.8, 2.0e25, 3.0e25), + "N_A": 1.0e24, + "N_D": 0.0, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-18, + "alpha": 0.0, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 300.0e-9, + "eps_r": 25.0, + "mu_n": 1.934e-3, + "mu_p": 1.934e-3, + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": _ni(1.6, 1.0e25, 1.0e25), + "n1": _ni(1.6, 1.0e25, 1.0e25), + "p1": _ni(1.6, 1.0e25, 1.0e25), + "N_A": 0.0, + "N_D": 0.0, + "tau_n": tau_s, + "tau_p": tau_s, + "B_rad": 1.0e-18, + "alpha": alpha_m_inv, + }, + { + "name": "ETL", + "role": "ETL", + "thickness": 80.0e-9, + "eps_r": 9.0, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "chi": 4.0, + "Eg": 2.0, + "Nc300": 4.0e25, + "Nv300": 2.0e25, + "ni": _ni(2.0, 4.0e25, 2.0e25), + "n1": _ni(2.0, 4.0e25, 2.0e25), + "p1": _ni(2.0, 4.0e25, 2.0e25), + "N_A": 0.0, + "N_D": 1.0e24, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-18, + "alpha": 0.0, + }, + ], + } + prepared, _ = prepare_solarscale_device(doc) + dev = compile_device_1d(prepared, intervals_per_layer=2) + pol = float(dev.voltage_polarity) + opts = SteadyOptions(max_iterations=200, max_bias_step_V=0.10) + sol_sc = solve_steady_state(dev, voltage_V=0.0, generation_scale=1.0, options=opts) + sol_mid = solve_steady_state( + dev, + initial_state=sol_sc.state, + voltage_V=0.80, + generation_scale=1.0, + options=opts, + ) + sol_hi = solve_steady_state( + dev, + initial_state=sol_mid.state, + voltage_V=0.96, + generation_scale=1.0, + options=opts, + ) + out = np.array( + [ + -pol * float(sol_sc.current_density_A_m2[0]), + -pol * float(sol_mid.current_density_A_m2[0]), + -pol * float(sol_hi.current_density_A_m2[0]), + ], + dtype=float, + ) + _OBS_CACHE[key] = out + return out.copy() + + +def test_live_1d_compiled_device_protocol_identifiability_and_confounding() -> None: + identifiable_proto = new_id.GenericIdentifiabilityProtocol( + protocol_id="live_1d_alpha_tau_jv", + parameters=( + new_id.GenericIdentifiabilityParameter("log_alpha_m_inv", 5.5, 6.8, 6.2), + new_id.GenericIdentifiabilityParameter("log_tau_s", -8.0, -6.0, -7.0), + ), + observable_labels=("J_0V", "J_0p80V", "J_0p96V"), + observable_units=("A/m^2", "A/m^2", "A/m^2"), + standard_deviations=(1.0, 1.0, 1.0), + finite_difference_step_log10=1.0e-2, + profile_grid_count=5, + least_squares_max_nfev=10, + ) + + res_id = new_id.run_protocol_identifiability( + identifiable_proto, + lambda coords: _solve_1d_observables( + alpha_m_inv=10.0 ** float(coords[0]), + tau_s=10.0 ** float(coords[1]), + ), + multistart_fractions=((0.5, 0.5),), + ) + assert res_id.parameters_identifiable is True + assert res_id.analysis_certified is True + assert res_id.failed_samples == () + assert res_id.collinearity_index is not None and res_id.collinearity_index < 25.0 + + # Confounded product tau_s = 10**(c0 + c1 - 7.0) with explicit out-of-domain failure probe. + confounded_proto = new_id.GenericIdentifiabilityProtocol( + protocol_id="live_1d_confounded_tau_factors", + parameters=( + new_id.GenericIdentifiabilityParameter("tau_factor_a", -0.5, 0.5, 0.0), + new_id.GenericIdentifiabilityParameter("tau_factor_b", -0.5, 0.5, 0.0), + ), + observable_labels=("J_0V", "J_0p80V", "J_0p96V"), + observable_units=("A/m^2", "A/m^2", "A/m^2"), + standard_deviations=(1.0, 1.0, 1.0), + finite_difference_step_log10=1.0e-2, + profile_grid_count=5, + least_squares_max_nfev=10, + ) + + def _confounded_forward(coords: np.ndarray) -> np.ndarray: + if float(coords[0]) > 0.42 and float(coords[1]) > 0.42: + raise ValueError("declared_domain_exclusion") + tau_eff = 10.0 ** (-7.0 + float(coords[0]) + float(coords[1])) + return _solve_1d_observables(alpha_m_inv=2.0e6, tau_s=tau_eff) + + res_conf = new_id.run_protocol_identifiability( + confounded_proto, + _confounded_forward, + multistart_fractions=((0.5, 0.5), (0.95, 0.95)), + ) + assert res_conf.parameters_identifiable is False + assert res_conf.confounded_parameter_groups == (("tau_factor_a", "tau_factor_b"),) + assert len(res_conf.failed_samples) >= 1 + assert res_conf.analysis_certified is False diff --git a/tests/integration/test_solarscale_screening_parity.py b/tests/integration/test_solarscale_screening_parity.py new file mode 100644 index 00000000..2400997f --- /dev/null +++ b/tests/integration/test_solarscale_screening_parity.py @@ -0,0 +1,452 @@ +"""Integration and parity tests for SolarScale screening and evaluation reports.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from perovskite_sim.experiments.jv_sweep import run_jv_sweep as legacy_run_jv_sweep +from perovskite_sim.models.config_loader import load_device_from_yaml +from perovskite_sim.screening import solarscale as legacy_ss +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.experiments.evaluation_report import ( + ReportQualityError, + run_material_evaluation_report, + run_solarscale_suns_voc_1d, +) +from solarlab.experiments.solarscale import ( + BOLTZMANN_CONSTANT_J_K, + expand_sweep_manifest, + generate_solarlab_inputs, + manifest_sha256, + plan_solarlab_import, + run_smoke_device_results, + solve_solarscale_jv_1d, + write_device_results, +) + + +def _consistent_ni(eg_ev: float, nc: float = 1.0e25, nv: float = 1.0e25) -> float: + vt = BOLTZMANN_CONSTANT_J_K * 300.0 / ELEMENTARY_CHARGE_C + return math.sqrt(nc * nv) * math.exp(-eg_ev / (2.0 * vt)) + + +def _band_aligned_template( + *, + absorber_eg: float = 1.60, + interface_srv: float = 0.0, + optical_material: str | None = None, +) -> dict[str, Any]: + ni_htl = _consistent_ni(2.0, 2.0e25, 3.0e25) + ni_abs = _consistent_ni(absorber_eg, 1.0e25, 1.0e25) + ni_etl = _consistent_ni(2.0, 4.0e25, 2.0e25) + absorber_layer: dict[str, Any] = { + "name": "absorber", + "role": "absorber", + "thickness": 300.0e-9, + "eps_r": 25.0, + "mu_n": 1.934e-3, + "mu_p": 1.934e-3, + "chi": 3.9, + "Eg": absorber_eg, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + "N_A": 0.0, + "N_D": 0.0, + "tau_n": 2.0e-7, + "tau_p": 2.0e-7, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "P0": 0.0, + "D_ion": 0.0, + "P_lim": 1.0e28, + } + if optical_material is not None: + absorber_layer["optical_material"] = optical_material + return { + "device": { + "T": 300.0, + "Phi": 2.0e21, + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "interfaces": [ + [interface_srv, interface_srv], + [interface_srv, interface_srv], + ], + }, + "layers": [ + { + "name": "HTL", + "role": "HTL", + "thickness": 80.0e-9, + "eps_r": 3.0, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "chi": 3.6, + "Eg": 2.0, + "Nc300": 2.0e25, + "Nv300": 3.0e25, + "ni": ni_htl, + "n1": ni_htl, + "p1": ni_htl, + "N_A": 1.0e24, + "N_D": 0.0, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "P0": 0.0, + "D_ion": 0.0, + "P_lim": 1.0e28, + }, + absorber_layer, + { + "name": "ETL", + "role": "ETL", + "thickness": 80.0e-9, + "eps_r": 9.0, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "chi": 4.0, + "Eg": 2.0, + "Nc300": 4.0e25, + "Nv300": 2.0e25, + "ni": ni_etl, + "n1": ni_etl, + "p1": ni_etl, + "N_A": 0.0, + "N_D": 1.0e24, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "P0": 0.0, + "D_ion": 0.0, + "P_lim": 1.0e28, + }, + ], + } + + +def _sample_records_payload() -> dict[str, Any]: + return { + "records": [ + { + "material_id": "cand_alpha", + "formula": "CsPbI2Br", + "screening": { + "production_solarlab_ready": True, + "provisional_solarlab_ready": True, + "readiness": "promising", + "final_fom_score": 0.94, + "gates": {"stability": "pass", "bandgap": True, "toxicity": "pass"}, + }, + "properties": { + "band_gap_hse_ev": { + "value": 1.60, + "unit": "eV", + "provenance": {"kind": "computed", "source": "vasp_hse06"}, + }, + "dielectric_static_avg": { + "value": 25.0, + "unit": "1", + "provenance": {"kind": "computed", "source": "dfpt"}, + }, + "electron_affinity_ev": { + "value": 3.9, + "unit": "eV", + "provenance": {"kind": "computed", "source": "slab"}, + }, + "electron_mobility_cm2_v_s": { + "value": 19.34, + "unit": "cm^2/(V s)", + "provenance": {"kind": "computed", "source": "amset"}, + }, + "hole_mobility_cm2_v_s": { + "value": 19.34, + "unit": "cm^2/(V s)", + "provenance": {"kind": "computed", "source": "amset"}, + }, + "band_alignment_provenance": { + "value": "dft_slab_v1", + "unit": "", + "provenance": {"kind": "computed", "source": "slab"}, + }, + }, + }, + { + "material_id": "cand_exploratory_only", + "formula": "RbSnI3", + "screening": { + "production_solarlab_ready": False, + "provisional_solarlab_ready": True, + "readiness": "phonon", + "ml_pv_score": 0.72, + }, + "properties": { + "band_gap_hse_ev": { + "value": 1.60, + "unit": "eV", + "provenance": {"kind": "computed", "source": "vasp"}, + }, + "dielectric_static_avg": { + "value": 22.0, + "unit": "1", + "provenance": {"kind": "computed", "source": "dfpt"}, + }, + }, + }, + ] + } + + +def test_import_plan_and_sweep_manifest_parity(tmp_path: Path) -> None: + records_path = tmp_path / "records.json" + template_path = tmp_path / "template.yaml" + records_path.write_text(json.dumps(_sample_records_payload()), encoding="utf-8") + template_path.write_text( + yaml.safe_dump(_band_aligned_template(), sort_keys=False), encoding="utf-8" + ) + + for policy in ("production", "exploratory"): + plan_old = legacy_ss.plan_solarlab_import( + records_path, + template_path=template_path, + import_policy=policy, + activate_bandgap=True, + ) + plan_new = plan_solarlab_import( + records_path, + template_path=template_path, + import_policy=policy, + activate_bandgap=True, + ) + assert plan_new["selected"] == plan_old["selected"] + assert plan_new["skipped"] == plan_old["skipped"] + assert plan_new["summary"] == plan_old["summary"] + + out_old = tmp_path / "out_old" + out_new = tmp_path / "out_new" + man_old = legacy_ss.generate_solarlab_inputs( + records_path, + template_path=template_path, + out_dir=out_old, + import_policy="production", + activate_bandgap=True, + ) + man_new = generate_solarlab_inputs( + records_path, + template_path=template_path, + out_dir=out_new, + import_policy="production", + activate_bandgap=True, + ) + assert len(man_new["generated"]) == len(man_old["generated"]) == 1 + assert (out_new / "cand_alpha.yaml").read_text(encoding="utf-8") == ( + out_old / "cand_alpha.yaml" + ).read_text(encoding="utf-8") + + sw_old = legacy_ss.expand_sweep_manifest( + man_old, + out_dir=tmp_path / "sw_old", + max_points=4, + ) + sw_new = expand_sweep_manifest( + man_new, + out_dir=tmp_path / "sw_new", + max_points=4, + ) + assert [g["sweep_values"] for g in sw_new["generated"]] == [ + g["sweep_values"] for g in sw_old["generated"] + ] + assert len(manifest_sha256(sw_new)) == 64 + + +@pytest.mark.parametrize("iface_srv", [0.0, 1.0]) +def test_solarscale_steady_jv_numerical_parity_against_legacy( + tmp_path: Path, iface_srv: float +) -> None: + cfg_path = tmp_path / f"device_srv_{iface_srv}.yaml" + cfg_path.write_text( + yaml.safe_dump( + _band_aligned_template(absorber_eg=1.60, interface_srv=iface_srv), + sort_keys=False, + ), + encoding="utf-8", + ) + + res_new = solve_solarscale_jv_1d(cfg_path, N_grid=24, n_points=7, V_max=1.25) + stack_old = load_device_from_yaml(str(cfg_path)) + res_old = legacy_run_jv_sweep( + stack_old, + N_grid=24, + n_points=7, + v_rate=0.01, + V_max=1.25, + ) + + m_new = res_new.metrics_fwd + m_old = res_old.metrics_fwd + assert m_new.voc_bracketed is True and m_old.voc_bracketed is True + assert abs(m_new.V_oc - m_old.V_oc) <= 1.0e-4 + assert abs(m_new.J_sc - m_old.J_sc) / abs(m_old.J_sc) <= 1.0e-4 + assert abs(m_new.FF - m_old.FF) <= 1.0e-4 + assert abs(m_new.PCE - m_old.PCE) <= 1.0e-4 + assert res_new.scientific_qualification is False + + +def test_unsupported_legacy_manual_vbi_retained_as_failed_and_report_packs( + tmp_path: Path, +) -> None: + records_path = tmp_path / "records.json" + records_path.write_text(json.dumps(_sample_records_payload()), encoding="utf-8") + + # 1. Unsupported legacy manual V_bi template (chi=0, Eg=0) MUST fail closed per candidate. + bad_template = _band_aligned_template() + bad_template["device"]["built_in_potential_mode"] = "manual" + bad_template["device"]["V_bi"] = 1.0 + for layer in bad_template["layers"]: + layer["chi"] = 0.0 + layer["Eg"] = 0.0 + bad_tmpl_path = tmp_path / "bad_template.yaml" + bad_tmpl_path.write_text(yaml.safe_dump(bad_template, sort_keys=False), encoding="utf-8") + + bad_inputs = tmp_path / "bad_inputs" + bad_man = generate_solarlab_inputs( + records_path, + template_path=bad_tmpl_path, + out_dir=bad_inputs, + import_policy="exploratory", + activate_bandgap=False, + ) + bad_results = run_smoke_device_results( + bad_man, N_grid=12, n_points=3, V_max=0.2, max_configs=None + ) + assert bad_results["summary"]["status_counts"]["failed"] == 2 + for rec in bad_results["records"]: + assert rec["simulation_status"] == "failed" + assert rec["error"]["error_type"] in {"CapabilityError", "ValidationError"} + + # 2. Valid band-aligned template -> smoke device results + Suns-Voc + report packs. + good_tmpl_path = tmp_path / "good_template.yaml" + good_tmpl_path.write_text( + yaml.safe_dump(_band_aligned_template(), sort_keys=False), encoding="utf-8" + ) + good_inputs = tmp_path / "good_inputs" + good_man = generate_solarlab_inputs( + records_path, + template_path=good_tmpl_path, + out_dir=good_inputs, + import_policy="production", + activate_bandgap=True, + ) + cfg_file = good_inputs / "cand_alpha.yaml" + dev_res = run_smoke_device_results( + good_man, N_grid=12, n_points=4, V_max=1.25, max_configs=None + ) + assert dev_res["summary"]["status_counts"]["completed"] == 1 + dev_res_json = tmp_path / "device_results.json" + dev_res_csv = tmp_path / "device_results.csv" + write_device_results(dev_res, json_path=dev_res_json, csv_path=dev_res_csv) + assert dev_res_json.is_file() and dev_res_csv.is_file() + + suns = run_solarscale_suns_voc_1d(cfg_file, suns_levels=(0.2, 1.0, 5.0), N_grid=12) + assert suns.V_oc.shape == (3,) + assert float(suns.V_oc[2]) > float(suns.V_oc[1]) > float(suns.V_oc[0]) > 0.5 + assert 0.5 < suns.pseudo_FF < 0.95 + + compact_smoke_settings = { + "jv": {"N_grid": 12, "n_points": 3, "v_rate": 5.0, "V_max": 0.2}, + "suns_voc": {"suns_levels": (0.5, 1.0, 2.0), "N_grid": 12, "t_settle": 5.0e-4}, + } + smoke_report = run_material_evaluation_report( + config_path=cfg_file, + material_record_path=records_path, + device_results_path=dev_res_json, + out_dir=tmp_path / "report_smoke", + profile="smoke", + settings_override=compact_smoke_settings, + ) + assert smoke_report["report_profile"] == "smoke" + assert smoke_report["publication_ready"] is False + assert smoke_report["scientific_qualification"] is False + assert smoke_report["experiment_status"]["jv"]["status"] == "completed" + assert smoke_report["experiment_status"]["suns_voc"]["status"] == "completed" + assert smoke_report["experiment_status"]["eqe"]["status"] == "skipped" + assert Path(smoke_report["figures"]["eqe_skip_reason"]).is_file() + assert Path(smoke_report["report_path"]).is_file() + + # Production profile rejects missing absorber optical_material before running plots. + with pytest.raises(ReportQualityError, match="optical_material"): + run_material_evaluation_report( + config_path=cfg_file, + material_record_path=records_path, + device_results_path=dev_res_json, + out_dir=tmp_path / "report_prod_missing_optics", + profile="production", + ) + + # Production profile with optical_material placeholder runs JV + Suns-Voc and marks + # publication_blocked when material-specific n/k EQE resources are absent. + opt_tmpl_path = tmp_path / "opt_template.yaml" + opt_tmpl_path.write_text( + yaml.safe_dump( + _band_aligned_template(optical_material="MAPbI3"), sort_keys=False + ), + encoding="utf-8", + ) + opt_inputs = tmp_path / "opt_inputs" + generate_solarlab_inputs( + records_path, + template_path=opt_tmpl_path, + out_dir=opt_inputs, + import_policy="production", + activate_bandgap=True, + ) + compact_prod_settings = { + "jv": {"N_grid": 12, "n_points": 5, "v_rate": 0.5, "V_max": 1.25}, + "suns_voc": {"suns_levels": (0.5, 1.0, 2.0), "N_grid": 12, "t_settle": 1.0e-2}, + } + prod_report = run_material_evaluation_report( + config_path=opt_inputs / "cand_alpha.yaml", + material_record_path=records_path, + device_results_path=dev_res_json, + out_dir=tmp_path / "report_prod", + profile="production", + settings_override=compact_prod_settings, + ) + assert prod_report["physics_quality_status"] == "publication_blocked" + assert prod_report["publication_ready"] is False + + # Production profile fails closed with evaluation_failure.json if Voc is not bracketed. + unbracketed_cfg = yaml.safe_load((opt_inputs / "cand_alpha.yaml").read_text(encoding="utf-8")) + unbracketed_cfg["device"]["Phi"] = 0.0 + unbracketed_path = tmp_path / "unbracketed.yaml" + unbracketed_path.write_text( + yaml.safe_dump(unbracketed_cfg, sort_keys=False), encoding="utf-8" + ) + fail_dir = tmp_path / "report_prod_fail" + with pytest.raises(ReportQualityError, match="Production JV quality gate failed"): + run_material_evaluation_report( + config_path=unbracketed_path, + material_record_path=records_path, + device_results_path=dev_res_json, + out_dir=fail_dir, + profile="production", + settings_override=compact_prod_settings, + ) + assert (fail_dir / "evaluation_failure.json").is_file() diff --git a/tests/integration/test_working_point_transfer.py b/tests/integration/test_working_point_transfer.py new file mode 100644 index 00000000..7dc03371 --- /dev/null +++ b/tests/integration/test_working_point_transfer.py @@ -0,0 +1,511 @@ +"""Integration tests for P05-01b multi-stage working-point transfer and paired perturbations.""" + +from __future__ import annotations + +import math +from typing import Any + +import numpy as np + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import CompiledDevice1D, compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.equations.ionic_1d import IonicState1D +from solarlab.experiments.ionic_transient import IonicTransientOptions +from solarlab.experiments.protocol import Protocol +from solarlab.experiments.solarscale import ( + BOLTZMANN_CONSTANT_J_K, + prepare_solarscale_device, +) +from solarlab.experiments.transient import TransientOptions, TransientProtocol +from solarlab.experiments.working_point_transfer import ( + WorkingPointBundle, + capture_working_point, + integrate_stage_from_working_point, + physical_state_equivalent, + run_paired_perturbation_stages, + transfer_working_point, +) +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_steady_state + + +def _consistent_ni(eg_ev: float, nc: float = 1.0e25, nv: float = 1.0e25) -> float: + vt = BOLTZMANN_CONSTANT_J_K * 300.0 / ELEMENTARY_CHARGE_C + return math.sqrt(nc * nv) * math.exp(-eg_ev / (2.0 * vt)) + + +def _device_doc( + *, + absorber_eg: float = 1.6, + tau_s: float = 2.0e-7, + p0: float = 0.0, + d_ion: float = 0.0, +) -> dict[str, Any]: + ni_htl = _consistent_ni(2.2) + ni_abs = _consistent_ni(absorber_eg) + ni_etl = _consistent_ni(2.4) + return { + "device": { + "T": 300.0, + "Phi": 2.5e21, + "built_in_potential_mode": "semiconductor_work_function", + }, + "layers": [ + { + "name": "HTL", + "role": "HTL", + "thickness": 80.0e-9, + "eps_r": 3.5, + "mu_n": 1.0e-6, + "mu_p": 1.0e-4, + "chi": 3.5, + "Eg": 2.2, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_htl, + "n1": ni_htl, + "p1": ni_htl, + "N_A": 1.0e24, + "N_D": 0.0, + "tau_n": 1.0e-7, + "tau_p": 1.0e-7, + "B_rad": 1.0e-18, + "alpha": 1.0e5, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 320.0e-9, + "eps_r": 24.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "chi": 3.9, + "Eg": absorber_eg, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + "N_A": 0.0, + "N_D": 0.0, + "tau_n": tau_s, + "tau_p": tau_s, + "B_rad": 1.0e-18, + "alpha": 2.0e6, + "P0": p0, + "D_ion": d_ion, + "P_lim": 1.0e27, + }, + { + "name": "ETL", + "role": "ETL", + "thickness": 80.0e-9, + "eps_r": 4.0, + "mu_n": 1.0e-4, + "mu_p": 1.0e-6, + "chi": 4.0, + "Eg": 2.4, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_etl, + "n1": ni_etl, + "p1": ni_etl, + "N_A": 0.0, + "N_D": 1.0e24, + "tau_n": 1.0e-7, + "tau_p": 1.0e-7, + "B_rad": 1.0e-18, + "alpha": 1.0e5, + }, + ], + } + + +def _transient_opts() -> TransientOptions: + return TransientOptions( + 1.0e-11, + 1.0e-8, + 1.0e-11, + 0.1, + 2.0, + SolveBudget(50, 1000, 50, 24), + 32, + 30.0, + "previous", + POISSON_CONTACT_BALANCE_V1, + ) + + +def _stage_protocol_doc( + phases: list[str], + transfers: list[dict[str, Any]], +) -> Protocol: + return Protocol.from_document( + { + "schema": "solarlab.protocol.v1", + "id": "multistage_1d_protocol", + "version": 1, + "experiment_id": "multistage_transient_1d", + "preparation": {"schema": "solarlab.prep.v1", "mode": "finite_time"}, + "waveform": {"schema": "solarlab.waveform.v1", "kind": "piecewise_step"}, + "switches": {"schema": "solarlab.switches.v1", "light": "switched"}, + "sampling": {"schema": "solarlab.sampling.v1", "grid": "explicit"}, + "control_mode": "voltage_source", + "phases": phases, + "transfers": transfers, + } + ) + + +def test_electronic_multistage_transfer_continuity_and_displacement_current() -> None: + prepared, _ = prepare_solarscale_device(_device_doc()) + device = compile_device_1d(prepared, intervals_per_layer=6) + opts = _transient_opts() + + dc0 = solve_steady_state(device, voltage_V=0.0, generation_scale=1.0) + wp0 = capture_working_point( + device, + dc0.state, + point_id="wp_t0", + owner_epoch="ep1", + stage_id="stage1", + time_s=0.0, + generation_scale=1.0, + is_equilibrium=False, + prepared=prepared, + ) + + stage1_drive = TransientProtocol( + times_s=np.linspace(0.0, 2.0e-7, 4), + voltage_V=np.linspace(0.0, 0.30, 4), + generation_scale=np.ones(4), + ) + trace1 = integrate_stage_from_working_point( + device, + wp0, + stage1_drive, + options=opts, + stage_id="stage1", + final_point_id="wp_stage1_left", + owner_epoch="ep1", + ) + assert trace1.outcome == "completed" + assert trace1.final_bundle is not None + + left_json = trace1.final_bundle.to_json() + left_reloaded = WorkingPointBundle.from_json(left_json) + proto = _stage_protocol_doc( + ["stage1", "stage2"], + [ + { + "from": "stage1", + "to": "stage2", + "working_point": { + "id": left_reloaded.id, + "sha256": left_reloaded.sha256, + }, + "preserve": ["state", "inventories", "materials", "damage", "grid"], + } + ], + ) + + # Step voltage from 0.30 -> 0.45 V and illumination 1.0 -> 1.2 suns at t = 2e-7 s. + xfer = transfer_working_point( + proto, + left_reloaded, + device, + from_stage="stage1", + to_stage="stage2", + boundary_time_s=2.0e-7, + right_voltage_V=0.45, + right_generation_scale=1.2, + right_point_id="wp_stage2_right", + owner_epoch="ep1", + right_encoding="physical_fields", + ) + assert xfer.rebound_materials is False + assert physical_state_equivalent(trace1.states[-1], xfer.right_state, rtol=1.0e-12) + + stage2_drive = TransientProtocol( + times_s=np.linspace(2.0e-7, 4.0e-7, 4), + voltage_V=np.full(4, 0.45), + generation_scale=np.full(4, 1.2), + ) + trace2 = integrate_stage_from_working_point( + device, + xfer.boundary.right_bundle, + stage2_drive, + options=opts, + stage_id="stage2", + final_point_id="wp_stage2_end", + owner_epoch="ep1", + ) + assert trace2.outcome == "completed" + # Step-to-step Backward Euler displacement current across the voltage jump is non-zero! + assert abs(float(trace2.terminal_displacement_current_A_m2[0])) > 1.0e-2 + assert float(np.max(trace2.maxwell_spread_A_m2)) < 1.0e-7 + + +def test_coupled_ionic_multistage_transfer_and_inventory_conservation() -> None: + doc_ion = _device_doc(p0=2.0e23, d_ion=1.0e-12) + doc_ion["device"]["ion_steric_diffusion_only"] = True + doc_ion["layers"][0]["Eg"] = 1.8 + doc_ion["layers"][0]["chi"] = 3.6 + doc_ion["layers"][0]["ni"] = _consistent_ni(1.8) + doc_ion["layers"][0]["n1"] = _consistent_ni(1.8) + doc_ion["layers"][0]["p1"] = _consistent_ni(1.8) + doc_ion["layers"][2]["Eg"] = 2.0 + doc_ion["layers"][2]["ni"] = _consistent_ni(2.0) + doc_ion["layers"][2]["n1"] = _consistent_ni(2.0) + doc_ion["layers"][2]["p1"] = _consistent_ni(2.0) + prepared, _ = prepare_solarscale_device(doc_ion) + ion_layer_id = next(layer.id for layer in prepared.layers if layer.role == "absorber") + ion_dev = compile_ionic_device_1d( + prepared, + intervals_per_layer=6, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + steady_opts = IonicSteadyOptions( + SteadyOptions(), + 1.0e-11, + 1.0e6, + 1.0e6, + 1.0, + ion_dev.ion_node_count - 1, + SolveBudget(60, 600, 60, 24), + 30.0, + ) + steady0 = solve_ionic_steady_state( + ion_dev, voltage_V=0.002, generation_scale=0.0, options=steady_opts + ) + assert steady0.accepted and steady0.state is not None + inv0 = steady0.state.domain_inventory_m2 + + ion_opts = IonicTransientOptions( + electronic=_transient_opts(), + ion_balance_tolerance_m2_s=1.0e6, + ion_logit_step=1.0, + ) + wp0 = capture_working_point( + ion_dev, + steady0.state, + point_id="wp_ion_0", + owner_epoch="ep_ion", + stage_id="prebias", + time_s=0.0, + generation_scale=0.0, + is_equilibrium=False, + prepared=prepared, + ) + + stage1_drive = TransientProtocol( + times_s=np.array([0.0, 1.0e-4, 2.0e-4]), + voltage_V=np.array([0.002, 0.15, 0.30]), + generation_scale=np.zeros(3), + ) + trace1 = integrate_stage_from_working_point( + ion_dev, + wp0, + stage1_drive, + options=ion_opts, + stage_id="prebias", + final_point_id="wp_ion_1_left", + owner_epoch="ep_ion", + final_encoding="physical_fields", + ) + assert trace1.outcome == "completed" and trace1.final_bundle is not None + + proto = _stage_protocol_doc( + ["prebias", "relax"], + [ + { + "from": "prebias", + "to": "relax", + "working_point": { + "id": trace1.final_bundle.id, + "sha256": trace1.final_bundle.sha256, + }, + "preserve": ["state", "inventories", "materials", "damage", "grid"], + } + ], + ) + xfer = transfer_working_point( + proto, + trace1.final_bundle, + ion_dev, + from_stage="prebias", + to_stage="relax", + boundary_time_s=2.0e-4, + right_voltage_V=0.10, + right_generation_scale=0.0, + right_point_id="wp_ion_2_right", + owner_epoch="ep_ion", + right_encoding="coordinates", + ) + assert physical_state_equivalent(trace1.states[-1], xfer.right_state, rtol=1.0e-12) + + stage2_drive = TransientProtocol( + times_s=np.array([2.0e-4, 3.0e-4, 4.0e-4]), + voltage_V=np.full(3, 0.10), + generation_scale=np.zeros(3), + ) + trace2 = integrate_stage_from_working_point( + ion_dev, + xfer.boundary.right_bundle, + stage2_drive, + options=ion_opts, + stage_id="relax", + final_point_id="wp_ion_2_end", + owner_epoch="ep_ion", + ) + assert trace2.outcome == "completed" + final_ion = trace2.states[-1] + assert isinstance(final_ion, IonicState1D) + rel_inv_drift = abs(final_ion.domain_inventory_m2 - inv0) / inv0 + assert rel_inv_drift <= 1.0e-12 + + +def test_damage_rebinding_across_three_stages_and_paired_perturbation_runner() -> None: + prep_base, _ = prepare_solarscale_device(_device_doc(tau_s=2.0e-7)) + prep_dmg, _ = prepare_solarscale_device(_device_doc(tau_s=2.0e-8)) + dev_base = compile_device_1d(prep_base, intervals_per_layer=5) + dev_dmg = compile_device_1d(prep_dmg, intervals_per_layer=5) + opts = _transient_opts() + + dc0 = solve_steady_state(dev_base, voltage_V=0.0, generation_scale=1.0) + wp0 = capture_working_point( + dev_base, + dc0.state, + point_id="wp0", + owner_epoch="ep_dmg", + stage_id="s1", + time_s=0.0, + generation_scale=1.0, + is_equilibrium=False, + prepared=prep_base, + ) + # Finite-time non-equilibrium preparation in stage s1. + tr1 = integrate_stage_from_working_point( + dev_base, + wp0, + TransientProtocol( + times_s=np.array([0.0, 5.0e-8, 1.0e-7]), + voltage_V=np.array([0.0, 0.25, 0.40]), + generation_scale=np.ones(3), + ), + options=opts, + stage_id="s1", + final_point_id="wp1_left", + owner_epoch="ep_dmg", + ) + assert tr1.outcome == "completed" and tr1.final_bundle is not None + assert tr1.final_bundle.sections["history"]["is_equilibrium"] is False + + # Paired perturbation + unpulsed control from the non-equilibrium WorkingPointBundle! + paired_proto = _stage_protocol_doc(["s1", "pulse"], []) + pulsed_drive = TransientProtocol( + times_s=np.array([1.0e-7, 1.5e-7, 2.0e-7, 2.5e-7]), + voltage_V=np.array([0.40, 0.45, 0.40, 0.40]), + generation_scale=np.array([1.0, 1.15, 1.0, 1.0]), + ) + paired = run_paired_perturbation_stages( + dev_base, + tr1.final_bundle, + pulsed_drive, + options=opts, + protocol=paired_proto, + run_id="paired_run_01", + experiment_id="transient_perturbation_1d", + owner_epoch="ep_dmg", + ) + p_doc = paired.pulsed_result.export() + c_doc = paired.control_result.export() + assert p_doc["header"]["bindings"]["initial"] == c_doc["header"]["bindings"]["initial"] + assert p_doc["header"]["bindings"]["initial"]["sha256"] == tr1.final_bundle.sha256 + assert p_doc["header"]["evidence"][0]["label"] == "FIRST_SLICE" + assert float(np.max(np.abs(paired.differential_total_current_A_m2))) > 1.0e-1 + + # Stage 1 -> Stage 2 without damage change keeps dev_base; Stage 2 -> Stage 3 with damage rebinds! + proto_s12 = _stage_protocol_doc( + ["s1", "s2", "s3"], + [ + { + "from": "s1", + "to": "s2", + "working_point": { + "id": tr1.final_bundle.id, + "sha256": tr1.final_bundle.sha256, + }, + "preserve": ["state", "inventories", "grid"], + } + ], + ) + rebind_log: list[str] = [] + + def _rebind(_dmg: Any) -> CompiledDevice1D: + rebind_log.append("rebound") + return dev_dmg + + xfer12 = transfer_working_point( + proto_s12, + tr1.final_bundle, + dev_base, + from_stage="s1", + to_stage="s2", + boundary_time_s=1.0e-7, + right_voltage_V=0.40, + right_generation_scale=1.0, + right_point_id="wp2_right", + owner_epoch="ep_dmg", + rebind_damaged_device=_rebind, + ) + assert xfer12.rebound_materials is False and rebind_log == [] + + proto_s23 = _stage_protocol_doc( + ["s1", "s2", "s3"], + [ + { + "from": "s2", + "to": "s3", + "working_point": { + "id": xfer12.boundary.right_bundle.id, + "sha256": xfer12.boundary.right_bundle.sha256, + }, + "preserve": ["state", "inventories", "grid"], + } + ], + ) + xfer23 = transfer_working_point( + proto_s23, + xfer12.boundary.right_bundle, + dev_base, + from_stage="s2", + to_stage="s3", + boundary_time_s=1.0e-7, + right_voltage_V=0.40, + right_generation_scale=1.0, + right_point_id="wp3_right", + owner_epoch="ep_dmg", + next_damage_state={"status": "stress_trap_growth", "tau_s": 2.0e-8}, + rebind_damaged_device=_rebind, + ) + assert xfer23.rebound_materials is True and rebind_log == ["rebound"] + assert xfer23.compiled_device.identity == dev_dmg.identity + tr3 = integrate_stage_from_working_point( + dev_dmg, + xfer23.boundary.right_bundle, + TransientProtocol( + times_s=np.array([1.0e-7, 1.5e-7, 2.0e-7]), + voltage_V=np.full(3, 0.40), + generation_scale=np.ones(3), + ), + options=opts, + stage_id="s3", + final_point_id="wp3_end", + owner_epoch="ep_dmg", + ) + assert tr3.outcome == "completed" diff --git a/tests/unit/experiments/test_working_point_and_identifiability.py b/tests/unit/experiments/test_working_point_and_identifiability.py new file mode 100644 index 00000000..2197bf49 --- /dev/null +++ b/tests/unit/experiments/test_working_point_and_identifiability.py @@ -0,0 +1,671 @@ +"""Unit tests for P05-01b working-point transfer and P05-05 identifiability / SolarScale.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import CompiledDevice1D, compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.identifiability import ( + FailedSampleRecord, + GenericIdentifiabilityParameter, + GenericIdentifiabilityProtocol, + collinearity_index, + confounded_parameter_groups, + identifiability_to_experiment_result, + run_protocol_identifiability, + subset_collinearity_indices, +) +from solarlab.experiments.protocol import Protocol +from solarlab.experiments.results import EVIDENCE_LABELS, decode_array +from solarlab.experiments.solarscale import ( + BOLTZMANN_CONSTANT_J_K, + generate_solarlab_inputs, + manifest_sha256, + plan_solarlab_import, + prepare_solarscale_device, +) +from solarlab.experiments.transient import TransientOptions, TransientProtocol +from solarlab.experiments.working_point_transfer import ( + COORDINATE_ENCODING_1D, + PHYSICAL_FIELD_ENCODING_1D, + WorkingPointBundle, + WorkingPointTransferError, + build_stage_experiment_result, + capture_working_point, + integrate_stage_from_working_point, + physical_state_equivalent, + reconstruct_ionic_state_1d, + reconstruct_state_1d, + transfer_working_point, +) +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import solve_steady_state + + +def _consistent_ni(eg_ev: float, nc: float = 1.0e25, nv: float = 1.0e25) -> float: + vt = BOLTZMANN_CONSTANT_J_K * 300.0 / ELEMENTARY_CHARGE_C + return math.sqrt(nc * nv) * math.exp(-eg_ev / (2.0 * vt)) + + +def _inline_device_doc(*, absorber_eg: float = 1.6, p0: float = 0.0, d_ion: float = 0.0) -> dict[str, Any]: + ni_htl = _consistent_ni(2.2) + ni_abs = _consistent_ni(absorber_eg) + ni_etl = _consistent_ni(2.4) + return { + "device": { + "T": 300.0, + "Phi": 2.5e21, + "built_in_potential_mode": "semiconductor_work_function", + }, + "layers": [ + { + "name": "HTL", + "role": "HTL", + "thickness": 80.0e-9, + "eps_r": 3.5, + "mu_n": 1.0e-6, + "mu_p": 1.0e-4, + "chi": 3.5, + "Eg": 2.2, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_htl, + "n1": ni_htl, + "p1": ni_htl, + "N_A": 1.0e24, + "N_D": 0.0, + "tau_n": 1.0e-7, + "tau_p": 1.0e-7, + "B_rad": 1.0e-18, + "alpha": 1.0e5, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 320.0e-9, + "eps_r": 24.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "chi": 3.9, + "Eg": absorber_eg, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_abs, + "n1": ni_abs, + "p1": ni_abs, + "N_A": 0.0, + "N_D": 0.0, + "tau_n": 2.0e-7, + "tau_p": 2.0e-7, + "B_rad": 1.0e-18, + "alpha": 2.0e6, + "P0": p0, + "D_ion": d_ion, + "P_lim": 1.0e27, + }, + { + "name": "ETL", + "role": "ETL", + "thickness": 80.0e-9, + "eps_r": 4.0, + "mu_n": 1.0e-4, + "mu_p": 1.0e-6, + "chi": 4.0, + "Eg": 2.4, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "ni": ni_etl, + "n1": ni_etl, + "p1": ni_etl, + "N_A": 0.0, + "N_D": 1.0e24, + "tau_n": 1.0e-7, + "tau_p": 1.0e-7, + "B_rad": 1.0e-18, + "alpha": 1.0e5, + }, + ], + } + + +def _compile_electronic(absorber_eg: float = 1.6, intervals: int = 4) -> tuple[PreparedDevice, CompiledDevice1D]: + prepared, _ = prepare_solarscale_device(_inline_device_doc(absorber_eg=absorber_eg)) + return prepared, compile_device_1d(prepared, intervals_per_layer=intervals) + + +def _make_protocol( + *, + wp_id: str, + wp_sha: str, + preserve: list[str], + phases: list[str] | None = None, +) -> Protocol: + declared_phases = phases or ["prep", "probe"] + return Protocol.from_document( + { + "schema": "solarlab.protocol.v1", + "id": "proto_transfer_unit", + "version": 1, + "experiment_id": "transient_step_1d", + "preparation": {"schema": "solarlab.prep.v1", "mode": "transient"}, + "waveform": {"schema": "solarlab.waveform.v1", "kind": "step"}, + "switches": {"schema": "solarlab.switches.v1", "light": "step"}, + "sampling": {"schema": "solarlab.sampling.v1", "points": 3}, + "control_mode": "voltage_source", + "phases": declared_phases, + "transfers": [ + { + "from": declared_phases[0], + "to": declared_phases[1], + "working_point": {"id": wp_id, "sha256": wp_sha}, + "preserve": preserve, + } + ], + } + ) + + +def test_working_point_bundle_roundtrip_physical_identity_and_shifted_voltage() -> None: + prepared, device = _compile_electronic() + sol = solve_steady_state(device, voltage_V=0.35, generation_scale=1.0) + + bundle_coord = capture_working_point( + device, + sol.state, + point_id="wp_coord", + owner_epoch="epoch_1", + stage_id="prep", + time_s=1.0e-4, + generation_scale=1.0, + is_equilibrium=False, + encoding="coordinates", + prepared=prepared, + evidence_labels=("FIRST_SLICE",), + ) + bundle_shifted = capture_working_point( + device, + sol.state, + point_id="wp_shifted", + owner_epoch="epoch_1", + stage_id="prep", + time_s=1.0e-4, + generation_scale=1.0, + is_equilibrium=False, + encoding="coordinates", + reference_voltage_V=0.75, + prepared=prepared, + evidence_labels=("FIRST_SLICE",), + ) + bundle_phys = capture_working_point( + device, + sol.state, + point_id="wp_phys", + owner_epoch="epoch_1", + stage_id="prep", + time_s=1.0e-4, + generation_scale=1.0, + is_equilibrium=False, + encoding="physical_fields", + prepared=prepared, + evidence_labels=("FIRST_SLICE",), + ) + + assert bundle_coord.state_encoding == COORDINATE_ENCODING_1D + assert bundle_phys.state_encoding == PHYSICAL_FIELD_ENCODING_1D + # Physical identity depends strictly on physical fields + geometry, invariant to encoding / ref V. + assert bundle_coord.physical_identity == bundle_phys.physical_identity + assert bundle_coord.physical_identity == bundle_shifted.physical_identity + + restored = WorkingPointBundle.from_json(bundle_coord.to_json()) + assert restored.sha256 == bundle_coord.sha256 + + rec_coord = reconstruct_state_1d(restored, device) + rec_shifted = reconstruct_state_1d(bundle_shifted, device) + rec_phys = reconstruct_state_1d(bundle_phys, device) + assert physical_state_equivalent(sol.state, rec_coord) + assert physical_state_equivalent(sol.state, rec_shifted) + assert physical_state_equivalent(sol.state, rec_phys) + + # Tampering with any section invalidates SHA-256 verification. + bad_doc = bundle_phys.to_document() + bad_doc["sections"]["history"]["time_s"] = 9.99 + with pytest.raises(WorkingPointTransferError, match="SHA-256 mismatch"): + WorkingPointBundle.from_document(bad_doc) + + # Ionic bundle round-trip on finite-site positive ions. + prep_ion, _ = prepare_solarscale_device( + _inline_device_doc(p0=1.0e24, d_ion=1.0e-15) + ) + ion_layer_id = next(lyr.id for lyr in prep_ion.layers if lyr.role == "absorber") + ion_dev = compile_ionic_device_1d( + prep_ion, + intervals_per_layer=4, + ion_domain_layer=ion_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) + ion_state0 = ion_dev.initial_state(voltage_V=0.2) + ion_coord = capture_working_point( + ion_dev, + ion_state0, + point_id="wp_ion_c", + owner_epoch="ep_i", + stage_id="prep", + time_s=0.0, + generation_scale=0.0, + is_equilibrium=False, + encoding="coordinates", + prepared=prep_ion, + ) + ion_phys = capture_working_point( + ion_dev, + ion_state0, + point_id="wp_ion_p", + owner_epoch="ep_i", + stage_id="prep", + time_s=0.0, + generation_scale=0.0, + is_equilibrium=False, + encoding="physical_fields", + prepared=prep_ion, + ) + assert ion_coord.physical_identity == ion_phys.physical_identity + assert physical_state_equivalent( + ion_state0, reconstruct_ionic_state_1d(ion_phys, ion_dev) + ) + + +def test_transfer_preserve_refusals_and_damage_gated_material_rebinding() -> None: + prepared, device = _compile_electronic(absorber_eg=1.6, intervals=4) + _, finer_device = _compile_electronic(absorber_eg=1.6, intervals=6) + _, damaged_device = _compile_electronic(absorber_eg=1.55, intervals=4) + + sol = solve_steady_state(device, voltage_V=0.2, generation_scale=1.0) + bundle = capture_working_point( + device, + sol.state, + point_id="wp_stage1_end", + owner_epoch="epoch_1", + stage_id="prep", + time_s=2.0e-5, + generation_scale=1.0, + is_equilibrium=False, + prepared=prepared, + ) + + # 1. Grid mismatch refused when 'grid' is preserved. + proto_strict = _make_protocol( + wp_id=bundle.id, + wp_sha=bundle.sha256, + preserve=["state", "inventories", "materials", "damage", "grid"], + ) + with pytest.raises(WorkingPointTransferError): + transfer_working_point( + proto_strict, + bundle, + finer_device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.4, + right_generation_scale=1.0, + right_point_id="wp_stage2_start", + owner_epoch="epoch_1", + ) + + # 2. Preserving 'coordinate_reference' forbids reference-voltage jumps. + proto_coord_lock = _make_protocol( + wp_id=bundle.id, + wp_sha=bundle.sha256, + preserve=["state", "coordinate_reference", "materials", "grid"], + ) + with pytest.raises(WorkingPointTransferError, match="coordinate_reference"): + transfer_working_point( + proto_coord_lock, + bundle, + device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.5, + right_generation_scale=1.0, + right_point_id="wp_stage2_start", + owner_epoch="epoch_1", + ) + + # 3. Omitting 'state' from preserve NEVER silently resets to steady state. + proto_no_state = _make_protocol( + wp_id=bundle.id, + wp_sha=bundle.sha256, + preserve=["materials", "damage", "grid"], + ) + with pytest.raises(WorkingPointTransferError): + transfer_working_point( + proto_no_state, + bundle, + device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.2, + right_generation_scale=1.0, + right_point_id="wp_stage2_start", + owner_epoch="epoch_1", + ) + + # 4. Damage-gated rebinding: unchanged damage MUST NOT invoke rebind callback; + # changed damage invokes rebind callback ONLY when 'damage'/'materials' are not locked. + rebind_calls: list[dict[str, Any]] = [] + + def _rebind_cb(dmg: Any) -> CompiledDevice1D: + rebind_calls.append(dict(dmg)) + return damaged_device + + proto_damage_allowed = _make_protocol( + wp_id=bundle.id, + wp_sha=bundle.sha256, + preserve=["state", "inventories", "grid"], + ) + unchanged_res = transfer_working_point( + proto_damage_allowed, + bundle, + device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.4, + right_generation_scale=1.0, + right_point_id="wp_unchanged", + owner_epoch="epoch_1", + rebind_damaged_device=_rebind_cb, + ) + assert unchanged_res.rebound_materials is False + assert unchanged_res.compiled_device.identity == device.identity + assert rebind_calls == [] + + # Damage change refused if 'materials' is preserved. + with pytest.raises(WorkingPointTransferError, match="damage state changed"): + transfer_working_point( + proto_strict, + bundle, + device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.4, + right_generation_scale=1.0, + right_point_id="wp_fail_dmg", + owner_epoch="epoch_1", + next_damage_state={"status": "photo_degraded", "delta_eg_ev": -0.05}, + rebind_damaged_device=_rebind_cb, + ) + + changed_res = transfer_working_point( + proto_damage_allowed, + bundle, + device, + from_stage="prep", + to_stage="probe", + boundary_time_s=2.0e-5, + right_voltage_V=0.4, + right_generation_scale=1.0, + right_point_id="wp_damaged", + owner_epoch="epoch_1", + next_damage_state={"status": "photo_degraded", "delta_eg_ev": -0.05}, + rebind_damaged_device=_rebind_cb, + ) + assert changed_res.rebound_materials is True + assert len(rebind_calls) == 1 + assert changed_res.compiled_device.identity == damaged_device.identity + assert physical_state_equivalent(sol.state, changed_res.right_state) + + +def test_partial_stage_trace_nan_masking_and_evidence_label_preservation() -> None: + prepared, device = _compile_electronic() + sol = solve_steady_state(device, voltage_V=0.0, generation_scale=1.0) + bundle = capture_working_point( + device, + sol.state, + point_id="wp_init", + owner_epoch="epoch_1", + stage_id="prep", + time_s=0.0, + generation_scale=1.0, + is_equilibrium=False, + prepared=prepared, + evidence_labels=("FIRST_SLICE",), + limitations=("synthetic_unit_test",), + ) + proto = _make_protocol( + wp_id=bundle.id, + wp_sha=bundle.sha256, + preserve=["state", "inventories", "materials", "damage", "grid"], + ) + # Force an incomplete trajectory on step 2 via 1-iteration Newton budget on a huge jump. + stage_proto = TransientProtocol( + times_s=np.array([0.0, 1.0e-7, 2.0e-7]), + voltage_V=np.array([0.0, 0.0, 4.5]), + generation_scale=np.array([1.0, 1.0, 1.0]), + ) + tight_opts = TransientOptions( + 1.0e-11, + 1.0e-8, + 1.0e-11, + 0.05, + 0.5, + SolveBudget(1, 2, 1, 0), + 10, + 5.0, + "previous", + POISSON_CONTACT_BALANCE_V1, + ) + trace = integrate_stage_from_working_point( + device, + bundle, + stage_proto, + options=tight_opts, + stage_id="probe", + final_point_id="wp_end", + owner_epoch="epoch_1", + ) + assert trace.outcome != "completed" + assert math.isfinite(float(trace.terminal_total_current_A_m2[0])) + assert math.isnan(float(trace.terminal_total_current_A_m2[1])) + + exp_res = build_stage_experiment_result( + trace, + protocol=proto, + run_id="run_partial", + attempt_id="att_1", + experiment_id="transient_step_1d", + ) + exported = exp_res.export() + assert exported["header"]["outcome"] == trace.outcome + assert exported["header"]["evidence"][0]["label"] == "FIRST_SLICE" + assert exported["header"]["evidence"][0]["label"] in EVIDENCE_LABELS + assert exported["metrics"]["final_terminal_total_current_A_m2"]["status"] == "unidentified" + decoded_tot = decode_array(exported["payload"]["terminal_total_current_A_m2"]) + assert math.isfinite(float(decoded_tot[0])) + assert math.isnan(float(decoded_tot[1])) + + +def test_collinearity_confounding_failed_samples_and_solarscale_provenance( + tmp_path: Path, +) -> None: + # Orthogonal columns -> collinearity index == 1.0, no confounded groups. + j_orth = np.array([[2.0, 0.0], [0.0, 5.0], [0.0, 0.0]]) + gamma_orth = collinearity_index(j_orth) + assert gamma_orth is not None and math.isclose(gamma_orth, 1.0, rel_tol=1e-12) + assert confounded_parameter_groups(j_orth, ("p1", "p2"), collinearity_limit=20.0) == () + + # Near-collinear columns -> large collinearity index and grouped confounding. + j_coll = np.array([[1.0, 1.0, 0.0], [2.0, 2.0 + 1e-5, 0.0], [0.0, 0.0, 3.0]]) + subsets = subset_collinearity_indices(j_coll, ("nt", "sigma", "offset")) + assert subsets[("nt", "sigma")] is not None and subsets[("nt", "sigma")] > 1.0e4 + assert subsets[("nt", "offset")] is not None and math.isclose( + subsets[("nt", "offset")] or 0.0, 1.0, rel_tol=1e-10 + ) + groups = confounded_parameter_groups( + j_coll, ("nt", "sigma", "offset"), collinearity_limit=100.0 + ) + assert groups == (("nt", "sigma"),) + + # FailedSampleRecord retention in run_protocol_identifiability + ExperimentResult export. + gen_proto = GenericIdentifiabilityProtocol( + protocol_id="synthetic_fail_probe", + parameters=( + GenericIdentifiabilityParameter("a", -1.0, 1.0, 0.0), + GenericIdentifiabilityParameter("b", -1.0, 1.0, 0.0), + ), + observable_labels=("obs0", "obs1", "obs2"), + observable_units=("A/m^2", "A/m^2", "A/m^2"), + standard_deviations=(0.05, 0.05, 0.05), + profile_grid_count=5, + ) + + def _forward_with_domain_hole(coords: np.ndarray) -> np.ndarray: + if float(coords[0]) > 0.65: + raise RuntimeError("out_of_domain_probe") + a_val = 10.0 ** float(coords[0]) + b_val = 10.0 ** float(coords[1]) + return np.array([a_val + b_val, 2.0 * a_val - b_val, a_val * b_val], dtype=float) + + id_res = run_protocol_identifiability( + gen_proto, + _forward_with_domain_hole, + multistart_fractions=((0.5, 0.5), (0.9, 0.5)), + ) + assert len(id_res.failed_samples) >= 1 + assert isinstance(id_res.failed_samples[0], FailedSampleRecord) + assert id_res.analysis_certified is False + + exp_env = identifiability_to_experiment_result( + id_res, + run_id="id_run_1", + attempt_id="id_att_1", + evidence_label="FIRST_SLICE", + ) + env_doc = exp_env.export() + assert env_doc["header"]["outcome"] == "partial" + assert len(env_doc["payload"]["failed_samples"]) == len(id_res.failed_samples) + + # SolarScale provenance filtering: reject 'missing' and 'swept' as fixed inputs, + # and convert cm^2/(V s) -> m^2/(V s) (* 1e-4). + records_file = tmp_path / "records.json" + template_file = tmp_path / "template.yaml" + records_payload = { + "records": [ + { + "material_id": "mat_valid", + "formula": "CsPbI3", + "screening": { + "production_solarlab_ready": True, + "readiness": "promising", + "final_fom_score": 0.91, + }, + "properties": { + "band_gap_hse_ev": { + "value": 1.68, + "unit": "eV", + "provenance": {"kind": "computed", "source": "vasp"}, + }, + "dielectric_static_avg": { + "value": 21.5, + "unit": "1", + "provenance": {"kind": "computed", "source": "dfpt"}, + }, + "electron_mobility_cm2_v_s": { + "value": 25.0, + "unit": "cm^2/(V s)", + "provenance": {"kind": "computed", "source": "amset"}, + }, + "hole_mobility_cm2_v_s": { + "value": 999.0, + "unit": "cm^2/(V s)", + "provenance": {"kind": "swept", "source": "grid"}, + }, + "absorber_thickness_m": { + "value": 500.0e-9, + "unit": "m", + "provenance": {"kind": "swept", "source": "grid"}, + }, + }, + }, + { + "material_id": "mat_missing_eps", + "formula": "CsSnI3", + "screening": { + "production_solarlab_ready": True, + "readiness": "promising", + "final_fom_score": 0.85, + }, + "properties": { + "band_gap_hse_ev": { + "value": 1.35, + "unit": "eV", + "provenance": {"kind": "computed", "source": "vasp"}, + }, + "dielectric_static_avg": { + "value": 30.0, + "unit": "1", + "provenance": {"kind": "missing", "source": "none"}, + }, + }, + }, + ] + } + records_file.write_text(json.dumps(records_payload), encoding="utf-8") + import yaml + + template_file.write_text( + yaml.safe_dump(_inline_device_doc(absorber_eg=1.6), sort_keys=False), + encoding="utf-8", + ) + + plan = plan_solarlab_import( + records_file, + template_path=template_file, + import_policy="production", + activate_bandgap=True, + ) + selected_by_id = {c["material_id"]: c for c in plan["selected"]} + skipped_by_id = {c["material_id"]: c for c in plan["skipped"]} + assert "mat_valid" in selected_by_id + assert math.isclose( + selected_by_id["mat_valid"]["mapped_parameters"]["absorber.mu_n"], 25.0e-4 + ) + assert "absorber.mu_p" not in selected_by_id["mat_valid"]["mapped_parameters"] + assert "mat_missing_eps" in skipped_by_id + assert "dielectric_static_avg" in skipped_by_id["mat_missing_eps"]["missing_required"] + + out_a = tmp_path / "gen_a" + out_b = tmp_path / "gen_b" + man_a = generate_solarlab_inputs( + records_file, + template_path=template_file, + out_dir=out_a, + import_policy="production", + activate_bandgap=True, + ) + _ = generate_solarlab_inputs( + records_file, + template_path=template_file, + out_dir=out_b, + import_policy="production", + activate_bandgap=True, + ) + # Volatile fields ignored; config contents match; manifest digest deterministic when paths match. + assert len(man_a["generated"]) == 1 + assert manifest_sha256(man_a) == manifest_sha256(json.loads(json.dumps(man_a))) + assert (out_a / "mat_valid.yaml").read_text(encoding="utf-8") == ( + out_b / "mat_valid.yaml" + ).read_text(encoding="utf-8") From 0b03de5028e2124e743483671de890278dd038de Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Fri, 13 Nov 2026 00:04:27 +0800 Subject: [PATCH 13/46] N(physics): migrate 1D heterointerface transport, SRH, and two-sided sheet-charge closures onto unified assembly (P04-09) --- src/solarlab/device/compile_1d.py | 778 +++++++++- src/solarlab/device/compile_ionic_1d.py | 11 +- .../device/compile_multiple_ionic_1d.py | 14 +- .../equations/assembly/classical_1d.py | 278 +++- src/solarlab/equations/assembly/ionic_1d.py | 15 +- src/solarlab/equations/dc_1d.py | 811 ++++++++++- .../electrostatics/interface_traces.py | 30 +- .../physics/interface_transport/__init__.py | 61 + .../physics/interface_transport/thermionic.py | 689 +++++++++ .../physics/interface_transport/two_sided.py | 1255 +++++++++++++++++ .../physics/recombination/__init__.py | 42 +- .../physics/recombination/interface.py | 773 ++++++++++ tests/integration/test_core_1d.py | 19 +- tests/integration/test_interface_parity_1d.py | 1177 ++++++++++++++++ tests/integration/test_neutral_defects_1d.py | 8 +- .../equations/test_interface_assembly_1d.py | 1083 ++++++++++++++ .../physics/test_interface_recombination.py | 532 +++++++ .../unit/physics/test_interface_transport.py | 679 +++++++++ 18 files changed, 8179 insertions(+), 76 deletions(-) create mode 100644 src/solarlab/physics/interface_transport/__init__.py create mode 100644 src/solarlab/physics/interface_transport/thermionic.py create mode 100644 src/solarlab/physics/interface_transport/two_sided.py create mode 100644 src/solarlab/physics/recombination/interface.py create mode 100644 tests/integration/test_interface_parity_1d.py create mode 100644 tests/unit/equations/test_interface_assembly_1d.py create mode 100644 tests/unit/physics/test_interface_recombination.py create mode 100644 tests/unit/physics/test_interface_transport.py diff --git a/src/solarlab/device/compile_1d.py b/src/solarlab/device/compile_1d.py index 4bd89539..84214fcf 100644 --- a/src/solarlab/device/compile_1d.py +++ b/src/solarlab/device/compile_1d.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Mapping, Sequence import hashlib import json import math @@ -22,19 +22,41 @@ import numpy as np +from solarlab.contracts.units import ELEMENTARY_CHARGE_C from solarlab.device.resolved import PreparedDevice, PreparedLayer from solarlab.device.neutral_defects import LITERAL_ABOVE_VB_DOS_REFERENCE_V1, bind_neutral_defects from solarlab.device.optical_generation import bind_optical_generation_1d from solarlab.equations.dc_1d import ( CapabilityError, CompiledDevice1D, + CompiledInterfaceModel1D, + DeduplicatedBareSRHSpec, + DeduplicatedDefectSRHSpec, + DeduplicatedThermionicFaceSpec, LocalRecombinationModel, + TERegularizationName, + TwoSidedInterfaceBindingSpec, ) -from solarlab.equations.field_transport_1d import bind_field_transport_1d -from solarlab.mesh import INTEGER_ENDPOINT_V1, RIGHT_LAYER_WINS, build_geometry, multilayer_grid +from solarlab.solvers.nonlinear.steady_1d import ( + POISSON_CONTACT_BALANCE_V1, + SteadyOptions, + SteadyStateError, + solve_equilibrium, +) +from solarlab.equations.field_transport_1d import FieldTransport1D, bind_field_transport_1d +from solarlab.physics.generation.profile import GenerationProfile +from solarlab.mesh import ( + INTEGER_ENDPOINT_V1, + RIGHT_LAYER_WINS, + TWO_SIDED_TRACE_V1, + build_geometry, + multilayer_grid, +) +from solarlab.mesh.geometry import ControlVolumeGeometry1D from solarlab.mesh.grid import layer_node_masks from solarlab.physics.band_structure.binding import ( LayerParameterInput, + ParameterBinding, TemperatureLawSpec, compile_layer_parameters, ) @@ -48,8 +70,26 @@ ) from solarlab.physics.contacts.exchange import resolve_exchange_velocities from solarlab.physics.electrostatics import PoissonOperator1D +from solarlab.physics.electrostatics.interface_traces import ( + TraceElectrostatics, + sheet_charge_row_weights, +) from solarlab.physics.generation.beer_lambert import BeerLambertBinding from solarlab.physics.generation.fixed import FixedGenerationProfile +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TE_BARRIER_THRESHOLD_EV, + TwoSidedBulkState, + TwoSidedInterfacePhysics, + remove_shared_interface_nodes, + resolve_layer_richardson, + solve_two_sided_interface_qss, +) +from solarlab.physics.recombination.interface import ( + InterfaceDefectSpec, + build_plane_closure_params, + resolve_interface_defect_references, +) from solarlab.physics.recombination.reaction import ( BulkRecombinationCoefficients, BulkRecombinationReaction, @@ -59,6 +99,9 @@ __all__ = ["CapabilityError", "CompiledDevice1D", "compile_device_1d", "unsupported"] +Q = ELEMENTARY_CHARGE_C +InterfaceTopologyName = Literal["deduplicated", "two_sided_trace"] + class _LayerScalars(TypedDict): """Resolved scalar fields consumed by this supported DC binding.""" @@ -101,17 +144,24 @@ def unsupported(prepared: PreparedDevice, data: dict[str, Any], layers: tuple[Pr if not settings["dos_band_potentials"]: missing.append("settings.dos_band_potentials: physical DOS transport requires this enabled") for flag in ( - "interface_plane_projection", "te_physical_norm", "flat_band_metal_contacts", - "interface_two_sided", "interface_shared_occupancy", "interface_plane_closure", - "interface_plane_generation", "graded_optics", "interface_tunneling", + "te_physical_norm", "flat_band_metal_contacts", + "interface_two_sided", "interface_shared_occupancy", + "graded_optics", "interface_tunneling", "ion_steric_diffusion_only", "ion_steric_shared_site", ): if settings[flag]: missing.append("settings." + flag) + if settings["interface_plane_generation"] and not settings["interface_plane_closure"]: + missing.append("settings.interface_plane_generation: requires settings.interface_plane_closure") + if settings["interface_plane_projection"] and settings["interface_plane_closure"]: + missing.append("settings.interface_plane_projection and settings.interface_plane_closure are mutually exclusive") if settings["het_recomb_despike"] != 0.0: missing.append("settings.het_recomb_despike") - if settings["interface_charge_closure"] != "off": + charge_closure = settings["interface_charge_closure"] + if charge_closure not in ("off", "equilibrium_referenced"): missing.append("settings.interface_charge_closure") + elif charge_closure == "equilibrium_referenced" and not settings["interface_charge_rebaseline_acknowledged"]: + missing.append("settings.interface_charge_closure: equilibrium_referenced requires interface_charge_rebaseline_acknowledged=True") if settings["jv_solver_policy"] != "general": missing.append("settings.jv_solver_policy: a separately qualified solver route is required") if data["grain_boundaries"]: @@ -152,17 +202,635 @@ def unsupported(prepared: PreparedDevice, data: dict[str, Any], layers: tuple[Pr not spectral and (layer.optical is not None or parameters["n_optical"] is not None) ): missing.append(prefix + "optical_material: requires an explicit spectrum; graded optics is not bound") - for interface in prepared.interfaces: - entry = interface.to_mapping() - if interface.electrical and ( - entry.get("defect") is not None - or any((entry.get(name) or 0.0) != 0.0 for name in ("v_n", "v_p")) - ): - missing.append("interfaces." + entry["id"] + ": interface recombination is not bound") if missing: raise CapabilityError("unsupported_classical_1d_dc: " + "; ".join(missing)) +def _solve_dark_uncharged_two_sided_equilibrium( + *, + device_id: str, + geometry: ControlVolumeGeometry1D, + binding: ParameterBinding, + poisson: PoissonOperator1D, + electron_diffusivity: np.ndarray, + hole_diffusivity: np.ndarray, + generation: GenerationProfile, + recombination: BulkRecombinationReaction, + channels: tuple[CarrierExchangeChannel, ...], + phi_left_V: float, + built_in_V: float, + fermi_eV: float, + reference_phi: np.ndarray, + reference_n: np.ndarray, + reference_p: np.ndarray, + additional_recombination: LocalRecombinationModel | None, + field_transport: FieldTransport1D | None, + provisional_specs: Sequence[tuple[int, int, int, int, TraceElectrostatics, TwoSidedInterfacePhysics, float]], +) -> np.ndarray: + """Certify dark (V=0, G=0) charge-off two_sided_trace steady state for equilibrium_referenced.""" + uncharged_specs = tuple( + TwoSidedInterfaceBindingSpec( + interface_index=k, + face=face, + left_node=l_node, + right_node=r_node, + trace_electrostatics=trace_elec, + physics=phys, + charge=None, + weight_left=0.0, + weight_right=0.0, + ) + for k, face, l_node, r_node, trace_elec, phys, _ in provisional_specs + ) + prov_model = CompiledInterfaceModel1D( + topology="two_sided_trace", + identity_sha256="0" * 64, + two_sided=uncharged_specs, + ) + prov_dev = CompiledDevice1D( + device_id, + "0" * 64, + geometry, + binding, + poisson, + electron_diffusivity, + hole_diffusivity, + generation, + recombination, + channels, + phi_left_V, + built_in_V, + fermi_eV, + reference_phi, + reference_n, + reference_p, + additional_recombination, + capabilities=("ion_free", "classical_1d_dc", "heterointerface_1d"), + field_transport=field_transport, + interface_model=prov_model, + ) + try: + return solve_equilibrium( + prov_dev, + options=SteadyOptions( + continuity_tolerance_A_m2=5.0e-11, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ), + ).state.u + except SteadyStateError as error: + raise CapabilityError( + "equilibrium_referenced: dark charge-off two-sided reference failed to converge" + ) from error + + +def _bind_interfaces_1d( + *, + device_id: str, + prepared: PreparedDevice, + settings: Mapping[str, Any], + layers: tuple[PreparedLayer, ...], + geometry: ControlVolumeGeometry1D, + binding: ParameterBinding, + poisson: PoissonOperator1D, + electron_diffusivity: np.ndarray, + hole_diffusivity: np.ndarray, + generation: GenerationProfile, + recombination: BulkRecombinationReaction, + channels: tuple[CarrierExchangeChannel, ...], + eps_r_node: np.ndarray, + reference_phi: np.ndarray, + reference_n: np.ndarray, + reference_p: np.ndarray, + phi_left_V: float, + built_in_V: float, + fermi_eV: float, + additional_recombination: LocalRecombinationModel | None, + field_transport: FieldTransport1D | None, + topology: InterfaceTopologyName, + te_softness: float, + te_regularization_mode: TERegularizationName, + interface_transmission: float, + equilibrium_occupancies: Sequence[float] | None, +) -> CompiledInterfaceModel1D | None: + iface_count = len(layers) - 1 + charge_closure = str(settings["interface_charge_closure"]) + plane_proj = bool(settings["interface_plane_projection"]) + plane_clos = bool(settings["interface_plane_closure"]) + plane_gen = bool(settings["interface_plane_generation"]) + + if iface_count == 0: + if topology == "two_sided_trace": + raise CapabilityError("unsupported_classical_1d_dc: two_sided_trace requires at least two electrical layers") + if charge_closure != "off" or plane_proj or plane_clos or plane_gen: + raise CapabilityError("unsupported_classical_1d_dc: heterointerface closure requires at least one electrical interface") + return None + + by_pair: dict[tuple[str, str], dict[str, Any]] = {} + for iface in prepared.interfaces: + if iface.electrical: + entry = iface.to_mapping() + by_pair[(str(entry["left"]), str(entry["right"]))] = entry + + ordered_entries: list[dict[str, Any]] = [] + for k in range(iface_count): + pair = (layers[k].id, layers[k + 1].id) + if pair not in by_pair: + raise CapabilityError(f"unsupported_classical_1d_dc: missing electrical interface for {pair[0]}->{pair[1]}") + ordered_entries.append(by_pair[pair]) + + bands = binding.band_structure + configured = binding.intrinsic_product_m6 + vt = binding.thermal_voltage_V + temp = binding.temperature_K + + if topology == "deduplicated": + if charge_closure != "off": + raise CapabilityError( + "unsupported_classical_1d_dc: settings.interface_charge_closure requires two_sided_trace topology" + ) + if equilibrium_occupancies is not None: + raise ValueError("equilibrium_occupancies applies only to equilibrium_referenced two_sided_trace") + + bare_specs: list[DeduplicatedBareSRHSpec] = [] + defect_specs: list[DeduplicatedDefectSRHSpec] = [] + te_specs: list[DeduplicatedThermionicFaceSpec] = [] + + for k, entry in enumerate(ordered_entries): + plane = geometry.interfaces[k] + if plane.shared_node is None or not (2 <= plane.shared_node <= geometry.node_count - 3): + raise CapabilityError("unsupported_classical_1d_dc: deduplicated interface requires an interior shared node") + idx = int(plane.shared_node) + face = idx - 1 + + left_p = dict(layers[k].parameters) + a_star_n = resolve_layer_richardson( + float(cast(float, left_p["A_star_n"])), + float(cast(float, left_p["Nc300"])), + temp, + ) + a_star_p = resolve_layer_richardson( + float(cast(float, left_p["A_star_p"])), + float(cast(float, left_p["Nv300"])), + temp, + ) + delta_ec = float( + bands.physical_electron_affinity_eV[face] + - bands.physical_electron_affinity_eV[face + 1] + ) + delta_ev = float( + (bands.physical_electron_affinity_eV[face] + bands.physical_band_gap_eV[face]) + - (bands.physical_electron_affinity_eV[face + 1] + bands.physical_band_gap_eV[face + 1]) + ) + cap_e = a_star_n > 0.0 and abs(delta_ec) > TE_BARRIER_THRESHOLD_EV + cap_h = a_star_p > 0.0 and abs(delta_ev) > TE_BARRIER_THRESHOLD_EV + if cap_e or cap_h: + te_specs.append( + DeduplicatedThermionicFaceSpec( + interface_index=k, + face=face, + delta_Ec_eV=delta_ec, + delta_Ev_eV=delta_ev, + a_star_n_A_m2_K2=a_star_n, + a_star_p_A_m2_K2=a_star_p, + cap_electron=cap_e, + cap_hole=cap_h, + ) + ) + + defect = entry.get("defect") + raw_vn = entry.get("v_n") + raw_vp = entry.get("v_p") + if defect is None: + vn = 0.0 if raw_vn is None else float(raw_vn) + vp = 0.0 if raw_vp is None else float(raw_vp) + if not (math.isfinite(vn) and math.isfinite(vp)) or vn < 0.0 or vp < 0.0: + raise CapabilityError(f"interfaces.{entry['id']}: velocities must be finite and non-negative") + if vn > 0.0 or vp > 0.0: + bare_specs.append( + DeduplicatedBareSRHSpec( + interface_index=k, + node=idx, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_m6=float(configured[idx]), + n1_m3=float(binding.srh_n1_m3[idx]), + p1_m3=float(binding.srh_p1_m3[idx]), + ) + ) + else: + kinetics = defect["kinetics"] + d_spec = InterfaceDefectSpec( + areal_density_m2=float(defect["total_density_m2"]), + trap_depth_eV=float(defect["trap_depth_eV"]), + energy_reference=defect["energy_reference"], + sigma_n_m2=float(kinetics["sigma_n_m2"]), + sigma_p_m2=float(kinetics["sigma_p_m2"]), + v_th_n_m_s=float(kinetics["thermal_velocity_n_m_s"]), + v_th_p_m_s=float(kinetics["thermal_velocity_p_m_s"]), + calibration_factor=float(defect["calibration_factor"]), + ) + vn, vp = d_spec.effective_capture_velocities_m_s() + i_l, i_r = idx - 1, idx + 1 + refs = resolve_interface_defect_references( + left_role=layers[k].role, + right_role=layers[k + 1].role, + left_chi_phys_eV=float(bands.physical_electron_affinity_eV[i_l]), + left_Eg_phys_eV=float(bands.physical_band_gap_eV[i_l]), + left_Nc_m3=float(binding.conduction_dos_m3[i_l]), + left_Nv_m3=float(binding.valence_dos_m3[i_l]), + right_chi_phys_eV=float(bands.physical_electron_affinity_eV[i_r]), + right_Eg_phys_eV=float(bands.physical_band_gap_eV[i_r]), + right_Nc_m3=float(binding.conduction_dos_m3[i_r]), + right_Nv_m3=float(binding.valence_dos_m3[i_r]), + thermal_voltage_V=vt, + trap_depth_eV=d_spec.trap_depth_eV, + energy_reference=d_spec.energy_reference, + ) + _, pl_eq = doping_equilibrium_densities( + float(binding.donor_density_m3[i_l]), + float(binding.acceptor_density_m3[i_l]), + float(configured[i_l]), + ) + nr_eq, _ = doping_equilibrium_densities( + float(binding.donor_density_m3[i_r]), + float(binding.acceptor_density_m3[i_r]), + float(configured[i_r]), + ) + plane_prm = None + if plane_clos: + ref_node = i_l if refs.reference_side == "left" else i_r + depth_below_cb = ( + d_spec.trap_depth_eV + if d_spec.energy_reference == "below_conduction_band" + else refs.reference_gap_eV - d_spec.trap_depth_eV + ) + plane_prm = build_plane_closure_params( + chi_left_folded_eV=float(bands.transport_electron_affinity_eV[i_l]), + chi_right_folded_eV=float(bands.transport_electron_affinity_eV[i_r]), + valence_left_folded_eV=float( + bands.transport_electron_affinity_eV[i_l] + + bands.transport_band_gap_eV[i_l] + ), + valence_right_folded_eV=float( + bands.transport_electron_affinity_eV[i_r] + + bands.transport_band_gap_eV[i_r] + ), + Nc_ref_m3=float(binding.conduction_dos_m3[ref_node]), + Nv_ref_m3=float(binding.valence_dos_m3[ref_node]), + chi_ref_phys_eV=float(bands.physical_electron_affinity_eV[ref_node]), + trap_depth_below_ref_cb_eV=depth_below_cb, + thermal_voltage_V=vt, + ) + if vn > 0.0 or vp > 0.0 or plane_clos or plane_proj: + defect_specs.append( + DeduplicatedDefectSRHSpec( + interface_index=k, + node=idx, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_eff_m6=float(nr_eq * pl_eq), + n1_m3=refs.n1_midgap_symmetric_m3, + p1_m3=refs.p1_midgap_symmetric_m3, + plane_params=plane_prm, + ) + ) + + if (plane_proj or plane_clos) and not defect_specs: + raise CapabilityError( + "unsupported_classical_1d_dc: interface_plane_projection/closure requires at least one interface defect" + ) + + if not bare_specs and not defect_specs and not te_specs: + return None + + manifest = { + "schema": "compiled_interface_model_1d_v1", + "topology": "deduplicated", + "plane_projection": plane_proj, + "plane_closure": plane_clos, + "plane_generation": plane_gen, + "te_softness": te_softness, + "te_regularization_mode": te_regularization_mode, + "bare_srh": [ + [s.interface_index, s.node, s.v_n_m_s, s.v_p_m_s, s.ni_sq_m6, s.n1_m3, s.p1_m3] + for s in bare_specs + ], + "defect_srh": [ + [ + s.interface_index, + s.node, + s.v_n_m_s, + s.v_p_m_s, + s.ni_sq_eff_m6, + s.n1_m3, + s.p1_m3, + None + if s.plane_params is None + else [ + s.plane_params.bn_L, + s.plane_params.bn_R, + s.plane_params.bp_L, + s.plane_params.bp_R, + s.plane_params.ni_s_sq_m6, + s.plane_params.n1_s_m3, + s.plane_params.p1_s_m3, + s.plane_params.s_supply_m_s, + ], + ] + for s in defect_specs + ], + "thermionic_faces": [ + [ + s.interface_index, + s.face, + s.delta_Ec_eV, + s.delta_Ev_eV, + s.a_star_n_A_m2_K2, + s.a_star_p_A_m2_K2, + s.cap_electron, + s.cap_hole, + ] + for s in te_specs + ], + } + iface_sha = hashlib.sha256( + json.dumps(manifest, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + return CompiledInterfaceModel1D( + topology="deduplicated", + identity_sha256=iface_sha, + bare_srh=tuple(bare_specs), + defect_srh=tuple(defect_specs), + thermionic_faces=tuple(te_specs), + plane_projection=plane_proj, + plane_closure=plane_clos, + plane_generation=plane_gen, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + ) + + # Two-sided trace topology + if plane_proj or plane_clos or plane_gen: + raise CapabilityError( + "unsupported_classical_1d_dc: deduplicated plane projection/closure flags cannot be combined with two_sided_trace" + ) + + provisional_specs: list[tuple[int, int, int, int, TraceElectrostatics, TwoSidedInterfacePhysics, float]] = [] + has_any_defect = False + for k, entry in enumerate(ordered_entries): + plane = geometry.interfaces[k] + l_node, r_node = int(plane.left_node), int(plane.right_node) + face = l_node + if r_node != l_node + 1 or l_node <= 0 or r_node >= geometry.node_count - 1: + raise CapabilityError("unsupported_classical_1d_dc: two_sided_trace requires adjacent interior bulk nodes") + + left_p = dict(layers[k].parameters) + right_p = dict(layers[k + 1].parameters) + a_n_l = resolve_layer_richardson(float(cast(float, left_p["A_star_n"])), float(cast(float, left_p["Nc300"])), temp) + a_n_r = resolve_layer_richardson(float(cast(float, right_p["A_star_n"])), float(cast(float, right_p["Nc300"])), temp) + a_p_l = resolve_layer_richardson(float(cast(float, left_p["A_star_p"])), float(cast(float, left_p["Nv300"])), temp) + a_p_r = resolve_layer_richardson(float(cast(float, right_p["A_star_p"])), float(cast(float, right_p["Nv300"])), temp) + rich_n = min(a_n_l, a_n_r) + rich_p = min(a_p_l, a_p_r) + if rich_n <= 0.0 or rich_p <= 0.0: + raise CapabilityError( + f"interfaces.{entry['id']}: two_sided_trace requires positive A_star_n and A_star_p on both adjacent layers" + ) + + defect = entry.get("defect") + raw_vn = entry.get("v_n") + raw_vp = entry.get("v_p") + if defect is None: + vn = 0.0 if raw_vn is None else float(raw_vn) + vp = 0.0 if raw_vp is None else float(raw_vp) + if charge_closure == "equilibrium_referenced": + raise CapabilityError( + f"interfaces.{entry['id']}: equilibrium_referenced charge closure requires a canonical microscopic defect on every electrical interface" + ) + if vn != 0.0 or vp != 0.0: + raise CapabilityError( + f"interfaces.{entry['id']}: two_sided_trace recombination requires an explicit interface defect to define two-sided emission densities" + ) + n1_l = p1_l = n1_r = p1_r = 0.0 + trap_density_m2 = 0.0 + else: + has_any_defect = True + kinetics = defect["kinetics"] + cal = float(defect["calibration_factor"]) + state_cal = float(defect["iface_state_calibration_factor"]) + if charge_closure == "equilibrium_referenced": + if cal != 1.0 or state_cal != 1.0: + raise CapabilityError( + f"interfaces.{entry['id']}: equilibrium_referenced charge closure forbids empirical interface calibration factors" + ) + micro_pair = tuple(float(v) for v in entry["microscopic_capture_velocities_m_s"]) + if raw_vn is not None and raw_vp is not None and not ( + math.isclose(float(raw_vn), micro_pair[0], rel_tol=1.0e-12, abs_tol=0.0) + and math.isclose(float(raw_vp), micro_pair[1], rel_tol=1.0e-12, abs_tol=0.0) + ): + raise CapabilityError( + f"interfaces.{entry['id']}: compatibility SRV {(raw_vn, raw_vp)!r} does not match microscopic sigma*v_th*N_t {micro_pair!r}" + ) + d_spec = InterfaceDefectSpec( + areal_density_m2=float(defect["total_density_m2"]), + trap_depth_eV=float(defect["trap_depth_eV"]), + energy_reference=defect["energy_reference"], + sigma_n_m2=float(kinetics["sigma_n_m2"]), + sigma_p_m2=float(kinetics["sigma_p_m2"]), + v_th_n_m_s=float(kinetics["thermal_velocity_n_m_s"]), + v_th_p_m_s=float(kinetics["thermal_velocity_p_m_s"]), + calibration_factor=cal, + ) + vn, vp = d_spec.effective_capture_velocities_m_s() + refs = resolve_interface_defect_references( + left_role=layers[k].role, + right_role=layers[k + 1].role, + left_chi_phys_eV=float(bands.physical_electron_affinity_eV[l_node]), + left_Eg_phys_eV=float(bands.physical_band_gap_eV[l_node]), + left_Nc_m3=float(binding.conduction_dos_m3[l_node]), + left_Nv_m3=float(binding.valence_dos_m3[l_node]), + right_chi_phys_eV=float(bands.physical_electron_affinity_eV[r_node]), + right_Eg_phys_eV=float(bands.physical_band_gap_eV[r_node]), + right_Nc_m3=float(binding.conduction_dos_m3[r_node]), + right_Nv_m3=float(binding.valence_dos_m3[r_node]), + thermal_voltage_V=vt, + trap_depth_eV=d_spec.trap_depth_eV, + energy_reference=d_spec.energy_reference, + require_in_gap=(charge_closure == "equilibrium_referenced"), + ) + n1_l, p1_l = refs.n1_left_m3, refs.p1_left_m3 + n1_r, p1_r = refs.n1_right_m3, refs.p1_right_m3 + trap_density_m2 = d_spec.areal_density_m2 + + trace_elec = TraceElectrostatics.from_plane( + plane, + float(eps_r_node[l_node]), + float(eps_r_node[r_node]), + ) + phys = TwoSidedInterfacePhysics( + thermal_voltage_V=vt, + temperature_K=temp, + D_n_left_m2_s=float(binding.electron_diffusivity_m2_s[l_node]), + D_n_right_m2_s=float(binding.electron_diffusivity_m2_s[r_node]), + D_p_left_m2_s=float(binding.hole_diffusivity_m2_s[l_node]), + D_p_right_m2_s=float(binding.hole_diffusivity_m2_s[r_node]), + N_C_left_m3=float(binding.conduction_dos_m3[l_node]), + N_C_right_m3=float(binding.conduction_dos_m3[r_node]), + N_V_left_m3=float(binding.valence_dos_m3[l_node]), + N_V_right_m3=float(binding.valence_dos_m3[r_node]), + richardson_n_A_m2_K2=rich_n, + richardson_p_A_m2_K2=rich_p, + conduction_band_step_eV=float( + bands.physical_electron_affinity_eV[l_node] + - bands.physical_electron_affinity_eV[r_node] + ), + hole_transport_step_eV=float( + (bands.physical_electron_affinity_eV[r_node] + bands.physical_band_gap_eV[r_node]) + - (bands.physical_electron_affinity_eV[l_node] + bands.physical_band_gap_eV[l_node]) + ), + transmission=interface_transmission, + surface_recombination_velocity_n_m_s=vn, + surface_recombination_velocity_p_m_s=vp, + n1_left_m3=n1_l, + n1_right_m3=n1_r, + p1_left_m3=p1_l, + p1_right_m3=p1_r, + ) + provisional_specs.append((k, face, l_node, r_node, trace_elec, phys, trap_density_m2)) + + eq_occ: list[float] | None = None + if charge_closure == "equilibrium_referenced": + if not has_any_defect: + raise CapabilityError( + "unsupported_classical_1d_dc: equilibrium_referenced charge closure requires interface defects" + ) + if equilibrium_occupancies is not None: + if len(equilibrium_occupancies) != iface_count: + raise ValueError("equilibrium_occupancies must match the number of electrical interfaces") + eq_occ = [float(v) for v in equilibrium_occupancies] + if any(not math.isfinite(v) or not 0.0 <= v <= 1.0 for v in eq_occ): + raise ValueError("equilibrium_occupancies must lie in [0, 1]") + else: + u_dark = _solve_dark_uncharged_two_sided_equilibrium( + device_id=device_id, + geometry=geometry, + binding=binding, + poisson=poisson, + electron_diffusivity=electron_diffusivity, + hole_diffusivity=hole_diffusivity, + generation=generation, + recombination=recombination, + channels=channels, + phi_left_V=phi_left_V, + built_in_V=built_in_V, + fermi_eV=fermi_eV, + reference_phi=reference_phi, + reference_n=reference_n, + reference_p=reference_p, + additional_recombination=additional_recombination, + field_transport=field_transport, + provisional_specs=provisional_specs, + ) + count_nodes = geometry.node_count + phi_eq = u_dark[:count_nodes] + zn_eq = u_dark[count_nodes:2 * count_nodes] + zp_eq = u_dark[2 * count_nodes:] + shift_eq = (phi_eq - reference_phi) / vt + n_eq = reference_n * np.exp(shift_eq + zn_eq) + p_eq = reference_p * np.exp(-shift_eq - zp_eq) + eq_occ = [] + for _, _, l_node, r_node, trace_elec, phys, _ in provisional_specs: + dark_qss = solve_two_sided_interface_qss( + trace_elec, + phys, + TwoSidedBulkState( + phi_left_V=float(phi_eq[l_node]), + phi_right_V=float(phi_eq[r_node]), + n_left_m3=float(n_eq[l_node]), + p_left_m3=float(p_eq[l_node]), + n_right_m3=float(n_eq[r_node]), + p_right_m3=float(p_eq[r_node]), + electron_electrochemical_step=float(zn_eq[r_node] - zn_eq[l_node]), + hole_electrochemical_step=float(-(zp_eq[r_node] - zp_eq[l_node])), + ), + ) + if dark_qss.occupancy is None: + eq_occ.append(0.0) + else: + eq_occ.append(float(dark_qss.occupancy)) + elif equilibrium_occupancies is not None: + raise ValueError("equilibrium_occupancies requires settings.interface_charge_closure='equilibrium_referenced'") + + two_sided_specs: list[TwoSidedInterfaceBindingSpec] = [] + manifest_two_sided: list[object] = [] + for idx_spec, (k, face, l_node, r_node, trace_elec, phys, trap_nt) in enumerate(provisional_specs): + charge_obj: EquilibriumReferencedSheetCharge | None = None + wl = wr = 0.0 + if eq_occ is not None: + charge_obj = EquilibriumReferencedSheetCharge( + equilibrium_occupancy=eq_occ[idx_spec], + trap_density_m2=trap_nt, + ) + wl, wr = sheet_charge_row_weights( + trace_elec.eps_r_left, + trace_elec.left_distance_m, + trace_elec.eps_r_right, + trace_elec.right_distance_m, + ) + two_sided_specs.append( + TwoSidedInterfaceBindingSpec( + interface_index=k, + face=face, + left_node=l_node, + right_node=r_node, + trace_electrostatics=trace_elec, + physics=phys, + charge=charge_obj, + weight_left=wl, + weight_right=wr, + ) + ) + manifest_two_sided.append( + [ + k, + face, + l_node, + r_node, + trace_elec.left_distance_m, + trace_elec.right_distance_m, + trace_elec.eps_r_left, + trace_elec.eps_r_right, + phys.richardson_n_A_m2_K2, + phys.richardson_p_A_m2_K2, + phys.conduction_band_step_eV, + phys.hole_transport_step_eV, + phys.transmission, + phys.surface_recombination_velocity_n_m_s, + phys.surface_recombination_velocity_p_m_s, + phys.n1_left_m3, + phys.n1_right_m3, + phys.p1_left_m3, + phys.p1_right_m3, + None if charge_obj is None else [charge_obj.equilibrium_occupancy, charge_obj.trap_density_m2, wl, wr], + ] + ) + + manifest_ts = { + "schema": "compiled_interface_model_1d_v1", + "topology": "two_sided_trace", + "charge_closure": charge_closure, + "two_sided": manifest_two_sided, + } + iface_sha = hashlib.sha256( + json.dumps(manifest_ts, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + return CompiledInterfaceModel1D( + topology="two_sided_trace", + identity_sha256=iface_sha, + two_sided=tuple(two_sided_specs), + ) + + def _layer_input(layer: PreparedLayer) -> LayerParameterInput: parameters = dict(layer.parameters) for name in ("chi", "Eg", "Nc300", "Nv300", "ni", "eps_r", "mu_n", "mu_p"): @@ -200,6 +868,11 @@ def compile_device_1d( *, intervals_per_layer: int | Sequence[int] = 24, additional_recombination: LocalRecombinationModel | None = None, + interface_topology: InterfaceTopologyName | None = None, + te_softness: float = 0.02, + te_regularization_mode: TERegularizationName = "legacy_logistic", + interface_transmission: float = 1.0, + equilibrium_occupancies: Sequence[float] | None = None, ) -> CompiledDevice1D: """Cold compile genuine resolved configuration; no legacy/test execution. @@ -210,10 +883,31 @@ def compile_device_1d( """ if not isinstance(prepared, PreparedDevice): raise TypeError("compile_device_1d requires an existing PreparedDevice") + if interface_topology is not None and interface_topology not in ("deduplicated", "two_sided_trace"): + raise ValueError("interface_topology must be 'deduplicated', 'two_sided_trace', or None") + if te_regularization_mode not in ("legacy_logistic", "compact_support"): + raise ValueError("te_regularization_mode must be 'legacy_logistic' or 'compact_support'") + if isinstance(te_softness, bool) or not math.isfinite(float(te_softness)) or float(te_softness) < 0.0: + raise ValueError("te_softness must be a finite non-negative float") + if ( + isinstance(interface_transmission, bool) + or not math.isfinite(float(interface_transmission)) + or not 0.0 < float(interface_transmission) <= 1.0 + ): + raise ValueError("interface_transmission must lie in (0, 1]") + data = prepared.to_mapping() settings = data["settings"] layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") unsupported(prepared, data, layers) + resolved_topology: InterfaceTopologyName = ( + interface_topology + if interface_topology is not None + else ("two_sided_trace" if settings["interface_charge_closure"] == "equilibrium_referenced" else "deduplicated") + ) + if resolved_topology == "two_sided_trace" and len(layers) < 2: + raise CapabilityError("unsupported_classical_1d_dc: two_sided_trace requires at least two electrical layers") + grid = {entry["layer"]: entry for entry in data["electrical_grid"]} if isinstance(intervals_per_layer, bool): raise ValueError("intervals_per_layer must be an integer or integer sequence") @@ -234,9 +928,15 @@ def compile_device_1d( counts[index] *= p["grading_N_mult"] alphas = [grid.get(layer.id, {}).get("alpha", 3.0) for layer in layers] thicknesses = [layer.thickness for layer in layers] - nodes = multilayer_grid(list(zip(thicknesses, counts)), alpha=alphas) + interface_positions: np.ndarray = np.cumsum(thicknesses, dtype=float)[:-1] + base_nodes = multilayer_grid(list(zip(thicknesses, counts)), alpha=alphas) + if resolved_topology == "two_sided_trace": + nodes = remove_shared_interface_nodes(base_nodes, interface_positions) + geometry = build_geometry(TWO_SIDED_TRACE_V1, nodes, interface_positions) + else: + nodes = base_nodes + geometry = build_geometry(INTEGER_ENDPOINT_V1, nodes, interface_positions) masks = layer_node_masks(nodes, thicknesses, RIGHT_LAYER_WINS) - geometry = build_geometry(INTEGER_ENDPOINT_V1, nodes, np.cumsum(thicknesses)[:-1]) binding = compile_layer_parameters( nodes, [_layer_input(layer) for layer in layers], temperature_K=settings["T"], temperature_scaling=True, @@ -268,7 +968,8 @@ def paint(name: str) -> np.ndarray: configured = binding.intrinsic_product_m6 if np.any(configured <= 0.0) or not np.all(np.isfinite(configured)) or np.max(np.abs(np.log(configured) - log_product)) > 1.0e-10: raise CapabilityError("inconsistent_intrinsic_product: configured ni and physical Nc/Nv/Eg do not share one Maxwell-Boltzmann equilibrium") - poisson = PoissonOperator1D.for_geometry(geometry, paint("eps_r")) + eps_r_node = paint("eps_r") + poisson = PoissonOperator1D.for_geometry(geometry, eps_r_node) coefficients = BulkRecombinationCoefficients( nodes.size, configured, paint("tau_n"), paint("tau_p"), binding.srh_n1_m3, binding.srh_p1_m3, binding.radiative_coefficient_m3_s, @@ -324,6 +1025,36 @@ def contact_material(node: int) -> ContactMaterial: ) if all(channel.kind == "blocking" for channel in channels): raise CapabilityError("fully_blocking_contacts: a closed carrier inventory constraint is not bound in this DC slice") + + interface_model = _bind_interfaces_1d( + device_id=data["id"], + prepared=prepared, + settings=settings, + layers=layers, + geometry=geometry, + binding=binding, + poisson=poisson, + electron_diffusivity=electron_diffusivity, + hole_diffusivity=hole_diffusivity, + generation=generation, + recombination=recombination, + channels=channels, + eps_r_node=eps_r_node, + reference_phi=reference_phi, + reference_n=reference_n, + reference_p=reference_p, + phi_left_V=phi_left, + built_in_V=built_in, + fermi_eV=fermi, + additional_recombination=additional_recombination, + field_transport=field_transport, + topology=resolved_topology, + te_softness=float(te_softness), + te_regularization_mode=te_regularization_mode, + interface_transmission=float(interface_transmission), + equilibrium_occupancies=equilibrium_occupancies, + ) + extra_id = None if additional_recombination is None else additional_recombination.model_id identity_parts: tuple[object, ...] = ( "electrode_quasi_fermi_1d_v1", prepared.content_sha256, binding.sha256, @@ -336,14 +1067,27 @@ def contact_material(node: int) -> ContactMaterial: identity_parts += (LITERAL_ABOVE_VB_DOS_REFERENCE_V1,) if field_transport is not None: identity_parts += (field_transport.identity_sha256,) + if interface_model is not None: + identity_parts += (interface_model.identity_sha256,) identity = hashlib.sha256(json.dumps( identity_parts, separators=(",", ":"), allow_nan=False, ).encode()).hexdigest() + capabilities: tuple[str, ...] = ( + "ion_free", + "classical_1d_dc", + "maxwell_boltzmann", + "semiconductor_work_function_contacts", + "bulk_srh_radiative_auger", + ) + if interface_model is not None: + capabilities = capabilities + ("heterointerface_1d",) return CompiledDevice1D( data["id"], identity, geometry, binding, poisson, electron_diffusivity, hole_diffusivity, generation, recombination, channels, phi_left, built_in, fermi, reference_phi, reference_n, reference_p, additional_recombination, + capabilities=capabilities, field_transport=field_transport, + interface_model=interface_model, ) diff --git a/src/solarlab/device/compile_ionic_1d.py b/src/solarlab/device/compile_ionic_1d.py index 576e4ca6..d981820b 100644 --- a/src/solarlab/device/compile_ionic_1d.py +++ b/src/solarlab/device/compile_ionic_1d.py @@ -19,7 +19,7 @@ from solarlab.device.compile_1d import compile_device_1d from solarlab.device.inputs import DeviceInput from solarlab.device.resolved import PreparedDevice -from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dc_1d import CapabilityError, TERegularizationName from solarlab.equations.ionic_1d import CompiledIonicDevice1D from solarlab.mesh.geometry import half_endpoint_geometry from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature @@ -36,6 +36,8 @@ def compile_ionic_device_1d( prepared: PreparedDevice, *, intervals_per_layer: int | Sequence[int] = 24, ion_domain_layer: str | None = None, ion_domain_endpoints: tuple[str, str] | None = None, + te_softness: float = 0.02, + te_regularization_mode: TERegularizationName = "legacy_logistic", ) -> CompiledIonicDevice1D: """Compile independent or shared finite-site ions in one blocking layer. @@ -117,7 +119,12 @@ def compile_ionic_device_1d( component_prepared = resolve_device( DeviceInput.model_validate(projection), prepared.defaults, prepared.resources, sources=prepared.sources, ) - component = compile_device_1d(component_prepared, intervals_per_layer=intervals_per_layer) + component = compile_device_1d( + component_prepared, + intervals_per_layer=intervals_per_layer, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + ) domain_index = layers.index(domain_layer) left = 0 if domain_index == 0 else component.geometry.interfaces[domain_index - 1].shared_node right = component.node_count - 1 if domain_index == len(layers) - 1 else component.geometry.interfaces[domain_index].shared_node diff --git a/src/solarlab/device/compile_multiple_ionic_1d.py b/src/solarlab/device/compile_multiple_ionic_1d.py index 46b5f702..af673370 100644 --- a/src/solarlab/device/compile_multiple_ionic_1d.py +++ b/src/solarlab/device/compile_multiple_ionic_1d.py @@ -11,7 +11,7 @@ from solarlab.device.compile_ionic_1d import ION_INPUTS, compile_ionic_device_1d from solarlab.device.inputs import DeviceInput from solarlab.device.resolved import PreparedDevice -from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dc_1d import CapabilityError, TERegularizationName from solarlab.equations.ionic_1d import CompiledIonicDevice1D from solarlab.equations.multiple_ionic_1d import CompiledMultipleIonicDevice1D @@ -21,6 +21,8 @@ def compile_multiple_ionic_device_1d( prepared: PreparedDevice, *, intervals_per_layer: int | Sequence[int] = 24, ion_domains: Sequence[tuple[str, tuple[str, str]]], + te_softness: float = 0.02, + te_regularization_mode: TERegularizationName = "legacy_logistic", ) -> CompiledMultipleIonicDevice1D: """Exactly two layer-wide blocking domains separated by inactive material. @@ -71,8 +73,14 @@ def compile_multiple_ionic_device_1d( "original_value": original[key], "component_value": 0.0}) isolated = resolve_device(DeviceInput.model_validate(editing), prepared.defaults, prepared.resources, sources=prepared.sources) - component = compile_ionic_device_1d(isolated, intervals_per_layer=intervals_per_layer, - ion_domain_layer=name, ion_domain_endpoints=endpoints) + component = compile_ionic_device_1d( + isolated, + intervals_per_layer=intervals_per_layer, + ion_domain_layer=name, + ion_domain_endpoints=endpoints, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + ) if components: if component.electronic_component.identity != components[0].electronic_component.identity: raise ValueError("isolated domains produced different electronic components") diff --git a/src/solarlab/equations/assembly/classical_1d.py b/src/solarlab/equations/assembly/classical_1d.py index 557ffcc7..9e4c459f 100644 --- a/src/solarlab/equations/assembly/classical_1d.py +++ b/src/solarlab/equations/assembly/classical_1d.py @@ -41,14 +41,16 @@ ) from solarlab.equations.assembly.terms import ( CELL_SOURCE, CONSTRAINT, FACE_FLUX, PORT_FLUX, STORAGE, Contribution, EvaluationState, - FaceValue, LocalValue, OperatingInputs, Term, TermValue, + FaceValue, FieldValues, LocalValue, OperatingInputs, Term, TermValue, ) from solarlab.equations.assembly.weighted import MEASURE from solarlab.equations.dc_1d import CapabilityError, CompiledDevice1D from solarlab.physics.contacts.boundary_flux import boundary_particle_flux from solarlab.physics.contacts.exchange import CarrierExchangeChannel from solarlab.physics.recombination.bulk import RecombinationRate, sum_recombination_rates -from solarlab.physics.transport.electrochemical_flux import CarrierFaceFluxes, carrier_particle_fluxes +from solarlab.physics.transport.electrochemical_flux import ( + CarrierFaceFlux, CarrierFaceFluxes, carrier_particle_fluxes, +) __all__ = [ "AssembledDC1DProblem", "BulkRecombination", "CarrierExchange", "CarrierGeneration", @@ -79,6 +81,103 @@ def _density(state: EvaluationState, block: str) -> Vector: return state.field("electron_density_m3" if block == ELECTRON else "hole_density_m3") +def populate_interface_fields( + device: CompiledDevice1D, + u: Vector, + phi: Vector, + n: Vector, + p: Vector, + fields: dict[str, Vector], +) -> bool: + """Evaluate ``device.interface_model`` once and store all interface fields.""" + model = device.interface_model + if model is None: + return True + try: + ev = model.evaluate_state(device, u, phi, n, p, derivatives=True) + except (RuntimeError, FloatingPointError, ValueError): + return False + ef = ev.fluxes.electron + hf = ev.fluxes.hole + fields.update({ + "iface:e_flux": ef.flux, + "iface:e_ld": ef.left_density_derivative, + "iface:e_rd": ef.right_density_derivative, + "iface:e_lpot": ef.left_potential_derivative, + "iface:e_rpot": ef.right_potential_derivative, + "iface:e_step": ef.energy_step, + "iface:e_coeff": ef.coefficient, + "iface:h_flux": hf.flux, + "iface:h_ld": hf.left_density_derivative, + "iface:h_rd": hf.right_density_derivative, + "iface:h_lpot": hf.left_potential_derivative, + "iface:h_rpot": hf.right_potential_derivative, + "iface:h_step": hf.energy_step, + "iface:h_coeff": hf.coefficient, + "iface:e_left_phi": ev.e_left_phi, + "iface:e_right_phi": ev.e_right_phi, + "iface:e_left_zn": ev.e_left_zn, + "iface:e_right_zn": ev.e_right_zn, + "iface:e_left_zp": ev.e_left_zp, + "iface:e_right_zp": ev.e_right_zp, + "iface:h_left_phi": ev.h_left_phi, + "iface:h_right_phi": ev.h_right_phi, + "iface:h_left_zn": ev.h_left_zn, + "iface:h_right_zn": ev.h_right_zn, + "iface:h_left_zp": ev.h_left_zp, + "iface:h_right_zp": ev.h_right_zp, + "iface:e_port_val": ev.e_port_val, + "iface:e_port_phi": ev.e_port_phi, + "iface:e_port_zn": ev.e_port_zn, + "iface:e_port_zp": ev.e_port_zp, + "iface:h_port_val": ev.h_port_val, + "iface:h_port_phi": ev.h_port_phi, + "iface:h_port_zn": ev.h_port_zn, + "iface:h_port_zp": ev.h_port_zp, + "iface:g_port_val": ev.g_port_val, + "iface:g_port_phi": ev.g_port_phi, + "iface:g_port_zn": ev.g_port_zn, + "iface:g_port_zp": ev.g_port_zp, + "iface:g_left_phi": ev.g_left_phi, + "iface:g_right_phi": ev.g_right_phi, + "iface:g_left_zn": ev.g_left_zn, + "iface:g_right_zn": ev.g_right_zn, + "iface:g_left_zp": ev.g_left_zp, + "iface:g_right_zp": ev.g_right_zp, + }) + return True + + +@dataclass(frozen=True) +class InterfaceQuasiFermiFields: + """Field map ``u -> (phi, n, p, interface_closure)`` evaluated once per trial.""" + + device: CompiledDevice1D + + @property + def identity(self) -> str: + model = self.device.interface_model + assert model is not None + return _identity("interface_quasi_fermi_fields_v1", self.device.identity, model.identity_sha256) + + def evaluate(self, layout: SystemLayout, u: Vector, inputs: OperatingInputs) -> FieldValues: + values = np.concatenate([layout.view(u, block) for block in (POTENTIAL, ELECTRON, HOLE)]) + phi, n, p = self.device.fields(values, voltage_V=inputs.voltage_V) + admissible = bool( + np.all(np.isfinite(n)) and np.all(np.isfinite(p)) + and not np.any(n <= 0.0) and not np.any(p <= 0.0) + ) + fields: dict[str, Vector] = { + "potential_V": phi, + "electron_density_m3": n, + "hole_density_m3": p, + } + if not admissible: + return FieldValues(fields, False) + ok = populate_interface_fields(self.device, values, phi, n, p, fields) + return FieldValues(fields, ok) + + @dataclass(frozen=True) class GaussDisplacement: """Displacement ``D = -C (phi_R - phi_L)`` [C/m2] on the Poisson channel's faces.""" @@ -88,10 +187,16 @@ class GaussDisplacement: kind: str = FACE_FLUX support: str = NODES equations: tuple[str, ...] = (POTENTIAL,) - dependencies: tuple[str, ...] = (POTENTIAL,) unit: Unit = DISPLACEMENT_UNIT port: str | None = None + @property + def dependencies(self) -> tuple[str, ...]: + model = self.device.interface_model + if model is not None and model.has_sheet_charge: + return (POTENTIAL, ELECTRON, HOLE) + return (POTENTIAL,) + @property def identity(self) -> str: return _identity(self.id, self.device.identity) @@ -101,6 +206,23 @@ def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, flux = poisson.face_displacement(state.field("potential_V")) if not derivatives: return {POTENTIAL: FaceValue(flux)} + model = self.device.interface_model + if model is not None and model.has_sheet_charge: + return { + POTENTIAL: FaceValue( + flux, + { + POTENTIAL: state.field("iface:g_left_phi"), + ELECTRON: state.field("iface:g_left_zn"), + HOLE: state.field("iface:g_left_zp"), + }, + { + POTENTIAL: state.field("iface:g_right_phi"), + ELECTRON: state.field("iface:g_right_zn"), + HOLE: state.field("iface:g_right_zp"), + }, + ) + } capacitance = poisson.face_capacitance_F_m2 return {POTENTIAL: FaceValue(flux, {POTENTIAL: capacitance}, {POTENTIAL: -capacitance})} @@ -178,6 +300,27 @@ def identity(self) -> str: def fluxes(self, state: EvaluationState) -> CarrierFaceFluxes: device = self.device + if device.interface_model is not None: + return CarrierFaceFluxes( + electron=CarrierFaceFlux( + flux=state.field("iface:e_flux"), + left_density_derivative=state.field("iface:e_ld"), + right_density_derivative=state.field("iface:e_rd"), + left_potential_derivative=state.field("iface:e_lpot"), + right_potential_derivative=state.field("iface:e_rpot"), + energy_step=state.field("iface:e_step"), + coefficient=state.field("iface:e_coeff"), + ), + hole=CarrierFaceFlux( + flux=state.field("iface:h_flux"), + left_density_derivative=state.field("iface:h_ld"), + right_density_derivative=state.field("iface:h_rd"), + left_potential_derivative=state.field("iface:h_lpot"), + right_potential_derivative=state.field("iface:h_rpot"), + energy_step=state.field("iface:h_step"), + coefficient=state.field("iface:h_coeff"), + ), + ) phi = state.field("potential_V") electron_diffusivity = device.electron_diffusivity_faces_m2_s hole_diffusivity = device.hole_diffusivity_faces_m2_s @@ -195,6 +338,39 @@ def fluxes(self, state: EvaluationState) -> CarrierFaceFluxes: def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: device = self.device + if device.interface_model is not None: + e_flux = state.field("iface:e_flux") + h_flux = state.field("iface:h_flux") + if not derivatives: + return {ELECTRON: FaceValue(e_flux), HOLE: FaceValue(h_flux)} + return { + ELECTRON: FaceValue( + e_flux, + { + POTENTIAL: state.field("iface:e_left_phi"), + ELECTRON: state.field("iface:e_left_zn"), + HOLE: state.field("iface:e_left_zp"), + }, + { + POTENTIAL: state.field("iface:e_right_phi"), + ELECTRON: state.field("iface:e_right_zn"), + HOLE: state.field("iface:e_right_zp"), + }, + ), + HOLE: FaceValue( + h_flux, + { + POTENTIAL: state.field("iface:h_left_phi"), + ELECTRON: state.field("iface:h_left_zn"), + HOLE: state.field("iface:h_left_zp"), + }, + { + POTENTIAL: state.field("iface:h_right_phi"), + ELECTRON: state.field("iface:h_right_zn"), + HOLE: state.field("iface:h_right_zp"), + }, + ), + } fluxes = self.fluxes(state) if not derivatives: return {ELECTRON: FaceValue(fluxes.electron.flux), HOLE: FaceValue(fluxes.hole.flux)} @@ -449,6 +625,80 @@ def increment(self, state: EvaluationState, previous: EvaluationState) -> Mappin } +@dataclass(frozen=True) +class InterfaceGaussPort: + """Eliminated interface sheet-charge Gauss balance contributions [C/m2].""" + + device: CompiledDevice1D + id: str = "potential.interfaces" + kind: str = PORT_FLUX + support: str = NODES + port: str = "interfaces" + equations: tuple[str, ...] = (POTENTIAL,) + dependencies: tuple[str, ...] = (POTENTIAL, ELECTRON, HOLE) + unit: Unit = DISPLACEMENT_UNIT + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, ELECTRODE_QUASI_FERMI_1D_V1) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + val = state.field("iface:g_port_val") + if not derivatives: + return {POTENTIAL: LocalValue(val)} + return { + POTENTIAL: LocalValue( + val, + { + POTENTIAL: state.field("iface:g_port_phi"), + ELECTRON: state.field("iface:g_port_zn"), + HOLE: state.field("iface:g_port_zp"), + }, + ) + } + + +@dataclass(frozen=True) +class InterfaceCarrierPort: + """Areal heterointerface recombination / trace continuity port [m-2 s-1].""" + + device: CompiledDevice1D + block: str + kind: str = PORT_FLUX + support: str = NODES + port: str = "interfaces" + dependencies: tuple[str, ...] = (POTENTIAL, ELECTRON, HOLE) + unit: Unit = FLUX_UNIT + + @property + def id(self) -> str: + return f"{self.block}.interfaces" + + @property + def equations(self) -> tuple[str, ...]: + return (self.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, ELECTRODE_QUASI_FERMI_1D_V1) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + prefix = "iface:e_port_" if self.block == ELECTRON else "iface:h_port_" + val = state.field(prefix + "val") + if not derivatives: + return {self.block: LocalValue(val)} + return { + self.block: LocalValue( + val, + { + POTENTIAL: state.field(prefix + "phi"), + ELECTRON: state.field(prefix + "zn"), + HOLE: state.field(prefix + "zp"), + }, + ) + } + + def _layout(device: CompiledDevice1D) -> SystemLayout: count = device.node_count constraints = [ConstraintRows(POTENTIAL, (0, count - 1), "potential.contacts", VOLT)] @@ -473,9 +723,12 @@ def _mesh(device: CompiledDevice1D) -> Mesh: contract = geometry.to_contract_geometry(cell_support=NODES, face_support=NODES + ".faces") # Per unit cross-section the port measure is the face area, unit ONE as # for the internal faces of the contract geometry. - ports = tuple(Port(face.id, (face.node,), face.outward_normal, np.array([face.area_m2]), ONE) - for face in geometry.ports) - return Mesh((SupportGeometry(NODES, contract, ports),)) + ports = [Port(face.id, (face.node,), face.outward_normal, np.array([face.area_m2]), ONE) + for face in geometry.ports] + if device.interface_model is not None: + interior = tuple(range(1, device.node_count - 1)) + ports.append(Port("interfaces", interior, -1, np.ones(len(interior)), ONE)) + return Mesh((SupportGeometry(NODES, contract, tuple(ports)),)) @dataclass(frozen=True) @@ -497,6 +750,12 @@ def __post_init__(self) -> None: GaussDisplacement(device), SpaceCharge(device), PotentialContacts(device), transport, CarrierGeneration(device), recombination, CarrierStorage(device), ] + if device.interface_model is not None: + if device.interface_model.has_sheet_charge: + terms.append(InterfaceGaussPort(device)) + if device.interface_model.has_carrier_port: + terms.append(InterfaceCarrierPort(device, ELECTRON)) + terms.append(InterfaceCarrierPort(device, HOLE)) exchanges: dict[tuple[str, str], CarrierExchange] = {} for block, carrier, _ in CARRIERS: fixed = [] @@ -509,8 +768,13 @@ def __post_init__(self) -> None: if fixed: terms.append(CarrierReservoirs(device, block, tuple(fixed))) terms.extend(exchanges.values()) + field_map = ( + ElectrodeQuasiFermiFields(device) + if device.interface_model is None + else InterfaceQuasiFermiFields(device) + ) object.__setattr__(self, "assembler", Assembler( - layout, _mesh(device), ElectrodeQuasiFermiFields(device), terms)) + layout, _mesh(device), field_map, terms)) object.__setattr__(self, "transport", transport) object.__setattr__(self, "recombination", recombination) object.__setattr__(self, "exchanges", exchanges) diff --git a/src/solarlab/equations/assembly/ionic_1d.py b/src/solarlab/equations/assembly/ionic_1d.py index 6fe82780..cc488eef 100644 --- a/src/solarlab/equations/assembly/ionic_1d.py +++ b/src/solarlab/equations/assembly/ionic_1d.py @@ -47,7 +47,9 @@ from solarlab.contracts.units import AREA, COULOMB, ELEMENTARY_CHARGE_C, ONE, PARTICLE, SECOND, VOLUME, Unit from solarlab.equations.assembly.assembler import AssembledSystem, Assembler, Mesh, SupportGeometry -from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem, ClassicalDC1D, classical_dc_1d +from solarlab.equations.assembly.classical_1d import ( + AssembledDC1DProblem, ClassicalDC1D, classical_dc_1d, populate_interface_fields, +) from solarlab.equations.assembly.layout import Block, ConstraintRows, NodeSet, SystemLayout from solarlab.equations.assembly.quasi_fermi import ELECTRODE_QUASI_FERMI_1D_V1 from solarlab.equations.assembly.terms import ( @@ -182,6 +184,17 @@ def evaluate(self, layout: SystemLayout, u: Vector, inputs: OperatingInputs) -> values = populations[domain.name] fields.update(zip(domain.blocks, values)) fields[domain.mass_field] = domain.coordinate_jacobian(values) + component = device.electronic_component + if component.interface_model is not None: + if not ( + np.all(np.isfinite(n)) and np.all(np.isfinite(p)) + and not np.any(n <= 0.0) and not np.any(p <= 0.0) + ): + return FieldValues(fields, False) + ok = populate_interface_fields( + component, u[:3 * component.node_count], phi, n, p, fields + ) + return FieldValues(fields, ok) return FieldValues(fields, True) diff --git a/src/solarlab/equations/dc_1d.py b/src/solarlab/equations/dc_1d.py index 82005cce..2e62d5aa 100644 --- a/src/solarlab/equations/dc_1d.py +++ b/src/solarlab/equations/dc_1d.py @@ -14,9 +14,9 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace import math -from typing import Protocol, TypeAlias +from typing import Literal, Protocol, TypeAlias import numpy as np from numpy.typing import ArrayLike, NDArray @@ -46,11 +46,25 @@ from solarlab.physics.contacts.boundary_flux import boundary_particle_flux from solarlab.physics.electrostatics import PoissonOperator1D from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger +from solarlab.physics.electrostatics.interface_traces import TraceElectrostatics from solarlab.physics.generation.profile import GenerationProfile +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + TwoSidedInterfacePhysics, + cap_particle_flux_thermionic, + solve_charged_two_sided_interface_qss, + solve_two_sided_interface_qss, +) from solarlab.physics.recombination.bulk import ( RecombinationRate, sum_recombination_rates, ) +from solarlab.physics.recombination.interface import ( + PlaneClosureParams, + interface_srh_rate, + solve_plane_closure, +) from solarlab.physics.recombination.reaction import BulkRecombinationReaction from solarlab.physics.transport.electrochemical_flux import ( CarrierFaceFlux, @@ -119,6 +133,626 @@ def __post_init__(self) -> None: raise ValueError("the state coordinate reference voltage must be finite") +VECTOR_EXP_CAP = 40.0 +TERegularizationName: TypeAlias = Literal["legacy_logistic", "compact_support"] + + +@dataclass(frozen=True) +class DeduplicatedBareSRHSpec: + """Single-node heterointerface SRH specification on a deduplicated grid.""" + + interface_index: int + node: int + v_n_m_s: float + v_p_m_s: float + ni_sq_m6: float + n1_m3: float + p1_m3: float + + +@dataclass(frozen=True) +class DeduplicatedDefectSRHSpec: + """Cross-carrier or plane-closure heterointerface defect SRH on a deduplicated grid.""" + + interface_index: int + node: int + v_n_m_s: float + v_p_m_s: float + ni_sq_eff_m6: float + n1_m3: float + p1_m3: float + plane_params: PlaneClosureParams | None = None + + +@dataclass(frozen=True) +class DeduplicatedThermionicFaceSpec: + """Direction-preserving 1D thermionic emission cap on an internal SG face.""" + + interface_index: int + face: int + delta_Ec_eV: float + delta_Ev_eV: float + a_star_n_A_m2_K2: float + a_star_p_A_m2_K2: float + cap_electron: bool + cap_hole: bool + + +@dataclass(frozen=True) +class TwoSidedInterfaceBindingSpec: + """Locally eliminated two-sided trace transport/SRH/sheet-charge binding.""" + + interface_index: int + face: int + left_node: int + right_node: int + trace_electrostatics: TraceElectrostatics + physics: TwoSidedInterfacePhysics + charge: EquilibriumReferencedSheetCharge | None = None + weight_left: float = 0.0 + weight_right: float = 0.0 + + +@dataclass(frozen=True) +class InterfaceEvaluation1D: + """Single-pass constitutive evaluation of all 1D heterointerface channels.""" + + fluxes: CarrierFaceFluxes + e_left_phi: Vector + e_right_phi: Vector + e_left_zn: Vector + e_right_zn: Vector + e_left_zp: Vector + e_right_zp: Vector + h_left_phi: Vector + h_right_phi: Vector + h_left_zn: Vector + h_right_zn: Vector + h_left_zp: Vector + h_right_zp: Vector + e_port_val: Vector + e_port_phi: Vector + e_port_zn: Vector + e_port_zp: Vector + h_port_val: Vector + h_port_phi: Vector + h_port_zn: Vector + h_port_zp: Vector + g_port_val: Vector + g_port_phi: Vector + g_port_zn: Vector + g_port_zp: Vector + g_left_phi: Vector + g_right_phi: Vector + g_left_zn: Vector + g_right_zn: Vector + g_left_zp: Vector + g_right_zp: Vector + sheet_charges_C_m2: Vector + occupancies: Vector + + +def _scatter_three_node_row_tangent( + idx: int, + g_left: float, + g_mid: float, + g_right: float, + face_left: Vector, + face_right: Vector, + port_diag: Vector, +) -> None: + """Scatter ``(g_left, g_mid, g_right)`` onto row ``idx`` via face + interior port.""" + if g_left != 0.0: + face_left[idx - 1] += g_left + port_diag[idx - 2] += g_left + if g_mid != 0.0: + port_diag[idx - 1] += g_mid + if g_right != 0.0: + face_right[idx] -= g_right + port_diag[idx] += g_right + + +def _scatter_two_sided_carrier_tangent( + face: int, + g_ll: float, + g_lr: float, + g_rl: float, + g_rr: float, + face_left: Vector, + face_right: Vector, + port_diag: Vector, +) -> None: + """Set 2x2 carrier Jacobian ``[[-g_ll, -g_lr], [-g_rl, -g_rr]]`` on ``(L, R)``.""" + face_left[face] = -g_rl + face_right[face] = g_lr + port_diag[face - 1] -= g_ll + g_rl + port_diag[face] -= g_rr + g_lr + + +@dataclass(frozen=True) +class CompiledInterfaceModel1D: + """Compiled 1D heterointerface transport, SRH, and sheet-charge closure.""" + + topology: Literal["deduplicated", "two_sided_trace"] + identity_sha256: str + bare_srh: tuple[DeduplicatedBareSRHSpec, ...] = () + defect_srh: tuple[DeduplicatedDefectSRHSpec, ...] = () + thermionic_faces: tuple[DeduplicatedThermionicFaceSpec, ...] = () + two_sided: tuple[TwoSidedInterfaceBindingSpec, ...] = () + plane_projection: bool = False + plane_closure: bool = False + plane_generation: bool = False + te_softness: float = 0.02 + te_regularization_mode: TERegularizationName = "legacy_logistic" + + @property + def has_carrier_port(self) -> bool: + return bool(self.bare_srh or self.defect_srh or self.two_sided) + + @property + def has_sheet_charge(self) -> bool: + return any(spec.charge is not None for spec in self.two_sided) + + def evaluate_state( + self, + device: CompiledDevice1D, + u: Vector, + phi: Vector, + n: Vector, + p: Vector, + *, + derivatives: bool = True, + ) -> InterfaceEvaluation1D: + """Evaluate all active heterointerface laws in a single constitutive pass.""" + count = device.node_count + thermal = device.thermal_voltage_V + temp = device.parameters.temperature_K + electron_diffusivity = device.electron_diffusivity_faces_m2_s + hole_diffusivity = device.hole_diffusivity_faces_m2_s + transport = None if device.field_transport is None else device.field_transport.evaluate(phi) + if transport is not None: + electron_diffusivity = transport.electron_diffusivity_m2_s + hole_diffusivity = transport.hole_diffusivity_m2_s + + zn = u[count:2 * count] + zp = u[2 * count:] + base = carrier_particle_fluxes( + device.nodes_m, + phi, + n, + p, + electron_diffusivity, + hole_diffusivity, + thermal, + device.parameters.band_structure, + electron_electrochemical_step=np.diff(zn), + hole_electrochemical_step=-np.diff(zp), + ) + e_flux = np.array(base.electron.flux, dtype=float, copy=True) + e_ld = np.array(base.electron.left_density_derivative, dtype=float, copy=True) + e_rd = np.array(base.electron.right_density_derivative, dtype=float, copy=True) + h_flux = np.array(base.hole.flux, dtype=float, copy=True) + h_ld = np.array(base.hole.left_density_derivative, dtype=float, copy=True) + h_rd = np.array(base.hole.right_density_derivative, dtype=float, copy=True) + + face_count = count - 1 + interior_count = count - 2 + e_port_val: Vector = np.zeros(interior_count, dtype=float) + h_port_val: Vector = np.zeros(interior_count, dtype=float) + g_port_val: Vector = np.zeros(interior_count, dtype=float) + + if derivatives: + e_left_phi, e_right_phi = quasi_fermi_potential_tangents( + base.electron, np.diff(zn), 1.0, thermal + ) + h_left_phi, h_right_phi = quasi_fermi_potential_tangents( + base.hole, -np.diff(zp), -1.0, thermal + ) + e_left_phi = np.array(e_left_phi, dtype=float, copy=True) + e_right_phi = np.array(e_right_phi, dtype=float, copy=True) + h_left_phi = np.array(h_left_phi, dtype=float, copy=True) + h_right_phi = np.array(h_right_phi, dtype=float, copy=True) + if transport is not None: + dx = np.diff(device.nodes_m) + e_chain = (e_flux / transport.electron_diffusivity_m2_s) * transport.electron_d_diffusivity_d_field / dx + h_chain = (h_flux / transport.hole_diffusivity_m2_s) * transport.hole_d_diffusivity_d_field / dx + e_left_phi = e_left_phi + e_chain + e_right_phi = e_right_phi - e_chain + h_left_phi = h_left_phi + h_chain + h_right_phi = h_right_phi - h_chain + e_left_zn = np.array(e_ld * n[:-1], dtype=float, copy=True) + e_right_zn = np.array(e_rd * n[1:], dtype=float, copy=True) + e_left_zp: Vector = np.zeros(face_count, dtype=float) + e_right_zp: Vector = np.zeros(face_count, dtype=float) + h_left_zn: Vector = np.zeros(face_count, dtype=float) + h_right_zn: Vector = np.zeros(face_count, dtype=float) + h_left_zp = np.array(-h_ld * p[:-1], dtype=float, copy=True) + h_right_zp = np.array(-h_rd * p[1:], dtype=float, copy=True) + g_left_phi = np.array(device.poisson.face_capacitance_F_m2, dtype=float, copy=True) + g_right_phi = -np.array(device.poisson.face_capacitance_F_m2, dtype=float, copy=True) + else: + e_left_phi = e_right_phi = e_left_zn = e_right_zn = e_left_zp = e_right_zp = np.empty(0) + h_left_phi = h_right_phi = h_left_zn = h_right_zn = h_left_zp = h_right_zp = np.empty(0) + g_left_phi = g_right_phi = np.empty(0) + + e_port_phi: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + e_port_zn: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + e_port_zp: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + h_port_phi: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + h_port_zn: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + h_port_zp: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + g_port_phi: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + g_port_zn: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + g_port_zp: Vector = np.zeros(interior_count, dtype=float) if derivatives else np.empty(0) + g_left_zn: Vector = np.zeros(face_count, dtype=float) if derivatives else np.empty(0) + g_right_zn: Vector = np.zeros(face_count, dtype=float) if derivatives else np.empty(0) + g_left_zp: Vector = np.zeros(face_count, dtype=float) if derivatives else np.empty(0) + g_right_zp: Vector = np.zeros(face_count, dtype=float) if derivatives else np.empty(0) + + iface_count = len(device.geometry.interfaces) + sheet_charges: Vector = np.zeros(iface_count, dtype=float) + occupancies: Vector = np.full(iface_count, np.nan, dtype=float) + + if self.topology == "deduplicated": + for tf in self.thermionic_faces: + f = tf.face + if tf.cap_electron: + cap_e = cap_particle_flux_thermionic( + float(e_flux[f]), + n_left_m3=float(n[f]), + n_right_m3=float(n[f + 1]), + delta_barrier_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_n_A_m2_K2, + te_softness=self.te_softness, + regularization_mode=self.te_regularization_mode, + ) + e_flux[f] = cap_e.flux_m2_s + e_ld[f] = cap_e.d_flux_d_sg_flux * e_ld[f] + cap_e.d_flux_d_n_left_m_s + e_rd[f] = cap_e.d_flux_d_sg_flux * e_rd[f] + cap_e.d_flux_d_n_right_m_s + if derivatives: + e_left_phi[f] = ( + cap_e.d_flux_d_sg_flux * e_left_phi[f] + + cap_e.d_flux_d_n_left_m_s * float(n[f]) / thermal + ) + e_right_phi[f] = ( + cap_e.d_flux_d_sg_flux * e_right_phi[f] + + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) / thermal + ) + e_left_zn[f] = ( + cap_e.d_flux_d_sg_flux * e_left_zn[f] + + cap_e.d_flux_d_n_left_m_s * float(n[f]) + ) + e_right_zn[f] = ( + cap_e.d_flux_d_sg_flux * e_right_zn[f] + + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) + ) + if tf.cap_hole: + cap_h = cap_particle_flux_thermionic( + float(h_flux[f]), + n_left_m3=float(p[f]), + n_right_m3=float(p[f + 1]), + delta_barrier_eV=tf.delta_Ev_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_p_A_m2_K2, + te_softness=self.te_softness, + regularization_mode=self.te_regularization_mode, + ) + h_flux[f] = cap_h.flux_m2_s + h_ld[f] = cap_h.d_flux_d_sg_flux * h_ld[f] + cap_h.d_flux_d_n_left_m_s + h_rd[f] = cap_h.d_flux_d_sg_flux * h_rd[f] + cap_h.d_flux_d_n_right_m_s + if derivatives: + h_left_phi[f] = ( + cap_h.d_flux_d_sg_flux * h_left_phi[f] + - cap_h.d_flux_d_n_left_m_s * float(p[f]) / thermal + ) + h_right_phi[f] = ( + cap_h.d_flux_d_sg_flux * h_right_phi[f] + - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) / thermal + ) + h_left_zp[f] = ( + cap_h.d_flux_d_sg_flux * h_left_zp[f] + - cap_h.d_flux_d_n_left_m_s * float(p[f]) + ) + h_right_zp[f] = ( + cap_h.d_flux_d_sg_flux * h_right_zp[f] + - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) + ) + + for bare in self.bare_srh: + idx = bare.node + srh = interface_srh_rate( + float(n[idx]), + float(p[idx]), + v_n_m_s=bare.v_n_m_s, + v_p_m_s=bare.v_p_m_s, + ni_sq_m6=bare.ni_sq_m6, + n1_m3=bare.n1_m3, + p1_m3=bare.p1_m3, + clamp_nonnegative=False, + ) + sink = -float(np.real(srh.rate_m2_s)) + e_port_val[idx - 1] += sink + h_port_val[idx - 1] += sink + if derivatives: + s_zn = -float(np.real(srh.d_rate_dn_m_s)) * float(n[idx]) + s_zp = float(np.real(srh.d_rate_dp_m_s)) * float(p[idx]) + s_phi = (s_zn + s_zp) / thermal + e_port_phi[idx - 1] += s_phi + e_port_zn[idx - 1] += s_zn + e_port_zp[idx - 1] += s_zp + h_port_phi[idx - 1] += s_phi + h_port_zn[idx - 1] += s_zn + h_port_zp[idx - 1] += s_zp + + for dspec in self.defect_srh: + idx = dspec.node + i_l, i_0, i_r = idx - 1, idx, idx + 1 + if self.plane_closure and dspec.plane_params is not None: + el_raw = (float(phi[i_0]) - float(phi[i_l])) / thermal + er_raw = (float(phi[i_0]) - float(phi[i_r])) / thermal + el = max(-VECTOR_EXP_CAP, min(VECTOR_EXP_CAP, el_raw)) + er = max(-VECTOR_EXP_CAP, min(VECTOR_EXP_CAP, er_raw)) + fl = math.exp(el) + fr = math.exp(er) + nl_p = float(n[i_l]) * fl + nr_p = float(n[i_r]) * fr + pl_p = float(p[i_l]) / fl + pr_p = float(p[i_r]) / fr + plane_res = solve_plane_closure( + nl_p, + nr_p, + pl_p, + pr_p, + dspec.plane_params, + dspec.v_n_m_s, + dspec.v_p_m_s, + allow_generation=self.plane_generation, + ) + sink = -plane_res.rate_m2_s + e_port_val[idx - 1] += sink + h_port_val[idx - 1] += sink + if derivatives: + b_nl = plane_res.d_rate_d_n_left_proj_m_s * nl_p + b_nr = plane_res.d_rate_d_n_right_proj_m_s * nr_p + b_pl = plane_res.d_rate_d_p_left_proj_m_s * pl_p + b_pr = plane_res.d_rate_d_p_right_proj_m_s * pr_p + chi_l = 1.0 if -VECTOR_EXP_CAP < el_raw < VECTOR_EXP_CAP else 0.0 + chi_r = 1.0 if -VECTOR_EXP_CAP < er_raw < VECTOR_EXP_CAP else 0.0 + s_phi_l = -((1.0 - chi_l) * (b_nl - b_pl)) / thermal + s_phi_0 = -(chi_l * (b_nl - b_pl) + chi_r * (b_nr - b_pr)) / thermal + s_phi_r = -((1.0 - chi_r) * (b_nr - b_pr)) / thermal + s_zn_l = -b_nl + s_zn_r = -b_nr + s_zp_l = b_pl + s_zp_r = b_pr + for f_l, f_r, p_d, gl, gm, gr in ( + (e_left_phi, e_right_phi, e_port_phi, s_phi_l, s_phi_0, s_phi_r), + (h_left_phi, h_right_phi, h_port_phi, s_phi_l, s_phi_0, s_phi_r), + (e_left_zn, e_right_zn, e_port_zn, s_zn_l, 0.0, s_zn_r), + (h_left_zn, h_right_zn, h_port_zn, s_zn_l, 0.0, s_zn_r), + (e_left_zp, e_right_zp, e_port_zp, s_zp_l, 0.0, s_zp_r), + (h_left_zp, h_right_zp, h_port_zp, s_zp_l, 0.0, s_zp_r), + ): + _scatter_three_node_row_tangent(idx, gl, gm, gr, f_l, f_r, p_d) + else: + n_raw = float(n[i_r]) + p_raw = float(p[i_l]) + if self.plane_projection: + en_raw = (float(phi[i_0]) - float(phi[i_r])) / thermal + ep_raw = (float(phi[i_0]) - float(phi[i_l])) / thermal + en = max(-VECTOR_EXP_CAP, min(VECTOR_EXP_CAP, en_raw)) + ep = max(-VECTOR_EXP_CAP, min(VECTOR_EXP_CAP, ep_raw)) + fac_n = math.exp(en) + fac_p = math.exp(-ep) + n_eval = n_raw * fac_n + p_eval = p_raw * fac_p + ni_eval = dspec.ni_sq_eff_m6 * fac_n * fac_p + else: + en_raw = ep_raw = 0.0 + n_eval = n_raw + p_eval = p_raw + ni_eval = dspec.ni_sq_eff_m6 + srh = interface_srh_rate( + n_eval, + p_eval, + v_n_m_s=dspec.v_n_m_s, + v_p_m_s=dspec.v_p_m_s, + ni_sq_m6=ni_eval, + n1_m3=dspec.n1_m3, + p1_m3=dspec.p1_m3, + clamp_nonnegative=True, + ) + sink = -float(np.real(srh.rate_m2_s)) + e_port_val[idx - 1] += sink + h_port_val[idx - 1] += sink + if derivatives: + a_n = float(np.real(srh.d_rate_dn_m_s)) * n_eval + a_p = float(np.real(srh.d_rate_dp_m_s)) * p_eval + s_zn_r = -a_n + s_zp_l = a_p + if self.plane_projection: + chi_en = 1.0 if -VECTOR_EXP_CAP < en_raw < VECTOR_EXP_CAP else 0.0 + chi_ep = 1.0 if -VECTOR_EXP_CAP < ep_raw < VECTOR_EXP_CAP else 0.0 + denom = dspec.v_n_m_s * (n_eval + dspec.n1_m3) + dspec.v_p_m_s * (p_eval + dspec.p1_m3) + unclamped = ( + dspec.v_n_m_s > 0.0 + and dspec.v_p_m_s > 0.0 + and denom > 1.0e-300 + and (n_eval * p_eval - ni_eval) >= 0.0 + ) + a_ni = -(dspec.v_n_m_s * dspec.v_p_m_s / denom) * ni_eval if unclamped else 0.0 + s_phi_l = -((-a_p * (1.0 - chi_ep) + a_ni * chi_ep) / thermal) + s_phi_0 = -(((a_n + a_ni) * chi_en - (a_p + a_ni) * chi_ep) / thermal) + s_phi_r = -((a_n * (1.0 - chi_en) - a_ni * chi_en) / thermal) + else: + s_phi_l = a_p / thermal + s_phi_0 = 0.0 + s_phi_r = -a_n / thermal + for f_l, f_r, p_d, gl, gm, gr in ( + (e_left_phi, e_right_phi, e_port_phi, s_phi_l, s_phi_0, s_phi_r), + (h_left_phi, h_right_phi, h_port_phi, s_phi_l, s_phi_0, s_phi_r), + (e_left_zn, e_right_zn, e_port_zn, 0.0, 0.0, s_zn_r), + (h_left_zn, h_right_zn, h_port_zn, 0.0, 0.0, s_zn_r), + (e_left_zp, e_right_zp, e_port_zp, s_zp_l, 0.0, 0.0), + (h_left_zp, h_right_zp, h_port_zp, s_zp_l, 0.0, 0.0), + ): + _scatter_three_node_row_tangent(idx, gl, gm, gr, f_l, f_r, p_d) + + else: + for tspec in self.two_sided: + k = tspec.interface_index + f = tspec.face + l_node = tspec.left_node + r_node = tspec.right_node + bulk = TwoSidedBulkState( + phi_left_V=float(phi[l_node]), + phi_right_V=float(phi[r_node]), + n_left_m3=float(n[l_node]), + p_left_m3=float(p[l_node]), + n_right_m3=float(n[r_node]), + p_right_m3=float(p[r_node]), + electron_electrochemical_step=float(zn[r_node] - zn[l_node]), + hole_electrochemical_step=float(-(zp[r_node] - zp[l_node])), + ) + if tspec.charge is not None: + charged = solve_charged_two_sided_interface_qss( + tspec.trace_electrostatics, + tspec.physics, + bulk, + tspec.charge, + ) + bflux = charged.bulk_flux_m2_s + j_bulk = charged.bulk_flux_jacobian_bulk + sigma = charged.incremental_sheet_charge_C_m2 + j_sigma = charged.sheet_charge_jacobian_bulk + sheet_charges[k] = sigma + occupancies[k] = charged.occupancy + g_port_val[l_node - 1] += tspec.weight_left * sigma + g_port_val[r_node - 1] += tspec.weight_right * sigma + if derivatives: + s_phi_l = float(j_sigma[0] + (j_sigma[2] - j_sigma[3]) / thermal) + s_phi_r = float(j_sigma[1] + (j_sigma[4] - j_sigma[5]) / thermal) + s_zn_l = float(j_sigma[2]) + s_zn_r = float(j_sigma[4]) + s_zp_l = float(-j_sigma[3]) + s_zp_r = float(-j_sigma[5]) + wl, wr = tspec.weight_left, tspec.weight_right + w_sum = wl + wr + g_left_phi[f] += wr * s_phi_l + g_right_phi[f] -= wl * s_phi_r + g_port_phi[l_node - 1] += w_sum * s_phi_l + g_port_phi[r_node - 1] += w_sum * s_phi_r + g_left_zn[f] += wr * s_zn_l + g_right_zn[f] -= wl * s_zn_r + g_port_zn[l_node - 1] += w_sum * s_zn_l + g_port_zn[r_node - 1] += w_sum * s_zn_r + g_left_zp[f] += wr * s_zp_l + g_right_zp[f] -= wl * s_zp_r + g_port_zp[l_node - 1] += w_sum * s_zp_l + g_port_zp[r_node - 1] += w_sum * s_zp_r + else: + uncharged = solve_two_sided_interface_qss( + tspec.trace_electrostatics, + tspec.physics, + bulk, + ) + bflux = uncharged.bulk_flux_m2_s + j_bulk = uncharged.bulk_flux_jacobian_bulk + if uncharged.occupancy is not None: + occupancies[k] = uncharged.occupancy + + e_flux[f] = float(bflux[0]) + h_flux[f] = float(bflux[1]) + e_ld[f] = float(j_bulk[0, 2]) / float(n[l_node]) + e_rd[f] = float(j_bulk[0, 4]) / float(n[r_node]) + h_ld[f] = float(j_bulk[1, 3]) / float(p[l_node]) + h_rd[f] = float(j_bulk[1, 5]) / float(p[r_node]) + e_port_val[r_node - 1] -= float(bflux[0] + bflux[2]) + h_port_val[r_node - 1] -= float(bflux[1] + bflux[3]) + + if derivatives: + for row_l, row_r, fl_phi, fr_phi, pd_phi, fl_zn, fr_zn, pd_zn, fl_zp, fr_zp, pd_zp in ( + (0, 2, e_left_phi, e_right_phi, e_port_phi, e_left_zn, e_right_zn, e_port_zn, e_left_zp, e_right_zp, e_port_zp), + (1, 3, h_left_phi, h_right_phi, h_port_phi, h_left_zn, h_right_zn, h_port_zn, h_left_zp, h_right_zp, h_port_zp), + ): + gl_phi = float(j_bulk[row_l, 0] + (j_bulk[row_l, 2] - j_bulk[row_l, 3]) / thermal) + gr_phi = float(j_bulk[row_l, 1] + (j_bulk[row_l, 4] - j_bulk[row_l, 5]) / thermal) + hl_phi = float(j_bulk[row_r, 0] + (j_bulk[row_r, 2] - j_bulk[row_r, 3]) / thermal) + hr_phi = float(j_bulk[row_r, 1] + (j_bulk[row_r, 4] - j_bulk[row_r, 5]) / thermal) + _scatter_two_sided_carrier_tangent(f, gl_phi, gr_phi, hl_phi, hr_phi, fl_phi, fr_phi, pd_phi) + _scatter_two_sided_carrier_tangent( + f, + float(j_bulk[row_l, 2]), + float(j_bulk[row_l, 4]), + float(j_bulk[row_r, 2]), + float(j_bulk[row_r, 4]), + fl_zn, + fr_zn, + pd_zn, + ) + _scatter_two_sided_carrier_tangent( + f, + float(-j_bulk[row_l, 3]), + float(-j_bulk[row_l, 5]), + float(-j_bulk[row_r, 3]), + float(-j_bulk[row_r, 5]), + fl_zp, + fr_zp, + pd_zp, + ) + + replaced_fluxes = CarrierFaceFluxes( + electron=replace( + base.electron, + flux=e_flux, + left_density_derivative=e_ld, + right_density_derivative=e_rd, + ), + hole=replace( + base.hole, + flux=h_flux, + left_density_derivative=h_ld, + right_density_derivative=h_rd, + ), + ) + return InterfaceEvaluation1D( + fluxes=replaced_fluxes, + e_left_phi=e_left_phi, + e_right_phi=e_right_phi, + e_left_zn=e_left_zn, + e_right_zn=e_right_zn, + e_left_zp=e_left_zp, + e_right_zp=e_right_zp, + h_left_phi=h_left_phi, + h_right_phi=h_right_phi, + h_left_zn=h_left_zn, + h_right_zn=h_right_zn, + h_left_zp=h_left_zp, + h_right_zp=h_right_zp, + e_port_val=e_port_val, + e_port_phi=e_port_phi, + e_port_zn=e_port_zn, + e_port_zp=e_port_zp, + h_port_val=h_port_val, + h_port_phi=h_port_phi, + h_port_zn=h_port_zn, + h_port_zp=h_port_zp, + g_port_val=g_port_val, + g_port_phi=g_port_phi, + g_port_zn=g_port_zn, + g_port_zp=g_port_zp, + g_left_phi=g_left_phi, + g_right_phi=g_right_phi, + g_left_zn=g_left_zn, + g_right_zn=g_right_zn, + g_left_zp=g_left_zp, + g_right_zp=g_right_zp, + sheet_charges_C_m2=sheet_charges, + occupancies=occupancies, + ) + + @dataclass(frozen=True) class CompiledDevice1D: """Cold-compiled geometry, physical models, and contact reservoirs.""" @@ -148,6 +782,7 @@ class CompiledDevice1D: "bulk_srh_radiative_auger", ) field_transport: FieldTransport1D | None = None + interface_model: CompiledInterfaceModel1D | None = None _carrier_layout: Layout = field(init=False, repr=False) _carrier_geometry: Geometry = field(init=False, repr=False) @@ -292,6 +927,26 @@ def charge_ledger(self, n: Vector, p: Vector) -> ChargeLedger: ), ) + def interface_sheet_charges_C_m2(self, u: ArrayLike, *, voltage_V: float = 0.0) -> Vector: + """Eliminated incremental interface sheet charges [C/m^2] at state ``u``.""" + if self.interface_model is None or not self.interface_model.has_sheet_charge: + return np.zeros(len(self.geometry.interfaces), dtype=float) + values = np.asarray(u, dtype=float) + phi, n, p = self.fields(values, voltage_V=voltage_V) + return self.interface_model.evaluate_state( + self, values, phi, n, p, derivatives=False + ).sheet_charges_C_m2 + + def interface_occupancies(self, u: ArrayLike, *, voltage_V: float = 0.0) -> Vector: + """Eliminated interface trap occupancies (or NaN where absent) at state ``u``.""" + if self.interface_model is None: + return np.full(len(self.geometry.interfaces), np.nan, dtype=float) + values = np.asarray(u, dtype=float) + phi, n, p = self.fields(values, voltage_V=voltage_V) + return self.interface_model.evaluate_state( + self, values, phi, n, p, derivatives=False + ).occupancies + def quasi_fermi_potential_tangents( flux: CarrierFaceFlux, drive: Vector, carrier_sign: float, thermal: float @@ -344,6 +999,10 @@ def fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: count = device.node_count values = np.asarray(u, dtype=float) phi, n, p = device.fields(values, voltage_V=self.voltage_V) + if device.interface_model is not None: + return device.interface_model.evaluate_state( + device, values, phi, n, p, derivatives=False + ).fluxes electron_diffusivity = device.electron_diffusivity_faces_m2_s hole_diffusivity = device.hole_diffusivity_faces_m2_s if device.field_transport is not None: @@ -399,23 +1058,37 @@ def residual(self, u: ArrayLike, udot: ArrayLike | None = None) -> Vector: if not np.all(np.isfinite(n)) or not np.all(np.isfinite(p)) or np.any(n <= 0.0) or np.any(p <= 0.0): return np.full(3 * count, np.nan) derivative = self._derivative(udot) - fluxes = self.fluxes(values) + iface_eval: InterfaceEvaluation1D | None = None + if device.interface_model is not None: + try: + iface_eval = device.interface_model.evaluate_state( + device, values, phi, n, p, derivatives=False + ) + except (RuntimeError, FloatingPointError, ValueError): + return np.full(3 * count, np.nan) + fluxes = iface_eval.fluxes + else: + fluxes = self.fluxes(values) rate = self.recombination_rate(n, p, derivatives=False) source = self.generation_scale * device.generation.source_m3_s - rate.rate result = np.empty(3 * count) left, right = device.contact_potentials(self.voltage_V) rho = device.charge_ledger(n, p).space_charge_C_m3() result[:count] = device.poisson.residual(phi, rho, left, right) + if iface_eval is not None and device.interface_model is not None and device.interface_model.has_sheet_charge: + result[1:count - 1] += iface_eval.g_port_val geometry = device._carrier_geometry - for carrier, offset, density, flux, sign in ( - ("n", count, n, fluxes.electron, 1.0), - ("p", 2 * count, p, fluxes.hole, -1.0), + for carrier, offset, density, flux, sign, port_val in ( + ("n", count, n, fluxes.electron, 1.0, None if iface_eval is None else iface_eval.e_port_val), + ("p", 2 * count, p, fluxes.hole, -1.0, None if iface_eval is None else iface_eval.h_port_val), ): name = "electron" if carrier == "n" else "hole" sink = TermSink(device._carrier_layout, name, geometry) sink.add(FaceFlux(name + ".sg", "faces", flux.flux, FLUX_UNIT)) sink.add(CellSource(name + ".net_pairs", "cells", source, SOURCE_UNIT)) rows = np.array(sink.value(), copy=True) + if port_val is not None: + rows[1:count - 1] += port_val rate_of_density = sign * density * ( derivative[:count] / device.thermal_voltage_V + derivative[offset:offset + count] ) @@ -457,21 +1130,55 @@ def jacobian(self, u: ArrayLike, udot: ArrayLike | None = None, *, alpha: float count = device.node_count thermal = device.thermal_voltage_V values = np.asarray(u, dtype=float) - _, n, p = device.fields(values, voltage_V=self.voltage_V) + phi, n, p = device.fields(values, voltage_V=self.voltage_V) derivative = self._derivative(udot) - fluxes = self.fluxes(values) + iface_eval: InterfaceEvaluation1D | None = None + if device.interface_model is not None: + if not np.all(np.isfinite(n)) or not np.all(np.isfinite(p)) or np.any(n <= 0.0) or np.any(p <= 0.0): + raise FloatingPointError("state outside the field map's admissible domain") + try: + iface_eval = device.interface_model.evaluate_state( + device, values, phi, n, p, derivatives=True + ) + except (RuntimeError, ValueError) as exc: + raise FloatingPointError("interface closure failed at trial state") from exc + fluxes = iface_eval.fluxes + else: + fluxes = self.fluxes(values) rate = self.recombination_rate(n, p) transport = None if device.field_transport is None else device.field_transport.evaluate(values[:count]) assert rate.d_rate_dn is not None and rate.d_rate_dp is not None widths = device.geometry.cell_measures_m matrix = lil_matrix((3 * count, 3 * count), dtype=float) - matrix[:count, :count] = device.poisson.jacobian() interior = range(1, count - 1) charge_widths = device.poisson.interior_widths_m - for local, node in enumerate(interior): - matrix[node, node] += -Q * charge_widths[local] * (n[node] + p[node]) / thermal - matrix[node, count + node] = -Q * charge_widths[local] * n[node] - matrix[node, 2 * count + node] = -Q * charge_widths[local] * p[node] + if iface_eval is not None and device.interface_model is not None and device.interface_model.has_sheet_charge: + matrix[0, 0] = 1.0 + matrix[count - 1, count - 1] = 1.0 + for face in range(count - 1): + for orientation, node in ((-1.0, face), (1.0, face + 1)): + if node == 0 or node == count - 1: + continue + matrix[node, face] += orientation * iface_eval.g_left_phi[face] + matrix[node, face + 1] += orientation * iface_eval.g_right_phi[face] + matrix[node, count + face] += orientation * iface_eval.g_left_zn[face] + matrix[node, count + face + 1] += orientation * iface_eval.g_right_zn[face] + matrix[node, 2 * count + face] += orientation * iface_eval.g_left_zp[face] + matrix[node, 2 * count + face + 1] += orientation * iface_eval.g_right_zp[face] + for local, node in enumerate(interior): + matrix[node, node] += -Q * charge_widths[local] * (n[node] + p[node]) / thermal + matrix[node, count + node] += -Q * charge_widths[local] * n[node] + matrix[node, 2 * count + node] += -Q * charge_widths[local] * p[node] + for local, node in enumerate(interior): + matrix[node, node] += iface_eval.g_port_phi[local] + matrix[node, count + node] += iface_eval.g_port_zn[local] + matrix[node, 2 * count + node] += iface_eval.g_port_zp[local] + else: + matrix[:count, :count] = device.poisson.jacobian() + for local, node in enumerate(interior): + matrix[node, node] += -Q * charge_widths[local] * (n[node] + p[node]) / thermal + matrix[node, count + node] = -Q * charge_widths[local] * n[node] + matrix[node, 2 * count + node] = -Q * charge_widths[local] * p[node] source_n = -np.asarray(rate.d_rate_dn) * n source_p = np.asarray(rate.d_rate_dp) * p source_phi = (source_n + source_p) / thermal @@ -479,27 +1186,51 @@ def jacobian(self, u: ArrayLike, udot: ArrayLike | None = None, *, alpha: float ("n", count, n, fluxes.electron, 1.0), ("p", 2 * count, p, fluxes.hole, -1.0), ): - drive = sign * np.diff(values[offset:offset + count]) - left_phi, right_phi = quasi_fermi_potential_tangents(flux, drive, sign, thermal) - if transport is not None: - diffusivity = (transport.electron_diffusivity_m2_s if carrier == "n" - else transport.hole_diffusivity_m2_s) - d_diffusivity = (transport.electron_d_diffusivity_d_field if carrier == "n" - else transport.hole_d_diffusivity_d_field) - # SG is linear in positive D. E = -(phi_R-phi_L)/dx, so - # this is the additional (dGamma/dD)(dD/dE)(dE/dphi) term. - field_chain = (flux.flux / diffusivity) * d_diffusivity / np.diff(device.nodes_m) - left_phi = left_phi + field_chain - right_phi = right_phi - field_chain - left_z = sign * flux.left_density_derivative * density[:-1] - right_z = sign * flux.right_density_derivative * density[1:] - for face in range(count - 1): - for orientation, node in ((-1.0, face), (1.0, face + 1)): - row = offset + node - matrix[row, face] += orientation * left_phi[face] - matrix[row, face + 1] += orientation * right_phi[face] - matrix[row, offset + face] += orientation * left_z[face] - matrix[row, offset + face + 1] += orientation * right_z[face] + p_phi: Vector | None = None + p_zn: Vector | None = None + p_zp: Vector | None = None + if iface_eval is None: + drive = sign * np.diff(values[offset:offset + count]) + left_phi, right_phi = quasi_fermi_potential_tangents(flux, drive, sign, thermal) + if transport is not None: + diffusivity = (transport.electron_diffusivity_m2_s if carrier == "n" + else transport.hole_diffusivity_m2_s) + d_diffusivity = (transport.electron_d_diffusivity_d_field if carrier == "n" + else transport.hole_d_diffusivity_d_field) + # SG is linear in positive D. E = -(phi_R-phi_L)/dx, so + # this is the additional (dGamma/dD)(dD/dE)(dE/dphi) term. + field_chain = (flux.flux / diffusivity) * d_diffusivity / np.diff(device.nodes_m) + left_phi = left_phi + field_chain + right_phi = right_phi - field_chain + left_z = sign * flux.left_density_derivative * density[:-1] + right_z = sign * flux.right_density_derivative * density[1:] + for face in range(count - 1): + for orientation, node in ((-1.0, face), (1.0, face + 1)): + row = offset + node + matrix[row, face] += orientation * left_phi[face] + matrix[row, face + 1] += orientation * right_phi[face] + matrix[row, offset + face] += orientation * left_z[face] + matrix[row, offset + face + 1] += orientation * right_z[face] + else: + if carrier == "n": + l_phi, r_phi = iface_eval.e_left_phi, iface_eval.e_right_phi + l_zn, r_zn = iface_eval.e_left_zn, iface_eval.e_right_zn + l_zp, r_zp = iface_eval.e_left_zp, iface_eval.e_right_zp + p_phi, p_zn, p_zp = iface_eval.e_port_phi, iface_eval.e_port_zn, iface_eval.e_port_zp + else: + l_phi, r_phi = iface_eval.h_left_phi, iface_eval.h_right_phi + l_zn, r_zn = iface_eval.h_left_zn, iface_eval.h_right_zn + l_zp, r_zp = iface_eval.h_left_zp, iface_eval.h_right_zp + p_phi, p_zn, p_zp = iface_eval.h_port_phi, iface_eval.h_port_zn, iface_eval.h_port_zp + for face in range(count - 1): + for orientation, node in ((-1.0, face), (1.0, face + 1)): + row = offset + node + matrix[row, face] += orientation * l_phi[face] + matrix[row, face + 1] += orientation * r_phi[face] + matrix[row, count + face] += orientation * l_zn[face] + matrix[row, count + face + 1] += orientation * r_zn[face] + matrix[row, 2 * count + face] += orientation * l_zp[face] + matrix[row, 2 * count + face + 1] += orientation * r_zp[face] density_rate = sign * density * ( derivative[:count] / thermal + derivative[offset:offset + count] ) @@ -509,6 +1240,18 @@ def jacobian(self, u: ArrayLike, udot: ArrayLike | None = None, *, alpha: float matrix[row, count + node] += widths[node] * source_n[node] matrix[row, 2 * count + node] += widths[node] * source_p[node] matrix[row, offset + node] -= widths[node] * sign * density_rate[node] + if ( + p_phi is not None + and p_zn is not None + and p_zp is not None + and device.interface_model is not None + and device.interface_model.has_carrier_port + ): + for local, node in enumerate(interior): + row = offset + node + matrix[row, node] += p_phi[local] + matrix[row, count + node] += p_zn[local] + matrix[row, 2 * count + node] += p_zp[local] for side, node in (("left", 0), ("right", count - 1)): row = offset + node channel = device.channel(carrier, side) diff --git a/src/solarlab/physics/electrostatics/interface_traces.py b/src/solarlab/physics/electrostatics/interface_traces.py index 14584319..12f5cc4b 100644 --- a/src/solarlab/physics/electrostatics/interface_traces.py +++ b/src/solarlab/physics/electrostatics/interface_traces.py @@ -33,8 +33,8 @@ __all__ = [ "CARRIER_TRACE_UNIT", "InterfaceTraceDeclaration", "OCCUPANCY_UNIT", "TraceElectrostatics", "add_sheet_charge_to_interior_residual", "electrostatic_trace_residual_and_jacobian", - "interface_trace_layout", "require_carrier_trace", "require_occupancy", - "sheet_charge_row_weights", "solve_electrostatic_traces", + "interface_displacement_sides", "interface_trace_layout", "require_carrier_trace", + "require_occupancy", "sheet_charge_row_weights", "solve_electrostatic_traces", ] EPS_0 = VACUUM_PERMITTIVITY_F_M @@ -208,3 +208,29 @@ def add_sheet_charge_to_interior_residual( sheet = sheets[index] interior_residual[left - 1] += weight_left * sheet interior_residual[right - 1] += weight_right * sheet + + +def interface_displacement_sides( + series_face_displacement_C_m2: float, + *, + eps_r_left: float, + left_distance_m: float, + eps_r_right: float, + right_distance_m: float, + sheet_charge_C_m2: float, +) -> tuple[float, float]: + """Return ``(D_left, D_right)`` [C/m^2] flanking a charged interface plane. + + With eliminated series displacement ``D_series = -C_series (phi_R - phi_L)`` + and zero potential jump across the plane, ``D_right - D_left == sheet_charge`` + with ``D_left = D_series - w_L * sheet_charge`` and + ``D_right = D_series + w_R * sheet_charge``. + """ + d_series = float(series_face_displacement_C_m2) + sigma = float(sheet_charge_C_m2) + if not (math.isfinite(d_series) and math.isfinite(sigma)): + raise ValueError("series displacement and sheet charge must be finite") + weight_left, weight_right = sheet_charge_row_weights( + eps_r_left, left_distance_m, eps_r_right, right_distance_m + ) + return d_series - weight_left * sigma, d_series + weight_right * sigma diff --git a/src/solarlab/physics/interface_transport/__init__.py b/src/solarlab/physics/interface_transport/__init__.py new file mode 100644 index 00000000..79366138 --- /dev/null +++ b/src/solarlab/physics/interface_transport/__init__.py @@ -0,0 +1,61 @@ +"""Finite heterointerface transport and two-sided trace elimination (P04-09).""" + +from solarlab.physics.interface_transport.thermionic import ( + A_STAR_FREE_ELECTRON_A_M2_K2, + ELECTRON_MASS_KG, + PLANCK_CONSTANT_J_S, + TE_BARRIER_THRESHOLD_EV, + ThermionicCapEvaluation, + TwoSidedCrossFluxEvaluation, + cap_particle_flux_thermionic, + effective_mass_from_dos, + emission_velocity, + fermi_dirac_one, + fermi_dirac_richardson_flux, + fermi_dirac_zero, + fermi_richardson_flux, + is_free_electron_default, + resolve_layer_richardson, + richardson_from_dos, + scaps_thermionic_flux, + thermionic_emission_bound_m2_s, +) +from solarlab.physics.interface_transport.two_sided import ( + ChargedTwoSidedInterfaceQSSResult, + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + TwoSidedInterfacePhysics, + TwoSidedInterfaceQSSResult, + remove_shared_interface_nodes, + solve_charged_two_sided_interface_qss, + solve_two_sided_interface_qss, +) + +__all__ = [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ChargedTwoSidedInterfaceQSSResult", + "ELECTRON_MASS_KG", + "EquilibriumReferencedSheetCharge", + "PLANCK_CONSTANT_J_S", + "TE_BARRIER_THRESHOLD_EV", + "ThermionicCapEvaluation", + "TwoSidedBulkState", + "TwoSidedCrossFluxEvaluation", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "cap_particle_flux_thermionic", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "remove_shared_interface_nodes", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "solve_charged_two_sided_interface_qss", + "solve_two_sided_interface_qss", + "thermionic_emission_bound_m2_s", +] diff --git a/src/solarlab/physics/interface_transport/thermionic.py b/src/solarlab/physics/interface_transport/thermionic.py new file mode 100644 index 00000000..43cdfe4a --- /dev/null +++ b/src/solarlab/physics/interface_transport/thermionic.py @@ -0,0 +1,689 @@ +"""Thermionic emission constants, Fermi-Dirac supply integrals, and flux kernels (P04-09). + +Provides: +* CODATA 2018 free-electron Richardson constant ``A_STAR_FREE_ELECTRON_A_M2_K2`` + and DOS-consistent effective-mass / Richardson helpers ``effective_mass_from_dos``, + ``richardson_from_dos``, ``emission_velocity``, ``is_free_electron_default``, + and ``resolve_layer_richardson`` (retaining the validated 300 K / existing DOS + convention for ``N``-class parity; prospective TE supply corrections belong to + ``P08-03``). +* Fermi-Dirac integrals ``fermi_dirac_zero`` (``F_0``) and ``fermi_dirac_one`` + (``F_1``) with exact derivative relation ``d F_1 / d eta = F_0``. +* Direction-preserving 1D thermionic emission particle-flux bound and smooth / + hard Scharfetter-Gummel flux capping ``cap_particle_flux_thermionic`` with + exact analytical derivatives wrt ``(sg_flux, n_left, n_right)``. +* Two-sided cross-interface transport kernels ``fermi_dirac_richardson_flux``, + ``fermi_richardson_flux``, and ``scaps_thermionic_flux`` with exact analytical + derivatives wrt trace log-densities and trace potentials. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +import math +from typing import Literal, TypeAlias + +import numpy as np +from numpy.typing import NDArray +from scipy.special import expit, spence + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.physics.statistics.fermi_dirac import ( + FERMI_DIRAC_HALF_TABLE_ETA_MAX, + fermi_dirac_half_log_derivative, + fermi_dirac_half_table, + inverse_fermi_dirac_half, +) +from solarlab.physics.statistics.thermal import ( + BOLTZMANN_CONSTANT_J_K, + REFERENCE_TEMPERATURE_K, + thermal_voltage, +) + +__all__ = [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ELECTRON_MASS_KG", + "PLANCK_CONSTANT_J_S", + "TE_BARRIER_THRESHOLD_EV", + "ThermionicCapEvaluation", + "TwoSidedCrossFluxEvaluation", + "cap_particle_flux_thermionic", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "thermionic_emission_bound_m2_s", +] + +Q: float = ELEMENTARY_CHARGE_C +K_B: float = BOLTZMANN_CONSTANT_J_K +PLANCK_CONSTANT_J_S: float = 6.62607015e-34 +ELECTRON_MASS_KG: float = 9.1093837015e-31 +A_STAR_FREE_ELECTRON_A_M2_K2: float = ( + 4.0 * math.pi * Q * ELECTRON_MASS_KG * K_B**2 / PLANCK_CONSTANT_J_S**3 +) +TE_BARRIER_THRESHOLD_EV: float = 0.05 + +TERegularizationMode: TypeAlias = Literal["legacy_logistic", "compact_support"] +RealArray: TypeAlias = NDArray[np.float64] + + +def is_free_electron_default(a_star_A_m2_K2: float, *, rel_tol: float = 1.0e-3) -> bool: + """Return True if ``a_star_A_m2_K2`` matches the free-electron default ``~1.2017e6``.""" + return math.isclose( + float(a_star_A_m2_K2), + A_STAR_FREE_ELECTRON_A_M2_K2, + rel_tol=rel_tol, + abs_tol=0.0, + ) + + +def effective_mass_from_dos(dos_m3: float, temperature_K: float = REFERENCE_TEMPERATURE_K) -> float: + """Invert ``N_C = 2 (2 pi m* k_B T / h^2)^{3/2}`` to return ``m* / m_0``.""" + n_dos = float(dos_m3) + temp = float(temperature_K) + if not (math.isfinite(n_dos) and n_dos > 0.0): + raise ValueError("dos_m3 must be finite and positive") + if not (math.isfinite(temp) and temp > 0.0): + raise ValueError("temperature_K must be finite and positive") + prefactor = 2.0 * math.pi * ELECTRON_MASS_KG * K_B * temp / PLANCK_CONSTANT_J_S**2 + return float((0.5 * n_dos) ** (2.0 / 3.0) / prefactor) + + +def richardson_from_dos(dos_m3: float, temperature_K: float = REFERENCE_TEMPERATURE_K) -> float: + """Effective Richardson constant ``A* = A_0 * (m* / m_0)`` [A m^-2 K^-2] from DOS.""" + return float(A_STAR_FREE_ELECTRON_A_M2_K2 * effective_mass_from_dos(dos_m3, temperature_K)) + + +def emission_velocity(temperature_K: float = REFERENCE_TEMPERATURE_K, m_eff_ratio: float = 1.0) -> float: + """Mean one-way thermal emission velocity ``sqrt(k_B T / (2 pi m*))`` [m/s].""" + temp = float(temperature_K) + ratio = float(m_eff_ratio) + if not (math.isfinite(temp) and temp > 0.0): + raise ValueError("temperature_K must be finite and positive") + if not (math.isfinite(ratio) and ratio > 0.0): + raise ValueError("m_eff_ratio must be finite and positive") + return float(math.sqrt(K_B * temp / (2.0 * math.pi * ratio * ELECTRON_MASS_KG))) + + +def resolve_layer_richardson( + a_star_A_m2_K2: float, + dos_300_m3: float, + temperature_K: float = REFERENCE_TEMPERATURE_K, +) -> float: + """Resolve layer ``A*`` using the existing 300 K DOS convention when defaulted. + + ``a_star_A_m2_K2 == 0.0`` disables thermionic emission on that carrier and is + preserved exactly. + """ + a_star = float(a_star_A_m2_K2) + if not math.isfinite(a_star) or a_star < 0.0: + raise ValueError("a_star_A_m2_K2 must be finite and non-negative") + if a_star == 0.0: + return 0.0 + dos = float(dos_300_m3) + if is_free_electron_default(a_star) and math.isfinite(dos) and dos > 0.0: + return richardson_from_dos(dos, temperature_K) + return a_star + + +def fermi_dirac_zero(eta: float) -> float: + """Complete Fermi-Dirac integral ``F_0(eta) = ln(1 + exp(eta))``.""" + x = float(eta) + if math.isnan(x): + raise ValueError("eta must not be NaN") + if x <= -700.0: + return 0.0 + if x <= -40.0: + return math.exp(x) + if x <= 20.0: + return math.log1p(math.exp(x)) + return x + math.log1p(math.exp(-x)) + + +def fermi_dirac_one(eta: float) -> float: + """Complete Fermi-Dirac integral ``F_1(eta) = integral_0^inf x/(1+exp(x-eta)) dx``.""" + x = float(eta) + if math.isnan(x): + raise ValueError("eta must not be NaN") + if x <= -700.0: + return 0.0 + if x < -4.0: + exp_x = math.exp(x) + power = exp_x + total = 0.0 + sign = 1.0 + for k in range(1, 13): + total += sign * power / (k * k) + power *= exp_x + sign = -sign + return total + if x > 40.0: + return 0.5 * x * x + (math.pi * math.pi) / 6.0 - math.exp(-x) + return float(-spence(1.0 + math.exp(x))) + + +def thermionic_emission_bound_m2_s( + n_left_m3: float, + n_right_m3: float, + delta_barrier_eV: float, + temperature_K: float, + a_star_A_m2_K2: float, + *, + dos_norm_m3: float | None = None, +) -> tuple[float, float, float]: + """Signed 1D thermionic particle-flux bound ``J_te / q`` [m^-2 s^-1] and partials. + + Returns ``(gamma_te, d_gamma_te_d_n_left, d_gamma_te_d_n_right)`` where + ``Q * gamma_te`` reproduces the historical ``thermionic_emission_flux`` in + ``A m^-2`` bit-for-bit up to the elementary-charge unit conversion. + """ + n_l = float(n_left_m3) + n_r = float(n_right_m3) + d_eb = float(delta_barrier_eV) + temp = float(temperature_K) + a_star = float(a_star_A_m2_K2) + if not all(math.isfinite(v) for v in (n_l, n_r, d_eb, temp, a_star)): + raise ValueError("thermionic inputs must be finite") + if temp <= 0.0 or a_star < 0.0: + raise ValueError("temperature must be positive and A* non-negative") + if a_star == 0.0: + return 0.0, 0.0, 0.0 + + vt = thermal_voltage(temp) + bar_lr = max(d_eb, 0.0) + bar_rl = max(-d_eb, 0.0) + exp_lr = math.exp(max(-500.0, -bar_lr / vt)) + exp_rl = math.exp(max(-500.0, -bar_rl / vt)) + scale = (a_star * temp * temp) / Q + if dos_norm_m3 is not None: + dos = float(dos_norm_m3) + if not (math.isfinite(dos) and dos > 0.0): + raise ValueError("dos_norm_m3 must be finite and positive when supplied") + scale /= dos + d_left = scale * exp_lr + d_right = -scale * exp_rl + return scale * (n_l * exp_lr - n_r * exp_rl), d_left, d_right + + +@dataclass(frozen=True) +class ThermionicCapEvaluation: + """Direction-preserving capped particle flux [m^-2 s^-1] and exact partials.""" + + flux_m2_s: float + d_flux_d_sg_flux: float + d_flux_d_n_left_m_s: float + d_flux_d_n_right_m_s: float + + +def cap_particle_flux_thermionic( + sg_flux_m2_s: float, + *, + n_left_m3: float, + n_right_m3: float, + delta_barrier_eV: float, + temperature_K: float, + a_star_A_m2_K2: float, + te_softness: float = 0.0, + regularization_mode: TERegularizationMode = "legacy_logistic", + dos_norm_m3: float | None = None, +) -> ThermionicCapEvaluation: + """Limit ``|sg_flux_m2_s|`` by the 1D thermionic particle-flux bound without sign flip.""" + sg = float(sg_flux_m2_s) + soft = float(te_softness) + if not (math.isfinite(sg) and math.isfinite(soft)) or soft < 0.0: + raise ValueError("sg_flux_m2_s must be finite and te_softness non-negative") + + te_signed, d_te_dl, d_te_dr = thermionic_emission_bound_m2_s( + n_left_m3, + n_right_m3, + delta_barrier_eV, + temperature_K, + a_star_A_m2_K2, + dos_norm_m3=dos_norm_m3, + ) + a_sg = abs(sg) + a_te = abs(te_signed) + sign_sg = math.copysign(1.0, sg) + sign_te = 0.0 if te_signed == 0.0 else math.copysign(1.0, te_signed) + + if soft == 0.0: + if a_sg <= a_te: + return ThermionicCapEvaluation(sg, 1.0, 0.0, 0.0) + flux = math.copysign(a_te, sg) + scale_te = sign_sg * sign_te + return ThermionicCapEvaluation(flux, 0.0, scale_te * d_te_dl, scale_te * d_te_dr) + + if regularization_mode == "legacy_logistic": + denom = soft * (a_sg + a_te) + 1.0e-300 + t_arg = (a_sg - a_te) / denom + if t_arg > 40.0: + weight = 1.0 + dw_dt = 0.0 + elif t_arg < -40.0: + weight = 0.0 + dw_dt = 0.0 + else: + weight = 1.0 / (1.0 + math.exp(-t_arg)) + dw_dt = weight * (1.0 - weight) + magnitude = weight * a_te + (1.0 - weight) * a_sg + denom_sq = denom * denom + dt_da_sg = (denom - (a_sg - a_te) * soft) / denom_sq + dt_da_te = (-denom - (a_sg - a_te) * soft) / denom_sq + dm_da_sg = (1.0 - weight) + (a_te - a_sg) * dw_dt * dt_da_sg + dm_da_te = weight + (a_te - a_sg) * dw_dt * dt_da_te + elif regularization_mode == "compact_support": + scale = soft * (a_sg + a_te) + if scale == 0.0: + return ThermionicCapEvaluation(math.copysign(0.0, sg), 0.5, 0.0, 0.0) + normalized = (a_sg - a_te) / scale + if normalized <= -1.0: + magnitude = a_sg + dm_da_sg = 1.0 + dm_da_te = 0.0 + elif normalized >= 1.0: + magnitude = a_te + dm_da_sg = 0.0 + dm_da_te = 1.0 + else: + u = 0.5 * (normalized + 1.0) + weight = 6.0 * u**5 - 15.0 * u**4 + 10.0 * u**3 + dw_du = 30.0 * u**2 * (1.0 - u) ** 2 + scale_sq = scale * scale + dn_da_sg = 2.0 * soft * a_te / scale_sq + dn_da_te = -2.0 * soft * a_sg / scale_sq + dw_da_sg = 0.5 * dw_du * dn_da_sg + dw_da_te = 0.5 * dw_du * dn_da_te + magnitude = (1.0 - weight) * a_sg + weight * a_te + dm_da_sg = (1.0 - weight) + (a_te - a_sg) * dw_da_sg + dm_da_te = weight + (a_te - a_sg) * dw_da_te + else: + raise ValueError( + "regularization_mode must be 'legacy_logistic' or 'compact_support'" + ) + + flux = math.copysign(magnitude, sg) + # flux = sign(sg) * M(|sg|, |te|), so d(flux)/d(sg) = dM/d(|sg|) for sg != 0, + # and d(flux)/d(n_side) = sign(sg) * dM/d(|te|) * sign(te) * d(te)/d(n_side). + d_flux_d_sg = dm_da_sg + te_chain = sign_sg * dm_da_te * sign_te + return ThermionicCapEvaluation( + flux_m2_s=flux, + d_flux_d_sg_flux=d_flux_d_sg, + d_flux_d_n_left_m_s=te_chain * d_te_dl, + d_flux_d_n_right_m_s=te_chain * d_te_dr, + ) + + +@dataclass(frozen=True) +class TwoSidedCrossFluxEvaluation: + """Two-sided cross-plane particle fluxes ``[Gamma_n, Gamma_p]`` [m^-2 s^-1]. + + State log-density column order is ``(log n_L, log p_L, log n_R, log p_R)``. + Trace-potential column order is ``(phi_trace_L, phi_trace_R)``. + """ + + cross_flux_m2_s: RealArray + d_cross_d_log_state_m2_s: RealArray + d_cross_d_trace_potentials_m2_s_V: RealArray + one_way_scale_m2_s: RealArray + + +def _inverse_fermi_dirac_half_log(log_ratio: float) -> float: + """Invert ``F_{1/2}(eta) = exp(log_ratio)`` directly in log-ratio space.""" + lr = float(log_ratio) + eta_grid, _table, log_table = fermi_dirac_half_table() + if lr <= float(log_table[0]): + return lr + if lr <= float(log_table[-1]): + return float(np.interp(lr, log_table, eta_grid)) + ratio = math.exp(lr) + coeff = 4.0 / (3.0 * math.sqrt(math.pi)) + eta = max(FERMI_DIRAC_HALF_TABLE_ETA_MAX, math.exp(2.0 / 3.0 * (lr - math.log(coeff)))) + for _ in range(6): + root = math.sqrt(eta) + val = ( + 4.0 * eta * root / (3.0 * math.sqrt(math.pi)) + + math.pi**2 / (6.0 * math.sqrt(math.pi) * root) + ) + der = ( + 2.0 * root / math.sqrt(math.pi) + - math.pi**2 / (12.0 * math.sqrt(math.pi) * eta * root) + ) + eta = max(FERMI_DIRAC_HALF_TABLE_ETA_MAX, eta - (val - ratio) / der) + return eta + + +@lru_cache(maxsize=1) +def _excess_table() -> NDArray[np.float64]: + """Cached ``eta_grid - log F_{1/2}(eta_grid)`` table for sawtooth-free excess interpolation.""" + eta_grid, _table, log_table = fermi_dirac_half_table() + excess = np.asarray(eta_grid - log_table, dtype=np.float64) + excess[0] = 0.0 + excess.setflags(write=False) + return excess + + +def _eta_excess_from_log_ratio(log_ratio: float) -> tuple[float, int]: + """Return ``(eta(lr) - lr, table_interval_index)`` without subtracting ``lr`` from ``eta``.""" + lr = float(log_ratio) + _eta_grid, _table, log_table = fermi_dirac_half_table() + if lr <= float(log_table[0]): + return 0.0, -1 + if lr <= float(log_table[-1]): + excess = _excess_table() + idx = min(max(int(np.searchsorted(log_table, lr, side="right")) - 1, 0), len(log_table) - 2) + t = float((lr - log_table[idx]) / (log_table[idx + 1] - log_table[idx])) + ex = float(excess[idx] + t * (excess[idx + 1] - excess[idx])) + return ex, idx + return _inverse_fermi_dirac_half_log(lr) - lr, len(log_table) + + +def _eta_excess_and_delta(base_log_ratio: float, u_shift: float) -> tuple[float, float, float]: + """Return ``(eta_full, eta(base) - base, eta(base + u) - eta(base))`` without sawtooth or ``u`` quantization.""" + base_lr = float(base_log_ratio) + shift = float(u_shift) + lr_full = base_lr + shift + ex0, idx0 = _eta_excess_from_log_ratio(base_lr) + if idx0 == -1 and lr_full <= float(fermi_dirac_half_table()[2][0]): + return lr_full, 0.0, shift + ex_full, idx1 = _eta_excess_from_log_ratio(lr_full) + if 0 <= idx0 == idx1 < len(fermi_dirac_half_table()[2]) - 1: + eta_grid, _table, log_table = fermi_dirac_half_table() + slope = float((eta_grid[idx0 + 1] - eta_grid[idx0]) / (log_table[idx0 + 1] - log_table[idx0])) + d_eta = slope * shift + return (base_lr + ex0) + d_eta, ex0, d_eta + d_eta = shift + (ex_full - ex0) + return lr_full + ex_full, ex0, d_eta + + +def _one_way_fermi_dirac_supply( + density_m3: float, + dos_m3: float, + barrier_eV: float, + vt_V: float, + *, + eta_override: float | None = None, +) -> tuple[float, float, float, float]: + if eta_override is None: + ratio = float(density_m3) / float(dos_m3) + eta = inverse_fermi_dirac_half(ratio) + else: + eta = float(eta_override) + argument = eta - float(barrier_eV) / float(vt_V) + supply = fermi_dirac_one(argument) + log_slope = fermi_dirac_half_log_derivative(eta) + if not math.isfinite(log_slope) or log_slope <= 0.0: + raise FloatingPointError("invalid Fermi-Dirac constitutive derivative") + f0 = fermi_dirac_zero(argument) + return supply, f0 / log_slope, -f0 / float(vt_V), argument + + +def _fermi_dirac_one_difference(arg_left: float, arg_right: float, delta: float, sup_left: float, sup_right: float) -> float: + """Evaluate ``F_1(arg_left) - F_1(arg_right)`` without catastrophic cancellation.""" + if abs(delta) <= 1.0e-3 and math.isfinite(arg_left) and math.isfinite(arg_right): + mid = 0.5 * (arg_left + arg_right) + s = float(expit(mid)) + return delta * (fermi_dirac_zero(mid) + (delta * delta / 24.0) * s * (1.0 - s)) + return sup_left - sup_right + + +def fermi_dirac_richardson_flux( + state_m3: NDArray[np.float64], + *, + phi_trace_left_V: float, + phi_trace_right_V: float, + conduction_band_step_eV: float, + hole_transport_step_eV: float, + N_C_left_m3: float, + N_C_right_m3: float, + N_V_left_m3: float, + N_V_right_m3: float, + richardson_n_A_m2_K2: float, + richardson_p_A_m2_K2: float, + temperature_K: float, + thermal_voltage_V: float, + transmission: float = 1.0, + base_log_to_dos: NDArray[np.float64] | None = None, + u_delta: NDArray[np.float64] | None = None, + electrochemical_steps: tuple[float | None, float | None] = (None, None), +) -> TwoSidedCrossFluxEvaluation: + """Reciprocal 3D Fermi-Dirac Bethe/Richardson cross-plane particle flux.""" + n_l, p_l, n_r, p_r = (float(v) for v in state_m3) + potential_jump = float(phi_trace_right_V - phi_trace_left_V) + electron_step = float(conduction_band_step_eV) - potential_jump + hole_step = float(hole_transport_step_eV) + potential_jump + vt = float(thermal_voltage_V) + + eta_nl: float | None + eta_pl: float | None + eta_nr: float | None + eta_pr: float | None + if base_log_to_dos is not None and u_delta is not None: + eta_nl, ex_nl, d_nl = _eta_excess_and_delta(float(base_log_to_dos[0]), float(u_delta[0])) + eta_pl, ex_pl, d_pl = _eta_excess_and_delta(float(base_log_to_dos[1]), float(u_delta[1])) + eta_nr, ex_nr, d_nr = _eta_excess_and_delta(float(base_log_to_dos[2]), float(u_delta[2])) + eta_pr, ex_pr, d_pr = _eta_excess_and_delta(float(base_log_to_dos[3]), float(u_delta[3])) + else: + eta_nl = eta_pl = eta_nr = eta_pr = None + ex_nl = ex_pl = ex_nr = ex_pr = 0.0 + d_nl = d_pl = d_nr = d_pr = 0.0 + + n_l_sup, dn_l, dn_l_bar, arg_nl = _one_way_fermi_dirac_supply( + n_l, N_C_left_m3, max(electron_step, 0.0), vt, eta_override=eta_nl + ) + n_r_sup, dn_r, dn_r_bar, arg_nr = _one_way_fermi_dirac_supply( + n_r, N_C_right_m3, max(-electron_step, 0.0), vt, eta_override=eta_nr + ) + p_l_sup, dp_l, dp_l_bar, arg_pl = _one_way_fermi_dirac_supply( + p_l, N_V_left_m3, max(hole_step, 0.0), vt, eta_override=eta_pl + ) + p_r_sup, dp_r, dp_r_bar, arg_pr = _one_way_fermi_dirac_supply( + p_r, N_V_right_m3, max(-hole_step, 0.0), vt, eta_override=eta_pr + ) + + ec_n, ec_p = electrochemical_steps + if eta_nl is not None and eta_nr is not None and ec_n is not None: + delta_arg_n = -float(ec_n) + (ex_nl - ex_nr) + (d_nl - d_nr) + elif eta_nl is not None and eta_nr is not None: + arg_nl0 = (eta_nl - d_nl) - max(electron_step, 0.0) / vt + arg_nr0 = (eta_nr - d_nr) - max(-electron_step, 0.0) / vt + delta_arg_n = (arg_nl0 - arg_nr0) + (d_nl - d_nr) + else: + delta_arg_n = arg_nl - arg_nr + + if eta_pl is not None and eta_pr is not None and ec_p is not None: + delta_arg_p = -float(ec_p) + (ex_pl - ex_pr) + (d_pl - d_pr) + elif eta_pl is not None and eta_pr is not None: + arg_pl0 = (eta_pl - d_pl) - max(hole_step, 0.0) / vt + arg_pr0 = (eta_pr - d_pr) - max(-hole_step, 0.0) / vt + delta_arg_p = (arg_pl0 - arg_pr0) + (d_pl - d_pr) + else: + delta_arg_p = arg_pl - arg_pr + + pref_n = float(transmission) * float(richardson_n_A_m2_K2) * float(temperature_K) ** 2 / Q + pref_p = float(transmission) * float(richardson_p_A_m2_K2) * float(temperature_K) ** 2 / Q + cross = np.array( + [ + pref_n * _fermi_dirac_one_difference(arg_nl, arg_nr, delta_arg_n, n_l_sup, n_r_sup), + pref_p * _fermi_dirac_one_difference(arg_pl, arg_pr, delta_arg_p, p_l_sup, p_r_sup), + ], + dtype=np.float64, + ) + d_log: NDArray[np.float64] = np.zeros((2, 4), dtype=np.float64) + d_log[0, 0] = pref_n * dn_l + d_log[0, 2] = -pref_n * dn_r + d_log[1, 1] = pref_p * dp_l + d_log[1, 3] = -pref_p * dp_r + + e_jump_deriv = 0.0 + if electron_step > 0.0: + e_jump_deriv = pref_n * (-dn_l_bar) + elif electron_step < 0.0: + e_jump_deriv = pref_n * (-dn_r_bar) + + h_jump_deriv = 0.0 + if hole_step > 0.0: + h_jump_deriv = pref_p * dp_l_bar + elif hole_step < 0.0: + h_jump_deriv = pref_p * dp_r_bar + + d_trace = np.array( + [[-e_jump_deriv, e_jump_deriv], [-h_jump_deriv, h_jump_deriv]], + dtype=np.float64, + ) + scale = np.array( + [pref_n * max(n_l_sup, n_r_sup), pref_p * max(p_l_sup, p_r_sup)], + dtype=np.float64, + ) + return TwoSidedCrossFluxEvaluation(cross, d_log, d_trace, scale) + + +def fermi_richardson_flux( + state_m3: NDArray[np.float64], + *, + phi_trace_left_V: float, + phi_trace_right_V: float, + conduction_band_step_eV: float, + hole_transport_step_eV: float, + N_C_left_m3: float, + N_C_right_m3: float, + N_V_left_m3: float, + N_V_right_m3: float, + richardson_n_A_m2_K2: float, + richardson_p_A_m2_K2: float, + temperature_K: float, + thermal_voltage_V: float, + transmission: float = 1.0, +) -> TwoSidedCrossFluxEvaluation: + """Boltzmann-limit reciprocal Bethe/Richardson cross-plane particle flux.""" + n_l, p_l, n_r, p_r = (float(v) for v in state_m3) + potential_jump = float(phi_trace_right_V - phi_trace_left_V) + electron_step = float(conduction_band_step_eV) - potential_jump + hole_step = float(hole_transport_step_eV) + potential_jump + vt = float(thermal_voltage_V) + + exp_n_l = math.exp(max(-500.0, -max(electron_step, 0.0) / vt)) + exp_n_r = math.exp(max(-500.0, -max(-electron_step, 0.0) / vt)) + exp_p_l = math.exp(max(-500.0, -max(hole_step, 0.0) / vt)) + exp_p_r = math.exp(max(-500.0, -max(-hole_step, 0.0) / vt)) + + n_l_sup = (n_l / float(N_C_left_m3)) * exp_n_l + n_r_sup = (n_r / float(N_C_right_m3)) * exp_n_r + p_l_sup = (p_l / float(N_V_left_m3)) * exp_p_l + p_r_sup = (p_r / float(N_V_right_m3)) * exp_p_r + + pref_n = float(transmission) * float(richardson_n_A_m2_K2) * float(temperature_K) ** 2 / Q + pref_p = float(transmission) * float(richardson_p_A_m2_K2) * float(temperature_K) ** 2 / Q + cross = np.array( + [pref_n * (n_l_sup - n_r_sup), pref_p * (p_l_sup - p_r_sup)], + dtype=np.float64, + ) + d_log: NDArray[np.float64] = np.zeros((2, 4), dtype=np.float64) + d_log[0, 0] = pref_n * n_l_sup + d_log[0, 2] = -pref_n * n_r_sup + d_log[1, 1] = pref_p * p_l_sup + d_log[1, 3] = -pref_p * p_r_sup + + e_jump_deriv = 0.0 + if electron_step > 0.0: + e_jump_deriv = pref_n * n_l_sup / vt + elif electron_step < 0.0: + e_jump_deriv = pref_n * n_r_sup / vt + + h_jump_deriv = 0.0 + if hole_step > 0.0: + h_jump_deriv = -pref_p * p_l_sup / vt + elif hole_step < 0.0: + h_jump_deriv = -pref_p * p_r_sup / vt + + d_trace = np.array( + [[-e_jump_deriv, e_jump_deriv], [-h_jump_deriv, h_jump_deriv]], + dtype=np.float64, + ) + scale = np.array( + [pref_n * max(n_l_sup, n_r_sup), pref_p * max(p_l_sup, p_r_sup)], + dtype=np.float64, + ) + return TwoSidedCrossFluxEvaluation(cross, d_log, d_trace, scale) + + +def scaps_thermionic_flux( + state_m3: NDArray[np.float64], + *, + phi_trace_left_V: float, + phi_trace_right_V: float, + conduction_band_step_eV: float, + hole_transport_step_eV: float, + N_C_left_m3: float, + N_C_right_m3: float, + N_V_left_m3: float, + N_V_right_m3: float, + richardson_n_left_A_m2_K2: float, + richardson_n_right_A_m2_K2: float, + richardson_p_left_A_m2_K2: float, + richardson_p_right_A_m2_K2: float, + temperature_K: float, + thermal_voltage_V: float, + transmission: float = 1.0, +) -> TwoSidedCrossFluxEvaluation: + """SCAPS effective-velocity cross-plane particle flux ``v_eff (n_L_eff - n_R_eff)``.""" + n_l, p_l, n_r, p_r = (float(v) for v in state_m3) + nc_l, nc_r = float(N_C_left_m3), float(N_C_right_m3) + nv_l, nv_r = float(N_V_left_m3), float(N_V_right_m3) + potential_jump = float(phi_trace_right_V - phi_trace_left_V) + electron_step = float(conduction_band_step_eV) - potential_jump + hole_step = float(hole_transport_step_eV) + potential_jump + vt = float(thermal_voltage_V) + temp_sq = float(temperature_K) ** 2 + trans = float(transmission) + + vn_l = float(richardson_n_left_A_m2_K2) * temp_sq / (Q * nc_l) + vn_r = float(richardson_n_right_A_m2_K2) * temp_sq / (Q * nc_r) + vp_l = float(richardson_p_left_A_m2_K2) * temp_sq / (Q * nv_l) + vp_r = float(richardson_p_right_A_m2_K2) * temp_sq / (Q * nv_r) + v_eff_n = trans * min(vn_l, vn_r * (nc_r / nc_l)) + v_eff_p = trans * min(vp_l, vp_r * (nv_r / nv_l)) + + exp_n_l = math.exp(max(-500.0, -max(electron_step, 0.0) / vt)) + exp_n_r = math.exp(max(-500.0, -max(-electron_step, 0.0) / vt)) + exp_p_l = math.exp(max(-500.0, -max(hole_step, 0.0) / vt)) + exp_p_r = math.exp(max(-500.0, -max(-hole_step, 0.0) / vt)) + + term_n_l = v_eff_n * n_l * exp_n_l + term_n_r = v_eff_n * n_r * (nc_l / nc_r) * exp_n_r + term_p_l = v_eff_p * p_l * exp_p_l + term_p_r = v_eff_p * p_r * (nv_l / nv_r) * exp_p_r + + cross = np.array([term_n_l - term_n_r, term_p_l - term_p_r], dtype=np.float64) + d_log: NDArray[np.float64] = np.zeros((2, 4), dtype=np.float64) + d_log[0, 0] = term_n_l + d_log[0, 2] = -term_n_r + d_log[1, 1] = term_p_l + d_log[1, 3] = -term_p_r + + e_jump_deriv = 0.0 + if electron_step > 0.0: + e_jump_deriv = term_n_l / vt + elif electron_step < 0.0: + e_jump_deriv = term_n_r / vt + + h_jump_deriv = 0.0 + if hole_step > 0.0: + h_jump_deriv = -term_p_l / vt + elif hole_step < 0.0: + h_jump_deriv = -term_p_r / vt + + d_trace = np.array( + [[-e_jump_deriv, e_jump_deriv], [-h_jump_deriv, h_jump_deriv]], + dtype=np.float64, + ) + scale = np.array([max(term_n_l, term_n_r), max(term_p_l, term_p_r)], dtype=np.float64) + return TwoSidedCrossFluxEvaluation(cross, d_log, d_trace, scale) diff --git a/src/solarlab/physics/interface_transport/two_sided.py b/src/solarlab/physics/interface_transport/two_sided.py new file mode 100644 index 00000000..d1304bef --- /dev/null +++ b/src/solarlab/physics/interface_transport/two_sided.py @@ -0,0 +1,1255 @@ +"""Two-sided heterointerface QSS trace elimination and IFT sensitivities (P04-09). + +Eliminates the local algebraic trace variables at a physical two-sided interface: +* Charge-off (:func:`solve_two_sided_interface_qss`): solves the 2x2 linear + electrostatic trace system exactly and the 4x4 nonlinear log-density carrier + trace balance ``bulk_flux - P cross_flux - capture == 0``, returning exact + 4x6 Implicit-Function-Theorem sensitivities wrt bulk coordinates + ``(phi_L, phi_R, log n_L, log p_L, log n_R, log p_R)``. +* Equilibrium-referenced sheet charge (:func:`solve_charged_two_sided_interface_qss`): + solves the coupled 6x6 electrostatic + carrier trace system where the Gauss + jump and the four carrier capture fluxes share ONE constitutive evaluation of + :func:`~solarlab.physics.recombination.interface.evaluate_shared_interface_trap`, + returning exact IFT sensitivities of ``bulk_flux``, ``occupancy``, and + ``incremental_sheet_charge_C_m2`` wrt all six bulk coordinates. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Sequence, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.optimize import least_squares + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M +from solarlab.discretization.stable_bernoulli import bernoulli_pair +from solarlab.physics.electrostatics.interface_traces import ( + TraceElectrostatics, + sheet_charge_row_weights, + solve_electrostatic_traces, +) +from solarlab.physics.interface_transport.thermionic import fermi_dirac_richardson_flux +from solarlab.physics.recombination.interface import ( + SharedInterfaceTrapEvaluation, + evaluate_shared_interface_trap, +) + +__all__ = [ + "ChargedTwoSidedInterfaceQSSResult", + "EquilibriumReferencedSheetCharge", + "TwoSidedBulkState", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "remove_shared_interface_nodes", + "solve_charged_two_sided_interface_qss", + "solve_two_sided_interface_qss", +] + +Q: float = ELEMENTARY_CHARGE_C +EPS_0: float = VACUUM_PERMITTIVITY_F_M +RealArray: TypeAlias = NDArray[np.float64] + +_N_LEFT = 0 +_P_LEFT = 1 +_N_RIGHT = 2 +_P_RIGHT = 3 +_STATE_SIZE = 4 + + +def _positive(value: float, name: str) -> float: + scalar = float(value) + if not math.isfinite(scalar) or scalar <= 0.0: + raise ValueError(f"{name} must be finite and positive") + return scalar + + +def _nonnegative(value: float, name: str) -> float: + scalar = float(value) + if not math.isfinite(scalar) or scalar < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + return scalar + + +def remove_shared_interface_nodes( + grid_m: ArrayLike, + interface_positions_m: Sequence[float] | ArrayLike, +) -> RealArray: + """Remove deduplicated shared interface nodes while keeping adjacent bulk cells.""" + grid = np.asarray(grid_m, dtype=np.float64) + if grid.ndim != 1 or grid.size < 3 or not np.all(np.isfinite(grid)) or np.any(np.diff(grid) <= 0.0): + raise ValueError("grid_m must be finite, strictly increasing, and have at least 3 nodes") + positions = [float(p) for p in np.asarray(interface_positions_m, dtype=np.float64).ravel()] + if not positions: + return grid.copy() + if any(not math.isfinite(p) for p in positions) or any( + right <= left for left, right in zip(positions[:-1], positions[1:]) + ): + raise ValueError("interface_positions_m must be finite and strictly increasing") + + tol = 32.0 * float(np.finfo(np.float64).eps) * max( + 1.0, abs(float(grid[0])), abs(float(grid[-1])), abs(float(grid[-1] - grid[0])) + ) + keep = np.ones(grid.size, dtype=bool) + for pos in positions: + matches = np.flatnonzero(np.abs(grid - pos) <= tol) + if matches.size != 1: + raise ValueError(f"expected exactly one shared node at interface {pos}") + idx = int(matches[0]) + if idx == 0 or idx == grid.size - 1: + raise ValueError("cannot remove an outer contact node") + keep[idx] = False + reduced = grid[keep] + if reduced.size < 3 or np.any(np.diff(reduced) <= 0.0): + raise ValueError("two-sided grid reduction collapsed bulk support") + return reduced + + +@dataclass(frozen=True) +class TwoSidedInterfacePhysics: + """Constitutive parameters for one physical two-sided heterointerface.""" + + thermal_voltage_V: float + temperature_K: float + D_n_left_m2_s: float + D_n_right_m2_s: float + D_p_left_m2_s: float + D_p_right_m2_s: float + N_C_left_m3: float + N_C_right_m3: float + N_V_left_m3: float + N_V_right_m3: float + richardson_n_A_m2_K2: float + richardson_p_A_m2_K2: float + conduction_band_step_eV: float + hole_transport_step_eV: float + transmission: float = 1.0 + surface_recombination_velocity_n_m_s: float = 0.0 + surface_recombination_velocity_p_m_s: float = 0.0 + n1_left_m3: float = 0.0 + n1_right_m3: float = 0.0 + p1_left_m3: float = 0.0 + p1_right_m3: float = 0.0 + + def __post_init__(self) -> None: + for name in ( + "thermal_voltage_V", + "temperature_K", + "D_n_left_m2_s", + "D_n_right_m2_s", + "D_p_left_m2_s", + "D_p_right_m2_s", + "N_C_left_m3", + "N_C_right_m3", + "N_V_left_m3", + "N_V_right_m3", + "richardson_n_A_m2_K2", + "richardson_p_A_m2_K2", + ): + _positive(getattr(self, name), name) + for name in ( + "transmission", + "surface_recombination_velocity_n_m_s", + "surface_recombination_velocity_p_m_s", + "n1_left_m3", + "n1_right_m3", + "p1_left_m3", + "p1_right_m3", + ): + _nonnegative(getattr(self, name), name) + if float(self.transmission) > 1.0: + raise ValueError("transmission must lie in [0, 1]") + for name in ("conduction_band_step_eV", "hole_transport_step_eV"): + if not math.isfinite(float(getattr(self, name))): + raise ValueError(f"{name} must be finite") + + +@dataclass(frozen=True) +class TwoSidedBulkState: + """Adjacent left and right bulk cell potentials and carrier densities.""" + + phi_left_V: float + phi_right_V: float + n_left_m3: float + p_left_m3: float + n_right_m3: float + p_right_m3: float + electron_electrochemical_step: float | None = None + hole_electrochemical_step: float | None = None + + def __post_init__(self) -> None: + if not (math.isfinite(float(self.phi_left_V)) and math.isfinite(float(self.phi_right_V))): + raise ValueError("bulk potentials must be finite") + for name in ("n_left_m3", "p_left_m3", "n_right_m3", "p_right_m3"): + _positive(getattr(self, name), name) + for step_name in ("electron_electrochemical_step", "hole_electrochemical_step"): + step_val = getattr(self, step_name) + if step_val is not None and not math.isfinite(float(step_val)): + raise ValueError(f"{step_name} must be finite when supplied") + + +@dataclass(frozen=True) +class EquilibriumReferencedSheetCharge: + """Certified dark-equilibrium reference parameters for static sheet charge.""" + + trap_density_m2: float + equilibrium_occupancy: float + + def __post_init__(self) -> None: + _nonnegative(self.trap_density_m2, "trap_density_m2") + f_ref = float(self.equilibrium_occupancy) + if not (math.isfinite(f_ref) and 0.0 <= f_ref <= 1.0): + raise ValueError("equilibrium_occupancy must lie in [0, 1]") + + +@dataclass(frozen=True) +class TwoSidedInterfaceQSSResult: + """Charge-off two-sided trace elimination result and 4x6 bulk IFT Jacobian. + + ``bulk_flux_m2_s`` has ordering ``(n_L, p_L, n_R, p_R)`` representing + particle flux from each adjacent bulk node INTO its corresponding trace + (so bulk continuity row ``L`` receives ``-bulk_flux[n_L]`` and row ``R`` + receives ``-bulk_flux[n_R]``). + ``bulk_flux_jacobian_bulk`` has shape ``(4, 6)`` with columns + ``(phi_L, phi_R, log n_L, log p_L, log n_R, log p_R)``. + """ + + phi_trace_left_V: float + phi_trace_right_V: float + state_m3: RealArray + bulk_flux_m2_s: RealArray + cross_flux_m2_s: RealArray + capture_flux_m2_s: RealArray + occupancy: float | None + occupancy_jacobian_bulk: RealArray + bulk_flux_jacobian_bulk: RealArray + normalized_residual: float + evaluations: int + converged: bool + + +@dataclass(frozen=True) +class ChargedTwoSidedInterfaceQSSResult: + """Self-consistent equilibrium-referenced charged two-sided QSS result. + + Shares ONE single constitutive evaluation of the shared trap at the converged + state for both ``capture_flux_m2_s`` and ``incremental_sheet_charge_C_m2``. + All bulk Jacobians use column ordering + ``(phi_L, phi_R, log n_L, log p_L, log n_R, log p_R)``. + """ + + phi_trace_left_V: float + phi_trace_right_V: float + state_m3: RealArray + bulk_flux_m2_s: RealArray + cross_flux_m2_s: RealArray + capture_flux_m2_s: RealArray + occupancy: float + occupancy_jacobian_bulk: RealArray + incremental_sheet_charge_C_m2: float + sheet_charge_jacobian_bulk: RealArray + bulk_flux_jacobian_bulk: RealArray + normalized_electrostatic_residual: float + normalized_carrier_residual: float + evaluations: int + converged: bool + + +def _two_prod(a: float, b: float) -> tuple[float, float]: + """Exact Veltkamp-Dekker error-free product ``p + err == a * b`` in IEEE-754 float64.""" + p = a * b + if not math.isfinite(p) or abs(a) > 1.0e145 or abs(b) > 1.0e145 or abs(p) < 1.0e-290: + return p, 0.0 + split = 134217729.0 # 2**27 + 1 + ca = split * a + a_hi = ca - (ca - a) + a_lo = a - a_hi + cb = split * b + b_hi = cb - (cb - b) + b_lo = b - b_hi + err = ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo + return p, err + + +def _product_difference(a: float, b: float, c: float, d: float) -> float: + """Compensated ``a * b - c * d`` retaining full precision under cancellation.""" + p1, e1 = _two_prod(a, b) + p2, e2 = _two_prod(c, d) + return math.fsum((p1, -p2, e1, -e2)) + + +def _safe_scaled_density(bulk_density: float, shift: float) -> float: + """Evaluate ``bulk_density * exp(shift)`` safely across extreme bias ranges.""" + log_target = math.log(bulk_density) + shift + if log_target >= 700.0: + return math.exp(700.0) + if log_target <= -690.0: + return math.exp(-690.0) + if abs(shift) <= 600.0: + return bulk_density * math.exp(shift) + return math.exp(log_target) + + +def _trace_and_bulk_log_maps(thermal_voltage_V: float) -> tuple[RealArray, RealArray]: + """Chain-rule maps ``∂log(state)/∂phi_t`` (4x2) and ``∂log(state)/∂bulk`` (4x6) at fixed ``u_delta``.""" + inv_vt = 1.0 / float(thermal_voltage_V) + m_trace = np.array( + [ + [inv_vt, 0.0], + [-inv_vt, 0.0], + [0.0, inv_vt], + [0.0, -inv_vt], + ], + dtype=np.float64, + ) + m_bulk = np.array( + [ + [-inv_vt, 0.0, 1.0, 0.0, 0.0, 0.0], + [inv_vt, 0.0, 0.0, 1.0, 0.0, 0.0], + [0.0, -inv_vt, 0.0, 0.0, 1.0, 0.0], + [0.0, inv_vt, 0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float64, + ) + return m_trace, m_bulk + + +def _electrostatic_seed_drops( + geometry: TraceElectrostatics, + bulk: TwoSidedBulkState, +) -> tuple[float, float, float, float, float]: + """Return ``(drop_left_0, drop_right_0, jump_0, phi_seed_l, phi_seed_r)`` without bulk-potential cancellation.""" + c_l = EPS_0 * float(geometry.eps_r_left) / float(geometry.left_distance_m) + c_r = EPS_0 * float(geometry.eps_r_right) / float(geometry.right_distance_m) + jump = float(geometry.potential_jump_right_minus_left_V) + fixed_q = float(geometry.fixed_sheet_charge_C_m2) + delta_bulk = float(bulk.phi_right_V) - float(bulk.phi_left_V) + denom = c_l + c_r + drop_left_0 = (c_r * (delta_bulk - jump) + fixed_q) / denom + drop_right_0 = (c_l * (delta_bulk - jump) - fixed_q) / denom + phi_seed_l = float(bulk.phi_left_V) + drop_left_0 + phi_seed_r = phi_seed_l + jump + return drop_left_0, drop_right_0, jump, phi_seed_l, phi_seed_r + + +def _state_from_u_delta( + u_delta: RealArray, + drop_left_V: float, + drop_right_V: float, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, +) -> RealArray: + """Resolve positive trace densities from incremental quasi-Fermi shifts ``u_delta``.""" + vt = float(physics.thermal_voltage_V) + xi_left = float(drop_left_V) / vt + xi_right = float(drop_right_V) / vt + return np.array( + [ + _safe_scaled_density(float(bulk.n_left_m3), xi_left + float(u_delta[_N_LEFT])), + _safe_scaled_density(float(bulk.p_left_m3), -xi_left + float(u_delta[_P_LEFT])), + _safe_scaled_density(float(bulk.n_right_m3), -xi_right + float(u_delta[_N_RIGHT])), + _safe_scaled_density(float(bulk.p_right_m3), xi_right + float(u_delta[_P_RIGHT])), + ], + dtype=np.float64, + ) + + +def _u_delta_from_log_state( + log_state: RealArray, + drop_left_V: float, + drop_right_V: float, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, +) -> RealArray: + """Map ``log(state_m3)`` to incremental quasi-Fermi shifts ``u_delta``.""" + vt = float(physics.thermal_voltage_V) + xi_left = float(drop_left_V) / vt + xi_right = float(drop_right_V) / vt + return np.array( + [ + float(log_state[_N_LEFT]) - math.log(float(bulk.n_left_m3)) - xi_left, + float(log_state[_P_LEFT]) - math.log(float(bulk.p_left_m3)) + xi_left, + float(log_state[_N_RIGHT]) - math.log(float(bulk.n_right_m3)) + xi_right, + float(log_state[_P_RIGHT]) - math.log(float(bulk.p_right_m3)) - xi_right, + ], + dtype=np.float64, + ) + + +def _bulk_sg_flux_and_derivatives_u( + u_delta: RealArray, + state_m3: RealArray, + drop_left_V: float, + drop_right_V: float, + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, +) -> tuple[RealArray, RealArray, RealArray, RealArray]: + """Half-cell SG particle fluxes and cancellation-free partials in ``(u_delta, phi_t, bulk)``.""" + n_l, p_l, n_r, p_r = (float(v) for v in state_m3) + vt = float(physics.thermal_voltage_V) + xi_left = float(drop_left_V) / vt + xi_right = float(drop_right_V) / vt + pair_l = bernoulli_pair(np.array([xi_left], dtype=np.float64)) + pair_r = bernoulli_pair(np.array([xi_right], dtype=np.float64)) + b_l = float(pair_l.forward[0]) + bm_l = float(pair_l.backward[0]) + db_l = float(pair_l.forward_derivative[0]) + dbm_l = float(pair_l.backward_derivative[0]) + b_r = float(pair_r.forward[0]) + bm_r = float(pair_r.backward[0]) + db_r = float(pair_r.forward_derivative[0]) + dbm_r = float(pair_r.backward_derivative[0]) + + kn_l = float(physics.D_n_left_m2_s) / float(geometry.left_distance_m) + kn_r = float(physics.D_n_right_m2_s) / float(geometry.right_distance_m) + kp_l = float(physics.D_p_left_m2_s) / float(geometry.left_distance_m) + kp_r = float(physics.D_p_right_m2_s) / float(geometry.right_distance_m) + + d_u = np.diag( + [ + -kn_l * b_l * n_l, + -kp_l * bm_l * p_l, + -kn_r * bm_r * n_r, + -kp_r * b_r * p_r, + ] + ) + + u0, u1, u2, u3 = (float(v) for v in u_delta) + log_n_l = math.log(float(bulk.n_left_m3)) + xi_left + u0 + log_p_l = math.log(float(bulk.p_left_m3)) - xi_left + u1 + log_n_r = math.log(float(bulk.n_right_m3)) - xi_right + u2 + log_p_r = math.log(float(bulk.p_right_m3)) + xi_right + u3 + unclipped = ( + -690.0 < log_n_l < 700.0 + and -690.0 < log_p_l < 700.0 + and -690.0 < log_n_r < 700.0 + and -690.0 < log_p_r < 700.0 + ) + + if unclipped and max(abs(xi_left), abs(xi_right), abs(u0), abs(u1), abs(u2), abs(u3)) <= 500.0: + # Exact identity B(x) * exp(x) == B(-x) eliminates both ULP quantization of + # log(n_trace) and two-term Bernoulli subtraction in fluxes and IFT Jacobians. + em0 = math.expm1(u0) + em1 = math.expm1(u1) + em2 = math.expm1(u2) + em3 = math.expm1(u3) + flux = np.array( + [ + -kn_l * bm_l * bulk.n_left_m3 * em0, + -kp_l * b_l * bulk.p_left_m3 * em1, + -kn_r * b_r * bulk.n_right_m3 * em2, + -kp_r * bm_r * bulk.p_right_m3 * em3, + ], + dtype=np.float64, + ) + d_trace_u: RealArray = np.zeros((_STATE_SIZE, 2), dtype=np.float64) + d_trace_u[_N_LEFT, 0] = (kn_l / vt) * dbm_l * bulk.n_left_m3 * em0 + d_trace_u[_P_LEFT, 0] = -(kp_l / vt) * db_l * bulk.p_left_m3 * em1 + d_trace_u[_N_RIGHT, 1] = (kn_r / vt) * db_r * bulk.n_right_m3 * em2 + d_trace_u[_P_RIGHT, 1] = -(kp_r / vt) * dbm_r * bulk.p_right_m3 * em3 + + d_bulk_u: RealArray = np.zeros((_STATE_SIZE, 6), dtype=np.float64) + d_bulk_u[_N_LEFT, 0] = -d_trace_u[_N_LEFT, 0] + d_bulk_u[_P_LEFT, 0] = -d_trace_u[_P_LEFT, 0] + d_bulk_u[_N_RIGHT, 1] = -d_trace_u[_N_RIGHT, 1] + d_bulk_u[_P_RIGHT, 1] = -d_trace_u[_P_RIGHT, 1] + d_bulk_u[_N_LEFT, 2 + _N_LEFT] = flux[_N_LEFT] + d_bulk_u[_P_LEFT, 2 + _P_LEFT] = flux[_P_LEFT] + d_bulk_u[_N_RIGHT, 2 + _N_RIGHT] = flux[_N_RIGHT] + d_bulk_u[_P_RIGHT, 2 + _P_RIGHT] = flux[_P_RIGHT] + return flux, d_u, d_trace_u, d_bulk_u + + small_l = b_l if xi_left >= 0.0 else bm_l + small_r = b_r if xi_right >= 0.0 else bm_r + flux = np.array( + [ + kn_l + * _product_difference( + small_l, + bulk.n_left_m3 - n_l, + -xi_left, + bulk.n_left_m3 if xi_left >= 0.0 else n_l, + ), + kp_l + * _product_difference( + small_l, + bulk.p_left_m3 - p_l, + xi_left, + p_l if xi_left >= 0.0 else bulk.p_left_m3, + ), + kn_r + * _product_difference( + small_r, + bulk.n_right_m3 - n_r, + xi_right, + n_r if xi_right >= 0.0 else bulk.n_right_m3, + ), + kp_r + * _product_difference( + small_r, + bulk.p_right_m3 - p_r, + -xi_right, + bulk.p_right_m3 if xi_right >= 0.0 else p_r, + ), + ], + dtype=np.float64, + ) + d_trace: RealArray = np.zeros((_STATE_SIZE, 2), dtype=np.float64) + d_trace[_N_LEFT, 0] = (kn_l / vt) * (-dbm_l * bulk.n_left_m3 - db_l * n_l) + d_trace[_P_LEFT, 0] = (kp_l / vt) * (db_l * bulk.p_left_m3 + dbm_l * p_l) + d_trace[_N_RIGHT, 1] = -(kn_r / vt) * (db_r * bulk.n_right_m3 + dbm_r * n_r) + d_trace[_P_RIGHT, 1] = (kp_r / vt) * (dbm_r * bulk.p_right_m3 + db_r * p_r) + + d_bulk: RealArray = np.zeros((_STATE_SIZE, 6), dtype=np.float64) + d_bulk[_N_LEFT, 0] = -d_trace[_N_LEFT, 0] + d_bulk[_P_LEFT, 0] = -d_trace[_P_LEFT, 0] + d_bulk[_N_RIGHT, 1] = -d_trace[_N_RIGHT, 1] + d_bulk[_P_RIGHT, 1] = -d_trace[_P_RIGHT, 1] + d_bulk[_N_LEFT, 2 + _N_LEFT] = kn_l * bm_l * bulk.n_left_m3 + d_bulk[_P_LEFT, 2 + _P_LEFT] = kp_l * b_l * bulk.p_left_m3 + d_bulk[_N_RIGHT, 2 + _N_RIGHT] = kn_r * b_r * bulk.n_right_m3 + d_bulk[_P_RIGHT, 2 + _P_RIGHT] = kp_r * bm_r * bulk.p_right_m3 + m_trace, m_bulk = _trace_and_bulk_log_maps(vt) + return flux, d_u, d_trace + d_u @ m_trace, d_bulk + d_u @ m_bulk + + +def _evaluate_trap_for_two_sided( + state_m3: RealArray, + physics: TwoSidedInterfacePhysics, + charge: EquilibriumReferencedSheetCharge | None = None, +) -> SharedInterfaceTrapEvaluation | None: + vn = float(physics.surface_recombination_velocity_n_m_s) + vp = float(physics.surface_recombination_velocity_p_m_s) + if vn == 0.0 and vp == 0.0: + if charge is not None: + raise ValueError("charged two-sided interface requires positive capture velocity") + return None + return evaluate_shared_interface_trap( + float(state_m3[_N_LEFT]), + float(state_m3[_P_LEFT]), + float(state_m3[_N_RIGHT]), + float(state_m3[_P_RIGHT]), + v_n_left_m_s=vn, + v_p_left_m_s=vp, + v_n_right_m_s=vn, + v_p_right_m_s=vp, + n1_left_m3=physics.n1_left_m3, + p1_left_m3=physics.p1_left_m3, + n1_right_m3=physics.n1_right_m3, + p1_right_m3=physics.p1_right_m3, + areal_density_m2=0.0 if charge is None else charge.trap_density_m2, + equilibrium_occupancy=None if charge is None else charge.equilibrium_occupancy, + ) + + +def _carrier_balance_terms( + u_delta: RealArray, + drop_left_V: float, + drop_right_V: float, + potential_jump_V: float, + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + charge: EquilibriumReferencedSheetCharge | None = None, +) -> tuple[ + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + SharedInterfaceTrapEvaluation | None, +]: + state = _state_from_u_delta(u_delta, drop_left_V, drop_right_V, physics, bulk) + bulk_flux, d_bulk_u, d_bulk_trace_u, d_bulk_coords_u = _bulk_sg_flux_and_derivatives_u( + u_delta, state, drop_left_V, drop_right_V, geometry, physics, bulk + ) + vt_local = float(physics.thermal_voltage_V) + xi_l = float(drop_left_V) / vt_local + xi_r_from_bulk = -float(drop_right_V) / vt_local + base_log_to_dos = np.array( + [ + math.log(float(bulk.n_left_m3) / float(physics.N_C_left_m3)) + xi_l, + math.log(float(bulk.p_left_m3) / float(physics.N_V_left_m3)) - xi_l, + math.log(float(bulk.n_right_m3) / float(physics.N_C_right_m3)) + xi_r_from_bulk, + math.log(float(bulk.p_right_m3) / float(physics.N_V_right_m3)) - xi_r_from_bulk, + ], + dtype=np.float64, + ) + cross_eval = fermi_dirac_richardson_flux( + state, + phi_trace_left_V=0.0, + phi_trace_right_V=float(potential_jump_V), + conduction_band_step_eV=physics.conduction_band_step_eV, + hole_transport_step_eV=physics.hole_transport_step_eV, + N_C_left_m3=physics.N_C_left_m3, + N_C_right_m3=physics.N_C_right_m3, + N_V_left_m3=physics.N_V_left_m3, + N_V_right_m3=physics.N_V_right_m3, + richardson_n_A_m2_K2=physics.richardson_n_A_m2_K2, + richardson_p_A_m2_K2=physics.richardson_p_A_m2_K2, + temperature_K=physics.temperature_K, + thermal_voltage_V=physics.thermal_voltage_V, + transmission=physics.transmission, + base_log_to_dos=base_log_to_dos, + u_delta=u_delta, + electrochemical_steps=( + bulk.electron_electrochemical_step, + bulk.hole_electrochemical_step, + ), + ) + trap = _evaluate_trap_for_two_sided(state, physics, charge) + if trap is None: + capture: RealArray = np.zeros(_STATE_SIZE, dtype=np.float64) + d_cap_log: RealArray = np.zeros((_STATE_SIZE, _STATE_SIZE), dtype=np.float64) + else: + capture = trap.capture_rates_m2_s + d_cap_log = trap.d_capture_d_densities_m_s * state[np.newaxis, :] + + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + cross = cross_eval.cross_flux_m2_s + residual = np.array( + [ + bulk_flux[_N_LEFT] - cross[0] - capture[_N_LEFT], + bulk_flux[_P_LEFT] - cross[1] - capture[_P_LEFT], + bulk_flux[_N_RIGHT] + cross[0] - capture[_N_RIGHT], + bulk_flux[_P_RIGHT] + cross[1] - capture[_P_RIGHT], + ], + dtype=np.float64, + ) + j_u = d_bulk_u - d_cap_log + j_u[_N_LEFT, :] -= cross_eval.d_cross_d_log_state_m2_s[0, :] + j_u[_P_LEFT, :] -= cross_eval.d_cross_d_log_state_m2_s[1, :] + j_u[_N_RIGHT, :] += cross_eval.d_cross_d_log_state_m2_s[0, :] + j_u[_P_RIGHT, :] += cross_eval.d_cross_d_log_state_m2_s[1, :] + + d_cross_trace_u = ( + cross_eval.d_cross_d_trace_potentials_m2_s_V + + cross_eval.d_cross_d_log_state_m2_s @ m_trace + ) + j_trace_u = d_bulk_trace_u - d_cap_log @ m_trace + j_trace_u[_N_LEFT, :] -= d_cross_trace_u[0, :] + j_trace_u[_P_LEFT, :] -= d_cross_trace_u[1, :] + j_trace_u[_N_RIGHT, :] += d_cross_trace_u[0, :] + j_trace_u[_P_RIGHT, :] += d_cross_trace_u[1, :] + + d_cross_bulk_u = cross_eval.d_cross_d_log_state_m2_s @ m_bulk + j_coords_u = d_bulk_coords_u - d_cap_log @ m_bulk + j_coords_u[_N_LEFT, :] -= d_cross_bulk_u[0, :] + j_coords_u[_P_LEFT, :] -= d_cross_bulk_u[1, :] + j_coords_u[_N_RIGHT, :] += d_cross_bulk_u[0, :] + j_coords_u[_P_RIGHT, :] += d_cross_bulk_u[1, :] + + return ( + state, + bulk_flux, + cross, + capture, + residual, + j_u, + j_trace_u, + j_coords_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + cross_eval.one_way_scale_m2_s, + trap, + ) + + +def _equilibrated_solve(matrix: RealArray, rhs: RealArray) -> RealArray: + """Column-equilibrated dense linear solve preserving accuracy across 30+ decades.""" + col_scale = np.max(np.abs(matrix), axis=0) + col_scale = np.where(col_scale > 0.0, col_scale, 1.0) + scaled_sol = np.linalg.solve(matrix / col_scale[np.newaxis, :], rhs) + if rhs.ndim == 1: + return scaled_sol / col_scale + return scaled_sol / col_scale[:, np.newaxis] + + +def _zero_bulk_flux_seed( + drop_left_V: float, + drop_right_V: float, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, +) -> RealArray: + return _state_from_u_delta( + np.zeros(_STATE_SIZE, dtype=np.float64), + drop_left_V, + drop_right_V, + physics, + bulk, + ) + + +def solve_two_sided_interface_qss( + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + *, + initial_state_m3: ArrayLike | None = None, + residual_tolerance: float = 1.0e-9, + max_evaluations: int = 200, + fail_on_residual: bool = True, +) -> TwoSidedInterfaceQSSResult: + """Eliminate charge-off two-sided electrostatic and carrier traces with exact IFT.""" + _positive(residual_tolerance, "residual_tolerance") + if int(max_evaluations) <= 0: + raise ValueError("max_evaluations must be positive") + + phi_t_l, phi_t_r = solve_electrostatic_traces( + geometry, bulk.phi_left_V, bulk.phi_right_V + ) + drop_l_0, drop_r_0, jump_0, _, _ = _electrostatic_seed_drops(geometry, bulk) + zero_flux_seed = _zero_bulk_flux_seed(drop_l_0, drop_r_0, physics, bulk) + u_seed_raw: RealArray + if initial_state_m3 is None: + seed = zero_flux_seed + u_seed_raw = np.zeros(_STATE_SIZE, dtype=np.float64) + else: + seed = np.asarray(initial_state_m3, dtype=np.float64) + if seed.shape != (_STATE_SIZE,) or not np.all(np.isfinite(seed)) or np.any(seed <= 0.0): + raise ValueError("initial_state_m3 must contain four positive finite densities") + u_seed_raw = _u_delta_from_log_state(np.log(seed), drop_l_0, drop_r_0, physics, bulk) + + density_ref = max( + float(np.max(seed)), + float(np.max(zero_flux_seed)), + physics.N_C_left_m3, + physics.N_C_right_m3, + physics.N_V_left_m3, + physics.N_V_right_m3, + physics.n1_left_m3, + physics.n1_right_m3, + physics.p1_left_m3, + physics.p1_right_m3, + 1.0, + ) + vt = float(physics.thermal_voltage_V) + xi_left = drop_l_0 / vt + xi_right = drop_r_0 / vt + base_log = np.array( + [ + math.log(float(bulk.n_left_m3)) + xi_left, + math.log(float(bulk.p_left_m3)) - xi_left, + math.log(float(bulk.n_right_m3)) - xi_right, + math.log(float(bulk.p_right_m3)) + xi_right, + ], + dtype=np.float64, + ) + log_lower = math.log(1.0e-100) + log_upper = math.log(density_ref) + math.log(1.0e12) + u_lower = np.maximum(log_lower - base_log, -490.0) + u_upper = np.minimum(log_upper - base_log, 490.0) + u_upper = np.maximum(u_upper, u_lower + 2.0) + u_seed = np.clip(u_seed_raw, u_lower + 0.5, u_upper - 0.5) + + ( + _, + seed_bulk_flux, + _, + seed_cap, + _, + _, + _, + _, + seed_d_bulk_u, + _, + _, + seed_one_way, + _, + ) = _carrier_balance_terms(u_seed, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk) + + e_scale = max( + abs(float(seed_bulk_flux[_N_LEFT])), + abs(float(seed_bulk_flux[_N_RIGHT])), + abs(float(seed_d_bulk_u[_N_LEFT, _N_LEFT])), + abs(float(seed_d_bulk_u[_N_RIGHT, _N_RIGHT])), + abs(float(seed_cap[_N_LEFT])), + abs(float(seed_cap[_N_RIGHT])), + float(seed_one_way[0]), + 1.0, + ) + h_scale = max( + abs(float(seed_bulk_flux[_P_LEFT])), + abs(float(seed_bulk_flux[_P_RIGHT])), + abs(float(seed_d_bulk_u[_P_LEFT, _P_LEFT])), + abs(float(seed_d_bulk_u[_P_RIGHT, _P_RIGHT])), + abs(float(seed_cap[_P_LEFT])), + abs(float(seed_cap[_P_RIGHT])), + float(seed_one_way[1]), + 1.0, + ) + row_scale = np.array([e_scale, h_scale, e_scale, h_scale], dtype=np.float64) + + def scaled_res(u_vec: RealArray) -> RealArray: + terms = _carrier_balance_terms(u_vec, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk) + return terms[4] / row_scale + + def scaled_jac(u_vec: RealArray) -> RealArray: + terms = _carrier_balance_terms(u_vec, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk) + return terms[5] / row_scale[:, np.newaxis] + + sol = least_squares( + scaled_res, + u_seed, + jac=scaled_jac, + bounds=(u_lower, u_upper), + x_scale="jac", + ftol=3.0e-16, + xtol=3.0e-16, + gtol=3.0e-16, + max_nfev=int(max_evaluations), + ) + x_best = sol.x.copy() + eval_count = int(sol.nfev) + + # Polish to machine precision with per-row equilibrated Newton steps. + best_terms = _carrier_balance_terms(x_best, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk) + for _ in range(6): + p_row = np.maximum(np.max(np.abs(best_terms[5]), axis=1), 1.0) + p_norm = float(np.max(np.abs(best_terms[4] / p_row))) + if p_norm <= 1.0e-16: + break + try: + delta = -_equilibrated_solve( + best_terms[5] / p_row[:, np.newaxis], + best_terms[4] / p_row, + ) + except np.linalg.LinAlgError: + break + if not np.all(np.isfinite(delta)): + break + cand = np.clip(x_best + delta, u_lower, u_upper) + cand_terms = _carrier_balance_terms(cand, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk) + eval_count += 1 + cand_norm = float(np.max(np.abs(cand_terms[4] / p_row))) + if cand_norm < p_norm or float(np.max(np.abs(delta))) <= 1.0e-15: + x_best = cand + best_terms = cand_terms + if float(np.max(np.abs(delta))) <= 1.0e-15: + break + else: + break + best_norm = float(np.max(np.abs(best_terms[4] / row_scale))) + + ( + state, + bulk_flux, + cross_flux, + capture_flux, + _, + j_u, + j_trace_u, + j_coords_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + _, + trap, + ) = best_terms + + w_l, w_r = sheet_charge_row_weights( + geometry.eps_r_left, + geometry.left_distance_m, + geometry.eps_r_right, + geometry.right_distance_m, + ) + d_trace_d_bulk: RealArray = np.zeros((2, 6), dtype=np.float64) + d_trace_d_bulk[0, 0] = w_l + d_trace_d_bulk[0, 1] = w_r + d_trace_d_bulk[1, 0] = w_l + d_trace_d_bulk[1, 1] = w_r + + j_bulk_total_u = j_coords_u + j_trace_u @ d_trace_d_bulk + ift_row = np.maximum(np.max(np.abs(j_u), axis=1), float(np.finfo(np.float64).tiny)) + du_d_bulk = _equilibrated_solve( + j_u / ift_row[:, np.newaxis], + -(j_bulk_total_u / ift_row[:, np.newaxis]), + ) + bulk_flux_jac = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk + + if trap is None: + occupancy: float | None = None + occ_jac: RealArray = np.zeros(6, dtype=np.float64) + else: + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + d_log_state_d_bulk = m_bulk + m_trace @ d_trace_d_bulk + du_d_bulk + occupancy = trap.occupancy + df_dlog = trap.d_occupancy_d_densities_m3 * state + occ_jac = df_dlog @ d_log_state_d_bulk + + converged = bool( + (sol.success or best_norm <= residual_tolerance) + and best_norm <= residual_tolerance + and np.all(np.isfinite(du_d_bulk)) + and np.all(np.isfinite(bulk_flux_jac)) + ) + if fail_on_residual and not converged: + raise RuntimeError( + f"two-sided interface QSS did not certify: residual={best_norm:.6g}" + ) + return TwoSidedInterfaceQSSResult( + phi_trace_left_V=phi_t_l, + phi_trace_right_V=phi_t_r, + state_m3=state, + bulk_flux_m2_s=bulk_flux, + cross_flux_m2_s=cross_flux, + capture_flux_m2_s=capture_flux, + occupancy=occupancy, + occupancy_jacobian_bulk=occ_jac, + bulk_flux_jacobian_bulk=bulk_flux_jac, + normalized_residual=best_norm, + evaluations=eval_count, + converged=converged, + ) + + +def _charged_balance_terms( + local_coords_u: RealArray, + drop_l_0: float, + drop_r_0: float, + jump_0: float, + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + charge: EquilibriumReferencedSheetCharge, +) -> tuple[ + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + SharedInterfaceTrapEvaluation, +]: + s_l = float(local_coords_u[0]) + s_r = float(local_coords_u[1]) + u_delta = local_coords_u[2:] + + drop_l = drop_l_0 + s_l + drop_r = drop_r_0 - s_r + pot_jump = jump_0 + (s_r - s_l) + + ( + state, + bulk_flux, + cross_flux, + capture_flux, + carrier_res, + j_carrier_u, + j_carrier_trace_u, + j_carrier_coords_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + one_way_scale, + trap, + ) = _carrier_balance_terms( + u_delta, drop_l, drop_r, pot_jump, geometry, physics, bulk, charge + ) + assert trap is not None + + c_l = EPS_0 * float(geometry.eps_r_left) / float(geometry.left_distance_m) + c_r = EPS_0 * float(geometry.eps_r_right) / float(geometry.right_distance_m) + elec_res = np.array( + [ + s_r - s_l, + c_l * s_l + c_r * s_r - trap.incremental_sheet_charge_C_m2, + ], + dtype=np.float64, + ) + elec_jac_trace = np.array([[-1.0, 1.0], [c_l, c_r]], dtype=np.float64) + + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + d_sheet_d_log = trap.d_sheet_charge_d_densities_C_m * state + + residual = np.concatenate((elec_res, carrier_res)) + j_local_u: RealArray = np.zeros((6, 6), dtype=np.float64) + j_local_u[:2, :2] = elec_jac_trace + j_local_u[1, :2] -= d_sheet_d_log @ m_trace + j_local_u[1, 2:] = -d_sheet_d_log + j_local_u[2:, :2] = j_carrier_trace_u + j_local_u[2:, 2:] = j_carrier_u + + j_bulk_u: RealArray = np.zeros((6, 6), dtype=np.float64) + j_bulk_u[1, 0] = -c_l + j_bulk_u[1, 1] = -c_r + j_bulk_u[1, :] -= d_sheet_d_log @ m_bulk + j_bulk_u[2:, :] = j_carrier_coords_u + + return ( + state, + bulk_flux, + cross_flux, + capture_flux, + residual, + j_local_u, + j_bulk_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + one_way_scale, + trap, + ) + + +def solve_charged_two_sided_interface_qss( + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + charge: EquilibriumReferencedSheetCharge, + *, + initial_coordinates: ArrayLike | None = None, + residual_tolerance: float = 1.0e-9, + max_evaluations: int = 300, + fail_on_residual: bool = True, +) -> ChargedTwoSidedInterfaceQSSResult: + """Solve coupled 6x6 equilibrium-referenced charged two-sided QSS + exact IFT.""" + _positive(residual_tolerance, "residual_tolerance") + if int(max_evaluations) <= 0: + raise ValueError("max_evaluations must be positive") + + phi_seed_l, phi_seed_r = solve_electrostatic_traces( + geometry, bulk.phi_left_V, bulk.phi_right_V + ) + drop_l_0, drop_r_0, jump_0, _, _ = _electrostatic_seed_drops(geometry, bulk) + c_l = EPS_0 * float(geometry.eps_r_left) / float(geometry.left_distance_m) + c_r = EPS_0 * float(geometry.eps_r_right) / float(geometry.right_distance_m) + phi_margin = Q * float(charge.trap_density_m2) / (c_l + c_r) + max( + 20.0 * float(physics.thermal_voltage_V), 2.0 + ) + u_bound = 480.0 + lower = np.array( + [ + -phi_margin, + -phi_margin, + -u_bound, + -u_bound, + -u_bound, + -u_bound, + ], + dtype=np.float64, + ) + upper = np.array( + [ + phi_margin, + phi_margin, + u_bound, + u_bound, + u_bound, + u_bound, + ], + dtype=np.float64, + ) + + if initial_coordinates is None: + state_seed = solve_two_sided_interface_qss( + geometry, + physics, + bulk, + residual_tolerance=max(residual_tolerance, 1.0e-9), + max_evaluations=max_evaluations, + ).state_m3 + u_seed = _u_delta_from_log_state( + np.log(state_seed), drop_l_0, drop_r_0, physics, bulk + ) + coords = np.concatenate( + ( + np.zeros(2, dtype=np.float64), + np.clip(u_seed, -u_bound + 1.0, u_bound - 1.0), + ) + ) + else: + raw_coords = np.asarray(initial_coordinates, dtype=np.float64) + if raw_coords.shape != (6,) or not np.all(np.isfinite(raw_coords)): + raise ValueError("initial_coordinates must contain 6 finite values") + s_l_init = float(raw_coords[0]) - phi_seed_l + s_r_init = float(raw_coords[1]) - phi_seed_r + u_seed = _u_delta_from_log_state( + raw_coords[2:], drop_l_0 + s_l_init, drop_r_0 - s_r_init, physics, bulk + ) + coords = np.concatenate( + ( + np.clip(np.array([s_l_init, s_r_init], dtype=np.float64), lower[:2] + 1.0e-6, upper[:2] - 1.0e-6), + np.clip(u_seed, -u_bound + 1.0, u_bound - 1.0), + ) + ) + + seed_terms = _charged_balance_terms(coords, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk, charge) + seed_bulk_flux = seed_terms[1] + seed_cap = seed_terms[3] + seed_d_bulk_u = seed_terms[7] + seed_one_way = seed_terms[10] + + e_scale = max( + abs(float(seed_bulk_flux[_N_LEFT])), + abs(float(seed_bulk_flux[_N_RIGHT])), + abs(float(seed_d_bulk_u[_N_LEFT, _N_LEFT])), + abs(float(seed_d_bulk_u[_N_RIGHT, _N_RIGHT])), + abs(float(seed_cap[_N_LEFT])), + abs(float(seed_cap[_N_RIGHT])), + float(seed_one_way[0]), + 1.0, + ) + h_scale = max( + abs(float(seed_bulk_flux[_P_LEFT])), + abs(float(seed_bulk_flux[_P_RIGHT])), + abs(float(seed_d_bulk_u[_P_LEFT, _P_LEFT])), + abs(float(seed_d_bulk_u[_P_RIGHT, _P_RIGHT])), + abs(float(seed_cap[_P_LEFT])), + abs(float(seed_cap[_P_RIGHT])), + float(seed_one_way[1]), + 1.0, + ) + cap_scale = (c_l + c_r) * float(physics.thermal_voltage_V) + gauss_scale = max( + cap_scale, + abs(float(geometry.fixed_sheet_charge_C_m2)), + Q * float(charge.trap_density_m2), + float(np.finfo(np.float64).tiny), + ) + row_scale = np.array( + [physics.thermal_voltage_V, gauss_scale, e_scale, h_scale, e_scale, h_scale], + dtype=np.float64, + ) + + def scaled_res(y_loc: RealArray) -> RealArray: + return _charged_balance_terms(y_loc, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk, charge)[4] / row_scale + + def scaled_jac(y_loc: RealArray) -> RealArray: + return ( + _charged_balance_terms(y_loc, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk, charge)[5] + / row_scale[:, np.newaxis] + ) + + sol = least_squares( + scaled_res, + coords, + jac=scaled_jac, + bounds=(lower, upper), + x_scale="jac", + ftol=3.0e-16, + xtol=3.0e-16, + gtol=3.0e-16, + max_nfev=int(max_evaluations), + ) + y_best = sol.x.copy() + eval_count = int(sol.nfev) + + # Polish coupled 6x6 system to full binary64 precision using per-row Jacobian scaling. + best_terms = _charged_balance_terms(y_best, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk, charge) + vt_coord = np.array( + [physics.thermal_voltage_V, physics.thermal_voltage_V, 1.0, 1.0, 1.0, 1.0], + dtype=np.float64, + ) + for _ in range(8): + p_row = np.maximum(np.max(np.abs(best_terms[5]), axis=1), float(np.finfo(np.float64).tiny)) + p_norm = float(np.max(np.abs(best_terms[4] / p_row))) + if p_norm <= 1.0e-16: + break + try: + delta = -_equilibrated_solve( + best_terms[5] / p_row[:, np.newaxis], + best_terms[4] / p_row, + ) + except np.linalg.LinAlgError: + break + if not np.all(np.isfinite(delta)): + break + step_norm = float(np.max(np.abs(delta / vt_coord))) + cand = np.clip(y_best + delta, lower, upper) + cand_terms = _charged_balance_terms(cand, drop_l_0, drop_r_0, jump_0, geometry, physics, bulk, charge) + eval_count += 1 + cand_norm = float(np.max(np.abs(cand_terms[4] / p_row))) + if cand_norm < p_norm or step_norm <= 1.0e-13: + y_best = cand + best_terms = cand_terms + if step_norm <= 1.0e-15: + break + else: + break + + ( + state, + bulk_flux, + cross_flux, + capture_flux, + residual, + j_local_u, + j_bulk_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + _, + trap, + ) = best_terms + + norm_vec = np.abs(residual / row_scale) + norm_elec = float(np.max(norm_vec[:2])) + norm_carrier = float(np.max(norm_vec[2:])) + + ift_row = np.maximum(np.max(np.abs(j_local_u), axis=1), float(np.finfo(np.float64).tiny)) + sensitivity_u = _equilibrated_solve( + j_local_u / ift_row[:, np.newaxis], + -(j_bulk_u / ift_row[:, np.newaxis]), + ) + d_phi_t_d_bulk = sensitivity_u[:2, :] + d_u_d_bulk = sensitivity_u[2:, :] + bulk_flux_jac = ( + d_bulk_coords_u + + d_bulk_trace_u @ d_phi_t_d_bulk + + d_bulk_u @ d_u_d_bulk + ) + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + d_log_state_d_bulk = m_bulk + m_trace @ d_phi_t_d_bulk + d_u_d_bulk + d_sheet_d_log = trap.d_sheet_charge_d_densities_C_m * state + sheet_jac_bulk = d_sheet_d_log @ d_log_state_d_bulk + d_occ_d_log = trap.d_occupancy_d_densities_m3 * state + occ_jac_bulk = d_occ_d_log @ d_log_state_d_bulk + + converged = bool( + (sol.success or max(norm_elec, norm_carrier) <= residual_tolerance) + and max(norm_elec, norm_carrier) <= residual_tolerance + and np.all(np.isfinite(sensitivity_u)) + and np.all(np.isfinite(bulk_flux_jac)) + and np.all(np.isfinite(sheet_jac_bulk)) + ) + if fail_on_residual and not converged: + raise RuntimeError( + "charged two-sided interface QSS did not certify: " + f"electrostatic={norm_elec:.6g}, carrier={norm_carrier:.6g}" + ) + + return ChargedTwoSidedInterfaceQSSResult( + phi_trace_left_V=float(phi_seed_l + y_best[0]), + phi_trace_right_V=float(phi_seed_r + y_best[1]), + state_m3=state, + bulk_flux_m2_s=bulk_flux, + cross_flux_m2_s=cross_flux, + capture_flux_m2_s=capture_flux, + occupancy=trap.occupancy, + occupancy_jacobian_bulk=occ_jac_bulk, + incremental_sheet_charge_C_m2=trap.incremental_sheet_charge_C_m2, + sheet_charge_jacobian_bulk=sheet_jac_bulk, + bulk_flux_jacobian_bulk=bulk_flux_jac, + normalized_electrostatic_residual=norm_elec, + normalized_carrier_residual=norm_carrier, + evaluations=eval_count, + converged=converged, + ) diff --git a/src/solarlab/physics/recombination/__init__.py b/src/solarlab/physics/recombination/__init__.py index edc5c3d0..8f1890a0 100644 --- a/src/solarlab/physics/recombination/__init__.py +++ b/src/solarlab/physics/recombination/__init__.py @@ -1,10 +1,10 @@ -"""Bulk recombination constitutive laws (P04-07, values, tangents and DC). +"""Bulk and heterointerface recombination constitutive laws (P04-07, P04-09). Maxwell-Boltzmann lifetime SRH, radiative and Auger recombination; the DEF-1 explicit neutral SRH inventory and its node ownership; position-dependent -trap profiles; and the energy-resolved bulk-trap closure. Interface SRH -belongs to the interface-transport slice and dynamic, multivalent and -metastable defect closures to the defect slice; neither is provided here. +trap profiles; the energy-resolved bulk-trap closure; and electrical +heterointerface SRH, plane closure, and static sheet-charge closure. Dynamic, +multivalent and metastable defect closures belong to the defect slice. """ from solarlab.physics.recombination.bulk import ( @@ -33,6 +33,24 @@ compile_neutral_defect_species, evaluate_neutral_explicit_defects, ) +from solarlab.physics.recombination.interface import ( + CrossCarrierCellPairEvaluation, + InterfaceDefectReferences, + InterfaceDefectSpec, + InterfaceSRHRate, + PlaneClosureParams, + PlaneClosureResult, + S_SUPPLY_M_S, + SharedInterfaceTrapEvaluation, + TwoDimensionalInterfaceSRHMode, + build_plane_closure_params, + equilibrium_referenced_sheet_charge, + evaluate_cross_carrier_cell_pair_srh, + evaluate_shared_interface_trap, + interface_srh_rate, + resolve_interface_defect_references, + solve_plane_closure, +) from solarlab.physics.recombination.reaction import ( BulkRecombinationCoefficients, BulkRecombinationEvaluation, @@ -56,27 +74,43 @@ "BulkTrapQuadrature", "BulkTrapState", "CarrierSources", + "CrossCarrierCellPairEvaluation", + "InterfaceDefectReferences", + "InterfaceDefectSpec", + "InterfaceSRHRate", "NeutralDefectSpecies", "NeutralExplicitDefectEvaluation", "NeutralExplicitDefectModel", + "PlaneClosureParams", + "PlaneClosureResult", "RecombinationDomainError", "RecombinationRate", + "S_SUPPLY_M_S", + "SharedInterfaceTrapEvaluation", "TrapAwareNeutrality", "TrapProfile", "TrapProfileBinding", + "TwoDimensionalInterfaceSRHMode", "auger_recombination", "build_bulk_trap_quadrature", + "build_plane_closure_params", "bulk_trap_distribution_from_mapping", "compile_neutral_defect_species", + "equilibrium_referenced_sheet_charge", "evaluate_bulk_trap_state", + "evaluate_cross_carrier_cell_pair_srh", "evaluate_neutral_explicit_defects", + "evaluate_shared_interface_trap", "exponential_edge_profile", "gaussian_edge_profile", + "interface_srh_rate", "lifetime_srh_denominator", "lifetime_srh_from_denominator", "lifetime_srh_recombination", "radiative_recombination", + "resolve_interface_defect_references", "solve_bulk_trap_charge_neutrality", + "solve_plane_closure", "sum_recombination_rates", "tau_from_trap_density", ] diff --git a/src/solarlab/physics/recombination/interface.py b/src/solarlab/physics/recombination/interface.py new file mode 100644 index 00000000..732d8503 --- /dev/null +++ b/src/solarlab/physics/recombination/interface.py @@ -0,0 +1,773 @@ +"""Heterointerface recombination and static sheet-charge constitutive laws (P04-09). + +All rates returned here are areal particle rates in ``m^-2 s^-1`` (never +pre-divided by cell width ``dx`` or ``dy``), and all interface sheet charges +are areal charge densities in ``C m^-2``. Deposition onto control volumes or +Gauss jump rows belongs exclusively to geometry and the unified Assembler. + +Provided laws: + +* :func:`interface_srh_rate` -- single-plane or cross-carrier Shockley-Read-Hall + rate ``v_n v_p (n p - n_i^2) / (v_n (n + n_1) + v_p (p + p_1))`` with + cancellation-free analytical density derivatives (real and complex-step). +* :func:`resolve_interface_defect_references` -- physical band-aligned single-level + interface defect emission densities ``(n_1, p_1)`` on the reference side and + across both sides of a two-sided heterointerface. +* :func:`evaluate_shared_interface_trap` -- single-evaluation two-sided shared + trap occupancy ``f``, side-resolved capture rates ``(C_{n,L}, C_{p,L}, + C_{n,R}, C_{p,R})`` obeying ``C_{n,L} + C_{n,R} == C_{p,L} + C_{p,R}``, and + optional equilibrium-referenced sheet charge ``Delta sigma = -q N_t (f - f_ref)`` + with complete analytical derivatives. +* :func:`solve_plane_closure` -- local 2x2 carrier-plane QSS closure with exact + implicit-function-theorem derivatives wrt projected adjacent densities. +* :class:`TwoDimensionalInterfaceSRHMode` and + :func:`evaluate_cross_carrier_cell_pair_srh` -- explicit constitutive contract + for the 2D cross-row cell-pair SRH channel (retaining ``interface_two_sided`` + for 2D while 1D additive mirror channels remain refused). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +import math +from typing import Literal, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C + +__all__ = [ + "CrossCarrierCellPairEvaluation", + "InterfaceDefectReferences", + "InterfaceDefectSpec", + "InterfaceSRHRate", + "PlaneClosureParams", + "PlaneClosureResult", + "S_SUPPLY_M_S", + "SharedInterfaceTrapEvaluation", + "TwoDimensionalInterfaceSRHMode", + "build_plane_closure_params", + "equilibrium_referenced_sheet_charge", + "evaluate_cross_carrier_cell_pair_srh", + "evaluate_shared_interface_trap", + "interface_srh_rate", + "resolve_interface_defect_references", + "solve_plane_closure", +] + +Q = ELEMENTARY_CHARGE_C +S_SUPPLY_M_S: float = 2.5e4 +_DENOM_FLOOR: float = 1.0e-300 +_EXP_CLIP: float = 500.0 +_QSS_MAX_ITER: int = 40 +_QSS_TOL: float = 1.0e-13 +_QSS_STEP_TOL: float = 1.0e-14 +_QSS_DENSITY_FLOOR: float = 1.0e-30 +_QSS_LOG_STEP_CLIP: float = 30.0 + +NumericArray: TypeAlias = NDArray[np.float64] | NDArray[np.complex128] +RealArray: TypeAlias = NDArray[np.float64] +EnergyReference: TypeAlias = Literal["below_conduction_band", "above_valence_band"] + + +def _finite_real(value: float, name: str) -> float: + scalar = float(value) + if not math.isfinite(scalar): + raise ValueError(f"{name} must be finite") + return scalar + + +def _finite_nonnegative(value: float, name: str) -> float: + scalar = float(value) + if not math.isfinite(scalar) or scalar < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + return scalar + + +def _finite_positive(value: float, name: str) -> float: + scalar = float(value) + if not math.isfinite(scalar) or scalar <= 0.0: + raise ValueError(f"{name} must be finite and positive") + return scalar + + +def _boltzmann_emission_density(dos_m3: float, delta_eV: float, vt_V: float) -> float: + dos = _finite_positive(dos_m3, "dos_m3") + vt = _finite_positive(vt_V, "thermal_voltage_V") + exponent = max(-_EXP_CLIP, min(_EXP_CLIP, -float(delta_eV) / vt)) + return float(dos * math.exp(exponent)) + + +@dataclass(frozen=True) +class InterfaceSRHRate: + """Areal interface SRH rate [m^-2 s^-1] and its carrier-density partials [m/s].""" + + rate_m2_s: NumericArray + d_rate_dn_m_s: NumericArray + d_rate_dp_m_s: NumericArray + + +def interface_srh_rate( + n_m3: ArrayLike, + p_m3: ArrayLike, + *, + v_n_m_s: ArrayLike, + v_p_m_s: ArrayLike, + ni_sq_m6: ArrayLike, + n1_m3: ArrayLike, + p1_m3: ArrayLike, + clamp_nonnegative: bool = False, +) -> InterfaceSRHRate: + """Evaluate areal Shockley-Read-Hall interface recombination [m^-2 s^-1]. + + Supports scalar or array inputs and both real ``float64`` and complex-step + ``complex128`` carrier densities. The density derivatives use the exact + positive-numerator quotient form so no catastrophic cancellation occurs near + thermal equilibrium ``n p == n_i^2``. + """ + raw_n = np.asarray(n_m3) + raw_p = np.asarray(p_m3) + is_complex = np.iscomplexobj(raw_n) or np.iscomplexobj(raw_p) + dtype = np.complex128 if is_complex else np.float64 + + n_arr, p_arr = np.broadcast_arrays( + np.asarray(raw_n, dtype=dtype), + np.asarray(raw_p, dtype=dtype), + ) + vn = np.broadcast_to(np.asarray(v_n_m_s, dtype=np.float64), n_arr.shape) + vp = np.broadcast_to(np.asarray(v_p_m_s, dtype=np.float64), n_arr.shape) + ni_sq = np.broadcast_to(np.asarray(ni_sq_m6, dtype=np.float64), n_arr.shape) + n1 = np.broadcast_to(np.asarray(n1_m3, dtype=np.float64), n_arr.shape) + p1 = np.broadcast_to(np.asarray(p1_m3, dtype=np.float64), n_arr.shape) + + for name, arr in ( + ("v_n_m_s", vn), + ("v_p_m_s", vp), + ("ni_sq_m6", ni_sq), + ("n1_m3", n1), + ("p1_m3", p1), + ): + if not np.all(np.isfinite(arr)) or np.any(arr < 0.0): + raise ValueError(f"{name} must be finite and non-negative") + if not (np.all(np.isfinite(n_arr)) and np.all(np.isfinite(p_arr))): + raise ValueError("carrier densities must be finite") + + rate = np.zeros(n_arr.shape, dtype=dtype) + d_dn = np.zeros(n_arr.shape, dtype=dtype) + d_dp = np.zeros(n_arr.shape, dtype=dtype) + + active = (vn > 0.0) & (vp > 0.0) + if not np.any(active): + return InterfaceSRHRate(rate, d_dn, d_dp) + + denom = vn * (n_arr + n1) + vp * (p_arr + p1) + valid = active & (np.abs(denom) > _DENOM_FLOOR) + if not np.any(valid): + return InterfaceSRHRate(rate, d_dn, d_dp) + + vn_v = vn[valid] + vp_v = vp[valid] + n_v = n_arr[valid] + p_v = p_arr[valid] + n1_v = n1[valid] + p1_v = p1[valid] + ni_v = ni_sq[valid] + den_v = denom[valid] + den_sq = den_v * den_v + pref = vn_v * vp_v + + raw_rate = pref * (n_v * p_v - ni_v) / den_v + raw_dn = pref * (vn_v * (p_v * n1_v + ni_v) + vp_v * p_v * (p_v + p1_v)) / den_sq + raw_dp = pref * (vp_v * (n_v * p1_v + ni_v) + vn_v * n_v * (n_v + n1_v)) / den_sq + + if clamp_nonnegative: + keep = np.real(raw_rate) >= 0.0 + zero = np.zeros_like(raw_rate) + raw_rate = np.where(keep, raw_rate, zero) + raw_dn = np.where(keep, raw_dn, zero) + raw_dp = np.where(keep, raw_dp, zero) + + rate[valid] = raw_rate + d_dn[valid] = raw_dn + d_dp[valid] = raw_dp + return InterfaceSRHRate(rate, d_dn, d_dp) + + +@dataclass(frozen=True) +class InterfaceDefectSpec: + """Single-level microscopic heterointerface defect specification.""" + + areal_density_m2: float + trap_depth_eV: float + energy_reference: EnergyReference + sigma_n_m2: float + sigma_p_m2: float + v_th_n_m_s: float + v_th_p_m_s: float + calibration_factor: float = 1.0 + charge_state_empty: int = 0 + charge_state_occupied: int = -1 + + def __post_init__(self) -> None: + _finite_nonnegative(self.areal_density_m2, "areal_density_m2") + _finite_nonnegative(self.trap_depth_eV, "trap_depth_eV") + if self.energy_reference not in ("below_conduction_band", "above_valence_band"): + raise ValueError(f"unsupported energy_reference {self.energy_reference!r}") + _finite_nonnegative(self.sigma_n_m2, "sigma_n_m2") + _finite_nonnegative(self.sigma_p_m2, "sigma_p_m2") + _finite_positive(self.v_th_n_m_s, "v_th_n_m_s") + _finite_positive(self.v_th_p_m_s, "v_th_p_m_s") + _finite_nonnegative(self.calibration_factor, "calibration_factor") + if (self.charge_state_empty, self.charge_state_occupied) not in ((0, -1), (1, 0)): + raise ValueError("interface defect charge states must be (0, -1) or (1, 0)") + + @property + def microscopic_capture_velocities_m_s(self) -> tuple[float, float]: + return ( + float(self.areal_density_m2 * self.sigma_n_m2 * self.v_th_n_m_s), + float(self.areal_density_m2 * self.sigma_p_m2 * self.v_th_p_m_s), + ) + + def effective_capture_velocities_m_s( + self, + *, + override_v_n_m_s: float | None = None, + override_v_p_m_s: float | None = None, + ) -> tuple[float, float]: + micro_n, micro_p = self.microscopic_capture_velocities_m_s + base_n = micro_n if override_v_n_m_s is None else _finite_nonnegative(override_v_n_m_s, "v_n") + base_p = micro_p if override_v_p_m_s is None else _finite_nonnegative(override_v_p_m_s, "v_p") + cal = float(self.calibration_factor) + return cal * base_n, cal * base_p + + +@dataclass(frozen=True) +class InterfaceDefectReferences: + """Resolved reference side and SRH emission densities for an interface defect.""" + + reference_side: Literal["left", "right"] + reference_gap_eV: float + n1_reference_m3: float + p1_reference_m3: float + n1_midgap_symmetric_m3: float + p1_midgap_symmetric_m3: float + n1_left_m3: float + p1_left_m3: float + n1_right_m3: float + p1_right_m3: float + + +def resolve_interface_defect_references( + *, + left_role: str, + right_role: str, + left_chi_phys_eV: float, + left_Eg_phys_eV: float, + left_Nc_m3: float, + left_Nv_m3: float, + right_chi_phys_eV: float, + right_Eg_phys_eV: float, + right_Nc_m3: float, + right_Nv_m3: float, + thermal_voltage_V: float, + trap_depth_eV: float, + energy_reference: EnergyReference, + require_in_gap: bool = False, +) -> InterfaceDefectReferences: + """Resolve reference side and Boltzmann emission densities on physical bands. + + Reference-layer rule (validated legacy contract): + 1. Unique ``role == "absorber"`` among ``(left, right)``; otherwise + 2. Smaller physical band gap ``Eg_phys`` (left wins exact ties). + + Physical band edges ``E_c = -chi_phys`` and ``E_v = -chi_phys - Eg_phys`` are + kept strictly distinct from DOS-folded transport potentials. + """ + vt = _finite_positive(thermal_voltage_V, "thermal_voltage_V") + depth = _finite_nonnegative(trap_depth_eV, "trap_depth_eV") + left_eg = _finite_positive(left_Eg_phys_eV, "left_Eg_phys_eV") + right_eg = _finite_positive(right_Eg_phys_eV, "right_Eg_phys_eV") + left_nc = _finite_positive(left_Nc_m3, "left_Nc_m3") + left_nv = _finite_positive(left_Nv_m3, "left_Nv_m3") + right_nc = _finite_positive(right_Nc_m3, "right_Nc_m3") + right_nv = _finite_positive(right_Nv_m3, "right_Nv_m3") + left_chi = float(left_chi_phys_eV) + right_chi = float(right_chi_phys_eV) + if not (math.isfinite(left_chi) and math.isfinite(right_chi)): + raise ValueError("physical electron affinities must be finite") + if energy_reference not in ("below_conduction_band", "above_valence_band"): + raise ValueError(f"unsupported energy_reference {energy_reference!r}") + + if left_role == "absorber" and right_role != "absorber": + ref_side: Literal["left", "right"] = "left" + elif right_role == "absorber" and left_role != "absorber": + ref_side = "right" + elif left_eg <= right_eg: + ref_side = "left" + else: + ref_side = "right" + + ref_chi = left_chi if ref_side == "left" else right_chi + ref_eg = left_eg if ref_side == "left" else right_eg + if require_in_gap and depth > ref_eg: + raise ValueError( + f"trap_depth_eV={depth} lies outside reference physical band gap {ref_eg}" + ) + + if energy_reference == "below_conduction_band": + trap_energy_eV = -ref_chi - depth + else: + trap_energy_eV = -ref_chi - ref_eg + depth + + ec_left, ev_left = -left_chi, -left_chi - left_eg + ec_right, ev_right = -right_chi, -right_chi - right_eg + + n1_left = _boltzmann_emission_density(left_nc, ec_left - trap_energy_eV, vt) + p1_left = _boltzmann_emission_density(left_nv, trap_energy_eV - ev_left, vt) + n1_right = _boltzmann_emission_density(right_nc, ec_right - trap_energy_eV, vt) + p1_right = _boltzmann_emission_density(right_nv, trap_energy_eV - ev_right, vt) + + if ref_side == "left": + n1_ref, p1_ref = n1_left, p1_left + ref_dos = math.sqrt(left_nc) * math.sqrt(left_nv) + ec_ref, ev_ref = ec_left, ev_left + else: + n1_ref, p1_ref = n1_right, p1_right + ref_dos = math.sqrt(right_nc) * math.sqrt(right_nv) + ec_ref, ev_ref = ec_right, ev_right + + n1_sym = _boltzmann_emission_density(ref_dos, ec_ref - trap_energy_eV, vt) + p1_sym = _boltzmann_emission_density(ref_dos, trap_energy_eV - ev_ref, vt) + + return InterfaceDefectReferences( + reference_side=ref_side, + reference_gap_eV=ref_eg, + n1_reference_m3=n1_ref, + p1_reference_m3=p1_ref, + n1_midgap_symmetric_m3=n1_sym, + p1_midgap_symmetric_m3=p1_sym, + n1_left_m3=n1_left, + p1_left_m3=p1_left, + n1_right_m3=n1_right, + p1_right_m3=p1_right, + ) + + +def equilibrium_referenced_sheet_charge( + occupancy: float, + *, + areal_density_m2: float, + equilibrium_occupancy: float, +) -> float: + """Static interface sheet-charge closure ``Delta sigma = -q N_t (f - f_ref)`` [C/m^2]. + + Because each change of electron occupancy ``Delta f`` adds electronic charge + ``-q N_t Delta f`` regardless of whether the trap is acceptor ``(0/-)`` or + donor ``(+/0)`` relative to its certified dark equilibrium occupancy + ``f_ref``, the incremental sheet charge has one universal sign and vanishes + identically at dark equilibrium ``f == f_ref``. + """ + nt = _finite_nonnegative(areal_density_m2, "areal_density_m2") + f = float(occupancy) + f_ref = float(equilibrium_occupancy) + if not (math.isfinite(f) and 0.0 <= f <= 1.0): + raise ValueError("occupancy must lie in [0, 1]") + if not (math.isfinite(f_ref) and 0.0 <= f_ref <= 1.0): + raise ValueError("equilibrium_occupancy must lie in [0, 1]") + return float(-Q * nt * (f - f_ref)) + + +@dataclass(frozen=True) +class SharedInterfaceTrapEvaluation: + """Single constitutive evaluation of a two-sided shared interface trap. + + Density ordering for derivative vectors and matrices is + ``(n_left, p_left, n_right, p_right)``. + Capture-rate ordering is ``(C_n_left, C_p_left, C_n_right, C_p_right)`` in + ``m^-2 s^-1``. + """ + + occupancy: float + d_occupancy_d_densities_m3: RealArray + capture_rates_m2_s: RealArray + d_capture_d_densities_m_s: RealArray + incremental_sheet_charge_C_m2: float + d_sheet_charge_d_densities_C_m: RealArray + + +def evaluate_shared_interface_trap( + n_left_m3: float, + p_left_m3: float, + n_right_m3: float, + p_right_m3: float, + *, + v_n_left_m_s: float, + v_p_left_m_s: float, + v_n_right_m_s: float, + v_p_right_m_s: float, + n1_left_m3: float, + p1_left_m3: float, + n1_right_m3: float, + p1_right_m3: float, + areal_density_m2: float = 0.0, + equilibrium_occupancy: float | None = None, +) -> SharedInterfaceTrapEvaluation: + """Evaluate shared trap occupancy, side capture rates, and optional sheet charge once.""" + densities = ( + _finite_nonnegative(n_left_m3, "n_left_m3"), + _finite_nonnegative(p_left_m3, "p_left_m3"), + _finite_nonnegative(n_right_m3, "n_right_m3"), + _finite_nonnegative(p_right_m3, "p_right_m3"), + ) + vn_l = _finite_nonnegative(v_n_left_m_s, "v_n_left_m_s") + vp_l = _finite_nonnegative(v_p_left_m_s, "v_p_left_m_s") + vn_r = _finite_nonnegative(v_n_right_m_s, "v_n_right_m_s") + vp_r = _finite_nonnegative(v_p_right_m_s, "v_p_right_m_s") + n1_l = _finite_nonnegative(n1_left_m3, "n1_left_m3") + p1_l = _finite_nonnegative(p1_left_m3, "p1_left_m3") + n1_r = _finite_nonnegative(n1_right_m3, "n1_right_m3") + p1_r = _finite_nonnegative(p1_right_m3, "p1_right_m3") + nt = _finite_nonnegative(areal_density_m2, "areal_density_m2") + + n_l, p_l, n_r, p_r = densities + alpha = vn_l * n_l + vn_r * n_r + vp_l * p1_l + vp_r * p1_r + beta = vn_l * n1_l + vn_r * n1_r + vp_l * p_l + vp_r * p_r + denom = alpha + beta + + if denom <= _DENOM_FLOOR: + zero4: RealArray = np.zeros(4, dtype=np.float64) + zero44: RealArray = np.zeros((4, 4), dtype=np.float64) + sheet = ( + 0.0 + if equilibrium_occupancy is None + else equilibrium_referenced_sheet_charge( + 0.0, + areal_density_m2=nt, + equilibrium_occupancy=equilibrium_occupancy, + ) + ) + return SharedInterfaceTrapEvaluation( + occupancy=0.0, + d_occupancy_d_densities_m3=zero4, + capture_rates_m2_s=zero4.copy(), + d_capture_d_densities_m_s=zero44, + incremental_sheet_charge_C_m2=sheet, + d_sheet_charge_d_densities_C_m=zero4.copy(), + ) + + occupancy = float(alpha / denom) + one_minus_f = float(beta / denom) + denom_sq = denom * denom + + df_d = np.array( + [ + vn_l * beta / denom_sq, + -vp_l * alpha / denom_sq, + vn_r * beta / denom_sq, + -vp_r * alpha / denom_sq, + ], + dtype=np.float64, + ) + + # Numerators avoid rounding f and (1 - f) independently near equilibrium. + cn_l = vn_l * (n_l * beta - n1_l * alpha) / denom + cp_l = vp_l * (p_l * alpha - p1_l * beta) / denom + cn_r = vn_r * (n_r * beta - n1_r * alpha) / denom + cp_r = vp_r * (p_r * alpha - p1_r * beta) / denom + capture = np.array([cn_l, cp_l, cn_r, cp_r], dtype=np.float64) + + # C_n,s = v_n,s * (n_s * (1 - f) - n1_s * f) + # dC_n,s/dx = v_n,s * (delta_{x,n_s}*(1 - f) - (n_s + n1_s) * df/dx) + # C_p,s = v_p,s * (p_s * f - p1_s * (1 - f)) + # dC_p,s/dx = v_p,s * (delta_{x,p_s}*f + (p_s + p1_s) * df/dx) + d_cap: RealArray = np.empty((4, 4), dtype=np.float64) + d_cap[0, :] = -vn_l * (n_l + n1_l) * df_d + d_cap[0, 0] += vn_l * one_minus_f + d_cap[1, :] = vp_l * (p_l + p1_l) * df_d + d_cap[1, 1] += vp_l * occupancy + d_cap[2, :] = -vn_r * (n_r + n1_r) * df_d + d_cap[2, 2] += vn_r * one_minus_f + d_cap[3, :] = vp_r * (p_r + p1_r) * df_d + d_cap[3, 3] += vp_r * occupancy + + if equilibrium_occupancy is None: + sheet = 0.0 + d_sheet: RealArray = np.zeros(4, dtype=np.float64) + else: + sheet = equilibrium_referenced_sheet_charge( + occupancy, + areal_density_m2=nt, + equilibrium_occupancy=equilibrium_occupancy, + ) + d_sheet = -Q * nt * df_d + + return SharedInterfaceTrapEvaluation( + occupancy=occupancy, + d_occupancy_d_densities_m3=df_d, + capture_rates_m2_s=capture, + d_capture_d_densities_m_s=d_cap, + incremental_sheet_charge_C_m2=sheet, + d_sheet_charge_d_densities_C_m=d_sheet, + ) + + +@dataclass(frozen=True) +class PlaneClosureParams: + """Build-time constants of one defect interface's 1D plane closure. + + Constructed from post-DOS-fold ``chi`` and ``chi + Eg`` values at the two + interface-adjacent nodes plus the reference-layer physical DOS and raw + electron affinity. + """ + + bn_L: float + bn_R: float + bp_L: float + bp_R: float + ni_s_sq_m6: float + n1_s_m3: float + p1_s_m3: float + s_supply_m_s: float = S_SUPPLY_M_S + + +@dataclass(frozen=True) +class PlaneClosureResult: + """Converged plane densities, net areal rate, and exact IFT derivatives.""" + + n_plane_m3: float + p_plane_m3: float + rate_m2_s: float + d_rate_d_n_left_proj_m_s: float + d_rate_d_n_right_proj_m_s: float + d_rate_d_p_left_proj_m_s: float + d_rate_d_p_right_proj_m_s: float + converged: bool + iterations: int + + +def build_plane_closure_params( + *, + chi_left_folded_eV: float, + chi_right_folded_eV: float, + valence_left_folded_eV: float, + valence_right_folded_eV: float, + Nc_ref_m3: float, + Nv_ref_m3: float, + chi_ref_phys_eV: float, + trap_depth_below_ref_cb_eV: float, + thermal_voltage_V: float, + s_supply_m_s: float = S_SUPPLY_M_S, +) -> PlaneClosureParams: + """Construct :class:`PlaneClosureParams` from folded interface band edges. + + ``valence_*_folded_eV`` are the folded ``chi + Eg`` quantities at the two + interface-adjacent nodes; ``chi_ref_phys_eV`` is the raw physical electron + affinity on the defect reference layer. + """ + chi_l = _finite_real(chi_left_folded_eV, "chi_left_folded_eV") + chi_r = _finite_real(chi_right_folded_eV, "chi_right_folded_eV") + ceg_l = _finite_real(valence_left_folded_eV, "valence_left_folded_eV") + ceg_r = _finite_real(valence_right_folded_eV, "valence_right_folded_eV") + nc_ref = _finite_positive(Nc_ref_m3, "Nc_ref_m3") + nv_ref = _finite_positive(Nv_ref_m3, "Nv_ref_m3") + chi_ref = _finite_real(chi_ref_phys_eV, "chi_ref_phys_eV") + et_depth = _finite_nonnegative(trap_depth_below_ref_cb_eV, "trap_depth_below_ref_cb_eV") + vt = _finite_positive(thermal_voltage_V, "thermal_voltage_V") + s_sup = _finite_positive(s_supply_m_s, "s_supply_m_s") + + chi_s = max(chi_l, chi_r) + ceg_s = min(ceg_l, ceg_r) + eg_s = ceg_s - chi_s + + def _penalty(delta: float) -> float: + return math.exp(-min(max(delta, 0.0), 60.0 * vt) / vt) + + depth_n = min(max(et_depth - (chi_s - chi_ref), 0.0), max(eg_s, 0.0)) + + def _exp_guarded(arg: float) -> float: + return math.exp(max(-120.0, min(120.0, arg))) + + return PlaneClosureParams( + bn_L=_penalty(chi_s - chi_l), + bn_R=_penalty(chi_s - chi_r), + bp_L=_penalty(ceg_l - ceg_s), + bp_R=_penalty(ceg_r - ceg_s), + ni_s_sq_m6=nc_ref * nv_ref * _exp_guarded(-eg_s / vt), + n1_s_m3=nc_ref * _exp_guarded(-depth_n / vt), + p1_s_m3=nv_ref * _exp_guarded(-(eg_s - depth_n) / vt), + s_supply_m_s=s_sup, + ) + + +def solve_plane_closure( + n_left_proj_m3: float, + n_right_proj_m3: float, + p_left_proj_m3: float, + p_right_proj_m3: float, + params: PlaneClosureParams, + v_n_m_s: float, + v_p_m_s: float, + *, + allow_generation: bool = False, +) -> PlaneClosureResult: + """Solve the 2x2 carrier-plane QSS balance with exact IFT sensitivities.""" + s = _finite_positive(params.s_supply_m_s, "s_supply_m_s") + vn = _finite_nonnegative(v_n_m_s, "v_n_m_s") + vp = _finite_nonnegative(v_p_m_s, "v_p_m_s") + nl = float(n_left_proj_m3) + nr = float(n_right_proj_m3) + pl = float(p_left_proj_m3) + pr = float(p_right_proj_m3) + nb = params.bn_L * max(nl, 0.0) + params.bn_R * max(nr, 0.0) + pb = params.bp_L * max(pl, 0.0) + params.bp_R * max(pr, 0.0) + + if vn <= 0.0 or vp <= 0.0: + return PlaneClosureResult( + n_plane_m3=0.5 * nb, + p_plane_m3=0.5 * pb, + rate_m2_s=0.0, + d_rate_d_n_left_proj_m_s=0.0, + d_rate_d_n_right_proj_m_s=0.0, + d_rate_d_p_left_proj_m_s=0.0, + d_rate_d_p_right_proj_m_s=0.0, + converged=True, + iterations=0, + ) + + s2 = 2.0 * s + ln_n = math.log(max(0.5 * nb, _QSS_DENSITY_FLOOR)) + ln_p = math.log(max(0.5 * pb, _QSS_DENSITY_FLOOR)) + converged = False + iters = 0 + + for it in range(1, _QSS_MAX_ITER + 1): + iters = it + n_s = math.exp(ln_n) + p_s = math.exp(ln_p) + num = n_s * p_s - params.ni_s_sq_m6 + den = (n_s + params.n1_s_m3) / vp + (p_s + params.p1_s_m3) / vn + signed = num > 0.0 or allow_generation + rate = num / den if signed else 0.0 + f1 = s * nb - s2 * n_s - rate + f2 = s * pb - s2 * p_s - rate + scale = s * (nb + pb) + abs(rate) + _QSS_DENSITY_FLOOR + if abs(f1) + abs(f2) < _QSS_TOL * scale: + converged = True + break + if signed: + dr_dn = (p_s * den - num / vp) / (den * den) + dr_dp = (n_s * den - num / vn) / (den * den) + else: + dr_dn = 0.0 + dr_dp = 0.0 + j11 = (-s2 - dr_dn) * n_s + j12 = (-dr_dp) * p_s + j21 = (-dr_dn) * n_s + j22 = (-s2 - dr_dp) * p_s + det = j11 * j22 - j12 * j21 + if det == 0.0 or not math.isfinite(det): + break + d_ln_n = (-f1 * j22 + f2 * j12) / det + d_ln_p = (-f2 * j11 + f1 * j21) / det + d_ln_n = max(-_QSS_LOG_STEP_CLIP, min(_QSS_LOG_STEP_CLIP, d_ln_n)) + d_ln_p = max(-_QSS_LOG_STEP_CLIP, min(_QSS_LOG_STEP_CLIP, d_ln_p)) + ln_n += d_ln_n + ln_p += d_ln_p + if abs(d_ln_n) + abs(d_ln_p) <= _QSS_STEP_TOL: + converged = True + break + + n_s = math.exp(ln_n) + p_s = math.exp(ln_p) + srh_final = interface_srh_rate( + n_s, + p_s, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_m6=params.ni_s_sq_m6, + n1_m3=params.n1_s_m3, + p1_m3=params.p1_s_m3, + clamp_nonnegative=not allow_generation, + ) + r_final = float(np.real(srh_final.rate_m2_s)) + r_n_final = float(np.real(srh_final.d_rate_dn_m_s)) + r_p_final = float(np.real(srh_final.d_rate_dp_m_s)) + + # Exact IFT wrt (nb, pb) via F1 - F2 = s*(nb - pb) - 2*s*(n_s - p_s) == 0: + # dR/dnb = s * r_n / (2*s + r_n + r_p), dR/dpb = s * r_p / (2*s + r_n + r_p). + ift_denom = s2 + r_n_final + r_p_final + dr_dnb = s * r_n_final / ift_denom + dr_dpb = s * r_p_final / ift_denom + + return PlaneClosureResult( + n_plane_m3=n_s, + p_plane_m3=p_s, + rate_m2_s=r_final, + d_rate_d_n_left_proj_m_s=(params.bn_L if nl > 0.0 else 0.0) * dr_dnb, + d_rate_d_n_right_proj_m_s=(params.bn_R if nr > 0.0 else 0.0) * dr_dnb, + d_rate_d_p_left_proj_m_s=(params.bp_L if pl > 0.0 else 0.0) * dr_dpb, + d_rate_d_p_right_proj_m_s=(params.bp_R if pr > 0.0 else 0.0) * dr_dpb, + converged=converged, + iterations=iters, + ) + + +class TwoDimensionalInterfaceSRHMode(StrEnum): + """Explicit 2D heterointerface SRH modes (P04-09 item 4). + + The legacy ``settings.interface_two_sided`` boolean remains in configuration + for the 2D cross-row cell-pair channel while the falsified 1D additive + mirror channel stays refused in ``compile_device_1d``. + """ + + OFF = "off" + CROSS_CARRIER_CELL_PAIR_V1 = "cross_carrier_cell_pair_v1" + + +@dataclass(frozen=True) +class CrossCarrierCellPairEvaluation: + """Areal rate [m^-2 s^-1] and half-plane split for 2D cell-pair SRH.""" + + areal_rate_m2_s: RealArray + d_areal_rate_d_n_other_m_s: RealArray + d_areal_rate_d_p_self_m_s: RealArray + half_rate_m2_s: RealArray + + +def evaluate_cross_carrier_cell_pair_srh( + mode: TwoDimensionalInterfaceSRHMode, + *, + n_other_m3: ArrayLike, + p_self_m3: ArrayLike, + v_n_m_s: ArrayLike, + v_p_m_s: ArrayLike, + ni_sq_m6: ArrayLike, + n1_m3: ArrayLike, + p1_m3: ArrayLike, + clamp_nonnegative: bool = True, +) -> CrossCarrierCellPairEvaluation: + """Evaluate 2D cross-row cell-pair SRH areal rate without ``dy`` division.""" + n_arr = np.asarray(n_other_m3, dtype=np.float64) + p_arr = np.asarray(p_self_m3, dtype=np.float64) + if mode == TwoDimensionalInterfaceSRHMode.OFF: + shape = np.broadcast_shapes(n_arr.shape, p_arr.shape) + zeros = np.zeros(shape, dtype=np.float64) + return CrossCarrierCellPairEvaluation(zeros, zeros.copy(), zeros.copy(), zeros.copy()) + if mode != TwoDimensionalInterfaceSRHMode.CROSS_CARRIER_CELL_PAIR_V1: + raise ValueError(f"unsupported 2D interface SRH mode {mode!r}") + srh = interface_srh_rate( + n_arr, + p_arr, + v_n_m_s=v_n_m_s, + v_p_m_s=v_p_m_s, + ni_sq_m6=ni_sq_m6, + n1_m3=n1_m3, + p1_m3=p1_m3, + clamp_nonnegative=clamp_nonnegative, + ) + rate = np.asarray(srh.rate_m2_s, dtype=np.float64) + dn = np.asarray(srh.d_rate_dn_m_s, dtype=np.float64) + dp = np.asarray(srh.d_rate_dp_m_s, dtype=np.float64) + return CrossCarrierCellPairEvaluation(rate, dn, dp, 0.5 * rate) diff --git a/tests/integration/test_core_1d.py b/tests/integration/test_core_1d.py index ce0702ab..3b824078 100644 --- a/tests/integration/test_core_1d.py +++ b/tests/integration/test_core_1d.py @@ -338,8 +338,8 @@ def test_local_model_injection_has_independent_partials_and_real_solution(prepar @pytest.mark.parametrize("feature", [ "ions", "fermi_dirac", "dopant_ionization", "band_gap_narrowing", - "field_mobility", "interface_recombination", "optics", "manual_contacts", - "ion_steric", "qualified_solver_policy", + "field_mobility", "interface_shared_occupancy", "interface_two_sided", + "optics", "manual_contacts", "ion_steric", "qualified_solver_policy", ]) def test_unsupported_enabled_physics_fails_before_execution(prepared, feature): document = prepared.to_input().editing_data() @@ -354,8 +354,10 @@ def test_unsupported_enabled_physics_fails_before_execution(prepared, feature): parameters["band_gap_narrowing_model"] = "slotboom" elif feature == "field_mobility": parameters["pf_gamma_n"] = 1e-4 - elif feature == "interface_recombination": - document["interfaces"] = [dict(id="interface", left="htl", right="absorber", v_n=1.0, v_p=1.0)] + elif feature == "interface_shared_occupancy": + document["settings"]["interface_shared_occupancy"] = True + elif feature == "interface_two_sided": + document["settings"]["interface_two_sided"] = True elif feature == "optics": parameters["n_optical"] = 2.0 elif feature == "ion_steric": @@ -368,6 +370,15 @@ def test_unsupported_enabled_physics_fails_before_execution(prepared, feature): compile_device_1d(edited(prepared, document)) +def test_interface_recombination_compiles_and_solves_steady_state(prepared): + document = prepared.to_input().editing_data() + document["interfaces"] = [dict(id="interface", left="htl", right="absorber", v_n=10.0, v_p=10.0)] + compiled = compile_device_1d(edited(prepared, document)) + assert compiled.interface_model is not None + result = solve_steady_state(compiled, voltage_V=0.8) + assert np.all(np.isfinite(result.current_density_A_m2)) + + def test_inconsistent_dos_intrinsic_product_is_not_silently_replaced(prepared): document = prepared.to_input().editing_data() document["layers"][1]["parameters"]["ni"] *= 2.0 diff --git a/tests/integration/test_interface_parity_1d.py b/tests/integration/test_interface_parity_1d.py new file mode 100644 index 00000000..10b2f10f --- /dev/null +++ b/tests/integration/test_interface_parity_1d.py @@ -0,0 +1,1177 @@ +"""Live numerical parity tests (T4) between new-core solarlab and legacy perovskite_sim (P04-09). + +Verifies end-to-end 1D numerical parity across: +1. Illuminated DC J-V figures of merit (|dVoc| <= 1e-4 V, relative Jsc/FF/PCE <= 1e-4) on + multilayer HTL/perovskite/ETL devices with: + - Active bare v_n/v_p heterointerface SRH + finite 1D thermionic emission (TE); + - Explicit single-level interface defects (cross-carrier, plane projection, plane closure); + - Equilibrium-referenced charged two-sided heterointerfaces (f_eq, Delta_sigma(V), f(V), J-V). +2. Implicit Backward Euler transient step (BackwardEuler1DStep on AssembledDC1DProblem vs + perovskite_sim assemble_rhs implicit Euler step) with active interface SRH, defect, and TE. +3. Small-signal AC admittance/impedance across 1 Hz .. 1 MHz (solve_frequency_systems on + AssembledDC1DProblem vs perovskite_sim run_quasi_fermi_impedance & solve_frequency_domain). +""" + +from __future__ import annotations + +from collections.abc import Iterator +import copy +import dataclasses +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from numpy.typing import NDArray +import pytest +from scipy.optimize import root +from threadpoolctl import threadpool_limits + +from perovskite_sim.constants import EPS_0, K_B, Q +from perovskite_sim.experiments import steady_state as legacy_ss +from perovskite_sim.experiments.interface_charge_jv import ( + build_interface_charge_jv_protocol, + solve_interface_charge_jv, +) +from perovskite_sim.experiments.jv_sweep import ( + JVMetrics, + _compute_current_ss, + build_electrical_grid, + compute_metrics, +) +from perovskite_sim.experiments.quasi_fermi_impedance import run_quasi_fermi_impedance +from perovskite_sim.experiments.quasi_fermi_steady_state import ( + build_equilibrium_referenced_interface_charge_dark_reference, + build_two_sided_trace_grid, + solve_equilibrium_referenced_interface_charge_steady_state, +) +from perovskite_sim.models.config_loader import load_device_from_yaml +from perovskite_sim.models.device import DeviceStack +from perovskite_sim.physics.continuity import carrier_face_currents +from perovskite_sim.physics.generation import beer_lambert_generation +from perovskite_sim.solver.mol import ( + MaterialArrays, + _harmonic_face_average, + assemble_rhs, + build_material_arrays, +) +from perovskite_sim.solver.small_signal import ( + SmallSignalEvaluation, + solve_frequency_domain, +) + +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.config.yaml import load_yaml_mapping +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.assembly.terms import FaceValue +from solarlab.equations.dc_1d import CompiledDevice1D, State1D +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.physics.generation.profile import GenerationProfile +from solarlab.solvers.linear.frequency_domain import solve_frequency_systems +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.production import ( + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.nonlinear.steady_1d import ( + POISSON_CONTACT_BALANCE_V1, + SteadyOptions, + SteadyStateError, + solve_steady_state, +) +from solarlab.solvers.time.backward_euler import BackwardEuler1DStep + +ROOT = Path(__file__).resolve().parents[2] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + +Vector = NDArray[np.float64] + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def legacy_catalog() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_DEFAULTS) + ) + + +def _thermodynamic_ni(nc_m3: float, nv_m3: float, eg_eV: float, temp_K: float = 300.0) -> float: + vt = K_B * temp_K / Q + return float(math.sqrt(nc_m3 * nv_m3) * math.exp(-eg_eV / (2.0 * vt))) + + +def _base_pin_yaml_dict() -> dict[str, Any]: + """Explicit 3-layer HTL / perovskite absorber / ETL stack with exact ni^2 == Nc*Nv*exp(-Eg/Vt).""" + ni_htl = _thermodynamic_ni(2.0e25, 3.0e25, 1.80) + ni_abs = _thermodynamic_ni(1.0e25, 1.0e25, 1.60) + ni_etl = _thermodynamic_ni(4.0e25, 2.0e25, 2.00) + return { + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "T": 300.0, + "Phi": 2.0e21, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"htl": 1.0, "absorber": 2.0, "etl": 1.0}, + "alphas": {"htl": 3.0, "absorber": 3.0, "etl": 3.0}, + }, + "layers": [ + { + "name": "htl", + "role": "HTL", + "thickness": 8.0e-8, + "eps_r": 3.0, + "mu_n": 3.8681727071833605e-5, + "mu_p": 3.8681727071833605e-5, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_htl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_htl, + "p1": ni_htl, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "N_A": 1.0e24, + "N_D": 0.0, + "chi": 3.6, + "Eg": 1.80, + "Nc300": 2.0e25, + "Nv300": 3.0e25, + "A_star_n": 0.0, + "A_star_p": 0.0, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 3.0e-7, + "eps_r": 25.0, + "mu_n": 0.0019340863535916802, + "mu_p": 0.0019340863535916802, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_abs, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_abs, + "p1": ni_abs, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.9, + "Eg": 1.60, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "A_star_n": 0.0, + "A_star_p": 0.0, + }, + { + "name": "etl", + "role": "ETL", + "thickness": 8.0e-8, + "eps_r": 9.0, + "mu_n": 3.8681727071833605e-5, + "mu_p": 3.8681727071833605e-5, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_etl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_etl, + "p1": ni_etl, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 1.0e24, + "chi": 4.0, + "Eg": 2.00, + "Nc300": 4.0e25, + "Nv300": 2.0e25, + "A_star_n": 0.0, + "A_star_p": 0.0, + }, + ], + } + + +def _moderate_pin_yaml_dict() -> dict[str, Any]: + """Moderate-doping 3-layer HTL / absorber / ETL stack keeping minority carriers well above floor.""" + doc = _base_pin_yaml_dict() + ni_htl = _thermodynamic_ni(2.0e25, 3.0e25, 1.70) + ni_etl = _thermodynamic_ni(4.0e25, 2.0e25, 1.80) + doc["layers"][0].update( + {"N_A": 5.0e21, "Eg": 1.70, "ni": ni_htl, "n1": ni_htl, "p1": ni_htl} + ) + doc["layers"][2].update( + {"N_D": 5.0e21, "Eg": 1.80, "ni": ni_etl, "n1": ni_etl, "p1": ni_etl} + ) + return doc + + +def _load_paired_models( + raw_doc: dict[str, Any], + catalog: DefaultCatalog, + tmp_path: Path, + name: str, +) -> tuple[PreparedDevice, DeviceStack]: + """Load the exact same JSON/YAML payload into both PreparedDevice and legacy DeviceStack.""" + payload = json.dumps(raw_doc, allow_nan=False).encode() + yaml_file = tmp_path / f"{name}.yaml" + yaml_file.write_bytes(payload) + source = SourceDocument(str(yaml_file), payload) + dev_input = import_standard_device(source, id=name, defaults=catalog) + prepared = resolve_device(dev_input, catalog, ResourceLibrary(), sources=(source,)) + stack = load_device_from_yaml(str(yaml_file)) + return prepared, stack + + +def _step_solarlab_to_voltage( + dev: CompiledDevice1D, + prev_state: State1D | None, + v_prev: float | None, + v_target: float, + opts: SteadyOptions, +) -> State1D: + """Advance steady-state solution to ``v_target`` using bounded bias substeps + bisection.""" + if prev_state is None or v_prev is None: + return solve_steady_state( + dev, + voltage_V=v_target, + generation_scale=1.0, + options=opts, + ).state + + state_cur = prev_state + v_cur = v_prev + max_step = max(float(opts.max_bias_step_V), 1.0e-3) + while abs(v_target - v_cur) > 1.0e-12: + step = min(max_step, abs(v_target - v_cur)) * (1.0 if v_target >= v_cur else -1.0) + v_try = v_target if abs(v_target - v_cur) <= abs(step) + 1.0e-12 else v_cur + step + while True: + try: + ss = solve_steady_state( + dev, + initial_state=state_cur, + voltage_V=v_try, + generation_scale=1.0, + options=opts, + ) + state_cur = ss.state + v_cur = v_try + break + except SteadyStateError: + if abs(v_try - v_cur) <= 1.0e-3: + raise + v_try = 0.5 * (v_cur + v_try) + return state_cur + + +def _sweep_solarlab_jv( + dev: CompiledDevice1D, + voltages_V: Vector, + *, + options: SteadyOptions | None = None, + stop_after_voc: bool = True, +) -> tuple[Vector, Vector, JVMetrics, list[State1D]]: + """Sweep illuminated J-V on AssembledDC1DProblem and extract solar J-V metrics.""" + opts = ( + SteadyOptions(max_bias_step_V=0.025, convergence_policy=POISSON_CONTACT_BALANCE_V1) + if options is None + else options + ) + v_done: list[float] = [] + j_done: list[float] = [] + states: list[State1D] = [] + prev_state: State1D | None = None + v_prev: float | None = None + for v_raw in voltages_V: + v_val = float(v_raw) + st = _step_solarlab_to_voltage(dev, prev_state, v_prev, v_val, opts) + assm = AssembledDC1DProblem(dev, voltage_V=v_val, generation_scale=1.0) + j_faces = assm.current_density(st.u) + j_val = float(-dev.voltage_polarity * np.median(j_faces)) + v_done.append(v_val) + j_done.append(j_val) + states.append(st) + prev_state = st + v_prev = v_val + if stop_after_voc and len(j_done) >= 2 and j_done[0] > 0.0 and j_val <= 0.0: + break + v_arr = np.asarray(v_done, dtype=float) + j_arr = np.asarray(j_done, dtype=float) + metrics = compute_metrics(v_arr, j_arr, P_in=1000.0) + assert metrics.voc_bracketed, f"Voc not bracketed: V={v_arr[-1]:.3f}, J={j_arr[-1]:.3e}" + return v_arr, j_arr, metrics, states + + +def _sweep_legacy_ss_jv( + stack: DeviceStack, + x: Vector, + voltages_V: Vector, + *, + te_softness: float = 0.02, + stop_after_voc: bool = True, + max_step_V: float = 0.025, +) -> tuple[Vector, Vector, JVMetrics, list[Vector], MaterialArrays]: + """Sweep illuminated J-V on perovskite_sim steady_state.solve_steady_state on identical grid x.""" + mat = dataclasses.replace(build_material_arrays(x, stack), te_softness=te_softness) + v_done: list[float] = [] + j_done: list[float] = [] + ys: list[Vector] = [] + y_prev: Vector | None = None + v_prev: float | None = None + for v_raw in voltages_V: + v_target = float(v_raw) + if y_prev is None or v_prev is None: + res = legacy_ss.solve_steady_state(x, stack, v_target, illuminated=True, mat=mat) + y_cur = res.y + else: + y_cur = y_prev + v_cur = v_prev + while abs(v_target - v_cur) > 1.0e-12: + step = min(max_step_V, abs(v_target - v_cur)) * ( + 1.0 if v_target >= v_cur else -1.0 + ) + v_try = v_target if abs(v_target - v_cur) <= abs(step) + 1.0e-12 else v_cur + step + while True: + try: + res = legacy_ss.solve_steady_state( + x, + stack, + v_try, + illuminated=True, + mat=mat, + y0=y_cur, + ) + y_cur = res.y + v_cur = v_try + break + except legacy_ss.SteadyStateError: + if abs(v_try - v_cur) <= 1.0e-3: + raise + v_try = 0.5 * (v_cur + v_try) + j_val = float(_compute_current_ss(x, y_cur, stack, v_target, mat=mat)) + v_done.append(v_target) + j_done.append(j_val) + ys.append(y_cur) + y_prev = y_cur + v_prev = v_target + if stop_after_voc and len(j_done) >= 2 and j_done[0] > 0.0 and j_val <= 0.0: + break + v_arr = np.asarray(v_done, dtype=float) + j_arr = np.asarray(j_done, dtype=float) + metrics = compute_metrics(v_arr, j_arr, P_in=1000.0) + assert metrics.voc_bracketed, f"Legacy Voc not bracketed: V={v_arr[-1]:.3f}, J={j_arr[-1]:.3e}" + return v_arr, j_arr, metrics, ys, mat + + +def _assert_jv_metrics_parity(m_new: JVMetrics, m_old: JVMetrics) -> dict[str, float]: + d_voc = abs(m_new.V_oc - m_old.V_oc) + rel_jsc = abs(m_new.J_sc - m_old.J_sc) / abs(m_old.J_sc) + rel_ff = abs(m_new.FF - m_old.FF) / abs(m_old.FF) + rel_pce = abs(m_new.PCE - m_old.PCE) / abs(m_old.PCE) + assert d_voc <= 1.0e-4, f"|dVoc| = {d_voc:.3e} V > 1e-4 V" + assert rel_jsc <= 1.0e-4, f"rel_dJsc = {rel_jsc:.3e} > 1e-4" + assert rel_ff <= 1.0e-4, f"rel_dFF = {rel_ff:.3e} > 1e-4" + assert rel_pce <= 1.0e-4, f"rel_dPCE = {rel_pce:.3e} > 1e-4" + return { + "abs_dVoc_V": d_voc, + "rel_dJsc": rel_jsc, + "rel_dFF": rel_ff, + "rel_dPCE": rel_pce, + } + + +def _clean_json(val: Any) -> Any: + if isinstance(val, dict): + return {k: _clean_json(v) for k, v in val.items()} + if isinstance(val, (list, tuple)): + return [_clean_json(v) for v in val] + if hasattr(val, "as_tuple"): + return float(val) + return val + + +def test_live_jv_parity_bare_srh_and_finite_thermionic_emission( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 DC J-V parity: active bare v_n/v_p SRH + finite 1D TE on 3-layer HTL/perovskite/ETL.""" + doc_zero = _base_pin_yaml_dict() + doc_zero["device"]["interfaces"] = [[0.0, 0.0], [0.0, 0.0]] + prep_zero, _ = _load_paired_models(doc_zero, legacy_catalog, tmp_path, "pin_zero_srh") + dev_zero = compile_device_1d(prep_zero, intervals_per_layer=(8, 16, 8)) + + doc_active = _base_pin_yaml_dict() + doc_active["device"]["interfaces"] = [[35.0, 20.0], [18.0, 40.0]] + for layer in doc_active["layers"]: + layer["A_star_n"] = 1.2017e6 + layer["A_star_p"] = 1.2017e6 + prep_active, stack_active = _load_paired_models( + doc_active, legacy_catalog, tmp_path, "pin_bare_srh_te" + ) + dev_active = compile_device_1d( + prep_active, + intervals_per_layer=(8, 16, 8), + te_softness=0.02, + te_regularization_mode="legacy_logistic", + ) + x_legacy = build_electrical_grid(stack_active, 32) + np.testing.assert_allclose(dev_active.nodes_m, x_legacy, rtol=0.0, atol=1.0e-15) + + voltages = np.linspace(0.0, 1.32, 34) + _, _, m_zero, _ = _sweep_solarlab_jv(dev_zero, voltages) + v_old, j_old, m_old, _, _ = _sweep_legacy_ss_jv( + stack_active, x_legacy, voltages, te_softness=0.02 + ) + v_new, j_new, m_new, _ = _sweep_solarlab_jv(dev_active, v_old, stop_after_voc=False) + np.testing.assert_array_equal(v_new, v_old) + + assert m_zero.V_oc - m_new.V_oc > 0.03 + _assert_jv_metrics_parity(m_new, m_old) + np.testing.assert_allclose(j_new, j_old, rtol=5.0e-5, atol=5.0e-4) + + # Flux-limiting small Richardson constant where the 1D TE cap is visibly active! + doc_te_cap = copy.deepcopy(doc_active) + for layer in doc_te_cap["layers"]: + layer["A_star_n"] = 1.0e-22 + layer["A_star_p"] = 1.0e-22 + prep_cap, stack_cap = _load_paired_models( + doc_te_cap, legacy_catalog, tmp_path, "pin_strong_te_cap" + ) + dev_cap = compile_device_1d( + prep_cap, + intervals_per_layer=(8, 16, 8), + te_softness=0.02, + te_regularization_mode="legacy_logistic", + ) + v_cap_old, j_cap_old, m_cap_old, _, _ = _sweep_legacy_ss_jv( + stack_cap, x_legacy, voltages, te_softness=0.02 + ) + _, j_cap_new, m_cap_new, _ = _sweep_solarlab_jv(dev_cap, v_cap_old, stop_after_voc=False) + assert abs(m_cap_new.J_sc - m_new.J_sc) > 0.03 + _assert_jv_metrics_parity(m_cap_new, m_cap_old) + np.testing.assert_allclose(j_cap_new, j_cap_old, rtol=5.0e-5, atol=5.0e-4) + + +@pytest.mark.parametrize( + "closure_mode", + ["cross_carrier", "plane_projection", "plane_closure"], +) +def test_live_jv_parity_interface_defect_modes( + closure_mode: str, + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 DC J-V parity: explicit single-level interface defects across deduplicated modes.""" + doc_ref = _moderate_pin_yaml_dict() + prep_ref, _ = _load_paired_models( + doc_ref, legacy_catalog, tmp_path, f"pin_defect_zero_{closure_mode}" + ) + dev_ref = compile_device_1d(prep_ref, intervals_per_layer=(8, 16, 8)) + + # Mix bare SRV on HTL/absorber with an explicit microscopic defect on absorber/ETL! + doc = _moderate_pin_yaml_dict() + for layer in doc["layers"]: + layer["A_star_n"] = 1.2017e6 + layer["A_star_p"] = 1.2017e6 + doc["device"]["interfaces"] = [[20.0, 15.0], [0.0, 0.0]] + doc["device"]["interface_defects"] = [ + None, + { + "sigma_n_cm2": 8.0e-17, + "sigma_p_cm2": 6.0e-17, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 5.0e10, + "E_t_eV_below_cb": 0.60, + }, + ] + if closure_mode == "plane_projection": + doc["device"]["interface_plane_projection"] = True + elif closure_mode == "plane_closure": + doc["device"]["interface_plane_closure"] = True + doc["device"]["interface_plane_generation"] = True + + prep, stack = _load_paired_models(doc, legacy_catalog, tmp_path, f"pin_defect_{closure_mode}") + dev = compile_device_1d( + prep, + intervals_per_layer=(8, 16, 8), + te_softness=0.02, + te_regularization_mode="legacy_logistic", + ) + x_legacy = build_electrical_grid(stack, 32) + np.testing.assert_allclose(dev.nodes_m, x_legacy, rtol=0.0, atol=1.0e-15) + + voltages = np.linspace(0.0, 1.25, 26) + _, _, m_ref, _ = _sweep_solarlab_jv(dev_ref, voltages) + v_old, j_old, m_old, _, _ = _sweep_legacy_ss_jv(stack, x_legacy, voltages, te_softness=0.02) + _, j_new, m_new, _ = _sweep_solarlab_jv(dev, v_old, stop_after_voc=False) + + assert m_ref.V_oc - m_new.V_oc > 0.04 + _assert_jv_metrics_parity(m_new, m_old) + np.testing.assert_allclose(j_new, j_old, rtol=5.0e-5, atol=5.0e-4) + + +def test_live_jv_parity_charged_two_sided_interface_closure( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 DC J-V + sheet-charge parity: equilibrium-referenced two-sided heterointerfaces.""" + # Part 1: Public D4-E3 photovoltaic reference fixture (interface_charge_jv_research.yaml) + ref_yaml = ROOT / "perovskite-sim/tests/fixtures/configs/interface_charge_jv_research.yaml" + raw_ref_doc = _clean_json(dict(load_yaml_mapping(ref_yaml.read_bytes()))) + raw_ref_doc["device"] = { + **dict(raw_ref_doc["device"]), + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + } + prep_ref, stack_ref = _load_paired_models( + raw_ref_doc, + legacy_catalog, + tmp_path, + "iface_charge_ref", + ) + x_dedup = build_electrical_grid(stack_ref, 16) + l0 = stack_ref.layers[0].thickness + n_l0 = int(np.sum(x_dedup <= l0 + 1.0e-15)) - 1 + n_l1 = (x_dedup.size - 1) - n_l0 + x_ref = build_two_sided_trace_grid(x_dedup, stack_ref) + dev_ref_native = compile_device_1d(prep_ref, intervals_per_layer=(n_l0, n_l1)) + np.testing.assert_allclose(dev_ref_native.nodes_m, x_ref, rtol=0.0, atol=1.0e-15) + + # Bind exact nodal Beer-Lambert source used by legacy QF solver so discrete PDEs match 1-to-1 + stack_ref_off = dataclasses.replace( + stack_ref, + interface_charge_closure="off", + interface_charge_rebaseline_acknowledged=False, + ) + mat_ref_off = build_material_arrays(x_ref, stack_ref_off) + g_ref_leg = beer_lambert_generation(x_ref, mat_ref_off.alpha, stack_ref.Phi) + dev_ref = dataclasses.replace( + dev_ref_native, + generation=GenerationProfile( + method="legacy_beer_lambert_midpoint_oracle", + geometry_name=dev_ref_native.geometry.name, + source_m3_s=g_ref_leg, + absorbed_m2_s=g_ref_leg * dev_ref_native.geometry.cell_measures_m, + binding_sha256=dev_ref_native.generation.binding_sha256, + control_volume_sha256=dev_ref_native.generation.control_volume_sha256, + ), + ) + + voltages_ref = np.linspace(0.0, 0.12, 7) + proto_ref = build_interface_charge_jv_protocol(stack_ref, voltages_ref) + legacy_ref = solve_interface_charge_jv(x_ref, stack_ref, proto_ref) + v_ref_used = np.asarray(legacy_ref.sweep.voltages_V, dtype=float) + ref_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-11, + max_bias_step_V=0.02, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + _, j_ref_new, m_ref_new, states_ref = _sweep_solarlab_jv( + dev_ref, + v_ref_used, + options=ref_opts, + stop_after_voc=False, + ) + _assert_jv_metrics_parity(m_ref_new, legacy_ref.sweep.metrics) + np.testing.assert_allclose(j_ref_new, legacy_ref.sweep.currents_A_m2, rtol=1.0e-5, atol=1.0e-6) + + # Also verify native BeerLambertBinding end-to-end compilation agrees within O(dx^2) optical quadrature on N=16 + _, _, m_ref_native, _ = _sweep_solarlab_jv( + dev_ref_native, + voltages_ref, + options=ref_opts, + stop_after_voc=True, + ) + assert abs(m_ref_native.V_oc - legacy_ref.sweep.metrics.V_oc) <= 5.0e-4 + + # Dark equilibrium reference occupancy + biased sheet charge & occupancy parity! + assert dev_ref.interface_model is not None + f_eq_new = np.array( + [ + s.charge.equilibrium_occupancy + for s in dev_ref.interface_model.two_sided + if s.charge is not None + ] + ) + np.testing.assert_allclose( + f_eq_new, + legacy_ref.dark_reference.equilibrium_occupancy, + rtol=1.0e-7, + atol=1.0e-9, + ) + for k, (st, pt_old) in enumerate(zip(states_ref, legacy_ref.sweep.points)): + sigma_new = dev_ref.interface_sheet_charges_C_m2(st.u, voltage_V=float(v_ref_used[k])) + occ_new = dev_ref.interface_occupancies(st.u, voltage_V=float(v_ref_used[k])) + np.testing.assert_allclose( + sigma_new, + np.asarray(pt_old.interface_incremental_sheet_charge_C_m2, dtype=float), + rtol=1.0e-6, + atol=1.0e-11, + ) + np.testing.assert_allclose( + occ_new, + np.asarray(pt_old.interface_occupancy, dtype=float), + rtol=1.0e-6, + atol=1.0e-8, + ) + + # Part 2: 3-layer HTL / perovskite / ETL stack with simultaneous charged defects at BOTH junctions! + htl_3l = copy.deepcopy(raw_ref_doc["layers"][1]) + htl_3l.update({"name": "charge_htl", "role": "HTL", "N_A": 1.0e21, "N_D": 0.0, "chi": 3.95}) + etl_3l = copy.deepcopy(raw_ref_doc["layers"][1]) + etl_3l["N_D"] = 1.0e21 + doc_3l = copy.deepcopy(raw_ref_doc) + doc_3l["device"]["Phi"] = 0.0 + doc_3l["layers"] = [htl_3l, raw_ref_doc["layers"][0], etl_3l] + doc_3l["electrical_grid"] = { + "interval_weights": {"charge_htl": 1.0, "charge_absorber": 1.0, "charge_etl": 1.0}, + "alphas": {"charge_htl": 2.0, "charge_absorber": 2.0, "charge_etl": 2.0}, + } + doc_3l["device"]["interface_defects"] = [ + { + "sigma_n_cm2": 6.0e-18, + "sigma_p_cm2": 1.0e-17, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 1.0e11, + "E_t_eV_below_cb": 0.60, + }, + { + "sigma_n_cm2": 8.0e-18, + "sigma_p_cm2": 6.0e-18, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 1.5e11, + "E_t_eV_below_cb": 0.55, + }, + ] + prep_3l, stack_3l = _load_paired_models(doc_3l, legacy_catalog, tmp_path, "pin_3l_charged") + x_3l = build_two_sided_trace_grid(build_electrical_grid(stack_3l, 12), stack_3l) + dev_3l = compile_device_1d(prep_3l, intervals_per_layer=(4, 4, 4)) + np.testing.assert_allclose(dev_3l.nodes_m, x_3l, rtol=0.0, atol=1.0e-15) + + dark_ref_3l = build_equilibrium_referenced_interface_charge_dark_reference(x_3l, stack_3l) + assert dev_3l.interface_model is not None + f_eq_3l = np.array( + [ + s.charge.equilibrium_occupancy + for s in dev_3l.interface_model.two_sided + if s.charge is not None + ] + ) + np.testing.assert_allclose( + f_eq_3l, dark_ref_3l.equilibrium_occupancy, rtol=1.0e-9, atol=1.0e-11 + ) + + seed_old = None + prev_new: State1D | None = None + opts_3l = SteadyOptions( + continuity_tolerance_A_m2=1.0e-11, + max_bias_step_V=0.04, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + for v_val in (0.0, 0.08, 0.16, 0.24): + res_old = solve_equilibrium_referenced_interface_charge_steady_state( + x_3l, + stack_3l, + v_val, + dark_reference=dark_ref_3l, + illuminated=False, + initial_state=seed_old, + ) + seed_old = res_old + st_new = solve_steady_state( + dev_3l, + initial_state=prev_new, + voltage_V=v_val, + generation_scale=0.0, + options=opts_3l, + ).state + prev_new = st_new + assm_3l = AssembledDC1DProblem(dev_3l, voltage_V=v_val, generation_scale=0.0) + j_3l_new = float(-dev_3l.voltage_polarity * np.median(assm_3l.current_density(st_new.u))) + sigma_3l_new = dev_3l.interface_sheet_charges_C_m2(st_new.u, voltage_V=v_val) + occ_3l_new = dev_3l.interface_occupancies(st_new.u, voltage_V=v_val) + np.testing.assert_allclose( + sigma_3l_new, + np.asarray(res_old.interface_incremental_sheet_charge_C_m2, dtype=float), + rtol=1.0e-7, + atol=1.0e-12, + ) + np.testing.assert_allclose( + occ_3l_new, + np.asarray(res_old.interface_occupancy, dtype=float), + rtol=1.0e-7, + atol=1.0e-9, + ) + np.testing.assert_allclose( + j_3l_new, + float(res_old.current_A_m2), + rtol=1.0e-4, + atol=2.5e-8, + ) + assert np.max(np.abs(sigma_3l_new)) > 1.0e-5 + + +def test_live_backward_euler_step_parity_vs_perovskite_sim( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 Backward Euler transient step parity on 3-layer device with active interface defect + TE.""" + doc = _moderate_pin_yaml_dict() + for layer in doc["layers"]: + layer["A_star_n"] = 1.2017e6 + layer["A_star_p"] = 1.2017e6 + doc["device"]["interfaces"] = [[20.0, 15.0], [0.0, 0.0]] + doc["device"]["interface_plane_projection"] = True + doc["device"]["interface_defects"] = [ + None, + { + "sigma_n_cm2": 2.0e-16, + "sigma_p_cm2": 1.5e-16, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 5.0e10, + "E_t_eV_below_cb": 0.60, + }, + ] + prep, stack = _load_paired_models(doc, legacy_catalog, tmp_path, "pin_be_parity") + dev = compile_device_1d( + prep, + intervals_per_layer=(8, 16, 8), + te_softness=0.02, + te_regularization_mode="legacy_logistic", + ) + x = build_electrical_grid(stack, 32) + np.testing.assert_allclose(dev.nodes_m, x, rtol=0.0, atol=1.0e-15) + mat = dataclasses.replace(build_material_arrays(x, stack), te_softness=0.02) + n_nodes = dev.node_count + + v0, v1, dt_s = 0.50, 0.65, 1.0e-7 + + # 1. Solve initial steady state at V = 0.50 V in both engines and confirm steady parity + ss0_new = solve_steady_state( + dev, + voltage_V=v0, + generation_scale=1.0, + options=SteadyOptions(max_bias_step_V=0.05), + ) + ss0_old = legacy_ss.solve_steady_state(x, stack, v0, illuminated=True, mat=mat) + np.testing.assert_allclose(ss0_new.state.electron_density_m3, ss0_old.y[:n_nodes], rtol=1.0e-6) + np.testing.assert_allclose( + ss0_new.state.hole_density_m3, ss0_old.y[n_nodes : 2 * n_nodes], rtol=1.0e-6 + ) + + # 2. Solve implicit Backward Euler step V0 -> V1 over dt_s on AssembledDC1DProblem in solarlab + endpoint_new = AssembledDC1DProblem(dev, voltage_V=v1, generation_scale=1.0) + be_step = BackwardEuler1DStep(endpoint=endpoint_new, previous=ss0_new.state, dt_s=dt_s) # type: ignore[arg-type] + be_settings = NewtonSettings( + production_residual_scaling(dev), + 1.0, + production_coordinates(dev), + SteadyOptions().budget(), + (), + False, + ) + be_res_new = solve_newton(be_step, be_step.initial_coordinates(voltage_lift=True), be_settings) + assert be_res_new.accepted + st1_new = dev.state(be_res_new.state, voltage_V=v1) + + # 3. Solve the identical implicit Backward Euler step on perovskite_sim assemble_rhs + y0_old = ss0_old.y.copy() + n_int = n_nodes - 2 + z_init = np.r_[np.log(y0_old[1 : n_nodes - 1]), np.log(y0_old[n_nodes + 1 : 2 * n_nodes - 1])] + + def legacy_be_residual(z: Vector) -> Vector: + y_trial = y0_old.copy() + y_trial[1 : n_nodes - 1] = np.exp(z[:n_int]) + y_trial[n_nodes + 1 : 2 * n_nodes - 1] = np.exp(z[n_int:]) + y_trial[0] = mat.n_L + y_trial[n_nodes - 1] = mat.n_R + y_trial[n_nodes] = mat.p_L + y_trial[2 * n_nodes - 1] = mat.p_R + dydt = assemble_rhs(0.0, y_trial, x, stack, mat=mat, illuminated=True, V_app=v1) + dn = (y_trial[1 : n_nodes - 1] - y0_old[1 : n_nodes - 1]) / dt_s - dydt[1 : n_nodes - 1] + dp = ( + (y_trial[n_nodes + 1 : 2 * n_nodes - 1] - y0_old[n_nodes + 1 : 2 * n_nodes - 1]) / dt_s + - dydt[n_nodes + 1 : 2 * n_nodes - 1] + ) + return np.r_[ + dn * dt_s / y_trial[1 : n_nodes - 1], + dp * dt_s / y_trial[n_nodes + 1 : 2 * n_nodes - 1], + ] + + sol_old = root(legacy_be_residual, z_init, method="hybr", tol=1.0e-12) + assert sol_old.success, sol_old.message + y1_old = y0_old.copy() + y1_old[1 : n_nodes - 1] = np.exp(sol_old.x[:n_int]) + y1_old[n_nodes + 1 : 2 * n_nodes - 1] = np.exp(sol_old.x[n_int:]) + phi0_old = legacy_ss._phi_from_y(x, mat, y0_old, v0) + phi1_old = legacy_ss._phi_from_y(x, mat, y1_old, v1) + + np.testing.assert_allclose(st1_new.potential_V, phi1_old, rtol=1.0e-8, atol=1.0e-9) + np.testing.assert_allclose( + st1_new.electron_density_m3, y1_old[:n_nodes], rtol=1.0e-6, atol=1.0e-3 + ) + np.testing.assert_allclose( + st1_new.hole_density_m3, y1_old[n_nodes : 2 * n_nodes], rtol=1.0e-6, atol=1.0e-3 + ) + + dx = np.diff(x) + eps_face = EPS_0 * _harmonic_face_average(mat.eps_r) + j_cond_new = endpoint_new.current_density(st1_new.u) + j_disp_new = ( + eps_face * (-(np.diff(st1_new.potential_V) - np.diff(ss0_new.state.potential_V)) / dx) / dt_s + ) + j_tot_new = j_cond_new + j_disp_new + + jn_old, jp_old = carrier_face_currents( + x, + phi1_old, + y1_old[:n_nodes], + y1_old[n_nodes : 2 * n_nodes], + dict(mat.carrier_params), + ) + j_disp_old = eps_face * (-(np.diff(phi1_old) - np.diff(phi0_old)) / dx) / dt_s + j_tot_old = (jn_old + jp_old) + j_disp_old + np.testing.assert_allclose(j_tot_new, j_tot_old, rtol=1.0e-6, atol=1.0e-5) + + +def _solarlab_ac_admittance_spectrum( + dev: CompiledDevice1D, + steady_state: State1D, + v_dc: float, + frequencies_Hz: Vector, + *, + generation_scale: float = 1.0, +) -> tuple[NDArray[np.complex128], NDArray[np.complex128], float]: + """Compute passive-convention small-signal AC admittance Y(omega) on AssembledDC1DProblem.""" + op = AssembledDC1DProblem(dev, voltage_V=v_dc, generation_scale=generation_scale) + u0 = steady_state.u + n_nodes = dev.node_count + j0 = op.jacobian(u0) + k0 = op.storage_jacobian(u0) + + phi_right_per_V = complex(-dev.voltage_polarity, 0.0) + rhs = np.zeros(3 * n_nodes, dtype=np.complex128) + rhs[n_nodes - 1] = phi_right_per_V + fixed: dict[int, complex] = {0: 0.0j, n_nodes - 1: phi_right_per_V} + for offset in (n_nodes, 2 * n_nodes): + fixed[offset] = 0.0j + fixed[offset + n_nodes - 1] = -phi_right_per_V / dev.thermal_voltage_V + + ac_sols = solve_frequency_systems(j0, k0, rhs, frequencies_Hz, fixed_coordinates=fixed) + + # Exact cancellation-free analytical face conduction tangents from CarrierTransport! + eval_state = op.binding.assembler.state(u0, op.inputs) + assert eval_state is not None + t_eval = op.binding.transport.evaluate(eval_state, derivatives=True) + e_fv = t_eval["electron"] + h_fv = t_eval["hole"] + assert isinstance(e_fv, FaceValue) and isinstance(h_fv, FaceValue) + + n_faces = n_nodes - 1 + d_jcond_du = np.zeros((n_faces, 3 * n_nodes), dtype=float) + zero_vec = np.zeros(n_faces, dtype=float) + for charge, fv in ((-Q, e_fv), (Q, h_fv)): + l_phi = np.asarray(fv.left.get("potential", zero_vec), dtype=float) + r_phi = np.asarray(fv.right.get("potential", zero_vec), dtype=float) + l_zn = np.asarray(fv.left.get("electron", zero_vec), dtype=float) + r_zn = np.asarray(fv.right.get("electron", zero_vec), dtype=float) + l_zp = np.asarray(fv.left.get("hole", zero_vec), dtype=float) + r_zp = np.asarray(fv.right.get("hole", zero_vec), dtype=float) + for f in range(n_faces): + d_jcond_du[f, f] += charge * l_phi[f] + d_jcond_du[f, f + 1] += charge * r_phi[f] + d_jcond_du[f, n_nodes + f] += charge * l_zn[f] + d_jcond_du[f, n_nodes + f + 1] += charge * r_zn[f] + d_jcond_du[f, 2 * n_nodes + f] += charge * l_zp[f] + d_jcond_du[f, 2 * n_nodes + f + 1] += charge * r_zp[f] + + cap_face = dev.poisson.face_capacitance_F_m2 + dx = np.diff(dev.nodes_m) + stencil_faces: set[int] = set() + if dev.interface_model is not None: + for dspec in dev.interface_model.defect_srh: + if dspec.plane_params is not None or dspec.projection_weight > 0.0: + stencil_faces.update((dspec.node - 1, dspec.node)) + for tspec in dev.interface_model.two_sided: + stencil_faces.add(tspec.face) + bulk_mask = np.array([f not in stencil_faces for f in range(n_faces)], dtype=bool) + dx_bulk = dx[bulk_mask] + weights = dx_bulk / float(np.sum(dx_bulk)) + polarity = dev.voltage_polarity + + y_spectrum = np.empty(frequencies_Hz.size, dtype=np.complex128) + y_faces_all = np.empty((frequencies_Hz.size, n_faces), dtype=np.complex128) + max_rel_spread = 0.0 + for idx_f, (freq, sol) in enumerate(zip(frequencies_Hz, ac_sols)): + assert sol.componentwise_backward_error <= 1.0e-11 + du = sol.solution + dphi = du[:n_nodes] + omega = 2.0 * np.pi * float(freq) + j_cond_ac = polarity * (d_jcond_du @ du) + j_disp_ac = polarity * 1j * omega * (-cap_face * np.diff(dphi)) + y_faces = j_cond_ac + j_disp_ac + y_faces_all[idx_f] = y_faces + y_bulk = y_faces[bulk_mask] + y_avg = complex(np.sum(weights * y_bulk)) + y_spectrum[idx_f] = y_avg + spread = float(np.max(np.abs(y_bulk - y_avg)) / max(abs(y_avg), 1.0e-30)) + max_rel_spread = max(max_rel_spread, spread) + + return y_spectrum, y_faces_all, max_rel_spread + + +def test_live_small_signal_ac_admittance_parity_vs_perovskite_sim( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 small-signal AC admittance/impedance parity across 1 Hz .. 1 MHz vs perovskite_sim.""" + freqs = np.logspace(0.0, 6.0, 7) + v_dc = 0.65 + + # Case 1: Active bare v_n/v_p heterointerface SRH compared directly against run_quasi_fermi_impedance + # (run_quasi_fermi_impedance builds a matched-band stack without heterojunction offsets; match chi/Eg/DOS) + doc_srh = _moderate_pin_yaml_dict() + ni_match = _thermodynamic_ni(1.0e25, 1.0e25, 1.60) + for layer in doc_srh["layers"]: + layer["chi"] = 3.9 + layer["Eg"] = 1.60 + layer["Nc300"] = 1.0e25 + layer["Nv300"] = 1.0e25 + layer["ni"] = ni_match + layer["n1"] = ni_match + layer["p1"] = ni_match + doc_srh["device"]["interfaces"] = [[30.0, 20.0], [15.0, 35.0]] + prep_srh, stack_srh = _load_paired_models(doc_srh, legacy_catalog, tmp_path, "pin_ac_srh") + dev_srh = compile_device_1d(prep_srh, intervals_per_layer=(8, 16, 8)) + x_srh = build_electrical_grid(stack_srh, 32) + + ss_srh = solve_steady_state( + dev_srh, + voltage_V=v_dc, + generation_scale=1.0, + options=SteadyOptions(max_bias_step_V=0.05), + ) + y_new_srh, _, spread_srh = _solarlab_ac_admittance_spectrum(dev_srh, ss_srh.state, v_dc, freqs) + qf_imp = run_quasi_fermi_impedance( + x_srh, + stack_srh, + freqs, + V_dc=v_dc, + delta_V=0.005, + illuminated=True, + ) + assert spread_srh <= 1.0e-8 + np.testing.assert_allclose(y_new_srh, qf_imp.Y, rtol=1.0e-4, atol=1.0e-6) + np.testing.assert_allclose(1.0 / y_new_srh, qf_imp.Z, rtol=1.0e-4, atol=1.0e-8) + + # Case 2: Full heterojunction explicit interface defects (plane_closure) + finite 1D TE vs solve_frequency_domain + doc_def = _moderate_pin_yaml_dict() + for layer in doc_def["layers"]: + layer["A_star_n"] = 1.2017e6 + layer["A_star_p"] = 1.2017e6 + doc_def["device"]["interfaces"] = [[20.0, 15.0], [0.0, 0.0]] + doc_def["device"]["interface_plane_closure"] = True + doc_def["device"]["interface_plane_generation"] = True + doc_def["device"]["interface_defects"] = [ + None, + { + "sigma_n_cm2": 2.0e-16, + "sigma_p_cm2": 1.5e-16, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 5.0e10, + "E_t_eV_below_cb": 0.60, + }, + ] + prep_def, stack_def = _load_paired_models(doc_def, legacy_catalog, tmp_path, "pin_ac_defect_te") + dev_def = compile_device_1d( + prep_def, + intervals_per_layer=(8, 16, 8), + te_softness=0.02, + te_regularization_mode="legacy_logistic", + ) + x_def = build_electrical_grid(stack_def, 32) + mat_def = dataclasses.replace(build_material_arrays(x_def, stack_def), te_softness=0.02) + ss_def_new = solve_steady_state( + dev_def, + voltage_V=v_dc, + generation_scale=1.0, + options=SteadyOptions(max_bias_step_V=0.05), + ) + y_new_def, _, spread_def = _solarlab_ac_admittance_spectrum( + dev_def, ss_def_new.state, v_dc, freqs + ) + assert spread_def <= 1.0e-7 + + ss_def_old = legacy_ss.solve_steady_state(x_def, stack_def, v_dc, illuminated=True, mat=mat_def) + n_nodes = x_def.size + n_int = n_nodes - 2 + y0_old = ss_def_old.y.copy() + z0_old = np.zeros(2 * n_int, dtype=float) + dx_def = np.diff(x_def) + eps_face_def = EPS_0 * _harmonic_face_average(mat_def.eps_r) + weights_def = dx_def / float(x_def[-1] - x_def[0]) + pol_def = float(mat_def.junction_polarity) + + def legacy_eval(coord: Vector, voltage: float) -> SmallSignalEvaluation: + y_vec = y0_old.copy() + y_vec[1 : n_nodes - 1] = y0_old[1 : n_nodes - 1] * np.exp(coord[:n_int]) + y_vec[n_nodes + 1 : 2 * n_nodes - 1] = y0_old[n_nodes + 1 : 2 * n_nodes - 1] * np.exp( + coord[n_int:] + ) + y_vec[0] = mat_def.n_L + y_vec[n_nodes - 1] = mat_def.n_R + y_vec[n_nodes] = mat_def.p_L + y_vec[2 * n_nodes - 1] = mat_def.p_R + phi_vec = legacy_ss._phi_from_y(x_def, mat_def, y_vec, voltage) + dydt = assemble_rhs( + 0.0, y_vec, x_def, stack_def, mat=mat_def, illuminated=True, V_app=voltage + ) + jn, jp = carrier_face_currents( + x_def, + phi_vec, + y_vec[:n_nodes], + y_vec[n_nodes : 2 * n_nodes], + dict(mat_def.carrier_params), + ) + storage = np.r_[y_vec[1 : n_nodes - 1], y_vec[n_nodes + 1 : 2 * n_nodes - 1]] + rate = np.r_[dydt[1 : n_nodes - 1], dydt[n_nodes + 1 : 2 * n_nodes - 1]] + cond_passive = pol_def * (jn + jp) + disp_charge_passive = pol_def * eps_face_def * (-np.diff(phi_vec) / dx_def) + return SmallSignalEvaluation( + storage=storage, + rate=rate, + conduction_current_faces=cond_passive, + displacement_charge_faces=disp_charge_passive, + ) + + fd_old = solve_frequency_domain( + legacy_eval, + z0_old, + v_dc, + freqs, + state_step=1.0e-5, + voltage_step=1.0e-5, + face_weights=weights_def, + ) + np.testing.assert_allclose(y_new_def, fd_old.admittance, rtol=1.0e-4, atol=1.0e-6) + np.testing.assert_allclose(1.0 / y_new_def, fd_old.impedance, rtol=1.0e-4, atol=1.0e-8) + + # Case 3: Equilibrium-referenced charged two-sided trace small-signal AC Maxwell conservation + # + quasi-static DC conductance parity against perovskite_sim charged QF steady-state slope! + ref_yaml = ROOT / "perovskite-sim/tests/fixtures/configs/interface_charge_jv_research.yaml" + raw_ch = _clean_json(dict(load_yaml_mapping(ref_yaml.read_bytes()))) + raw_ch["device"] = { + **dict(raw_ch["device"]), + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + } + prep_ch, stack_ch = _load_paired_models(raw_ch, legacy_catalog, tmp_path, "pin_ac_charged") + x_ch_dedup = build_electrical_grid(stack_ch, 16) + l0_ch = stack_ch.layers[0].thickness + n0_ch = int(np.sum(x_ch_dedup <= l0_ch + 1.0e-15)) - 1 + n1_ch = (x_ch_dedup.size - 1) - n0_ch + x_ch = build_two_sided_trace_grid(x_ch_dedup, stack_ch) + dev_ch_nat = compile_device_1d(prep_ch, intervals_per_layer=(n0_ch, n1_ch)) + stack_ch_off = dataclasses.replace( + stack_ch, + interface_charge_closure="off", + interface_charge_rebaseline_acknowledged=False, + ) + mat_ch_off = build_material_arrays(x_ch, stack_ch_off) + g_ch_leg = beer_lambert_generation(x_ch, mat_ch_off.alpha, stack_ch.Phi) + dev_ch = dataclasses.replace( + dev_ch_nat, + generation=GenerationProfile( + method="legacy_beer_lambert_midpoint_oracle", + geometry_name=dev_ch_nat.geometry.name, + source_m3_s=g_ch_leg, + absorbed_m2_s=g_ch_leg * dev_ch_nat.geometry.cell_measures_m, + binding_sha256=dev_ch_nat.generation.binding_sha256, + control_volume_sha256=dev_ch_nat.generation.control_volume_sha256, + ), + ) + + v_ch_dc = 0.05 + ss_ch = solve_steady_state( + dev_ch, + voltage_V=v_ch_dc, + generation_scale=1.0, + options=SteadyOptions( + continuity_tolerance_A_m2=1.0e-11, + max_bias_step_V=0.02, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ), + ) + freqs_ch = np.r_[1.0e-4, freqs] + _, y_faces_ch, _ = _solarlab_ac_admittance_spectrum(dev_ch, ss_ch.state, v_ch_dc, freqs_ch) + assert dev_ch.interface_model is not None + assert len(dev_ch.interface_model.two_sided) == 1 + f_iface = dev_ch.interface_model.two_sided[0].face + # Within each bulk layer, Maxwell total current J_cond + j*omega*D is spatially uniform; + # across the QSS static sheet-charge plane, D jumps by Delta_sigma(u) so J_tot jumps by j*omega*d(Delta_sigma). + for k_f in range(freqs_ch.size): + left_y = y_faces_ch[k_f, :f_iface] + right_y = y_faces_ch[k_f, f_iface + 1 :] + for seg in (left_y, right_y): + rel_seg_spread = float( + np.max(np.abs(seg - seg[0])) / max(abs(seg[0]), 1.0e-30) + ) + assert rel_seg_spread <= 1.0e-6 + + dv = 5.0e-4 + dark_ref_ch = build_equilibrium_referenced_interface_charge_dark_reference(x_ch, stack_ch) + s_minus = solve_equilibrium_referenced_interface_charge_steady_state( + x_ch, stack_ch, v_ch_dc - dv, dark_reference=dark_ref_ch, illuminated=True + ) + s_plus = solve_equilibrium_referenced_interface_charge_steady_state( + x_ch, + stack_ch, + v_ch_dc + dv, + dark_reference=dark_ref_ch, + illuminated=True, + initial_state=s_minus, + ) + # Passive current is -J_solar, so dI_passive/dV == -(J_solar(V+dv) - J_solar(V-dv)) / (2*dv) + g_dc_legacy = -(float(s_plus.current_A_m2 - s_minus.current_A_m2) / (2.0 * dv)) + for y_dc_seg in (complex(y_faces_ch[0, 0]), complex(y_faces_ch[0, -1])): + np.testing.assert_allclose(y_dc_seg.real, g_dc_legacy, rtol=1.0e-4, atol=1.0e-6) + assert abs(y_dc_seg.imag) <= 1.0e-5 * abs(y_dc_seg.real) diff --git a/tests/integration/test_neutral_defects_1d.py b/tests/integration/test_neutral_defects_1d.py index 5309a75a..da7ec9dc 100644 --- a/tests/integration/test_neutral_defects_1d.py +++ b/tests/integration/test_neutral_defects_1d.py @@ -212,7 +212,10 @@ def test_species_order_stable_ids_and_document_identity(prepared: PreparedDevice assert compile_device_1d(provenance, intervals_per_layer=example.INTERVALS).identity != compile_device_1d(prepared, intervals_per_layer=example.INTERVALS).identity -@pytest.mark.parametrize("kind", ["charged", "distributed", "spatial", "degeneracy", "interface", "multivalent", "metastable"]) +@pytest.mark.parametrize( + "kind", + ["charged", "distributed", "spatial", "degeneracy", "interface_shared_occupancy", "multivalent", "metastable"], +) def test_unsupported_declarations_refuse_before_solver( prepared: PreparedDevice, kind: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: @@ -234,10 +237,11 @@ def test_unsupported_declarations_refuse_before_solver( {"position_fraction": 0.0, "density_multiplier": 1.0}, {"position_fraction": 1.0, "density_multiplier": 1.0}]} elif kind == "degeneracy": defect["degeneracy"] = 2.0 - elif kind == "interface": + elif kind == "interface_shared_occupancy": document["interfaces"] = [{"id": "interface_trap", "left": "htl", "right": "absorber", "defect": { "id": "surface", "trap_depth_eV": 0.5, "energy_reference": "above_valence_band", "total_density_m2": 1e15, "kinetics": kinetics, "calibration_factor": 1.0, "iface_state_calibration_factor": 1.0}}] + document["settings"]["interface_shared_occupancy"] = True else: donor = {"family": "single_donor", "charge_states_e": [1, 0], "degeneracy_convention": "unity", "state_degeneracies": [1.0, 1.0], "energy_levels": {"first_transition_eV_above_vb": 0.75, diff --git a/tests/unit/equations/test_interface_assembly_1d.py b/tests/unit/equations/test_interface_assembly_1d.py new file mode 100644 index 00000000..56953149 --- /dev/null +++ b/tests/unit/equations/test_interface_assembly_1d.py @@ -0,0 +1,1083 @@ +"""Unit and assembly tests for 1D heterointerface closures on the unified Assembler (P04-09). + +Covers: +- Exact binary64 equality between ``DC1DProblem`` and ``AssembledDC1DProblem`` across all + supported 1D heterointerface modes (bare SRH, single-level defect SRH, plane projection, + plane closure with/without generation, 1D thermionic emission capping, uncharged and + equilibrium-referenced charged two-sided traces); +- Exact analytical sparse Jacobians vs directional finite differences across every mode; +- Invariant 1: finite interface transport (1D TE cap and two-sided trace) replaces—never + acts in parallel with—the internal Scharfetter-Gummel face flux; +- Invariant 2: ``v_n = v_p = 0``, ``A_star = 0``, default flags remain 100% bitwise identical + to a device without interface declarations; +- Invariant 3: falsified ``interface_shared_occupancy``, 1D ``interface_two_sided``, + ``te_physical_norm``, ``interface_tunneling``, enabled ``tunnelling_channels``, + ``het_recomb_despike != 0``, and unqualified combinations raise ``CapabilityError`` + before any nonlinear solve; +- Single constitutive evaluation per trial state for Gauss sheet-charge jump + carrier + capture/emission, dark thermal equilibrium ``sigma == 0``, Gauss jump ``D_R - D_L == sigma``, + and left/right stack reversal symmetry; +- Backward Euler storage-difference step, small-signal AC frequency solve, and multilayer + 1D single-domain + two-domain ionic assembly parity with active heterointerface closures. +""" + +from __future__ import annotations + +from collections.abc import Iterator +import copy +import math +from typing import Any +from unittest import mock + +import numpy as np +from numpy.typing import NDArray +import pytest +from scipy.sparse import csc_matrix, issparse +from threadpoolctl import threadpool_limits + +from examples.research_1d.steady import load_device +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.assembly.ionic_1d import ( + AssembledIonic1DProblem, + AssembledMultipleIonic1DProblem, +) +from solarlab.equations.assembly.small_signal import AssembledIonicSmallSignal1D +from solarlab.equations.dc_1d import CapabilityError, CompiledDevice1D, CompiledInterfaceModel1D, DC1DProblem +from solarlab.equations.ionic_1d import Ionic1DProblem +from solarlab.equations.ionic_small_signal import IonicSmallSignal1D +from solarlab.equations.multiple_ionic_1d import MultipleIonic1DProblem +from solarlab.physics.electrostatics.interface_traces import sheet_charge_row_weights +from solarlab.physics.interface_transport import TwoSidedBulkState, solve_charged_two_sided_interface_qss +from solarlab.physics.recombination.interface import interface_srh_rate +from solarlab.solvers.linear.frequency_domain import solve_frequency_systems +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_equilibrium, solve_steady_state +from solarlab.solvers.time.assembled_ionic_backward_euler import AssembledIonicBackwardEuler1DStep +from solarlab.solvers.time.backward_euler import BackwardEuler1DStep +from solarlab.solvers.time.ionic_backward_euler import IonicBackwardEuler1DStep + +Vector = NDArray[np.float64] + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def base_prepared() -> PreparedDevice: + return load_device() + + +def _edit_prepared(prepared: PreparedDevice, mutate_fn: Any) -> PreparedDevice: + doc = copy.deepcopy(prepared.to_input().editing_data()) + mutate_fn(doc) + return resolve_device( + DeviceInput.model_validate(doc), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + + +def _defect_dict( + defect_id: str, + *, + trap_depth_eV: float = 0.55, + energy_reference: str = "below_conduction_band", + total_density_m2: float = 2.5e15, + sigma_n_m2: float = 1.0e-19, + sigma_p_m2: float = 2.0e-19, + v_th_n_m_s: float = 1.0e5, + v_th_p_m_s: float = 1.0e5, + calibration_factor: float = 1.0, +) -> dict[str, Any]: + return { + "id": defect_id, + "trap_depth_eV": trap_depth_eV, + "energy_reference": energy_reference, + "total_density_m2": total_density_m2, + "kinetics": { + "sigma_n_m2": sigma_n_m2, + "sigma_p_m2": sigma_p_m2, + "thermal_velocity_n_m_s": v_th_n_m_s, + "thermal_velocity_p_m_s": v_th_p_m_s, + }, + "calibration_factor": calibration_factor, + "iface_state_calibration_factor": 1.0, + } + + +def _canonical_csc_bytes(mat: csc_matrix) -> tuple[tuple[int, int], bytes, bytes, bytes]: + c = csc_matrix(mat, copy=True) + c.sum_duplicates() + c.sort_indices() + return c.shape, c.indptr.tobytes(), c.indices.tobytes(), c.data.tobytes() + + +def _assert_dc_assembled_bitwise_equal( + device: CompiledDevice1D, u: Vector, *, voltage_V: float, generation_scale: float +) -> None: + orig = DC1DProblem(device, voltage_V=voltage_V, generation_scale=generation_scale) + assm = AssembledDC1DProblem(device, voltage_V=voltage_V, generation_scale=generation_scale) + + f_orig = orig.residual(u) + f_assm = assm.residual(u) + assert f_orig.tobytes() == f_assm.tobytes() + + j_orig = orig.jacobian(u) + j_assm = assm.jacobian(u) + assert issparse(j_orig) and issparse(j_assm) + assert _canonical_csc_bytes(j_orig) == _canonical_csc_bytes(j_assm) + + fl_orig = orig.fluxes(u) + fl_assm = assm.fluxes(u) + assert fl_orig.electron.flux.tobytes() == fl_assm.electron.flux.tobytes() + assert fl_orig.hole.flux.tobytes() == fl_assm.hole.flux.tobytes() + + +def _perturbed_trial_state(device: CompiledDevice1D, *, voltage_V: float, seed: int = 7) -> Vector: + rng = np.random.default_rng(seed) + n = device.node_count + u_ref = np.r_[device.reference_potential_V, np.zeros(2 * n)] + u0 = device.rebase_coordinates(u_ref, 0.0, voltage_V) + # Smooth interior perturbation keeping boundary potentials and reservoirs clean. + interior = np.sin(np.linspace(0.0, math.pi, n)) + dphi = 0.015 * interior * (1.0 + 0.2 * rng.standard_normal(n)) + dphi[0] = 0.0 + dphi[-1] = 0.0 + dzn = 0.25 * interior * (0.6 + 0.3 * rng.standard_normal(n)) + dzp = -0.20 * interior * (0.5 + 0.3 * rng.standard_normal(n)) + dzn[[0, -1]] = 0.0 + dzp[[0, -1]] = 0.0 + u = u0.copy() + u[:n] += dphi + u[n : 2 * n] += dzn + u[2 * n :] += dzp + return u + + +def _assert_directional_jacobian_fd( + problem: AssembledDC1DProblem, + u: Vector, + *, + step: float = 1.0e-5, + rtol: float = 2.0e-6, + directions: int = 5, +) -> float: + """Verify ``J(u) @ v`` against central FD along random unit directions; return max rel err.""" + jac = problem.jacobian(u) + rng = np.random.default_rng(12345) + dense = jac.toarray() + row_scale = np.maximum(np.linalg.norm(dense, axis=1), 1.0) + worst_rel = 0.0 + for _ in range(directions): + v = rng.standard_normal(u.size) + v /= np.linalg.norm(v) + jv = jac @ v + fp = problem.residual(u + step * v) + fm = problem.residual(u - step * v) + fd = (fp - fm) / (2.0 * step) + diff = np.abs(jv - fd) + denom = np.maximum(np.abs(fd), 1.0e-7 * row_scale) + rel = float(np.max(diff / denom)) + worst_rel = max(worst_rel, rel) + np.testing.assert_allclose(jv, fd, rtol=rtol, atol=1.0e-7 * float(np.max(row_scale))) + return worst_rel + + +def test_invariant2_zero_interface_parameters_are_bitwise_identical( + base_prepared: PreparedDevice, +) -> None: + explicit_zero = _edit_prepared( + base_prepared, + lambda doc: doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 0.0, "v_p": 0.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 0.0, "v_p": 0.0}, + ], + ), + ) + dev_base = compile_device_1d(base_prepared, intervals_per_layer=8) + dev_zero = compile_device_1d(explicit_zero, intervals_per_layer=8) + assert dev_base.interface_model is None + assert dev_zero.interface_model is None + assert "heterointerface_1d" not in dev_base.capabilities + assert "heterointerface_1d" not in dev_zero.capabilities + + u = _perturbed_trial_state(dev_base, voltage_V=0.55) + p_base = AssembledDC1DProblem(dev_base, voltage_V=0.55, generation_scale=1.0) + p_zero = AssembledDC1DProblem(dev_zero, voltage_V=0.55, generation_scale=1.0) + assert p_base.residual(u).tobytes() == p_zero.residual(u).tobytes() + assert _canonical_csc_bytes(p_base.jacobian(u)) == _canonical_csc_bytes(p_zero.jacobian(u)) + + +@pytest.mark.parametrize( + ("mode_name", "mutate"), + [ + ( + "bare_srh", + lambda doc: doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 25.0, "v_p": 40.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 15.0, "v_p": 35.0}, + ], + ), + ), + ( + "defect_cross_carrier_out_of_order", + lambda doc: doc.__setitem__( + "interfaces", + [ + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.50, calibration_factor=0.75), + }, + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict( + "d_htl", + trap_depth_eV=1.05, + energy_reference="above_valence_band", + ), + }, + ], + ), + ), + ( + "plane_projection", + lambda doc: ( + doc["settings"].__setitem__("interface_plane_projection", True), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.60), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.55), + }, + ], + ), + ), + ), + ( + "plane_closure_clamped", + lambda doc: ( + doc["settings"].__setitem__("interface_plane_closure", True), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.60), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.55), + }, + ], + ), + ), + ), + ( + "plane_closure_with_generation", + lambda doc: ( + doc["settings"].__setitem__("interface_plane_closure", True), + doc["settings"].__setitem__("interface_plane_generation", True), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.60), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.55), + }, + ], + ), + ), + ), + ( + "thermionic_cap_and_srh", + lambda doc: ( + doc["layers"][0]["parameters"].update({"A_star_n": 2.5e5, "A_star_p": 3.0e5}), + doc["layers"][1]["parameters"].update({"A_star_n": 1.2017e6, "A_star_p": 1.2017e6}), + doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 20.0, "v_p": 30.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 10.0, "v_p": 25.0}, + ], + ), + ), + ), + ], +) +def test_deduplicated_modes_bitwise_parity_and_directional_fd( + base_prepared: PreparedDevice, mode_name: str, mutate: Any +) -> None: + prep = _edit_prepared(base_prepared, mutate) + reg_mode = "compact_support" if mode_name == "thermionic_cap_and_srh" else "legacy_logistic" + dev = compile_device_1d(prep, intervals_per_layer=8, te_regularization_mode=reg_mode) + assert dev.interface_model is not None + assert "heterointerface_1d" in dev.capabilities + + for voltage_V, gen_scale in ((0.0, 0.0), (0.65, 1.0), (-0.35, 0.0)): + u = _perturbed_trial_state(dev, voltage_V=voltage_V) + _assert_dc_assembled_bitwise_equal(dev, u, voltage_V=voltage_V, generation_scale=gen_scale) + prob = AssembledDC1DProblem(dev, voltage_V=voltage_V, generation_scale=gen_scale) + _assert_directional_jacobian_fd(prob, u) + + +def test_bare_srh_areal_rate_deposition_not_confused_with_volumetric( + base_prepared: PreparedDevice, +) -> None: + """Verify that doubling SRV changes only the shared interface cell residual by exactly R_areal (m^-2 s^-1).""" + prep1 = _edit_prepared( + base_prepared, + lambda doc: doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 12.0, "v_p": 18.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 0.0, "v_p": 0.0}, + ], + ), + ) + prep2 = _edit_prepared( + base_prepared, + lambda doc: doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 24.0, "v_p": 36.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 0.0, "v_p": 0.0}, + ], + ), + ) + d0 = compile_device_1d(base_prepared, intervals_per_layer=8) + d1 = compile_device_1d(prep1, intervals_per_layer=8) + d2 = compile_device_1d(prep2, intervals_per_layer=8) + + # Evaluate at the converged zero-SRV steady state where f0[n + idx] ~ 0, + # avoiding catastrophic cancellation from O(1e20) unrelaxed bulk fluxes. + u = solve_steady_state(d0, voltage_V=0.6, generation_scale=1.0).state.u + f0 = AssembledDC1DProblem(d0, voltage_V=0.6, generation_scale=1.0).residual(u) + f1 = AssembledDC1DProblem(d1, voltage_V=0.6, generation_scale=1.0).residual(u) + f2 = AssembledDC1DProblem(d2, voltage_V=0.6, generation_scale=1.0).residual(u) + + n = d0.node_count + idx = int(d0.geometry.interfaces[0].shared_node) # type: ignore[arg-type] + diff1 = f1 - f0 + diff2 = f2 - f0 + # Continuity equations on the Assembler carry integrated areal residual [m^-2 s^-1]: + # CELL_SOURCE multiplies (-R_areal / dx_cell[idx]) by dx_cell[idx] == -R_areal, + # independent of mesh spacing dx_cell[idx]! + _, n_u, p_u = d1.fields(u, voltage_V=0.6) + assert d1.interface_model is not None + spec1 = d1.interface_model.bare_srh[0] + expected_srh = interface_srh_rate( + float(n_u[idx]), + float(p_u[idx]), + v_n_m_s=spec1.v_n_m_s, + v_p_m_s=spec1.v_p_m_s, + ni_sq_m6=spec1.ni_sq_m6, + n1_m3=spec1.n1_m3, + p1_m3=spec1.p1_m3, + ) + assert abs(diff1[n + idx]) > 1.0e5 + assert diff1[n + idx] == pytest.approx(-expected_srh.rate_m2_s, rel=1e-14) + np.testing.assert_allclose(diff1[n + idx], diff1[2 * n + idx], rtol=1e-14) + np.testing.assert_allclose(diff2[n + idx], 2.0 * diff1[n + idx], rtol=1e-14) + + mask = np.ones(3 * n, dtype=bool) + mask[[n + idx, 2 * n + idx]] = False + np.testing.assert_array_equal(diff1[mask], 0.0) + + +def test_invariant1_thermionic_cap_replaces_not_parallels_sg_face_flux( + base_prepared: PreparedDevice, +) -> None: + """When 1D TE capping activates on an internal heterointerface face, |J_face| <= |J_SG|.""" + prep_te = _edit_prepared( + base_prepared, + lambda doc: ( + # Tiny Richardson constant so legacy unnormalized TE bound (A* T^2 n / q) strongly caps SG. + doc["layers"][0]["parameters"].update({"A_star_n": 1.0e-45, "A_star_p": 1.0e-45}), + doc["layers"][1]["parameters"].update({"A_star_n": 1.0e-45, "A_star_p": 1.0e-45}), + ), + ) + dev_sg = compile_device_1d(base_prepared, intervals_per_layer=8) + dev_hard = compile_device_1d(prep_te, intervals_per_layer=8, te_softness=0.0) + dev_soft = compile_device_1d(prep_te, intervals_per_layer=8, te_softness=0.03) + assert dev_hard.interface_model is not None + assert len(dev_hard.interface_model.thermionic_faces) == 2 + assert any(s.cap_electron for s in dev_hard.interface_model.thermionic_faces) + assert any(s.cap_hole for s in dev_hard.interface_model.thermionic_faces) + + u = _perturbed_trial_state(dev_sg, voltage_V=0.75) + fl_sg = AssembledDC1DProblem(dev_sg, voltage_V=0.75, generation_scale=1.0).fluxes(u) + fl_hard = AssembledDC1DProblem(dev_hard, voltage_V=0.75, generation_scale=1.0).fluxes(u) + fl_soft = AssembledDC1DProblem(dev_soft, voltage_V=0.75, generation_scale=1.0).fluxes(u) + + for te_spec in dev_hard.interface_model.thermionic_faces: + f = te_spec.face + # Replacement caps the magnitude strictly below uncapped SG; parallel addition would increase it! + if te_spec.cap_electron: + assert abs(fl_hard.electron.flux[f]) < 0.05 * abs(fl_sg.electron.flux[f]) + assert abs(fl_soft.electron.flux[f]) < 0.05 * abs(fl_sg.electron.flux[f]) + if te_spec.cap_hole: + assert abs(fl_hard.hole.flux[f]) < 0.05 * abs(fl_sg.hole.flux[f]) + assert abs(fl_soft.hole.flux[f]) < 0.05 * abs(fl_sg.hole.flux[f]) + + # Non-interface faces remain 100% identical to SG! + non_iface = np.ones(dev_sg.node_count - 1, dtype=bool) + for te_spec in dev_hard.interface_model.thermionic_faces: + non_iface[te_spec.face] = False + np.testing.assert_array_equal(fl_hard.electron.flux[non_iface], fl_sg.electron.flux[non_iface]) + np.testing.assert_array_equal(fl_hard.hole.flux[non_iface], fl_sg.hole.flux[non_iface]) + + +def _enable_all_layer_richardson(doc: dict[str, Any]) -> None: + for layer in doc["layers"]: + layer.setdefault("parameters", {}).update({"A_star_n": 1.2017e6, "A_star_p": 1.2017e6}) + + +def test_two_sided_uncharged_and_charged_closures_equilibrium_gauss_jump_and_single_eval( + base_prepared: PreparedDevice, +) -> None: + prep_uncharged = _edit_prepared( + base_prepared, + lambda doc: ( + _enable_all_layer_richardson(doc), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.58, total_density_m2=4.0e15), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.52, total_density_m2=3.0e15), + }, + ], + ), + ), + ) + prep_charged = _edit_prepared( + prep_uncharged, + lambda doc: doc["settings"].update( + { + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + } + ), + ) + + dev_dedup = compile_device_1d(prep_uncharged, intervals_per_layer=8) + dev_ts_uncharged = compile_device_1d( + prep_uncharged, intervals_per_layer=8, interface_topology="two_sided_trace" + ) + dev_ts_charged = compile_device_1d(prep_charged, intervals_per_layer=8) + + # Two shared interface nodes were removed in two_sided_trace! + assert dev_ts_uncharged.node_count == dev_dedup.node_count - 2 + assert dev_ts_charged.node_count == dev_dedup.node_count - 2 + assert dev_ts_charged.interface_model is not None + assert dev_ts_charged.interface_model.has_sheet_charge + + # 1. Dark equilibrium solve on charged two-sided trace: zero net current and zero incremental sheet charge! + dark_charged = solve_equilibrium(dev_ts_charged) + assert dark_charged.converged + np.testing.assert_allclose(dark_charged.current_density_A_m2, 0.0, atol=1e-10) + phi_eq, n_eq, p_eq = ( + dark_charged.state.potential_V, + dark_charged.state.electron_density_m3, + dark_charged.state.hole_density_m3, + ) + u_eq = dark_charged.state.u + n_cnt = dev_ts_charged.node_count + zn_eq = u_eq[n_cnt:2 * n_cnt] + zp_eq = u_eq[2 * n_cnt:] + for spec in dev_ts_charged.interface_model.two_sided: + assert spec.charge is not None + qss_eq = solve_charged_two_sided_interface_qss( + spec.trace_electrostatics, + spec.physics, + TwoSidedBulkState( + float(phi_eq[spec.left_node]), + float(phi_eq[spec.right_node]), + float(n_eq[spec.left_node]), + float(p_eq[spec.left_node]), + float(n_eq[spec.right_node]), + float(p_eq[spec.right_node]), + electron_electrochemical_step=float(zn_eq[spec.right_node] - zn_eq[spec.left_node]), + hole_electrochemical_step=float(-(zp_eq[spec.right_node] - zp_eq[spec.left_node])), + ), + spec.charge, + ) + assert qss_eq.incremental_sheet_charge_C_m2 == pytest.approx(0.0, abs=1e-15) + + # 2. Biased/illuminated state: bitwise parity DC1DProblem == AssembledDC1DProblem, FD Jacobian, + # Gauss sheet-charge row deposition, and single evaluate_state call per assemble()! + for dev in (dev_ts_uncharged, dev_ts_charged): + u = _perturbed_trial_state(dev, voltage_V=0.55) + _assert_dc_assembled_bitwise_equal(dev, u, voltage_V=0.55, generation_scale=1.0) + prob = AssembledDC1DProblem(dev, voltage_V=0.55, generation_scale=1.0) + _assert_directional_jacobian_fd(prob, u, step=1.0e-5, rtol=5.0e-6) + + u_ch = _perturbed_trial_state(dev_ts_charged, voltage_V=0.62) + prob_ch = AssembledDC1DProblem(dev_ts_charged, voltage_V=0.62, generation_scale=1.0) + prob_un = AssembledDC1DProblem(dev_ts_uncharged, voltage_V=0.62, generation_scale=1.0) + + # Verify single constitutive evaluation per trial state in AssembledDC1DProblem! + with mock.patch.object( + CompiledInterfaceModel1D, + "evaluate_state", + wraps=dev_ts_charged.interface_model.evaluate_state, + ) as spy: + _ = prob_ch.residual(u_ch) + assert spy.call_count == 1 + _ = prob_ch.jacobian(u_ch) + assert spy.call_count == 2 + + # Verify Poisson residual difference between charged and uncharged at the SAME (u_ch) + # equals the exact sheet-charge row weights w_L * sigma, w_R * sigma! + f_ch = prob_ch.residual(u_ch) + f_un = prob_un.residual(u_ch) + phi_c, n_c, p_c = dev_ts_charged.fields(u_ch, voltage_V=0.62) + expected_poisson_diff = np.zeros(dev_ts_charged.node_count) + for spec in dev_ts_charged.interface_model.two_sided: + assert spec.charge is not None + qss = solve_charged_two_sided_interface_qss( + spec.trace_electrostatics, + spec.physics, + TwoSidedBulkState( + float(phi_c[spec.left_node]), + float(phi_c[spec.right_node]), + float(n_c[spec.left_node]), + float(p_c[spec.left_node]), + float(n_c[spec.right_node]), + float(p_c[spec.right_node]), + electron_electrochemical_step=float( + u_ch[dev_ts_charged.node_count + spec.right_node] + - u_ch[dev_ts_charged.node_count + spec.left_node] + ), + hole_electrochemical_step=float( + -( + u_ch[2 * dev_ts_charged.node_count + spec.right_node] + - u_ch[2 * dev_ts_charged.node_count + spec.left_node] + ) + ), + ), + spec.charge, + ) + wl, wr = sheet_charge_row_weights( + spec.trace_electrostatics.eps_r_left, + spec.trace_electrostatics.left_distance_m, + spec.trace_electrostatics.eps_r_right, + spec.trace_electrostatics.right_distance_m, + ) + # Note: Assembler negates CELL_SOURCE into F = div(flux) - source, so source = -w * sigma -> F += +w * sigma! + expected_poisson_diff[spec.left_node] += wl * qss.incremental_sheet_charge_C_m2 + expected_poisson_diff[spec.right_node] += wr * qss.incremental_sheet_charge_C_m2 + + assert np.max(np.abs(expected_poisson_diff)) > 1.0e-6 + np.testing.assert_allclose( + f_ch[: dev_ts_charged.node_count] - f_un[: dev_ts_charged.node_count], + expected_poisson_diff, + rtol=1e-13, + atol=1e-18, + ) + + +def test_left_right_stack_reversal_symmetry_on_charged_two_sided_device( + base_prepared: PreparedDevice, +) -> None: + """Reversing HTL/absorber/ETL -> ETL/absorber/HTL (zero optics) gives J_rev(V) == -J_fwd(V).""" + prep_fwd = _edit_prepared( + base_prepared, + lambda doc: ( + _enable_all_layer_richardson(doc), + doc["settings"].update( + { + "Phi": 0.0, + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + } + ), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.58, total_density_m2=2.0e15), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.52, total_density_m2=3.0e15), + }, + ], + ), + ), + ) + prep_rev = _edit_prepared( + prep_fwd, + lambda doc: ( + doc.__setitem__("layers", list(reversed(doc["layers"]))), + doc.__setitem__("electrical_grid", list(reversed(doc["electrical_grid"]))), + doc.__setitem__( + "interfaces", + [ + { + "id": "etl_abs", + "left": "etl", + "right": "absorber", + "defect": _defect_dict("d_etl", trap_depth_eV=0.52, total_density_m2=3.0e15), + }, + { + "id": "abs_htl", + "left": "absorber", + "right": "htl", + "defect": _defect_dict("d_htl", trap_depth_eV=0.58, total_density_m2=2.0e15), + }, + ], + ), + ), + ) + + dev_fwd = compile_device_1d(prep_fwd, intervals_per_layer=(8, 12, 8)) + dev_rev = compile_device_1d(prep_rev, intervals_per_layer=(8, 12, 8)) + assert dev_fwd.voltage_polarity == -dev_rev.voltage_polarity + + # Same forward diode bias V_diode = 0.45 V under each stack's polarity convention! + sym_opts = SteadyOptions(max_bias_step_V=0.025) + sol_fwd = solve_steady_state(dev_fwd, voltage_V=0.45, generation_scale=0.0, options=sym_opts) + sol_rev = solve_steady_state(dev_rev, voltage_V=0.45, generation_scale=0.0, options=sym_opts) + assert sol_fwd.converged and sol_rev.converged + + j_out_fwd = float(-dev_fwd.voltage_polarity * sol_fwd.contact_current_density_A_m2[0]) + j_out_rev = float(-dev_rev.voltage_polarity * sol_rev.contact_current_density_A_m2[0]) + assert abs(j_out_fwd) > 1.0e-7 + assert j_out_rev == pytest.approx(j_out_fwd, rel=1e-9) + np.testing.assert_allclose( + sol_rev.state.electron_density_m3, + sol_fwd.state.electron_density_m3[::-1], + rtol=1e-9, + ) + np.testing.assert_allclose( + sol_rev.state.hole_density_m3, + sol_fwd.state.hole_density_m3[::-1], + rtol=1e-9, + ) + + +@pytest.mark.parametrize( + ("case_id", "mutate", "compile_kwargs", "match_substr"), + [ + ( + "shared_occupancy", + lambda doc: doc["settings"].__setitem__("interface_shared_occupancy", True), + {}, + "interface_shared_occupancy", + ), + ( + "two_sided_additive_1d", + lambda doc: doc["settings"].__setitem__("interface_two_sided", True), + {}, + "interface_two_sided", + ), + ( + "te_physical_norm_p08_03", + lambda doc: doc["layers"][0]["parameters"].__setitem__("A_star_n", 1.0e5) + or doc["settings"].__setitem__("te_physical_norm", True), + {}, + "te_physical_norm", + ), + ( + "interface_tunneling", + lambda doc: doc["settings"].__setitem__("interface_tunneling", True), + {}, + "interface_tunneling", + ), + ( + "het_recomb_despike", + lambda doc: doc["settings"].__setitem__("het_recomb_despike", 0.05), + {}, + "het_recomb_despike", + ), + ( + "charge_closure_unacknowledged", + lambda doc: doc["settings"].update( + { + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": False, + } + ), + {}, + "rebaseline", + ), + ( + "charge_closure_on_deduplicated", + lambda doc: ( + _enable_all_layer_richardson(doc), + doc["settings"].update( + { + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + } + ), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d1"), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d2"), + }, + ], + ), + ), + {"interface_topology": "deduplicated"}, + "two_sided_trace", + ), + ( + "charge_closure_with_nonunit_calibration", + lambda doc: ( + _enable_all_layer_richardson(doc), + doc["settings"].update( + { + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + } + ), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d1", calibration_factor=0.5), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d2"), + }, + ], + ), + ), + {}, + "calibration factors", + ), + ( + "plane_generation_without_closure", + lambda doc: doc["settings"].__setitem__("interface_plane_generation", True), + {}, + "interface_plane_closure", + ), + ( + "plane_projection_and_closure_together", + lambda doc: doc["settings"].update( + {"interface_plane_projection": True, "interface_plane_closure": True} + ), + {}, + "mutually exclusive", + ), + ( + "plane_closure_without_defect", + lambda doc: doc["settings"].__setitem__("interface_plane_closure", True), + {}, + "requires at least one interface defect", + ), + ], +) +def test_invariant3_refused_interface_combinations_raise_capability_error( + base_prepared: PreparedDevice, + case_id: str, + mutate: Any, + compile_kwargs: dict[str, Any], + match_substr: str, +) -> None: + with pytest.raises((CapabilityError, ValueError), match=match_substr): + prep = _edit_prepared(base_prepared, mutate) + compile_device_1d(prep, intervals_per_layer=6, **compile_kwargs) + + +def test_backward_euler_and_small_signal_ac_on_assembled_charged_interface( + base_prepared: PreparedDevice, +) -> None: + prep = _edit_prepared( + base_prepared, + lambda doc: ( + _enable_all_layer_richardson(doc), + doc["settings"].update( + { + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + } + ), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.58, total_density_m2=3.0e15), + }, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "defect": _defect_dict("d_etl", trap_depth_eV=0.52, total_density_m2=3.0e15), + }, + ], + ), + ), + ) + dev = compile_device_1d(prep, intervals_per_layer=8) + steady = solve_steady_state( + dev, + voltage_V=0.55, + generation_scale=1.0, + options=SteadyOptions(max_bias_step_V=0.05), + ) + assert steady.converged + + # 1. Backward Euler step on AssembledDC1DProblem: verify BE Jacobian matches directional FD! + endpoint = AssembledDC1DProblem(dev, voltage_V=0.60, generation_scale=1.0) + be_step = BackwardEuler1DStep(endpoint=endpoint, previous=steady.state, dt_s=1.0e-7) # type: ignore[arg-type] + u_trial = be_step.initial_coordinates(voltage_lift=True) + j_be = be_step.jacobian(u_trial) + v = np.random.default_rng(99).standard_normal(u_trial.size) + v /= np.linalg.norm(v) + h = 1.0e-5 + fd_be = (be_step.residual(u_trial + h * v) - be_step.residual(u_trial - h * v)) / (2.0 * h) + jv_be = j_be @ v + row_scale = float(np.max(np.linalg.norm(j_be.toarray(), axis=1))) + np.testing.assert_allclose(jv_be, fd_be, rtol=5.0e-6, atol=1.0e-7 * row_scale) + + # 2. Small-signal AC solve (J + j * omega * M) * du = rhs across 1 Hz .. 1 MHz! + op = AssembledDC1DProblem(dev, voltage_V=0.55, generation_scale=1.0) + u0 = steady.state.u + j0 = op.jacobian(u0) + k0 = op.storage_jacobian(u0) + n_nodes = dev.node_count + v_ac = complex(0.01, 0.0) + phi_right = -dev.voltage_polarity * v_ac + rhs_ac = np.zeros(3 * n_nodes, dtype=np.complex128) + rhs_ac[n_nodes - 1] = phi_right + fixed_ac: dict[int, complex] = {0: 0.0j, n_nodes - 1: phi_right} + for offset in (n_nodes, 2 * n_nodes): + fixed_ac[offset] = 0.0j + fixed_ac[offset + n_nodes - 1] = -phi_right / dev.thermal_voltage_V + + freqs = (1.0, 1.0e2, 1.0e4, 1.0e6) + ac_solutions = solve_frequency_systems(j0, k0, rhs_ac, freqs, fixed_coordinates=fixed_ac) + assert len(ac_solutions) == len(freqs) + for sol in ac_solutions: + assert np.all(np.isfinite(sol.solution)) + assert np.linalg.norm(sol.solution) > 0.0 + assert sol.componentwise_backward_error <= 1.0e-11 + + +def test_multilayer_ionic_and_multiple_ionic_interface_assembly_parity( + base_prepared: PreparedDevice, +) -> None: + """Verify Ionic1DProblem == AssembledIonic1DProblem + BE + AC and 2-domain MultipleIonic parity.""" + prep_ion = _edit_prepared( + base_prepared, + lambda doc: ( + doc["layers"][0]["parameters"].update({"A_star_n": 2.5e5, "A_star_p": 3.0e5}), + doc["layers"][1]["parameters"].update( + { + "A_star_n": 2.0e5, + "A_star_p": 2.5e5, + "P0": 1.0e23, + "P_lim": 1.0e26, + "D_ion": 1.0e-15, + } + ), + doc.__setitem__( + "interfaces", + [ + { + "id": "htl_abs", + "left": "htl", + "right": "absorber", + "defect": _defect_dict("d_htl", trap_depth_eV=0.60), + }, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 18.0, "v_p": 32.0}, + ], + ), + ), + ) + ion_dev = compile_ionic_device_1d( + prep_ion, + intervals_per_layer=6, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + assert ion_dev.electronic_component.interface_model is not None + + n_e = ion_dev.node_count + u_e = _perturbed_trial_state(ion_dev.electronic_component, voltage_V=0.45) + u_ion = np.r_[u_e, 0.05 * np.cos(np.linspace(0.0, math.pi, ion_dev.ion_node_count))] + + orig_ion = Ionic1DProblem(ion_dev, voltage_V=0.45, generation_scale=1.0) + assm_ion = AssembledIonic1DProblem(ion_dev, voltage_V=0.45, generation_scale=1.0) + assert orig_ion.residual(u_ion).tobytes() == assm_ion.residual(u_ion).tobytes() + assert _canonical_csc_bytes(orig_ion.jacobian(u_ion)) == _canonical_csc_bytes( + assm_ion.jacobian(u_ion) + ) + + # Directional FD check on AssembledIonic1DProblem Jacobian! + j_ion = assm_ion.jacobian(u_ion) + rng = np.random.default_rng(314) + v = rng.standard_normal(u_ion.size) + v /= np.linalg.norm(v) + h = 1.0e-5 + fd_ion = (assm_ion.residual(u_ion + h * v) - assm_ion.residual(u_ion - h * v)) / (2.0 * h) + row_scale = float(np.max(np.linalg.norm(j_ion.toarray(), axis=1))) + np.testing.assert_allclose(j_ion @ v, fd_ion, rtol=5.0e-6, atol=1.0e-7 * row_scale) + + # AssembledIonicBackwardEuler1DStep == IonicBackwardEuler1DStep + AssembledIonicSmallSignal1D! + prev_state = ion_dev.state(u_ion, voltage_V=0.45) + be_orig = IonicBackwardEuler1DStep(orig_ion, prev_state, dt_s=1.0e-4) + be_ion = AssembledIonicBackwardEuler1DStep(assm_ion, prev_state, dt_s=1.0e-4) + assert be_orig.residual(u_ion).tobytes() == be_ion.residual(u_ion).tobytes() + assert _canonical_csc_bytes(be_orig.jacobian(u_ion)) == _canonical_csc_bytes(be_ion.jacobian(u_ion)) + assert np.all(np.isfinite(be_ion.residual(u_ion))) + assert np.all(np.isfinite(be_ion.jacobian(u_ion).data)) + + ac_orig = IonicSmallSignal1D(orig_ion, prev_state, "fixed_reference_v1") + ac_ion = AssembledIonicSmallSignal1D(assm_ion, prev_state, "fixed_reference_v1") + phasor = complex(0.01, 0.0) + sys_orig = ac_orig.system(1.0e3, voltage_phasor_V=phasor) + sys_assm = ac_ion.system(1.0e3, voltage_phasor_V=phasor) + assert _canonical_csc_bytes(sys_orig.jacobian) == _canonical_csc_bytes(sys_assm.jacobian) + assert sys_orig.rhs.tobytes() == sys_assm.rhs.tobytes() + ac_res = solve_frequency_systems( + sys_assm.jacobian, + sys_assm.storage_jacobian, + sys_assm.rhs, + [1.0e3], + fixed_coordinates=sys_assm.fixed_coordinates, + rhs_rate=sys_assm.rhs_rate, + )[0] + obs_orig = ac_orig.observe(ac_res.solution, 1.0e3, voltage_phasor_V=phasor) + obs_assm = ac_ion.observe(ac_res.solution, 1.0e3, voltage_phasor_V=phasor) + assert obs_assm["admittance_density_S_m2"] == obs_orig["admittance_density_S_m2"] + adm = obs_assm["admittance_density_S_m2"] + assert isinstance(adm, complex) and np.isfinite(adm.real) and np.isfinite(adm.imag) + + # Two-domain MultipleIonic1DProblem == AssembledMultipleIonic1DProblem with active interface SRH! + prep_multi = _edit_prepared( + base_prepared, + lambda doc: ( + doc["layers"][0]["parameters"].update({"P0": 5.0e22, "P_lim": 1.0e26, "D_ion": 1.0e-16}), + doc["layers"][2]["parameters"].update({"P0": 8.0e22, "P_lim": 1.0e26, "D_ion": 2.0e-16}), + doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 15.0, "v_p": 25.0}, + {"id": "abs_etl", "left": "absorber", "right": "etl", "v_n": 20.0, "v_p": 30.0}, + ], + ), + ), + ) + multi_dev = compile_multiple_ionic_device_1d( + prep_multi, + intervals_per_layer=6, + ion_domains=(("htl", ("blocking", "blocking")), ("etl", ("blocking", "blocking"))), + ) + assert multi_dev.electronic_component.interface_model is not None + u_multi = np.r_[ + _perturbed_trial_state(multi_dev.electronic_component, voltage_V=0.35), + np.zeros(multi_dev.state_size - 3 * n_e), + ] + orig_m = MultipleIonic1DProblem(multi_dev, voltage_V=0.35, generation_scale=1.0) + assm_m = AssembledMultipleIonic1DProblem(multi_dev, voltage_V=0.35, generation_scale=1.0) + assert orig_m.residual(u_multi).tobytes() == assm_m.residual(u_multi).tobytes() + assert _canonical_csc_bytes(orig_m.jacobian(u_multi)) == _canonical_csc_bytes( + assm_m.jacobian(u_multi) + ) + + +def test_mixed_interfaces_and_interface_defects_defect_slot_wins( + base_prepared: PreparedDevice, +) -> None: + """When an interface slot carries both v_n=v_p=0 and an explicit defect, the defect wins.""" + prep = _edit_prepared( + base_prepared, + lambda doc: doc.__setitem__( + "interfaces", + [ + {"id": "htl_abs", "left": "htl", "right": "absorber", "v_n": 20.0, "v_p": 15.0}, + { + "id": "abs_etl", + "left": "absorber", + "right": "etl", + "v_n": 0.0, + "v_p": 0.0, + "defect": _defect_dict("d_etl", trap_depth_eV=0.58, total_density_m2=5.0e14), + }, + ], + ), + ) + dev = compile_device_1d(prep, intervals_per_layer=6) + assert dev.interface_model is not None + assert len(dev.interface_model.bare_srh) == 1 + assert dev.interface_model.bare_srh[0].interface_index == 0 + assert dev.interface_model.bare_srh[0].v_n_m_s == pytest.approx(20.0) + assert len(dev.interface_model.defect_srh) == 1 + assert dev.interface_model.defect_srh[0].interface_index == 1 + assert dev.interface_model.defect_srh[0].v_n_m_s > 0.0 + assert dev.interface_model.defect_srh[0].v_p_m_s > 0.0 + diff --git a/tests/unit/physics/test_interface_recombination.py b/tests/unit/physics/test_interface_recombination.py new file mode 100644 index 00000000..a0c9371d --- /dev/null +++ b/tests/unit/physics/test_interface_recombination.py @@ -0,0 +1,532 @@ +"""Unit tests for heterointerface SRH, plane closure, and sheet-charge laws (P04-09).""" + +from __future__ import annotations + +from collections.abc import Iterator +import math + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.physics.recombination.interface import ( + InterfaceDefectSpec, + S_SUPPLY_M_S, + TwoDimensionalInterfaceSRHMode, + build_plane_closure_params, + equilibrium_referenced_sheet_charge, + evaluate_cross_carrier_cell_pair_srh, + evaluate_shared_interface_trap, + interface_srh_rate, + resolve_interface_defect_references, + solve_plane_closure, +) +from solarlab.physics.statistics.thermal import thermal_voltage + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +def test_interface_srh_rate_equilibrium_zero_and_disabled_velocities() -> None: + ni = 2.5e16 + ni_sq = ni * ni + n_eq = 5.0e18 + p_eq = ni_sq / n_eq + res = interface_srh_rate( + n_eq, + p_eq, + v_n_m_s=15.0, + v_p_m_s=40.0, + ni_sq_m6=ni_sq, + n1_m3=1.2e16, + p1_m3=5.2e16, + ) + assert float(res.rate_m2_s) == 0.0 + assert float(res.d_rate_dn_m_s) > 0.0 + assert float(res.d_rate_dp_m_s) > 0.0 + + for vn, vp in ((0.0, 25.0), (25.0, 0.0), (0.0, 0.0)): + off = interface_srh_rate( + 1.0e20, + 2.0e20, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_m6=ni_sq, + n1_m3=ni, + p1_m3=ni, + ) + assert float(off.rate_m2_s) == 0.0 + assert float(off.d_rate_dn_m_s) == 0.0 + assert float(off.d_rate_dp_m_s) == 0.0 + + +def test_interface_srh_areal_scaling_and_nonnegative_clamp() -> None: + ni_sq = 1.0e32 + r1 = interface_srh_rate( + 1.0e19, 4.0e18, v_n_m_s=3.0, v_p_m_s=7.0, ni_sq_m6=ni_sq, n1_m3=1.0e16, p1_m3=1.0e16 + ) + r2 = interface_srh_rate( + 1.0e19, 4.0e18, v_n_m_s=6.0, v_p_m_s=14.0, ni_sq_m6=ni_sq, n1_m3=1.0e16, p1_m3=1.0e16 + ) + np.testing.assert_allclose(r2.rate_m2_s, 2.0 * r1.rate_m2_s, rtol=1e-15, atol=0.0) + + # Depletion n * p < ni^2: signed vs clamped. + signed = interface_srh_rate( + 1.0e13, + 1.0e14, + v_n_m_s=10.0, + v_p_m_s=20.0, + ni_sq_m6=ni_sq, + n1_m3=1.0e16, + p1_m3=1.0e16, + clamp_nonnegative=False, + ) + clamped = interface_srh_rate( + 1.0e13, + 1.0e14, + v_n_m_s=10.0, + v_p_m_s=20.0, + ni_sq_m6=ni_sq, + n1_m3=1.0e16, + p1_m3=1.0e16, + clamp_nonnegative=True, + ) + assert float(signed.rate_m2_s) < 0.0 + assert float(clamped.rate_m2_s) == 0.0 + assert float(clamped.d_rate_dn_m_s) == 0.0 + assert float(clamped.d_rate_dp_m_s) == 0.0 + + +@pytest.mark.parametrize( + ("n_val", "p_val"), + [ + (1.0e14, 1.0e15), # deep depletion (generation) + (4.0e17, 6.25e14), # exact thermal equilibrium n*p == 2.5e32 + (4.0e17 * (1.0 + 1e-11), 6.25e14), # near-equilibrium cancellation test + (3.5e20, 8.2e19), # strong forward injection + ], +) +def test_interface_srh_derivatives_match_complex_step_and_fd(n_val: float, p_val: float) -> None: + ni_sq = 2.5e32 + vn, vp = 18.5, 42.0 + n1, p1 = 5.0e16, 5.0e15 + ev = interface_srh_rate( + n_val, p_val, v_n_m_s=vn, v_p_m_s=vp, ni_sq_m6=ni_sq, n1_m3=n1, p1_m3=p1 + ) + + eps_cs = 1.0e-30 + cs_n = interface_srh_rate( + n_val + 1j * eps_cs * n_val, + p_val, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_m6=ni_sq, + n1_m3=n1, + p1_m3=p1, + ) + cs_p = interface_srh_rate( + n_val, + p_val + 1j * eps_cs * p_val, + v_n_m_s=vn, + v_p_m_s=vp, + ni_sq_m6=ni_sq, + n1_m3=n1, + p1_m3=p1, + ) + dn_cs = float(np.imag(cs_n.rate_m2_s)) / (eps_cs * n_val) + dp_cs = float(np.imag(cs_p.rate_m2_s)) / (eps_cs * p_val) + np.testing.assert_allclose(float(ev.d_rate_dn_m_s), dn_cs, rtol=1e-14, atol=0.0) + np.testing.assert_allclose(float(ev.d_rate_dp_m_s), dp_cs, rtol=1e-14, atol=0.0) + + +def test_resolve_interface_defect_references_rules_and_detailed_balance() -> None: + vt = thermal_voltage(300.0) + # Unique absorber wins even if transport layer had smaller gap; test standard HTL/absorber. + refs_cb = resolve_interface_defect_references( + left_role="HTL", + right_role="absorber", + left_chi_phys_eV=3.6, + left_Eg_phys_eV=2.2, + left_Nc_m3=1.0e25, + left_Nv_m3=2.0e25, + right_chi_phys_eV=3.9, + right_Eg_phys_eV=1.6, + right_Nc_m3=3.0e24, + right_Nv_m3=5.0e24, + thermal_voltage_V=vt, + trap_depth_eV=0.55, + energy_reference="below_conduction_band", + require_in_gap=True, + ) + refs_vb = resolve_interface_defect_references( + left_role="HTL", + right_role="absorber", + left_chi_phys_eV=3.6, + left_Eg_phys_eV=2.2, + left_Nc_m3=1.0e25, + left_Nv_m3=2.0e25, + right_chi_phys_eV=3.9, + right_Eg_phys_eV=1.6, + right_Nc_m3=3.0e24, + right_Nv_m3=5.0e24, + thermal_voltage_V=vt, + trap_depth_eV=1.6 - 0.55, + energy_reference="above_valence_band", + require_in_gap=True, + ) + assert refs_cb.reference_side == "right" + np.testing.assert_allclose(refs_cb.n1_reference_m3, refs_vb.n1_reference_m3, rtol=1e-14) + np.testing.assert_allclose(refs_cb.p1_reference_m3, refs_vb.p1_reference_m3, rtol=1e-14) + np.testing.assert_allclose(refs_cb.n1_left_m3, refs_vb.n1_left_m3, rtol=1e-14) + np.testing.assert_allclose(refs_cb.p1_left_m3, refs_vb.p1_left_m3, rtol=1e-14) + + # Detailed balance on each physical band structure: n1_s * p1_s == Nc_s * Nv_s * exp(-Eg_s/vt) + ni_sq_left = 1.0e25 * 2.0e25 * math.exp(-2.2 / vt) + ni_sq_right = 3.0e24 * 5.0e24 * math.exp(-1.6 / vt) + np.testing.assert_allclose( + refs_cb.n1_left_m3 * refs_cb.p1_left_m3, ni_sq_left, rtol=1e-13 + ) + np.testing.assert_allclose( + refs_cb.n1_right_m3 * refs_cb.p1_right_m3, ni_sq_right, rtol=1e-13 + ) + + # Smaller Eg wins when neither (or both) is absorber; left wins exact ties. + tie = resolve_interface_defect_references( + left_role="absorber", + right_role="absorber", + left_chi_phys_eV=3.9, + left_Eg_phys_eV=1.55, + left_Nc_m3=2.0e24, + left_Nv_m3=2.0e24, + right_chi_phys_eV=4.0, + right_Eg_phys_eV=1.55, + right_Nc_m3=2.0e24, + right_Nv_m3=2.0e24, + thermal_voltage_V=vt, + trap_depth_eV=0.4, + energy_reference="below_conduction_band", + ) + assert tie.reference_side == "left" + + with pytest.raises(ValueError, match="outside reference physical band gap"): + resolve_interface_defect_references( + left_role="HTL", + right_role="absorber", + left_chi_phys_eV=3.6, + left_Eg_phys_eV=2.2, + left_Nc_m3=1.0e25, + left_Nv_m3=2.0e25, + right_chi_phys_eV=3.9, + right_Eg_phys_eV=1.6, + right_Nc_m3=3.0e24, + right_Nv_m3=5.0e24, + thermal_voltage_V=vt, + trap_depth_eV=1.7, + energy_reference="below_conduction_band", + require_in_gap=True, + ) + + spec = InterfaceDefectSpec( + areal_density_m2=2.0e15, + trap_depth_eV=0.5, + energy_reference="below_conduction_band", + sigma_n_m2=1.0e-19, + sigma_p_m2=3.0e-19, + v_th_n_m_s=1.0e5, + v_th_p_m_s=1.0e5, + calibration_factor=0.5, + ) + assert spec.microscopic_capture_velocities_m_s == pytest.approx((20.0, 60.0)) + assert spec.effective_capture_velocities_m_s() == pytest.approx((10.0, 30.0)) + + +def test_shared_interface_trap_detailed_balance_sheet_charge_and_fd_jacobians() -> None: + vt = thermal_voltage(300.0) + refs = resolve_interface_defect_references( + left_role="HTL", + right_role="absorber", + left_chi_phys_eV=3.7, + left_Eg_phys_eV=2.0, + left_Nc_m3=5.0e24, + left_Nv_m3=8.0e24, + right_chi_phys_eV=3.9, + right_Eg_phys_eV=1.6, + right_Nc_m3=2.5e24, + right_Nv_m3=3.5e24, + thermal_voltage_V=vt, + trap_depth_eV=0.65, + energy_reference="below_conduction_band", + ) + # Thermal equilibrium across potential jump delta_phi = phi_R - phi_L: + # wait: trace emission densities n1_L, n1_R are referenced to zero local electrostatic shift; + # at zero potential jump across the zero-thickness plane (phi_tL == phi_tR), + # equilibrium Fermi level E_F gives n_s / n1_s = exp((E_F - E_t)/vt) = p1_s / p_s = lambda_eq! + lam = 12.5 + n_eq_l = lam * refs.n1_left_m3 + p_eq_l = refs.p1_left_m3 / lam + n_eq_r = lam * refs.n1_right_m3 + p_eq_r = refs.p1_right_m3 / lam + f_expected = lam / (1.0 + lam) + + eq_eval = evaluate_shared_interface_trap( + n_eq_l, + p_eq_l, + n_eq_r, + p_eq_r, + v_n_left_m_s=15.0, + v_p_left_m_s=35.0, + v_n_right_m_s=25.0, + v_p_right_m_s=45.0, + n1_left_m3=refs.n1_left_m3, + p1_left_m3=refs.p1_left_m3, + n1_right_m3=refs.n1_right_m3, + p1_right_m3=refs.p1_right_m3, + areal_density_m2=4.0e15, + equilibrium_occupancy=f_expected, + ) + assert eq_eval.occupancy == pytest.approx(f_expected, rel=1e-14) + one_way_scale = max(25.0 * n_eq_r, 45.0 * p_eq_r, 15.0 * n_eq_l, 35.0 * p_eq_l) + np.testing.assert_allclose(eq_eval.capture_rates_m2_s, 0.0, atol=1e-14 * one_way_scale) + assert eq_eval.incremental_sheet_charge_C_m2 == pytest.approx(0.0, abs=1e-22) + + # Non-equilibrium trial state: check C_nL + C_nR == C_pL + C_pR, sheet charge formula, and FD Jacobians. + dens = np.array([2.4e18, 9.1e19, 7.3e19, 1.8e18], dtype=np.float64) + nt = 3.5e15 + f_ref = 0.28 + base = evaluate_shared_interface_trap( + float(dens[0]), + float(dens[1]), + float(dens[2]), + float(dens[3]), + v_n_left_m_s=12.0, + v_p_left_m_s=28.0, + v_n_right_m_s=19.0, + v_p_right_m_s=33.0, + n1_left_m3=refs.n1_left_m3, + p1_left_m3=refs.p1_left_m3, + n1_right_m3=refs.n1_right_m3, + p1_right_m3=refs.p1_right_m3, + areal_density_m2=nt, + equilibrium_occupancy=f_ref, + ) + assert 0.0 < base.occupancy < 1.0 + np.testing.assert_allclose( + base.capture_rates_m2_s[0] + base.capture_rates_m2_s[2], + base.capture_rates_m2_s[1] + base.capture_rates_m2_s[3], + rtol=1e-14, + ) + expected_sigma = equilibrium_referenced_sheet_charge( + base.occupancy, areal_density_m2=nt, equilibrium_occupancy=f_ref + ) + assert base.incremental_sheet_charge_C_m2 == pytest.approx(expected_sigma, rel=1e-15) + assert expected_sigma == pytest.approx(-Q * nt * (base.occupancy - f_ref), rel=1e-15) + + fd_df = np.zeros(4) + fd_dcap = np.zeros((4, 4)) + fd_dsigma = np.zeros(4) + for j in range(4): + step = 1.0e-6 * dens[j] + dp = dens.copy() + dm = dens.copy() + dp[j] += step + dm[j] -= step + ep = evaluate_shared_interface_trap( + float(dp[0]), + float(dp[1]), + float(dp[2]), + float(dp[3]), + v_n_left_m_s=12.0, + v_p_left_m_s=28.0, + v_n_right_m_s=19.0, + v_p_right_m_s=33.0, + n1_left_m3=refs.n1_left_m3, + p1_left_m3=refs.p1_left_m3, + n1_right_m3=refs.n1_right_m3, + p1_right_m3=refs.p1_right_m3, + areal_density_m2=nt, + equilibrium_occupancy=f_ref, + ) + em = evaluate_shared_interface_trap( + float(dm[0]), + float(dm[1]), + float(dm[2]), + float(dm[3]), + v_n_left_m_s=12.0, + v_p_left_m_s=28.0, + v_n_right_m_s=19.0, + v_p_right_m_s=33.0, + n1_left_m3=refs.n1_left_m3, + p1_left_m3=refs.p1_left_m3, + n1_right_m3=refs.n1_right_m3, + p1_right_m3=refs.p1_right_m3, + areal_density_m2=nt, + equilibrium_occupancy=f_ref, + ) + fd_df[j] = (ep.occupancy - em.occupancy) / (2.0 * step) + fd_dcap[:, j] = (ep.capture_rates_m2_s - em.capture_rates_m2_s) / (2.0 * step) + fd_dsigma[j] = ( + ep.incremental_sheet_charge_C_m2 - em.incremental_sheet_charge_C_m2 + ) / (2.0 * step) + + np.testing.assert_allclose(base.d_occupancy_d_densities_m3, fd_df, rtol=5e-8, atol=0.0) + np.testing.assert_allclose(base.d_capture_d_densities_m_s, fd_dcap, rtol=5e-8, atol=1e-18) + np.testing.assert_allclose(base.d_sheet_charge_d_densities_C_m, fd_dsigma, rtol=5e-8, atol=0.0) + + +@pytest.mark.parametrize("allow_generation", [False, True]) +def test_plane_closure_qss_balance_equilibrium_and_ift_derivatives( + allow_generation: bool, +) -> None: + vt = thermal_voltage(300.0) + chi_l, chi_r = 3.72, 3.91 + ceg_l, ceg_r = 5.85, 5.51 + nc_ref, nv_ref = 2.8e24, 3.6e24 + chi_ref_phys = 3.90 + et_depth = 0.62 + + params = build_plane_closure_params( + chi_left_folded_eV=chi_l, + chi_right_folded_eV=chi_r, + valence_left_folded_eV=ceg_l, + valence_right_folded_eV=ceg_r, + Nc_ref_m3=nc_ref, + Nv_ref_m3=nv_ref, + chi_ref_phys_eV=chi_ref_phys, + trap_depth_below_ref_cb_eV=et_depth, + thermal_voltage_V=vt, + ) + assert params.s_supply_m_s == S_SUPPLY_M_S + assert params.n1_s_m3 * params.p1_s_m3 == pytest.approx(params.ni_s_sq_m6, rel=1e-13) + + # Supply-balanced equilibrium point (nb = 2 * n_s_eq, pb = 2 * p_s_eq, n_s_eq * p_s_eq == ni_s^2) + # gives R = 0 under both clamped and signed-generation branches. + n_s_eq = math.sqrt(params.ni_s_sq_m6) * 2.0 + p_s_eq = params.ni_s_sq_m6 / n_s_eq + nl_bal = n_s_eq / params.bn_L + nr_bal = n_s_eq / params.bn_R + pl_bal = p_s_eq / params.bp_L + pr_bal = p_s_eq / params.bp_R + bal_res = solve_plane_closure( + nl_bal, nr_bal, pl_bal, pr_bal, params, 25.0, 55.0, allow_generation=allow_generation + ) + assert bal_res.converged + eq_supply_scale = S_SUPPLY_M_S * ( + params.bn_L * nl_bal + params.bn_R * nr_bal + params.bp_L * pl_bal + params.bp_R * pr_bal + ) + assert bal_res.rate_m2_s == pytest.approx(0.0, abs=1e-13 * eq_supply_scale) + + # Under default allow_generation=False (NOGEN clamp), Boltzmann equilibrium across the + # heterojunction step also gives exact zero recombination. + if not allow_generation: + chi_s = max(chi_l, chi_r) + ceg_s = min(ceg_l, ceg_r) + nl_eq = n_s_eq * math.exp((chi_l - chi_s) / vt) + nr_eq = n_s_eq * math.exp((chi_r - chi_s) / vt) + pl_eq = p_s_eq * math.exp((ceg_s - ceg_l) / vt) + pr_eq = p_s_eq * math.exp((ceg_s - ceg_r) / vt) + eq_res = solve_plane_closure( + nl_eq, nr_eq, pl_eq, pr_eq, params, 25.0, 55.0, allow_generation=False + ) + assert eq_res.converged + assert eq_res.rate_m2_s == 0.0 + + # Test both injection (n*p > ni_s^2) and depletion (n*p < ni_s^2) + for proj in ( + np.array([1.2e19, 4.5e19, 3.1e19, 8.0e18], dtype=np.float64), + np.array([1.0e12, 2.0e12, 3.0e12, 1.5e12], dtype=np.float64), + ): + res = solve_plane_closure( + float(proj[0]), + float(proj[1]), + float(proj[2]), + float(proj[3]), + params, + 25.0, + 55.0, + allow_generation=allow_generation, + ) + assert res.converged + nb = params.bn_L * proj[0] + params.bn_R * proj[1] + pb = params.bp_L * proj[2] + params.bp_R * proj[3] + qss_scale = S_SUPPLY_M_S * (nb + pb) + assert S_SUPPLY_M_S * (nb - 2.0 * res.n_plane_m3) == pytest.approx( + res.rate_m2_s, rel=1e-10, abs=1e-11 * qss_scale + ) + assert S_SUPPLY_M_S * (pb - 2.0 * res.p_plane_m3) == pytest.approx( + res.rate_m2_s, rel=1e-10, abs=1e-11 * qss_scale + ) + + analytic = np.array( + [ + res.d_rate_d_n_left_proj_m_s, + res.d_rate_d_n_right_proj_m_s, + res.d_rate_d_p_left_proj_m_s, + res.d_rate_d_p_right_proj_m_s, + ] + ) + fd = np.zeros(4) + for j in range(4): + h = 1.0e-4 * proj[j] + pp = proj.copy() + pm = proj.copy() + pp[j] += h + pm[j] -= h + rp = solve_plane_closure( + float(pp[0]), + float(pp[1]), + float(pp[2]), + float(pp[3]), + params, + 25.0, + 55.0, + allow_generation=allow_generation, + ).rate_m2_s + rm = solve_plane_closure( + float(pm[0]), + float(pm[1]), + float(pm[2]), + float(pm[3]), + params, + 25.0, + 55.0, + allow_generation=allow_generation, + ).rate_m2_s + fd[j] = (rp - rm) / (2.0 * h) + row_atol = 1.0e-8 * max(float(np.max(np.abs(analytic))), 1.0e-18) + np.testing.assert_allclose(analytic, fd, rtol=1e-6, atol=row_atol) + + +def test_two_dimensional_cell_pair_srh_mode() -> None: + n_other = np.array([1.0e18, 5.0e19]) + p_self = np.array([2.5e14, 4.0e18]) + ni_sq = 2.5e32 + off = evaluate_cross_carrier_cell_pair_srh( + TwoDimensionalInterfaceSRHMode.OFF, + n_other_m3=n_other, + p_self_m3=p_self, + v_n_m_s=10.0, + v_p_m_s=20.0, + ni_sq_m6=ni_sq, + n1_m3=1.0e16, + p1_m3=1.0e16, + ) + np.testing.assert_array_equal(off.areal_rate_m2_s, np.zeros(2)) + np.testing.assert_array_equal(off.half_rate_m2_s, np.zeros(2)) + + active = evaluate_cross_carrier_cell_pair_srh( + TwoDimensionalInterfaceSRHMode.CROSS_CARRIER_CELL_PAIR_V1, + n_other_m3=n_other, + p_self_m3=p_self, + v_n_m_s=10.0, + v_p_m_s=20.0, + ni_sq_m6=ni_sq, + n1_m3=1.0e16, + p1_m3=1.0e16, + ) + assert active.areal_rate_m2_s[0] == 0.0 # exact equilibrium on cell 0 + assert active.areal_rate_m2_s[1] > 0.0 + np.testing.assert_allclose(active.half_rate_m2_s, 0.5 * active.areal_rate_m2_s, rtol=1e-15) diff --git a/tests/unit/physics/test_interface_transport.py b/tests/unit/physics/test_interface_transport.py new file mode 100644 index 00000000..9c73ec1e --- /dev/null +++ b/tests/unit/physics/test_interface_transport.py @@ -0,0 +1,679 @@ +"""Unit tests for 1D thermionic capping, supply integrals, and two-sided QSS traces (P04-09).""" + +from __future__ import annotations + +from collections.abc import Iterator +import math + +import numpy as np +import pytest +from scipy.integrate import quad +from threadpoolctl import threadpool_limits + +from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M as EPS_0 +from solarlab.physics.electrostatics.interface_traces import ( + TraceElectrostatics, + interface_displacement_sides, + solve_electrostatic_traces, +) +from solarlab.physics.interface_transport import ( + A_STAR_FREE_ELECTRON_A_M2_K2, + ChargedTwoSidedInterfaceQSSResult, + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + TwoSidedInterfacePhysics, + cap_particle_flux_thermionic, + effective_mass_from_dos, + emission_velocity, + fermi_dirac_one, + fermi_dirac_richardson_flux, + fermi_dirac_zero, + fermi_richardson_flux, + is_free_electron_default, + remove_shared_interface_nodes, + resolve_layer_richardson, + richardson_from_dos, + scaps_thermionic_flux, + solve_charged_two_sided_interface_qss, + solve_two_sided_interface_qss, + thermionic_emission_bound_m2_s, +) +from solarlab.physics.recombination.interface import resolve_interface_defect_references +from solarlab.physics.statistics.fermi_dirac import fermi_dirac_half +from solarlab.physics.statistics.thermal import thermal_voltage + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +def test_richardson_dos_relations_and_layer_resolution() -> None: + assert is_free_electron_default(A_STAR_FREE_ELECTRON_A_M2_K2) + assert is_free_electron_default(1.2017e6) + assert not is_free_electron_default(0.0) + assert not is_free_electron_default(2.5e5) + + dos = 2.5e24 + m_ratio = effective_mass_from_dos(dos, 300.0) + assert 0.05 < m_ratio < 1.0 + a_star = richardson_from_dos(dos, 300.0) + assert a_star == pytest.approx(A_STAR_FREE_ELECTRON_A_M2_K2 * m_ratio, rel=1e-15) + assert emission_velocity(300.0, m_ratio) > emission_velocity(300.0, 1.0) + + assert resolve_layer_richardson(0.0, dos, 300.0) == 0.0 + assert resolve_layer_richardson(1.2017e6, dos, 300.0) == pytest.approx(a_star, rel=1e-15) + assert resolve_layer_richardson(4.2e5, dos, 300.0) == pytest.approx(4.2e5, rel=1e-15) + + +@pytest.mark.parametrize("eta", [-60.0, -8.0, -4.0, -1.5, 0.0, 2.5, 15.0, 45.0]) +def test_fermi_dirac_zero_and_one_quadrature_and_derivative(eta: float) -> None: + f0 = fermi_dirac_zero(eta) + f1 = fermi_dirac_one(eta) + assert f0 >= 0.0 + assert f1 >= 0.0 + + if -15.0 <= eta <= 25.0: + quad_val, _ = quad( + lambda x: 0.0 if (x - eta) > 700.0 else x / (1.0 + math.exp(x - eta)), + 0.0, + math.inf, + epsrel=1e-12, + ) + assert f1 == pytest.approx(quad_val, rel=1e-11) + + h = 1.0e-5 + df1 = (fermi_dirac_one(eta + h) - fermi_dirac_one(eta - h)) / (2.0 * h) + assert df1 == pytest.approx(f0, rel=1e-8, abs=1e-28) + + +@pytest.mark.parametrize("mode", ["hard", "legacy_logistic", "compact_support"]) +@pytest.mark.parametrize("sg_flux", [-4.2e22, -1.5e20, 1.8e20, 5.6e22]) +def test_thermionic_cap_direction_equilibrium_and_fd_derivatives( + mode: str, sg_flux: float +) -> None: + temp = 300.0 + vt = thermal_voltage(temp) + barrier = 0.18 + a_star = 3.2e5 + + # Exact zero bound at Boltzmann equilibrium across delta_barrier_eV: + n_l_eq = 2.0e21 + n_r_eq = n_l_eq * math.exp(-barrier / vt) + bound_eq, _, _ = thermionic_emission_bound_m2_s(n_l_eq, n_r_eq, barrier, temp, a_star) + assert bound_eq == pytest.approx(0.0, abs=1e-8) + + # Non-equilibrium trial state where |sg_flux| and |te_bound| span both uncapped and capped + # regimes (with dos_norm_m3 = 2.5e24 so |te_bound| ~ 2.9e22 m^-2 s^-1 is comparable to |sg_flux|!) + n_l = 1.7e21 + n_r = 6.3e19 + dos_norm = 2.5e24 + soft = 0.0 if mode == "hard" else 0.05 + reg_mode = "legacy_logistic" if mode == "hard" else mode + res = cap_particle_flux_thermionic( + sg_flux, + n_left_m3=n_l, + n_right_m3=n_r, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ) + assert math.copysign(1.0, res.flux_m2_s) == math.copysign(1.0, sg_flux) + te_val, _, _ = thermionic_emission_bound_m2_s( + n_l, n_r, barrier, temp, a_star, dos_norm_m3=dos_norm + ) + if soft == 0.0: + assert abs(res.flux_m2_s) == pytest.approx(min(abs(sg_flux), abs(te_val)), rel=1e-15) + + # Verify analytical partials wrt (sg_flux, n_left, n_right) against central FD. + h_sg = 1.0e-6 * abs(sg_flux) + fp_sg = cap_particle_flux_thermionic( + sg_flux + h_sg, + n_left_m3=n_l, + n_right_m3=n_r, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + fm_sg = cap_particle_flux_thermionic( + sg_flux - h_sg, + n_left_m3=n_l, + n_right_m3=n_r, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + + h_nl = 1.0e-4 * n_l + fp_nl = cap_particle_flux_thermionic( + sg_flux, + n_left_m3=n_l + h_nl, + n_right_m3=n_r, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + fm_nl = cap_particle_flux_thermionic( + sg_flux, + n_left_m3=n_l - h_nl, + n_right_m3=n_r, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + + h_nr = 1.0e-4 * n_r + fp_nr = cap_particle_flux_thermionic( + sg_flux, + n_left_m3=n_l, + n_right_m3=n_r + h_nr, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + fm_nr = cap_particle_flux_thermionic( + sg_flux, + n_left_m3=n_l, + n_right_m3=n_r - h_nr, + delta_barrier_eV=barrier, + temperature_K=temp, + a_star_A_m2_K2=a_star, + te_softness=soft, + regularization_mode=reg_mode, # type: ignore[arg-type] + dos_norm_m3=dos_norm, + ).flux_m2_s + + assert res.d_flux_d_sg_flux == pytest.approx((fp_sg - fm_sg) / (2.0 * h_sg), rel=1e-7, abs=1e-12) + assert res.d_flux_d_n_left_m_s == pytest.approx( + (fp_nl - fm_nl) / (2.0 * h_nl), + rel=1e-6, + abs=1.0e-8 * max(abs(res.flux_m2_s) / n_l, 1.0e-12), + ) + assert res.d_flux_d_n_right_m_s == pytest.approx( + (fp_nr - fm_nr) / (2.0 * h_nr), + rel=1e-6, + abs=1.0e-8 * max(abs(res.flux_m2_s) / n_r, 1.0e-12), + ) + + +def test_cross_plane_flux_kernels_equilibrium_and_fd_jacobians() -> None: + temp = 300.0 + vt = thermal_voltage(temp) + nc_l, nc_r = 4.0e24, 2.5e24 + nv_l, nv_r = 6.0e24, 3.5e24 + cb_step = 0.14 # chi_L - chi_R + vb_step = 0.22 # (chi_R + Eg_R) - (chi_L + Eg_L) + phi_l, phi_r = 0.12, 0.21 + dphi = phi_r - phi_l + + # Fermi-Dirac thermal equilibrium: eta_n_R = eta_n_L - (cb_step - dphi)/vt, + # eta_p_R = eta_p_L - (vb_step + dphi)/vt. + eta_nl = -3.0 + eta_nr = eta_nl - (cb_step - dphi) / vt + eta_pl = -4.0 + eta_pr = eta_pl - (vb_step + dphi) / vt + eq_fd_state = np.array( + [ + nc_l * fermi_dirac_half(eta_nl), + nv_l * fermi_dirac_half(eta_pl), + nc_r * fermi_dirac_half(eta_nr), + nv_r * fermi_dirac_half(eta_pr), + ], + dtype=np.float64, + ) + fd_eq = fermi_dirac_richardson_flux( + eq_fd_state, + phi_trace_left_V=phi_l, + phi_trace_right_V=phi_r, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_A_m2_K2=2.5e5, + richardson_p_A_m2_K2=3.5e5, + temperature_K=temp, + thermal_voltage_V=vt, + ) + for c_idx in range(2): + assert fd_eq.cross_flux_m2_s[c_idx] == pytest.approx( + 0.0, abs=1.0e-13 * float(fd_eq.one_way_scale_m2_s[c_idx]) + ) + + # Boltzmann equilibrium for fermi_richardson_flux and scaps_thermionic_flux: + n_l_b = 1.0e18 + n_r_b = n_l_b * (nc_r / nc_l) * math.exp(-(cb_step - dphi) / vt) + p_l_b = 2.0e18 + p_r_b = p_l_b * (nv_r / nv_l) * math.exp(-(vb_step + dphi) / vt) + eq_mb_state = np.array([n_l_b, p_l_b, n_r_b, p_r_b], dtype=np.float64) + mb_eq = fermi_richardson_flux( + eq_mb_state, + phi_trace_left_V=phi_l, + phi_trace_right_V=phi_r, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_A_m2_K2=2.5e5, + richardson_p_A_m2_K2=3.5e5, + temperature_K=temp, + thermal_voltage_V=vt, + ) + sc_eq = scaps_thermionic_flux( + eq_mb_state, + phi_trace_left_V=phi_l, + phi_trace_right_V=phi_r, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_left_A_m2_K2=2.5e5, + richardson_n_right_A_m2_K2=1.8e5, + richardson_p_left_A_m2_K2=3.5e5, + richardson_p_right_A_m2_K2=2.9e5, + temperature_K=temp, + thermal_voltage_V=vt, + ) + for c_idx in range(2): + assert mb_eq.cross_flux_m2_s[c_idx] == pytest.approx( + 0.0, abs=1.0e-13 * float(mb_eq.one_way_scale_m2_s[c_idx]) + ) + assert sc_eq.cross_flux_m2_s[c_idx] == pytest.approx( + 0.0, abs=1.0e-13 * float(sc_eq.one_way_scale_m2_s[c_idx]) + ) + + # Check FD derivatives of all three kernels on a non-equilibrium state. + trial = np.array([4.2e20, 1.9e21, 8.7e19, 6.4e20], dtype=np.float64) + for eval_fn in ( + lambda s, pl, pr: fermi_dirac_richardson_flux( + s, + phi_trace_left_V=pl, + phi_trace_right_V=pr, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_A_m2_K2=2.5e5, + richardson_p_A_m2_K2=3.5e5, + temperature_K=temp, + thermal_voltage_V=vt, + transmission=0.85, + ), + lambda s, pl, pr: fermi_richardson_flux( + s, + phi_trace_left_V=pl, + phi_trace_right_V=pr, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_A_m2_K2=2.5e5, + richardson_p_A_m2_K2=3.5e5, + temperature_K=temp, + thermal_voltage_V=vt, + transmission=0.85, + ), + lambda s, pl, pr: scaps_thermionic_flux( + s, + phi_trace_left_V=pl, + phi_trace_right_V=pr, + conduction_band_step_eV=cb_step, + hole_transport_step_eV=vb_step, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_left_A_m2_K2=2.5e5, + richardson_n_right_A_m2_K2=1.8e5, + richardson_p_left_A_m2_K2=3.5e5, + richardson_p_right_A_m2_K2=2.9e5, + temperature_K=temp, + thermal_voltage_V=vt, + transmission=0.85, + ), + ): + base = eval_fn(trial, phi_l, phi_r) + log_trial = np.log(trial) + fd_log = np.zeros((2, 4)) + for j in range(4): + h = 1.0e-6 + lp = log_trial.copy() + lm = log_trial.copy() + lp[j] += h + lm[j] -= h + fd_log[:, j] = ( + eval_fn(np.exp(lp), phi_l, phi_r).cross_flux_m2_s + - eval_fn(np.exp(lm), phi_l, phi_r).cross_flux_m2_s + ) / (2.0 * h) + fd_phi = np.zeros((2, 2)) + h_v = 1.0e-6 + fd_phi[:, 0] = ( + eval_fn(trial, phi_l + h_v, phi_r).cross_flux_m2_s + - eval_fn(trial, phi_l - h_v, phi_r).cross_flux_m2_s + ) / (2.0 * h_v) + fd_phi[:, 1] = ( + eval_fn(trial, phi_l, phi_r + h_v).cross_flux_m2_s + - eval_fn(trial, phi_l, phi_r - h_v).cross_flux_m2_s + ) / (2.0 * h_v) + + scale_atol = 1.0e-8 * float(np.max(base.one_way_scale_m2_s)) + np.testing.assert_allclose(base.d_cross_d_log_state_m2_s, fd_log, rtol=1e-8, atol=scale_atol) + np.testing.assert_allclose( + base.d_cross_d_trace_potentials_m2_s_V, fd_phi, rtol=1e-8, atol=scale_atol + ) + + +def test_remove_shared_interface_nodes_and_displacement_jump() -> None: + grid = np.array([0.0, 20e-9, 50e-9, 90e-9, 450e-9, 500e-9]) + reduced = remove_shared_interface_nodes(grid, [50e-9, 450e-9]) + np.testing.assert_array_equal(reduced, np.array([0.0, 20e-9, 90e-9, 500e-9])) + + with pytest.raises(ValueError, match="outer contact"): + remove_shared_interface_nodes(grid, [0.0]) + with pytest.raises(ValueError, match="expected exactly one"): + remove_shared_interface_nodes(grid, [123e-9]) + + sigma = -2.4e-4 + geom = TraceElectrostatics( + left_distance_m=4.0e-9, + right_distance_m=6.0e-9, + eps_r_left=3.5, + eps_r_right=24.0, + fixed_sheet_charge_C_m2=sigma, + ) + phi_bulk_l, phi_bulk_r = 0.15, 0.42 + phi_tl, phi_tr = solve_electrostatic_traces(geom, phi_bulk_l, phi_bulk_r) + c_l = EPS_0 * geom.eps_r_left / geom.left_distance_m + c_r = EPS_0 * geom.eps_r_right / geom.right_distance_m + c_series = (c_l * c_r) / (c_l + c_r) + d_series = -c_series * (phi_bulk_r - phi_bulk_l) + d_l, d_r = interface_displacement_sides( + d_series, + eps_r_left=geom.eps_r_left, + left_distance_m=geom.left_distance_m, + eps_r_right=geom.eps_r_right, + right_distance_m=geom.right_distance_m, + sheet_charge_C_m2=sigma, + ) + assert d_l == pytest.approx(-c_l * (phi_tl - phi_bulk_l), rel=1e-14) + assert d_r == pytest.approx(-c_r * (phi_bulk_r - phi_tr), rel=1e-14) + assert (d_r - d_l) == pytest.approx(sigma, rel=1e-14) + + +def _sample_two_sided_setup() -> tuple[TraceElectrostatics, TwoSidedInterfacePhysics, float]: + temp = 300.0 + vt = thermal_voltage(temp) + geom = TraceElectrostatics( + left_distance_m=5.0e-9, + right_distance_m=7.0e-9, + eps_r_left=4.0, + eps_r_right=24.1, + ) + chi_l, eg_l, nc_l, nv_l = 3.75, 2.1, 4.0e24, 6.0e24 + chi_r, eg_r, nc_r, nv_r = 3.92, 1.6, 2.2e24, 3.1e24 + refs = resolve_interface_defect_references( + left_role="HTL", + right_role="absorber", + left_chi_phys_eV=chi_l, + left_Eg_phys_eV=eg_l, + left_Nc_m3=nc_l, + left_Nv_m3=nv_l, + right_chi_phys_eV=chi_r, + right_Eg_phys_eV=eg_r, + right_Nc_m3=nc_r, + right_Nv_m3=nv_r, + thermal_voltage_V=vt, + trap_depth_eV=0.58, + energy_reference="below_conduction_band", + ) + phys = TwoSidedInterfacePhysics( + thermal_voltage_V=vt, + temperature_K=temp, + D_n_left_m2_s=1.0e-6, + D_n_right_m2_s=5.0e-5, + D_p_left_m2_s=2.0e-5, + D_p_right_m2_s=4.0e-5, + N_C_left_m3=nc_l, + N_C_right_m3=nc_r, + N_V_left_m3=nv_l, + N_V_right_m3=nv_r, + richardson_n_A_m2_K2=min(richardson_from_dos(nc_l), richardson_from_dos(nc_r)), + richardson_p_A_m2_K2=min(richardson_from_dos(nv_l), richardson_from_dos(nv_r)), + conduction_band_step_eV=chi_l - chi_r, + hole_transport_step_eV=(chi_r + eg_r) - (chi_l + eg_l), + transmission=1.0, + surface_recombination_velocity_n_m_s=30.0, + surface_recombination_velocity_p_m_s=45.0, + n1_left_m3=refs.n1_left_m3, + n1_right_m3=refs.n1_right_m3, + p1_left_m3=refs.p1_left_m3, + p1_right_m3=refs.p1_right_m3, + ) + return geom, phys, vt + + +def test_two_sided_qss_ift_jacobian_equilibrium_and_mirror_symmetry() -> None: + geom, phys, vt = _sample_two_sided_setup() + + # Non-equilibrium bulk state: check 4x6 bulk_flux_jacobian_bulk and 1x6 occupancy_jacobian_bulk vs FD. + coords = np.array( + [0.18, 0.34, math.log(1.8e18), math.log(4.5e20), math.log(6.2e19), math.log(2.3e19)], + dtype=np.float64, + ) + + def _run_uncharged(c: np.ndarray): + return solve_two_sided_interface_qss( + geom, + phys, + TwoSidedBulkState( + phi_left_V=float(c[0]), + phi_right_V=float(c[1]), + n_left_m3=math.exp(float(c[2])), + p_left_m3=math.exp(float(c[3])), + n_right_m3=math.exp(float(c[4])), + p_right_m3=math.exp(float(c[5])), + ), + residual_tolerance=1.0e-12, + ) + + base = _run_uncharged(coords) + assert base.converged + assert base.normalized_residual < 1.0e-12 + assert base.occupancy is not None + + fd_flux = np.zeros((4, 6)) + fd_occ = np.zeros(6) + for j in range(6): + h = 1.0e-4 if j >= 2 else 1.0e-5 + cp = coords.copy() + cm = coords.copy() + cp[j] += h + cm[j] -= h + rp = _run_uncharged(cp) + rm = _run_uncharged(cm) + fd_flux[:, j] = (rp.bulk_flux_m2_s - rm.bulk_flux_m2_s) / (2.0 * h) + assert rp.occupancy is not None and rm.occupancy is not None + fd_occ[j] = (rp.occupancy - rm.occupancy) / (2.0 * h) + + for row in range(4): + row_atol = 1.0e-7 * max(float(np.max(np.abs(base.bulk_flux_jacobian_bulk[row]))), 1.0) + np.testing.assert_allclose( + base.bulk_flux_jacobian_bulk[row], fd_flux[row], rtol=1e-6, atol=row_atol + ) + np.testing.assert_allclose(base.occupancy_jacobian_bulk, fd_occ, rtol=1e-6, atol=1e-10) + + # Left/right layer reversal symmetry check! + geom_rev = TraceElectrostatics( + left_distance_m=geom.right_distance_m, + right_distance_m=geom.left_distance_m, + eps_r_left=geom.eps_r_right, + eps_r_right=geom.eps_r_left, + ) + phys_rev = TwoSidedInterfacePhysics( + thermal_voltage_V=phys.thermal_voltage_V, + temperature_K=phys.temperature_K, + D_n_left_m2_s=phys.D_n_right_m2_s, + D_n_right_m2_s=phys.D_n_left_m2_s, + D_p_left_m2_s=phys.D_p_right_m2_s, + D_p_right_m2_s=phys.D_p_left_m2_s, + N_C_left_m3=phys.N_C_right_m3, + N_C_right_m3=phys.N_C_left_m3, + N_V_left_m3=phys.N_V_right_m3, + N_V_right_m3=phys.N_V_left_m3, + richardson_n_A_m2_K2=phys.richardson_n_A_m2_K2, + richardson_p_A_m2_K2=phys.richardson_p_A_m2_K2, + conduction_band_step_eV=-phys.conduction_band_step_eV, + hole_transport_step_eV=-phys.hole_transport_step_eV, + transmission=phys.transmission, + surface_recombination_velocity_n_m_s=phys.surface_recombination_velocity_n_m_s, + surface_recombination_velocity_p_m_s=phys.surface_recombination_velocity_p_m_s, + n1_left_m3=phys.n1_right_m3, + n1_right_m3=phys.n1_left_m3, + p1_left_m3=phys.p1_right_m3, + p1_right_m3=phys.p1_left_m3, + ) + rev = solve_two_sided_interface_qss( + geom_rev, + phys_rev, + TwoSidedBulkState( + phi_left_V=float(coords[1]), + phi_right_V=float(coords[0]), + n_left_m3=math.exp(float(coords[4])), + p_left_m3=math.exp(float(coords[5])), + n_right_m3=math.exp(float(coords[2])), + p_right_m3=math.exp(float(coords[3])), + ), + residual_tolerance=1.0e-12, + ) + assert rev.occupancy == pytest.approx(base.occupancy, rel=1e-12) + np.testing.assert_allclose(rev.cross_flux_m2_s, -base.cross_flux_m2_s, rtol=1e-11) + # Bulk flux into trace has ordering (n_L, p_L, n_R, p_R): swapping sides swaps (0,1) <-> (2,3)! + np.testing.assert_allclose( + rev.bulk_flux_m2_s, + base.bulk_flux_m2_s[[2, 3, 0, 1]], + rtol=1e-11, + ) + + +def test_charged_two_sided_qss_gauss_jump_equilibrium_and_fd_jacobians() -> None: + geom, phys, _ = _sample_two_sided_setup() + + # First compute an uncharged equilibrium-like reference occupancy, then verify charged QSS + # at that same state gives zero incremental sheet charge! + eq_bulk = TwoSidedBulkState( + phi_left_V=0.10, + phi_right_V=0.25, + n_left_m3=2.0e17, + p_left_m3=3.0e20, + n_right_m3=8.0e18, + p_right_m3=4.0e18, + ) + uncharged = solve_two_sided_interface_qss(geom, phys, eq_bulk, residual_tolerance=1.0e-12) + assert uncharged.occupancy is not None + charge_spec = EquilibriumReferencedSheetCharge( + trap_density_m2=4.0e15, + equilibrium_occupancy=uncharged.occupancy, + ) + at_ref = solve_charged_two_sided_interface_qss( + geom, phys, eq_bulk, charge_spec, residual_tolerance=1.0e-12 + ) + assert at_ref.converged + assert at_ref.incremental_sheet_charge_C_m2 == pytest.approx(0.0, abs=1e-16) + assert at_ref.phi_trace_left_V == pytest.approx(at_ref.phi_trace_right_V, abs=1e-14) + + # Non-equilibrium biased state: check Gauss jump D_R - D_L == sigma and all 3 IFT Jacobians vs FD! + coords = np.array( + [0.21, 0.29, math.log(5.5e18), math.log(2.1e20), math.log(1.9e20), math.log(7.5e18)], + dtype=np.float64, + ) + + def _run_charged(c: np.ndarray) -> ChargedTwoSidedInterfaceQSSResult: + return solve_charged_two_sided_interface_qss( + geom, + phys, + TwoSidedBulkState( + phi_left_V=float(c[0]), + phi_right_V=float(c[1]), + n_left_m3=math.exp(float(c[2])), + p_left_m3=math.exp(float(c[3])), + n_right_m3=math.exp(float(c[4])), + p_right_m3=math.exp(float(c[5])), + ), + charge_spec, + residual_tolerance=1.0e-12, + ) + + charged = _run_charged(coords) + assert charged.converged + assert charged.normalized_electrostatic_residual < 1.0e-12 + assert charged.normalized_carrier_residual < 1.0e-12 + assert abs(charged.incremental_sheet_charge_C_m2) > 1.0e-6 + + c_l = EPS_0 * geom.eps_r_left / geom.left_distance_m + c_r = EPS_0 * geom.eps_r_right / geom.right_distance_m + c_series = (c_l * c_r) / (c_l + c_r) + d_series = -c_series * (float(coords[1]) - float(coords[0])) + d_l, d_r = interface_displacement_sides( + d_series, + eps_r_left=geom.eps_r_left, + left_distance_m=geom.left_distance_m, + eps_r_right=geom.eps_r_right, + right_distance_m=geom.right_distance_m, + sheet_charge_C_m2=charged.incremental_sheet_charge_C_m2, + ) + assert d_l == pytest.approx(-c_l * (charged.phi_trace_left_V - float(coords[0])), rel=1e-12) + assert d_r == pytest.approx(-c_r * (float(coords[1]) - charged.phi_trace_right_V), rel=1e-12) + assert (d_r - d_l) == pytest.approx(charged.incremental_sheet_charge_C_m2, rel=1e-12) + + fd_flux = np.zeros((4, 6)) + fd_sigma = np.zeros(6) + fd_occ = np.zeros(6) + for j in range(6): + h = 1.0e-4 if j >= 2 else 1.0e-5 + cp = coords.copy() + cm = coords.copy() + cp[j] += h + cm[j] -= h + rp = _run_charged(cp) + rm = _run_charged(cm) + fd_flux[:, j] = (rp.bulk_flux_m2_s - rm.bulk_flux_m2_s) / (2.0 * h) + fd_sigma[j] = ( + rp.incremental_sheet_charge_C_m2 - rm.incremental_sheet_charge_C_m2 + ) / (2.0 * h) + fd_occ[j] = (rp.occupancy - rm.occupancy) / (2.0 * h) + + for row in range(4): + row_atol = 1.0e-7 * max(float(np.max(np.abs(charged.bulk_flux_jacobian_bulk[row]))), 1.0) + np.testing.assert_allclose( + charged.bulk_flux_jacobian_bulk[row], fd_flux[row], rtol=1e-6, atol=row_atol + ) + np.testing.assert_allclose(charged.sheet_charge_jacobian_bulk, fd_sigma, rtol=1e-6, atol=1e-12) + np.testing.assert_allclose(charged.occupancy_jacobian_bulk, fd_occ, rtol=1e-6, atol=1e-10) From 19c19776ff0b13beb791683697035594718ff317 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 21:12:12 +0800 Subject: [PATCH 14/46] N(physics): migrate 1D photon recycling radiative reabsorption and bounded WKB tunnelling onto unified assembly (P04-12) --- src/solarlab/device/compile_nonlocal_1d.py | 1326 +++++++++++++ .../equations/assembly/nonlocal_1d.py | 648 ++++++ src/solarlab/equations/nonlocal_1d.py | 629 ++++++ .../physics/generation/photon_recycling.py | 399 ++++ .../generation/radiative_reabsorption.py | 876 +++++++++ .../physics/transport/tunneling_channels.py | 1747 +++++++++++++++++ .../physics/transport/wkb_tunneling.py | 744 +++++++ .../test_photon_recycling_and_wkb_parity.py | 580 ++++++ .../equations/test_nonlocal_assembly_1d.py | 513 +++++ .../physics/test_photon_recycling_and_wkb.py | 549 ++++++ 10 files changed, 8011 insertions(+) create mode 100644 src/solarlab/device/compile_nonlocal_1d.py create mode 100644 src/solarlab/equations/assembly/nonlocal_1d.py create mode 100644 src/solarlab/equations/nonlocal_1d.py create mode 100644 src/solarlab/physics/generation/photon_recycling.py create mode 100644 src/solarlab/physics/generation/radiative_reabsorption.py create mode 100644 src/solarlab/physics/transport/tunneling_channels.py create mode 100644 src/solarlab/physics/transport/wkb_tunneling.py create mode 100644 tests/integration/test_photon_recycling_and_wkb_parity.py create mode 100644 tests/unit/equations/test_nonlocal_assembly_1d.py create mode 100644 tests/unit/physics/test_photon_recycling_and_wkb.py diff --git a/src/solarlab/device/compile_nonlocal_1d.py b/src/solarlab/device/compile_nonlocal_1d.py new file mode 100644 index 00000000..92d53ce9 --- /dev/null +++ b/src/solarlab/device/compile_nonlocal_1d.py @@ -0,0 +1,1326 @@ +"""Cold-compile a ``PreparedDevice`` to 1D nonlocal radiative reabsorption and WKB tunnelling. + +Preserves strict separation from local-only ``compile_device_1d``: +* Disabled nonlocal configurations delegate directly to ``compile_device_1d`` and + reproduce ``CompiledDevice1D`` bit for bit. +* Active photon recycling binds band-edge escape probabilities from supplied + coherent spectral TMM optics (or explicit override probabilities) and builds + rank-1 ``AbsorberReabsorptionSpec`` operators (or local ``B_rad * P_esc`` + scaling when ``photon_recycling_mode='local_escape_scaled'``). +* Active WKB tunnelling validates ``TunnellingChannelDocument`` pre-solve, + requires ``driver='quasi_fermi_steady_state'``, and binds the single resolved + material electron barrier to ``CompiledTunnellingChannels``. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import hashlib +import json +import math +from typing import Any, Literal, TypedDict, cast + +import numpy as np +from numpy.typing import ArrayLike +from scipy.sparse import diags + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.neutral_defects import ( + LITERAL_ABOVE_VB_DOS_REFERENCE_V1, + bind_neutral_defects, +) +from solarlab.device.optical_generation import OpticalGeneration1D, bind_optical_generation_1d +from solarlab.device.resolved import PreparedDevice, PreparedLayer +from solarlab.equations.assembly.nonlocal_1d import ( + AssembledNonlocalDC1DProblem, + assembled_nonlocal_problem_factory, +) +from solarlab.equations.dc_1d import ( + CapabilityError, + CompiledDevice1D, + LocalRecombinationModel, + State1D, +) +from solarlab.equations.field_transport_1d import bind_field_transport_1d +from solarlab.equations.implementation import use_assembled +from solarlab.equations.nonlocal_1d import ( + CompiledNonlocalDevice1D, + NonlocalDC1DProblem, + SparsitySupportChangedError, + evaluate_nonlocal_couplings_1d, +) +from solarlab.mesh import INTEGER_ENDPOINT_V1, RIGHT_LAYER_WINS, build_geometry, multilayer_grid +from solarlab.mesh.grid import layer_node_masks +from solarlab.physics.band_structure.binding import ( + LayerParameterInput, + TemperatureLawSpec, + compile_layer_parameters, +) +from solarlab.physics.band_structure.doping_profile import DopingProfileSpec +from solarlab.physics.band_structure.grading import GradingSpec +from solarlab.physics.contacts import ( + CarrierExchangeChannel, + ContactEndpoint, + ContactMaterial, + assess_contact_thermodynamics, + doping_equilibrium_densities, + semiconductor_work_function, +) +from solarlab.physics.contacts.exchange import resolve_exchange_velocities +from solarlab.physics.electrostatics import PoissonOperator1D +from solarlab.physics.generation.beer_lambert import BeerLambertBinding +from solarlab.physics.generation.fixed import FixedGenerationProfile +from solarlab.physics.generation.photon_recycling import ( + ESCAPE_PROBABILITY_MODES, + TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + AbsorberEscapeBinding, + AbsorberEscapeInput, + PhotonRecyclingCapabilityError, + PhotonRecyclingError, + bind_absorber_escape_from_optical_stack, + effective_radiative_coefficient, + wavelength_at_gap, +) +from solarlab.physics.generation.radiative_reabsorption import ( + CONTROL_VOLUME_CONSERVATIVE_V1, + HISTORICAL_TRAPEZOID_UNIFORM_V1, + LAGGED_BAKED_GENERATION_V1, + AbsorberReabsorptionSpec, +) +from solarlab.physics.recombination.reaction import ( + BulkRecombinationCoefficients, + BulkRecombinationReaction, +) +from solarlab.physics.transport import legacy_face_diffusivity +from solarlab.physics.transport.field_mobility_tangents import FieldMobilityCapabilityError +from solarlab.physics.transport.tunneling_channels import ( + PREALLOCATED_RESERVOIR_SUPERSET_V1, + STRICT_WINDOW_REBIND_V1, + WKB_SPARSITY_POLICIES, + CompiledTunnellingChannels, + TunnellingChannelCapabilityError, + TunnellingChannelError, + TunnellingChannelSchemaError, + compile_tunnelling_channels, + tunnelling_channel_document_from_mapping, +) +from solarlab.solvers.nonlinear.newton import ( + NewtonResult, + NewtonSettings, + factorize, + gate_from, + solve_newton, +) +from solarlab.solvers.nonlinear.problem import ( + CallableProblem, + GateOutcome, + PhysicalGate, + ResidualScaling, + StepControl, +) +from solarlab.solvers.nonlinear.production import ( + POISSON_CONTACT_BALANCE_V1, + poisson_row_weights, + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + SteadyStateError, +) + +__all__ = [ + "PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED", + "PHOTON_RECYCLING_MODES", + "PHOTON_RECYCLING_OFF", + "CompiledNonlocalDevice1D", + "compile_nonlocal_device_1d", + "nonlocal_physical_gates", + "solve_nonlocal_equilibrium_1d", + "solve_nonlocal_steady_state_1d", +] + +Q: float = ELEMENTARY_CHARGE_C + +PHOTON_RECYCLING_OFF = "off" +PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED = "local_escape_scaled" +PHOTON_RECYCLING_MODES: tuple[str, ...] = ( + PHOTON_RECYCLING_OFF, + PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED, + CONTROL_VOLUME_CONSERVATIVE_V1, + HISTORICAL_TRAPEZOID_UNIFORM_V1, + LAGGED_BAKED_GENERATION_V1, +) + +NonlocalProblem = AssembledNonlocalDC1DProblem | NonlocalDC1DProblem + + +class _LayerScalars(TypedDict): + chi: float + Eg: float + Nc300: float + Nv300: float + ni: float + n1: float + p1: float + mu_n: float + mu_p: float + B_rad: float + v_th: float + N_A: float + N_D: float + N_A_bulk: float | None + N_D_bulk: float | None + doping_profile_shape: str | None + doping_decay_length: float | None + doping_edge: str + mu_T_gamma: float + B_rad_T_gamma: float + varshni_alpha: float + varshni_beta: float + Eg_back: float | None + chi_back: float | None + grading_profile: Literal["linear", "parabolic", "exponential"] + grading_direction: Literal["front_to_back", "back_to_front"] + grading_bowing: float + grading_char_length: float | None + + +def _has_uniform_dos(layers: tuple[PreparedLayer, ...]) -> bool: + if not layers: + return True + nc_vals = [float(cast(float, dict(layer.parameters)["Nc300"])) for layer in layers] + nv_vals = [float(cast(float, dict(layer.parameters)["Nv300"])) for layer in layers] + return len(set(nc_vals)) == 1 and len(set(nv_vals)) == 1 + + +def _validate_nonlocal_capabilities( + prepared: PreparedDevice, + data: dict[str, Any], + layers: tuple[PreparedLayer, ...], +) -> None: + settings = data["settings"] + missing: list[str] = [] + if settings["built_in_potential_mode"] != "semiconductor_work_function": + missing.append( + "settings.built_in_potential_mode: only explicit semiconductor_work_function contacts are bound" + ) + if not settings["dos_band_potentials"] and not _has_uniform_dos(layers): + missing.append( + "settings.dos_band_potentials: physical DOS transport requires this enabled when Nc300/Nv300 vary" + ) + has_ions = any( + dict(layer.parameters)[name] != 0.0 + for layer in layers + for name in ("P0", "P0_neg", "D_ion", "D_ion_neg") + ) + for flag in ( + "interface_plane_projection", + "te_physical_norm", + "flat_band_metal_contacts", + "interface_two_sided", + "interface_shared_occupancy", + "interface_plane_closure", + "interface_plane_generation", + "graded_optics", + "interface_tunneling", + ): + if settings[flag]: + missing.append("settings." + flag) + if has_ions: + for flag in ("ion_steric_diffusion_only", "ion_steric_shared_site"): + if settings[flag]: + missing.append("settings." + flag) + if settings["het_recomb_despike"] != 0.0: + missing.append("settings.het_recomb_despike") + if settings["interface_charge_closure"] != "off": + missing.append("settings.interface_charge_closure") + if settings["jv_solver_policy"] != "general": + missing.append("settings.jv_solver_policy: a separately qualified solver route is required") + if data["grain_boundaries"]: + missing.append("grain_boundaries: lateral geometry is not bound") + declaration = data["declaration"] + spectral = declaration.get("spectrum") is not None + if spectral and declaration.get("fixed_generation") is not None: + missing.append("spectrum and fixed_generation are mutually exclusive") + for layer in prepared.layers: + if layer.role == "substrate": + parameters = dict(layer.parameters) + if not spectral and ( + parameters["alpha"] != 0.0 + or layer.optical is not None + or parameters["n_optical"] is not None + ): + missing.append( + "layers." + layer.id + ": absorbing/optical substrate generation is not bound" + ) + for layer in layers: + parameters = dict(layer.parameters) + prefix = "layers." + layer.id + "." + for name in ("P0", "P0_neg", "D_ion", "D_ion_neg"): + if parameters[name] != 0.0: + missing.append(prefix + name + ": mobile or frozen ion populations are not bound") + if parameters["carrier_statistics"] != "maxwell_boltzmann": + missing.append(prefix + "carrier_statistics") + if parameters["dopant_ionization_model"] != "fully_ionized": + missing.append(prefix + "dopant_ionization_model") + if parameters["band_gap_narrowing_model"] != "off": + missing.append(prefix + "band_gap_narrowing_model") + if any(parameters[name] != 0.0 for name in ("pf_gamma_n", "pf_gamma_p")): + missing.append(prefix + "field_mobility: Poole-Frenkel enhancement is not bound") + if layer.bulk_trap_distribution_json is not None: + missing.append(prefix + "bulk_trap_distribution: distributed defects are not bound") + if layer.metastable_document_json is not None: + missing.append(prefix + "metastable_document") + if any( + parameters[name] is not None + for name in ("trap_N_t_interface", "trap_N_t_bulk", "trap_decay_length") + ): + missing.append(prefix + "trap_profile") + if layer.cigs_graded_optics_json is not None or ( + not spectral and (layer.optical is not None or parameters["n_optical"] is not None) + ): + missing.append( + prefix + "optical_material: requires an explicit spectrum; graded optics is not bound" + ) + for interface in prepared.interfaces: + entry = interface.to_mapping() + if interface.electrical and ( + entry.get("defect") is not None + or any((entry.get(name) or 0.0) != 0.0 for name in ("v_n", "v_p")) + ): + missing.append("interfaces." + entry["id"] + ": interface recombination is not bound") + if missing: + raise CapabilityError("unsupported_nonlocal_1d_dc: " + "; ".join(missing)) + + +def _layer_input(layer: PreparedLayer) -> LayerParameterInput: + parameters = dict(layer.parameters) + for name in ("chi", "Eg", "Nc300", "Nv300", "ni", "eps_r", "mu_n", "mu_p"): + value = parameters[name] + if value is None or not math.isfinite(float(value)) or float(value) <= 0.0: + raise CapabilityError( + f"layers.{layer.id}.{name}: nonlocal 1D DC requires a finite positive value" + ) + p = cast(_LayerScalars, parameters) + return LayerParameterInput( + name=layer.id, + role=layer.role, + thickness_m=layer.thickness, + electron_affinity_eV=p["chi"], + band_gap_eV=p["Eg"], + intrinsic_density_m3=p["ni"], + srh_n1_m3=p["n1"], + srh_p1_m3=p["p1"], + electron_mobility_m2_V_s=p["mu_n"], + hole_mobility_m2_V_s=p["mu_p"], + radiative_coefficient_m3_s=p["B_rad"], + thermal_velocity_m_s=p["v_th"], + doping=DopingProfileSpec( + p["N_A"], + p["N_D"], + p["N_A_bulk"], + p["N_D_bulk"], + p["doping_profile_shape"], + p["doping_decay_length"], + p["doping_edge"], + ), + conduction_dos_300_m3=p["Nc300"], + valence_dos_300_m3=p["Nv300"], + temperature_laws=TemperatureLawSpec( + mobility_exponent=p["mu_T_gamma"], + radiative_exponent=p["B_rad_T_gamma"], + varshni_alpha_eV_K=p["varshni_alpha"], + varshni_beta_K=p["varshni_beta"], + ), + grading=GradingSpec( + band_gap_back_eV=p["Eg_back"], + electron_affinity_back_eV=p["chi_back"], + profile=p["grading_profile"], + direction=p["grading_direction"], + bowing_eV=p["grading_bowing"], + characteristic_length_m=p["grading_char_length"], + ), + ) + + +def _explicit_escape_bindings( + absorber_layers: Sequence[PreparedLayer], + explicit_escape_probabilities: Mapping[str, float], + *, + mode: str, +) -> tuple[AbsorberEscapeBinding, ...]: + bindings: list[AbsorberEscapeBinding] = [] + for layer in absorber_layers: + if layer.id not in explicit_escape_probabilities: + raise CapabilityError( + f"explicit_escape_probabilities is missing absorber layer {layer.id!r}" + ) + raw_p = float(explicit_escape_probabilities[layer.id]) + if not math.isfinite(raw_p) or raw_p < 0.0 or raw_p > 1.0: + raise CapabilityError( + f"explicit escape probability for {layer.id!r} must lie in [0, 1], got {raw_p!r}" + ) + params = dict(layer.parameters) + eg_front = float(cast(float, params["Eg"])) + eg_back = params.get("Eg_back") + eg_eff = eg_front if eg_back is None else min(eg_front, float(eg_back)) + wl_gap = wavelength_at_gap(eg_eff) + alpha_val = float(cast(float, params["alpha"])) + n_opt_raw = params.get("n_optical") + n_gap = 1.0 if n_opt_raw is None else float(n_opt_raw) + k_gap = max(alpha_val, 0.0) * wl_gap / (4.0 * math.pi) + od = max(alpha_val, 0.0) * layer.thickness + bindings.append( + AbsorberEscapeBinding( + layer_id=layer.id, + mode=mode, + band_gap_eV=eg_eff, + wavelength_gap_m=wl_gap, + refractive_index_at_gap=n_gap, + extinction_at_gap=k_gap, + alpha_gap_m1=max(alpha_val, 0.0), + thickness_m=layer.thickness, + optical_depth=od, + escape_probability=raw_p, + ) + ) + return tuple(bindings) + + +def compile_nonlocal_device_1d( + prepared: PreparedDevice, + *, + intervals_per_layer: int | Sequence[int] = 24, + grid_alpha: float | Sequence[float] | None = None, + additional_recombination: LocalRecombinationModel | None = None, + photon_recycling_mode: str = PHOTON_RECYCLING_OFF, + escape_probability_mode: str = YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + explicit_escape_probabilities: Mapping[str, float] | None = None, + receiver_node_overrides: Mapping[str, ArrayLike] | None = None, + lagged_carrier_densities_m3: tuple[ArrayLike, ArrayLike] | None = None, + wkb_sparsity_policy: str = PREALLOCATED_RESERVOIR_SUPERSET_V1, + driver: str = "quasi_fermi_steady_state", +) -> CompiledNonlocalDevice1D: + """Cold-compile a ``PreparedDevice`` with optional photon recycling and WKB tunnelling.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("compile_nonlocal_device_1d requires a PreparedDevice") + if photon_recycling_mode not in PHOTON_RECYCLING_MODES: + raise CapabilityError( + f"unknown photon_recycling_mode {photon_recycling_mode!r}; expected {PHOTON_RECYCLING_MODES}" + ) + if escape_probability_mode not in ESCAPE_PROBABILITY_MODES: + raise CapabilityError( + f"unknown escape_probability_mode {escape_probability_mode!r}; expected {ESCAPE_PROBABILITY_MODES}" + ) + if wkb_sparsity_policy not in WKB_SPARSITY_POLICIES: + raise CapabilityError( + f"unknown wkb_sparsity_policy {wkb_sparsity_policy!r}; expected {WKB_SPARSITY_POLICIES}" + ) + + data = prepared.to_mapping() + settings = data["settings"] + raw_tun = data.get("tunnelling_channels") + try: + tun_doc = None if raw_tun is None else tunnelling_channel_document_from_mapping(raw_tun) + except (TunnellingChannelSchemaError, TunnellingChannelError) as exc: + raise CapabilityError(f"invalid tunnelling_channels schema: {exc}") from exc + + has_active_tunnelling = tun_doc is not None and tun_doc.any_enabled + if ( + photon_recycling_mode == PHOTON_RECYCLING_OFF + and raw_tun is None + and grid_alpha is None + and settings["dos_band_potentials"] + ): + base = compile_device_1d( + prepared, + intervals_per_layer=intervals_per_layer, + additional_recombination=additional_recombination, + ) + return CompiledNonlocalDevice1D(base=base, wkb_sparsity_policy=wkb_sparsity_policy) + + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + if not layers: + raise CapabilityError("unsupported_nonlocal_1d_dc: device has no electrical layers") + _validate_nonlocal_capabilities(prepared, data, layers) + + grid = {entry["layer"]: entry for entry in data["electrical_grid"]} + if isinstance(intervals_per_layer, bool): + raise ValueError("intervals_per_layer must be an integer or integer sequence") + if isinstance(intervals_per_layer, int): + if intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be at least 2") + weights = np.asarray( + [grid.get(layer.id, {}).get("interval_weight", 1.0) for layer in layers] + ) + counts = ( + np.maximum(2, np.rint(intervals_per_layer * weights / np.mean(weights))) + .astype(int) + .tolist() + ) + else: + if isinstance(intervals_per_layer, (str, bytes)): + raise ValueError("intervals_per_layer must be an integer or integer sequence") + counts = list(intervals_per_layer) + if len(counts) != len(layers) or any( + type(count) is not int or count < 2 for count in counts + ): + raise ValueError("interval counts must be integers >= 2, one per electrical layer") + + for index, layer in enumerate(layers): + p = dict(layer.parameters) + if settings["band_grading"] and (p["Eg_back"] is not None or p["chi_back"] is not None): + counts[index] *= p["grading_N_mult"] + + if grid_alpha is None: + alphas: list[float] = [float(grid.get(layer.id, {}).get("alpha", 3.0)) for layer in layers] + elif isinstance(grid_alpha, (int, float)) and not isinstance(grid_alpha, bool): + alphas = [float(grid_alpha) for _ in layers] + else: + if isinstance(grid_alpha, (str, bytes, bool)): + raise ValueError("grid_alpha must be a float, float sequence, or None") + alphas = [float(v) for v in cast(Sequence[float], grid_alpha)] + if len(alphas) != len(layers): + raise ValueError("grid_alpha sequence must match electrical layers") + + thicknesses = [layer.thickness for layer in layers] + interface_positions: np.ndarray = np.cumsum(thicknesses, dtype=float)[:-1] + nodes = multilayer_grid(list(zip(thicknesses, counts)), alpha=alphas) + masks = layer_node_masks(nodes, thicknesses, RIGHT_LAYER_WINS) + geometry = build_geometry(INTEGER_ENDPOINT_V1, nodes, interface_positions) + + binding = compile_layer_parameters( + nodes, + [_layer_input(layer) for layer in layers], + temperature_K=settings["T"], + temperature_scaling=True, + band_grading=settings["band_grading"], + dos_band_potentials=True, + dual_ions=False, + ) + + def paint(name: str) -> np.ndarray: + result = np.empty(nodes.size) + for layer, mask in zip(layers, masks): + result[mask] = dict(layer.parameters)[name] + return result + + electron_diffusivity = legacy_face_diffusivity(binding.electron_diffusivity_m2_s) + hole_diffusivity = legacy_face_diffusivity(binding.hole_diffusivity_m2_s) + try: + field_transport = bind_field_transport_1d( + nodes, + electron_diffusivity, + hole_diffusivity, + binding.thermal_voltage_V, + v_sat_n=paint("v_sat_n"), + v_sat_p=paint("v_sat_p"), + ct_beta_n=paint("ct_beta_n"), + ct_beta_p=paint("ct_beta_p"), + pf_gamma_n=paint("pf_gamma_n"), + pf_gamma_p=paint("pf_gamma_p"), + ) + except FieldMobilityCapabilityError as error: + raise CapabilityError("unsupported_nonlocal_1d_dc: " + str(error)) from error + + bands = binding.band_structure + log_product = ( + np.log(binding.conduction_dos_m3) + + np.log(binding.valence_dos_m3) + - bands.physical_band_gap_eV / binding.thermal_voltage_V + ) + configured = binding.intrinsic_product_m6 + if ( + np.any(configured <= 0.0) + or not np.all(np.isfinite(configured)) + or np.max(np.abs(np.log(configured) - log_product)) > 1.0e-10 + ): + raise CapabilityError( + "inconsistent_intrinsic_product: configured ni and physical Nc/Nv/Eg do not share one Maxwell-Boltzmann equilibrium" + ) + poisson = PoissonOperator1D.for_geometry(geometry, paint("eps_r")) + + optical_gen: OpticalGeneration1D | None = None + generation_name = data["declaration"].get("fixed_generation") + if generation_name is not None: + table = prepared.resources.get(generation_name, "fixed_generation") + if table.array.shape != (nodes.size, 2) or not np.array_equal(table.array[:, 0], nodes): + raise CapabilityError( + "fixed_generation: resource coordinates must exactly match the compiled nodes; interpolation is not bound" + ) + generation = FixedGenerationProfile(table.array[:, 1], nodes.size).generation_profile( + geometry + ) + elif data["declaration"].get("spectrum") is not None: + optical_gen = bind_optical_generation_1d(prepared, geometry) + generation = optical_gen.profile + else: + generation = BeerLambertBinding(nodes, paint("alpha"), settings["Phi"]).generation_profile( + geometry + ) + + escape_bindings: tuple[AbsorberEscapeBinding, ...] = () + reabsorption_specs: list[AbsorberReabsorptionSpec] = [] + effective_b_rad = binding.radiative_coefficient_m3_s + + if photon_recycling_mode != PHOTON_RECYCLING_OFF: + absorber_indices = [idx for idx, layer in enumerate(layers) if layer.role == "absorber"] + if not absorber_indices: + raise CapabilityError("photon_recycling requires at least one absorber layer") + absorber_layers = [layers[idx] for idx in absorber_indices] + absorber_masks = [masks[idx] for idx in absorber_indices] + absorber_cv_weights = [geometry.cell_measures_m[masks[idx]] for idx in absorber_indices] + + if explicit_escape_probabilities is not None: + try: + escape_bindings = _explicit_escape_bindings( + absorber_layers, + explicit_escape_probabilities, + mode=escape_probability_mode, + ) + except (PhotonRecyclingCapabilityError, PhotonRecyclingError) as exc: + raise CapabilityError(str(exc)) from exc + else: + if optical_gen is None: + raise CapabilityError( + "photon_recycling requires coherent spectral TMM optics or explicit_escape_probabilities" + ) + absorber_inputs = [ + AbsorberEscapeInput( + layer_id=layer.id, + thickness_m=layer.thickness, + band_gap_front_eV=float(cast(float, dict(layer.parameters)["Eg"])), + band_gap_back_eV=cast( + float | None, + dict(layer.parameters).get("Eg_back") + if settings["band_grading"] + else None, + ), + ) + for layer in absorber_layers + ] + try: + escape_bindings = bind_absorber_escape_from_optical_stack( + optical_gen.binding, + absorber_inputs, + mode=escape_probability_mode, + electrical_nodes_m=nodes, + absorber_node_masks=absorber_masks, + absorber_weights_m=( + absorber_cv_weights + if escape_probability_mode == TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1 + else None + ), + ) + except (PhotonRecyclingCapabilityError, PhotonRecyclingError) as exc: + raise CapabilityError(str(exc)) from exc + + if photon_recycling_mode == PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED: + effective_b_rad = effective_radiative_coefficient( + binding.radiative_coefficient_m3_s, + absorber_masks, + [item.escape_probability for item in escape_bindings], + ) + else: + lagged_n: np.ndarray | None = None + lagged_p: np.ndarray | None = None + if photon_recycling_mode == LAGGED_BAKED_GENERATION_V1: + if lagged_carrier_densities_m3 is None: + raise CapabilityError( + "lagged_baked_generation_v1 requires lagged_carrier_densities_m3=(n_lag, p_lag)" + ) + lagged_n = np.asarray(lagged_carrier_densities_m3[0], dtype=float) + lagged_p = np.asarray(lagged_carrier_densities_m3[1], dtype=float) + if lagged_n.shape != (nodes.size,) or lagged_p.shape != (nodes.size,): + raise CapabilityError( + "lagged_carrier_densities_m3 arrays must match compiled node_count" + ) + + for layer, mask, esc in zip(absorber_layers, absorber_masks, escape_bindings): + b_abs = binding.radiative_coefficient_m3_s[mask] + if not np.any(b_abs > 0.0): + continue + emit_nodes = np.flatnonzero(mask) + ni_abs = configured[mask] + try: + if photon_recycling_mode == CONTROL_VOLUME_CONSERVATIVE_V1: + recv_nodes = ( + np.asarray(receiver_node_overrides[layer.id], dtype=np.intp) + if receiver_node_overrides is not None + and layer.id in receiver_node_overrides + else emit_nodes + ) + reabsorption_specs.append( + AbsorberReabsorptionSpec.control_volume_conservative( + layer_id=layer.id, + node_count=nodes.size, + emitter_nodes=emit_nodes, + cell_measures_m=geometry.cell_measures_m, + escape_probability=esc.escape_probability, + intrinsic_radiative_B_m3_s=b_abs, + intrinsic_product_m6=ni_abs, + receiver_nodes=recv_nodes, + ) + ) + elif photon_recycling_mode == HISTORICAL_TRAPEZOID_UNIFORM_V1: + reabsorption_specs.append( + AbsorberReabsorptionSpec.historical_trapezoid_uniform( + layer_id=layer.id, + nodes_m=nodes, + absorber_mask=mask, + thickness_m=layer.thickness, + escape_probability=esc.escape_probability, + intrinsic_radiative_B_m3_s=b_abs, + intrinsic_product_m6=ni_abs, + ) + ) + elif photon_recycling_mode == LAGGED_BAKED_GENERATION_V1: + assert lagged_n is not None and lagged_p is not None + recv_nodes = ( + np.asarray(receiver_node_overrides[layer.id], dtype=np.intp) + if receiver_node_overrides is not None + and layer.id in receiver_node_overrides + else emit_nodes + ) + base_spec = AbsorberReabsorptionSpec.control_volume_conservative( + layer_id=layer.id, + node_count=nodes.size, + emitter_nodes=emit_nodes, + cell_measures_m=geometry.cell_measures_m, + escape_probability=esc.escape_probability, + intrinsic_radiative_B_m3_s=b_abs, + intrinsic_product_m6=ni_abs, + receiver_nodes=recv_nodes, + ) + reabsorption_specs.append( + AbsorberReabsorptionSpec.lagged_baked( + base_spec, + lagged_n, + lagged_p, + ) + ) + except (PhotonRecyclingCapabilityError, PhotonRecyclingError) as exc: + raise CapabilityError(str(exc)) from exc + + compiled_tunnelling: CompiledTunnellingChannels | None = None + if has_active_tunnelling: + interface_nodes = tuple( + int(plane.shared_node) + for plane in geometry.interfaces + if plane.shared_node is not None + ) + layer_names = tuple(layer.id for layer in layers) + layer_boundaries_m = np.r_[0.0, np.cumsum(thicknesses, dtype=float)] + try: + compiled_tunnelling = compile_tunnelling_channels( + tun_doc, + node_count=nodes.size, + interface_nodes=interface_nodes, + positions_m=nodes, + physical_affinity_eV=bands.physical_electron_affinity_eV, + layer_names=layer_names, + layer_boundaries_m=layer_boundaries_m, + driver=driver, + ) + except (TunnellingChannelCapabilityError, TunnellingChannelError) as exc: + raise CapabilityError(str(exc)) from exc + + coefficients = BulkRecombinationCoefficients( + nodes.size, + configured, + paint("tau_n"), + paint("tau_p"), + binding.srh_n1_m3, + binding.srh_p1_m3, + effective_b_rad, + paint("C_n"), + paint("C_p"), + ) + explicit_defects = bind_neutral_defects( + layers, + masks, + ni_sq_m6=configured, + band_gap_eV=bands.physical_band_gap_eV, + thermal_voltage_V=binding.thermal_voltage_V, + conduction_dos_m3=binding.conduction_dos_m3, + valence_dos_m3=binding.valence_dos_m3, + ) + recombination = BulkRecombinationReaction(coefficients, explicit_defects) + + def contact_material(node: int) -> ContactMaterial: + return ContactMaterial( + binding.temperature_K, + float(bands.physical_electron_affinity_eV[node]), + float(bands.physical_band_gap_eV[node]), + float(binding.conduction_dos_m3[node]), + float(binding.valence_dos_m3[node]), + float(binding.donor_density_m3[node]), + float(binding.acceptor_density_m3[node]), + ) + + left_material, right_material = contact_material(0), contact_material(-1) + work_left = semiconductor_work_function(left_material) + built_in = work_left - semiconductor_work_function(right_material) + phi_left = float(settings["phi_left"]) + reference_phi = phi_left + built_in * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + fermi = -work_left - phi_left + reference_n = binding.conduction_dos_m3 * np.exp( + (fermi + reference_phi + bands.physical_electron_affinity_eV) + / binding.thermal_voltage_V + ) + reference_p = binding.valence_dos_m3 * np.exp( + -( + fermi + + reference_phi + + bands.physical_electron_affinity_eV + + bands.physical_band_gap_eV + ) + / binding.thermal_voltage_V + ) + reservoirs = [ + doping_equilibrium_densities( + float(binding.donor_density_m3[node]), + float(binding.acceptor_density_m3[node]), + float(configured[node]), + ) + for node in (0, -1) + ] + for node, reservoir in zip((0, -1), reservoirs): + reference_n[node], reference_p[node] = reservoir + + contacts = {entry["side"]: entry for entry in data["contacts"]} + velocities = resolve_exchange_velocities( + tuple(contacts[side][name] for side in ("left", "right") for name in ("S_n", "S_p")), + flat_band_contacts=settings["flat_band_contacts"], + selective_contacts_enabled=True, + ) + channels = tuple( + CarrierExchangeChannel(carrier, side, velocity, reservoirs[side_index][carrier_index]) + for velocity, (side_index, side, carrier_index, carrier) in zip( + velocities, + ((0, "left", 0, "n"), (0, "left", 1, "p"), (1, "right", 0, "n"), (1, "right", 1, "p")), + ) + ) + if all(channel.kind == "blocking" for channel in channels): + raise CapabilityError( + "fully_blocking_contacts: a closed carrier inventory constraint is not bound in this DC slice" + ) + if compiled_tunnelling is not None and any( + channel.kind != "fixed_reservoir" for channel in channels + ): + raise CapabilityError( + "wkb_selective_contacts_unsupported: WKB tunnelling requires ohmic fixed_reservoir contacts" + ) + + extra_id = None if additional_recombination is None else additional_recombination.model_id + identity_parts: tuple[object, ...] = ( + "electrode_quasi_fermi_1d_v1", + prepared.content_sha256, + binding.sha256, + generation.binding_sha256, + geometry.name, + counts, + extra_id, + ) + if grid_alpha is not None: + identity_parts += ("grid_alpha", alphas) + if photon_recycling_mode == PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED: + identity_parts += ( + "local_escape_scaled", + [item.sha256 for item in escape_bindings], + ) + if explicit_defects is not None: + identity_parts += (explicit_defects.identity_sha256,) + owned = explicit_defects.owned_nodes + if np.any(binding.conduction_dos_m3[owned] != binding.valence_dos_m3[owned]): + identity_parts += (LITERAL_ABOVE_VB_DOS_REFERENCE_V1,) + if field_transport is not None: + identity_parts += (field_transport.identity_sha256,) + identity = hashlib.sha256( + json.dumps(identity_parts, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + base = CompiledDevice1D( + data["id"], + identity, + geometry, + binding, + poisson, + electron_diffusivity, + hole_diffusivity, + generation, + recombination, + channels, + phi_left, + built_in, + fermi, + reference_phi, + reference_n, + reference_p, + additional_recombination, + field_transport=field_transport, + ) + return CompiledNonlocalDevice1D( + base=base, + escape_bindings=escape_bindings, + radiative_reabsorption=tuple(reabsorption_specs), + tunnelling_channels=compiled_tunnelling, + wkb_sparsity_policy=wkb_sparsity_policy, + ) + + +def _continuity_current_bound(problem: NonlocalProblem, u: np.ndarray) -> float: + count = problem.device.node_count + residual = problem.residual(u) + total = 0.0 + for carrier, offset in (("n", count), ("p", 2 * count)): + rows = np.abs(residual[offset : offset + count]).copy() + for side, node in (("left", 0), ("right", count - 1)): + if problem.device.channel(carrier, side).kind == "fixed_reservoir": + rows[node] = 0.0 + total += float(np.sum(rows)) + return Q * total + + +def nonlocal_physical_gates( + problem: NonlocalProblem, + options: SteadyOptions, + *, + equilibrium: bool, +) -> tuple[PhysicalGate, ...]: + """Independent physical acceptance gates for nonlocal 1D steady states.""" + device = problem.device + base = device.base + count = device.node_count + + def all_currents(u: np.ndarray) -> np.ndarray: + contact = problem.contact_current_density(u) + return np.r_[contact[:1], problem.current_density(u), contact[1:]] + + gates: list[PhysicalGate] = [ + gate_from( + "poisson_balance", + lambda u: float( + np.max(np.abs(problem.residual(u)[:count] * poisson_row_weights(base))) + ), + options.poisson_tolerance, + "maximum normalized Gauss/contact residual", + ), + gate_from( + "continuity_current_bound", + lambda u: _continuity_current_bound(problem, u), + options.continuity_tolerance_A_m2, + "q * sum of absolute carrier balances, including nonlocal couplings", + ), + gate_from( + "all_face_current_spread", + lambda u: float(np.ptp(all_currents(u))), + options.current_spread_tolerance_A_m2, + "maximum minus minimum over every internal/external contact face", + ), + ] + if equilibrium: + + def thermodynamics(u: np.ndarray) -> GateOutcome: + state = device.state(u, voltage_V=problem.voltage_V) + bands = device.parameters.band_structure + + def endpoint(node: int) -> ContactEndpoint: + return ContactEndpoint( + float(state.electron_density_m3[node]), + float(state.hole_density_m3[node]), + float(device.parameters.conduction_dos_m3[node]), + float(device.parameters.valence_dos_m3[node]), + float(bands.physical_electron_affinity_eV[node]), + float(bands.physical_band_gap_eV[node]), + ) + + assessment = assess_contact_thermodynamics( + built_in_potential_mode="semiconductor_work_function", + left=endpoint(0), + right=endpoint(-1), + V_bi_bc=float(state.potential_V[-1] - state.potential_V[0]), + thermal_voltage_V=device.thermal_voltage_V, + has_band_reference=True, + ) + span = assessment.fermi_level_span_eV + return GateOutcome( + "contact_thermodynamics", + assessment.certified, + math.inf if span is None else span, + assessment.tolerance_eV, + assessment.status, + ) + + def max_equilibrium_current(u: np.ndarray) -> float: + fluxes = problem.fluxes(u) + jn = fluxes.electron_current() + if device.has_wkb_tunnelling: + ext = evaluate_nonlocal_couplings_1d( + device, u, voltage_V=problem.voltage_V, derivatives=False + ) + jn = jn + ext.electron_face_current_addition_A_m2 + return float( + max( + np.max(np.abs(jn)), + np.max(np.abs(fluxes.hole_current())), + np.max(np.abs(problem.contact_current_density(u))), + ) + ) + + gates.extend( + ( + gate_from( + "zero_equilibrium_carrier_current", + max_equilibrium_current, + options.equilibrium_current_tolerance_A_m2, + "each carrier (drift-diffusion + WKB) on every face and both contacts", + ), + thermodynamics, + ) + ) + return tuple(gates) + + +def _density_basin_seed_nonlocal(problem: NonlocalProblem, u: np.ndarray) -> np.ndarray: + count = problem.device.node_count + _, n, p = problem.device.fields(u, voltage_V=problem.voltage_V) + residual = problem.residual(u)[count:] + density_inverse = np.r_[1.0 / n, -1.0 / p] + matrix = problem.jacobian(u)[count:, count:] @ diags(density_inverse) + increment = factorize(matrix).solve(-residual) + trial_n, trial_p = n + increment[:count], p + increment[count:] + if not all( + np.all(np.isfinite(value)) and np.all(value > 0.0) for value in (trial_n, trial_p) + ): + raise ValueError("density preparation did not produce finite positive carriers") + seed = np.array(u, copy=True) + for offset, density, trial, delta, sign in ( + (count, n, trial_n, increment[:count], 1.0), + (2 * count, p, trial_p, increment[count:], -1.0), + ): + with np.errstate(over="ignore", divide="ignore"): + relative = delta / density + change = np.log1p(relative) + large = ~np.isfinite(change) + change[large] = np.log(trial[large]) - np.log(density[large]) + seed[offset : offset + count] += sign * change + return seed + + +def _build_nonlocal_problem( + device: CompiledNonlocalDevice1D, + voltage_V: float, + generation_scale: float, + *, + assembled_factory: Any | None, + use_assembled_system: bool, +) -> NonlocalProblem: + if use_assembled_system: + assert assembled_factory is not None + return cast(AssembledNonlocalDC1DProblem, assembled_factory(device, voltage_V, generation_scale)) + return NonlocalDC1DProblem(device, voltage_V, generation_scale) + + +def _solve_nonlocal_point( + device: CompiledNonlocalDevice1D, + u: np.ndarray, + voltage_V: float, + generation_scale: float, + options: SteadyOptions, + *, + equilibrium: bool = False, + assembled_factory: Any | None = None, + use_assembled_system: bool = True, +) -> tuple[NonlocalProblem, NewtonResult]: + problem = _build_nonlocal_problem( + device, + voltage_V, + generation_scale, + assembled_factory=assembled_factory, + use_assembled_system=use_assembled_system, + ) + seed = np.asarray(u, dtype=float) + max_rebinds = 8 if device.wkb_sparsity_policy == STRICT_WINDOW_REBIND_V1 else 0 + rebinds = 0 + while True: + if device.wkb_sparsity_policy == STRICT_WINDOW_REBIND_V1 and device.has_wkb_tunnelling: + problem = problem.rebind_for_state(seed) + settings = NewtonSettings( + production_residual_scaling( + device.base, + poisson_tolerance=options.poisson_tolerance, + continuity_tolerance_A_m2=options.continuity_tolerance_A_m2, + contact_log_tolerance=options.contact_log_tolerance, + ), + 1.0, + production_coordinates( + device.base, + potential_step_V=options.potential_step_V, + quasi_fermi_step=options.quasi_fermi_step, + ), + options.budget(), + nonlocal_physical_gates(problem, options, equilibrium=equilibrium), + False, + ) + try: + result = solve_newton( + problem, + seed, + settings, + convergence_norm=production_convergence_norm( + device.base, convergence_policy=options.convergence_policy + ), + ) + break + except SparsitySupportChangedError as exc: + if rebinds >= max_rebinds: + raise + if exc.state is not None: + seed = exc.state + rebinds += 1 + if not result.accepted: + raise SteadyStateError( + f"Nonlocal DC V={voltage_V:g}, generation_scale={generation_scale:g}", + result, + ) + return problem, result + + +def _nonlocal_point_result( + problem: NonlocalProblem, + result: NewtonResult, + preparation: tuple[NewtonResult, ...] = (), + density_basin_stages: tuple[tuple[float, float], ...] = (), +) -> SteadyState1D: + return SteadyState1D( + problem.device.state(result.state, voltage_V=problem.voltage_V), + problem.current_density(result.state), + problem.contact_current_density(result.state), + problem.voltage_V, + problem.generation_scale, + result, + preparation, + len(density_basin_stages), + density_basin_stages, + ) + + +def _default_nonlocal_steady_options( + device: CompiledNonlocalDevice1D, + *, + max_voltage_V: float = 0.0, +) -> SteadyOptions: + """Default steady-state controls accounting for IEEE-754 face-flux roundoff on WKB barriers.""" + base = device.base + donor = base.parameters.donor_density_m3 + acceptor = base.parameters.acceptor_density_m3 + unipolar = bool((donor[0] > acceptor[0]) == (donor[-1] > acceptor[-1])) + if not device.has_wkb_tunnelling and not unipolar: + return SteadyOptions() + dx = np.diff(base.nodes_m) + doping_face = np.maximum( + np.maximum(donor[:-1], donor[1:]), + np.maximum(acceptor[:-1], acceptor[1:]), + ) + diff_face = np.maximum( + base.electron_diffusivity_faces_m2_s, base.hole_diffusivity_faces_m2_s + ) + max_face_current_scale = float(np.max(Q * diff_face * np.maximum(doping_face, 1.0) / dx)) + bias_span = 1.0 + abs(float(max_voltage_V)) / base.thermal_voltage_V + roundoff_floor = 64.0 * float(np.finfo(float).eps) * max_face_current_scale * bias_span + if not device.has_wkb_tunnelling and roundoff_floor <= 1.0e-8: + return SteadyOptions() + cont_tol = max(1.0e-8, roundoff_floor) + return SteadyOptions( + continuity_tolerance_A_m2=cont_tol, + current_spread_tolerance_A_m2=cont_tol, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + + +def solve_nonlocal_equilibrium_1d( + device: CompiledNonlocalDevice1D, + *, + options: SteadyOptions | None = None, + use_assembled_system: bool | None = None, +) -> SteadyState1D: + """Solve dark equilibrium (V=0, generation_scale=0) and certify nonlocal gates.""" + device.require_driver_capability("quasi_fermi_steady_state") + controls = ( + _default_nonlocal_steady_options(device, max_voltage_V=0.0) + if options is None + else options + ) + assembled = use_assembled() if use_assembled_system is None else bool(use_assembled_system) + factory = assembled_nonlocal_problem_factory(device) if assembled else None + base = device.base + count = base.node_count + + def densities(phi: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + _, n, p = base.fields(np.r_[phi, np.zeros(2 * count)]) + return n, p + + def residual(phi: np.ndarray) -> np.ndarray: + n, p = densities(phi) + if not np.all(np.isfinite(n)) or not np.all(np.isfinite(p)): + return np.full(count, np.nan) + rho = base.charge_ledger(n, p).space_charge_C_m3() + return base.poisson.residual(phi, rho, *base.contact_potentials(0.0)) + + def jacobian(phi: np.ndarray) -> object: + n, p = densities(phi) + slope = np.zeros(count) + slope[1:-1] = ( + -Q + * base.poisson.interior_widths_m + * (n[1:-1] + p[1:-1]) + / base.thermal_voltage_V + ) + return base.poisson.jacobian() + diags(slope) + + pb_settings = NewtonSettings( + ResidualScaling(poisson_row_weights(base) / controls.poisson_tolerance), + 1.0, + StepControl(np.full(count, controls.potential_step_V)), + controls.budget(), + (), + False, + ) + prepared = solve_newton( + CallableProblem(residual, jacobian), + base.reference_potential_V, + pb_settings, + ) + if not prepared.accepted: + raise SteadyStateError("Poisson-Boltzmann equilibrium preparation", prepared) + u = np.r_[prepared.state, np.zeros(2 * count)] + problem, result = _solve_nonlocal_point( + device, + u, + 0.0, + 0.0, + controls, + equilibrium=True, + assembled_factory=factory, + use_assembled_system=assembled, + ) + return _nonlocal_point_result(problem, result, (prepared,)) + + +def solve_nonlocal_steady_state_1d( + device: CompiledNonlocalDevice1D, + *, + initial_state: State1D | None = None, + voltage_V: float = 0.0, + generation_scale: float = 1.0, + options: SteadyOptions | None = None, + use_assembled_system: bool | None = None, +) -> SteadyState1D: + """Solve a 1D steady-state operating point with nonlocal reabsorption / WKB tunnelling.""" + device.require_driver_capability("quasi_fermi_steady_state") + controls = ( + _default_nonlocal_steady_options(device, max_voltage_V=voltage_V) + if options is None + else options + ) + assembled = use_assembled() if use_assembled_system is None else bool(use_assembled_system) + factory = assembled_nonlocal_problem_factory(device) if assembled else None + target = _build_nonlocal_problem( + device, + voltage_V, + generation_scale, + assembled_factory=factory, + use_assembled_system=assembled, + ) + if initial_state is not None: + if not isinstance(initial_state, State1D) or initial_state.device_sha256 != device.sha256: + raise ValueError("initial_state must belong to the same compiled nonlocal device") + dv = abs(target.voltage_V - initial_state.voltage_V) + step_count = max(1, int(math.ceil(dv / controls.max_bias_step_V))) + if step_count > controls.max_continuation_steps: + raise ValueError("requested initialization exceeds the continuation-step budget") + u_cur = initial_state.u + prev_v = initial_state.voltage_V + prep_steps: list[NewtonResult] = [] + for idx, v_step in enumerate( + np.linspace(initial_state.voltage_V, target.voltage_V, step_count + 1)[1:] + ): + v_val = float(v_step) + u_cur = device.rebase_coordinates(u_cur, prev_v, v_val) + problem, result = _solve_nonlocal_point( + device, + u_cur, + v_val, + target.generation_scale, + controls, + equilibrium=(v_val == 0.0 and target.generation_scale == 0.0), + assembled_factory=factory, + use_assembled_system=assembled, + ) + u_cur = result.state + prev_v = v_val + if idx != step_count - 1: + prep_steps.append(result) + return _nonlocal_point_result(problem, result, tuple(prep_steps)) + + equilibrium = solve_nonlocal_equilibrium_1d( + device, options=controls, use_assembled_system=assembled + ) + if generation_scale == 0.0 and voltage_V == 0.0: + return equilibrium + + u = equilibrium.state.u + preparation = [*equilibrium.preparation, equilibrium.newton] + if generation_scale > 0.0: + fractions: tuple[float, ...] = ( + (1.0e-12, 1.0e-10, 1.0e-8, 1.0e-6, 1.0e-4, 1.0e-2, 1.0e-1, 1.0) + if device.has_wkb_tunnelling + else (1.0e-8, 1.0e-6, 1.0e-4, 1.0e-2, 1.0) + ) + light_steps = [fraction * generation_scale for fraction in fractions] + else: + light_steps = [] + + bias_count = int(math.ceil(abs(voltage_V) / controls.max_bias_step_V)) + if len(light_steps) + bias_count > controls.max_continuation_steps: + raise ValueError("requested initialization exceeds the continuation-step budget") + + points = [(0.0, value) for value in light_steps] + points.extend( + (float(value), generation_scale) + for value in np.linspace(0.0, voltage_V, bias_count + 1)[1:] + ) + previous_voltage = 0.0 + density_stages: list[tuple[float, float]] = [] + for index, (voltage, light) in enumerate(points): + u = device.rebase_coordinates(u, previous_voltage, voltage) + if index < len(light_steps) and light > 0.0 and not device.has_wkb_tunnelling: + stage_problem = _build_nonlocal_problem( + device, + voltage, + light, + assembled_factory=factory, + use_assembled_system=assembled, + ) + u = _density_basin_seed_nonlocal(stage_problem, u) + density_stages.append((voltage, light)) + problem, result = _solve_nonlocal_point( + device, + u, + voltage, + light, + controls, + assembled_factory=factory, + use_assembled_system=assembled, + ) + u = result.state + previous_voltage = voltage + if index != len(points) - 1: + preparation.append(result) + return _nonlocal_point_result(problem, result, tuple(preparation), tuple(density_stages)) diff --git a/src/solarlab/equations/assembly/nonlocal_1d.py b/src/solarlab/equations/assembly/nonlocal_1d.py new file mode 100644 index 00000000..f746b297 --- /dev/null +++ b/src/solarlab/equations/assembly/nonlocal_1d.py @@ -0,0 +1,648 @@ +"""Assembled 1D electronic DC and small-signal AC with nonlocal reabsorption and WKB tunnelling. + +Composes :class:`~solarlab.equations.assembly.classical_1d.ClassicalDC1D` with +the structured sparse nonlocal operators of +:mod:`solarlab.equations.nonlocal_1d`: + +* Disabled/empty nonlocal configurations delegate directly to + :class:`~solarlab.equations.assembly.classical_1d.AssembledDC1DProblem`, + preserving every residual, sparse Jacobian, storage, and current array bit for + bit. +* Active radiative reabsorption and WKB intraband electron tunnelling assemble + their rank-1 and windowed face-divergence Jacobians directly in sparse CSC + format with zero dense solver fallbacks. +* :func:`solve_nonlocal_small_signal_1d` enforces pre-solve differentiability + and quasi-static capability gates: WKB tunnelling, lagged baked reabsorption, + clamped ``R_tot = 0`` dark-equilibrium reabsorption, thermionic ``min`` + crossovers, and Poole-Frenkel cusps raise :class:`CapabilityError` rather than + assembling an ill-defined linear AC operator. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix, diags, eye +from scipy.sparse.linalg import splu + +from solarlab.contracts.arrays import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.equations.assembly.assembler import AssembledSystem +from solarlab.equations.assembly.classical_1d import ( + AssembledDC1DProblem, + ClassicalDC1D, + classical_dc_1d, +) +from solarlab.equations.assembly.layout import SystemLayout +from solarlab.equations.assembly.quasi_fermi import quasi_fermi_potential_tangents +from solarlab.equations.assembly.terms import OperatingInputs +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.nonlocal_1d import ( + CompiledNonlocalDevice1D, + SparsitySupportChangedError, + evaluate_device_tunnelling_1d, + evaluate_nonlocal_couplings_1d, +) +from solarlab.physics.contacts.exchange import CarrierExchangeChannel +from solarlab.physics.generation.photon_recycling import PhotonRecyclingCapabilityError +from solarlab.physics.generation.radiative_reabsorption import ( + LAGGED_BAKED_GENERATION_V1, + PhotonRecyclingBudget, + ReabsorptionEvaluation, + ThermionicCapDirectionalDerivative, + assess_switching_surfaces, + require_smooth_ac_surfaces, +) +from solarlab.physics.recombination.bulk import RecombinationRate +from solarlab.physics.transport.electrochemical_flux import CarrierFaceFluxes +from solarlab.physics.transport.field_mobility_tangents import FieldMobilityDirectionalDerivative +from solarlab.physics.transport.tunneling_channels import TunnellingChannelEvaluation + +__all__ = [ + "AssembledNonlocalDC1DProblem", + "NonlocalClassicalDC1D", + "NonlocalSmallSignal1D", + "SparsitySupportChangedError", + "assembled_nonlocal_problem_factory", + "nonlocal_classical_dc_1d", + "solve_nonlocal_small_signal_1d", +] + +Vector: TypeAlias = NDArray[np.float64] +ComplexVector: TypeAlias = NDArray[np.complex128] +ComplexMatrix: TypeAlias = NDArray[np.complex128] +Q: float = ELEMENTARY_CHARGE_C + + +@dataclass(frozen=True) +class NonlocalClassicalDC1D: + """Assembled classical 1D system paired with nonlocal coupling bindings.""" + + device: CompiledNonlocalDevice1D + classical: ClassicalDC1D = field(init=False, repr=False) + identity: str = field(init=False) + + def __post_init__(self) -> None: + if not isinstance(self.device, CompiledNonlocalDevice1D): + raise TypeError("NonlocalClassicalDC1D requires a CompiledNonlocalDevice1D") + classical = classical_dc_1d(self.device.base) + object.__setattr__(self, "classical", classical) + if not self.device.has_nonlocal_couplings and not self.device.escape_bindings: + object.__setattr__(self, "identity", classical.identity) + else: + digest = hashlib.sha256( + json.dumps( + { + "schema": "solarlab.nonlocal_classical_dc_1d.v1", + "classical": classical.identity, + "device": self.device.identity, + }, + sort_keys=True, + separators=(",", ":"), + ).encode("ascii") + ).hexdigest() + object.__setattr__(self, "identity", digest) + + @property + def layout(self) -> SystemLayout: + return self.classical.layout + + +def nonlocal_classical_dc_1d(device: CompiledNonlocalDevice1D) -> NonlocalClassicalDC1D: + """Bind the assembled local + nonlocal 1D electronic system of ``device``.""" + return NonlocalClassicalDC1D(device) + + +def assembled_nonlocal_problem_factory( + device: CompiledNonlocalDevice1D, +) -> Callable[[CompiledNonlocalDevice1D, float, float], AssembledNonlocalDC1DProblem]: + """Constructor-compatible factory reusing one ``NonlocalClassicalDC1D`` binding.""" + system = nonlocal_classical_dc_1d(device) + + def factory( + bound: CompiledNonlocalDevice1D, + voltage_V: float, + generation_scale: float, + ) -> AssembledNonlocalDC1DProblem: + return AssembledNonlocalDC1DProblem(bound, voltage_V, generation_scale, system) + + return factory + + +@dataclass(frozen=True) +class AssembledNonlocalDC1DProblem: + """Assembled 1D DC problem supporting nonlocal reabsorption and WKB tunnelling.""" + + device: CompiledNonlocalDevice1D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + system: NonlocalClassicalDC1D | None = field(default=None, repr=False, compare=False) + bound_wkb_signature: str | None = None + + def __post_init__(self) -> None: + self.device.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and non-negative") + if self.system is None: + object.__setattr__(self, "system", nonlocal_classical_dc_1d(self.device)) + elif self.system.device is not self.device: + raise ValueError("the assembled nonlocal system must be bound to this device") + + @property + def binding(self) -> NonlocalClassicalDC1D: + assert self.system is not None + return self.system + + @property + def base_problem(self) -> AssembledDC1DProblem: + return AssembledDC1DProblem( + self.device.base, + self.voltage_V, + self.generation_scale, + self.binding.classical, + ) + + @property + def inputs(self) -> OperatingInputs: + return OperatingInputs(self.voltage_V, self.generation_scale) + + def at(self, voltage_V: float, generation_scale: float) -> AssembledNonlocalDC1DProblem: + """Same bound system at another operating point.""" + return AssembledNonlocalDC1DProblem( + self.device, + voltage_V, + generation_scale, + self.system, + self.bound_wkb_signature, + ) + + def rebind_for_state(self, u: ArrayLike) -> AssembledNonlocalDC1DProblem: + """Bind active WKB turning-point support signature at ``u``.""" + if not self.device.has_wkb_tunnelling: + return self + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=None, + ) + sig = None if ext.wkb_support is None else ext.wkb_support.support_signature + return AssembledNonlocalDC1DProblem( + self.device, + self.voltage_V, + self.generation_scale, + self.system, + sig, + ) + + def _require_steady_for_wkb(self, udot: ArrayLike | None, *, alpha: float = 0.0) -> None: + if not self.device.has_wkb_tunnelling: + return + if alpha != 0.0: + raise CapabilityError( + "wkb_transient_unsupported: WKB tunnelling channels are quasi-static steady-state only" + ) + if udot is not None and np.any(np.asarray(udot, dtype=float) != 0.0): + raise CapabilityError( + "wkb_transient_unsupported: WKB tunnelling channels do not admit nonzero udot" + ) + + def assemble_local( + self, + u: ArrayLike, + *, + derivatives: bool = True, + storage: bool = False, + ) -> AssembledSystem: + return self.base_problem.assemble(u, derivatives=derivatives, storage=storage) + + def residual(self, u: ArrayLike, udot: ArrayLike | None = None) -> Vector: + self._require_steady_for_wkb(udot) + base_f = self.base_problem.residual(u, udot) + if not self.device.has_nonlocal_couplings: + return base_f + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=None, + ) + return base_f + ext.residual_addition + + def jacobian( + self, + u: ArrayLike, + udot: ArrayLike | None = None, + *, + alpha: float = 0.0, + ) -> csc_matrix: + self._require_steady_for_wkb(udot, alpha=alpha) + base_j = self.base_problem.jacobian(u, udot, alpha=alpha) + if not self.device.has_nonlocal_couplings: + return base_j + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=True, + bound_wkb_signature=self.bound_wkb_signature, + ) + assert ext.jacobian_addition is not None + return csc_matrix(base_j + ext.jacobian_addition) + + def storage(self, u: ArrayLike) -> Vector: + if self.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_transient_unsupported: storage time-stepping is unavailable with WKB tunnelling" + ) + return self.base_problem.storage(u) + + def storage_tangent(self, u: ArrayLike) -> csc_matrix: + if self.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_transient_unsupported: storage_tangent is unavailable with WKB tunnelling" + ) + return self.base_problem.storage_tangent(u) + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + if self.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_transient_unsupported: storage_jacobian is unavailable with WKB tunnelling" + ) + return self.base_problem.storage_jacobian(u) + + def storage_increment( + self, + u: ArrayLike, + old_problem: AssembledNonlocalDC1DProblem, + old_u: ArrayLike, + ) -> Vector: + if self.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_transient_unsupported: storage_increment is unavailable with WKB tunnelling" + ) + if old_problem.device.identity != self.device.identity: + raise ValueError("a storage increment needs a previous state of the same device") + return self.base_problem.storage_increment(u, old_problem.base_problem, old_u) + + def fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: + return self.base_problem.fluxes(u) + + def recombination_rate(self, n: Vector, p: Vector, *, derivatives: bool = True) -> RecombinationRate: + return self.base_problem.recombination_rate(n, p, derivatives=derivatives) + + def contact_exchange( + self, + u: ArrayLike, + channel: CarrierExchangeChannel, + node: int, + ) -> tuple[float, float]: + return self.base_problem.contact_exchange(u, channel, node) + + def current_density(self, u: ArrayLike) -> Vector: + base_j = self.base_problem.current_density(u) + if not self.device.has_wkb_tunnelling: + return base_j + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=self.bound_wkb_signature, + ) + return base_j + ext.electron_face_current_addition_A_m2 + + def contact_current_density(self, u: ArrayLike) -> Vector: + base_c = self.base_problem.contact_current_density(u) + if not self.device.has_nonlocal_couplings: + return base_c + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=self.bound_wkb_signature, + ) + dl_n, dl_p = ext.left_contact_exchange_addition + dr_n, dr_p = ext.right_contact_exchange_addition + delta = np.array([-Q * dl_n + Q * dl_p, -Q * dr_n + Q * dr_p], dtype=float) + return base_c + delta + + def photon_recycling_budgets(self, u: ArrayLike) -> tuple[PhotonRecyclingBudget, ...]: + if not self.device.radiative_reabsorption: + return () + ext = evaluate_nonlocal_couplings_1d( + self.device, u, voltage_V=self.voltage_V, derivatives=False + ) + assert ext.reabsorption is not None + return ext.reabsorption.budgets + + def tunnelling_evaluation(self, u: ArrayLike) -> TunnellingChannelEvaluation: + phi, n, p = self.device.fields(u, voltage_V=self.voltage_V) + return evaluate_device_tunnelling_1d(self.device, phi, n, p, derivatives=False) + + +@dataclass(frozen=True) +class NonlocalSmallSignal1D: + """Small-signal AC admittance and Maxwell face-current phasors for nonlocal 1D DC.""" + + frequencies_Hz: Vector + voltage_phasor_V: complex + admittance_density_S_m2: ComplexVector + conduction_current_density_A_m2: ComplexMatrix + displacement_current_density_A_m2: ComplexMatrix + total_current_density_A_m2: ComplexMatrix + maxwell_spread_A_m2_V: Vector + fixed_coordinate_perturbation: ComplexMatrix + compiled_identity: str + + +def _particle_perturbations( + problem: AssembledNonlocalDC1DProblem, + u: Vector, + x_vec: NDArray[np.float64] | ComplexVector, + voltage_drive: complex, + references: tuple[float, float], +) -> tuple[NDArray[np.float64] | ComplexVector, NDArray[np.float64] | ComplexVector]: + """Cancellation-safe quasi-Fermi face-flux tangent grouping uniform energy modes.""" + device = problem.device.base + count = device.node_count + fluxes = problem.fluxes(u) + transport = None if device.field_transport is None else device.field_transport.evaluate(u[:count]) + _, n, p = device.fields(u, voltage_V=problem.voltage_V) + + carrier_df: list[NDArray[np.float64] | ComplexVector] = [] + for offset, density, flux, sign, reference in ( + (count, n, fluxes.electron, 1.0, references[0]), + (2 * count, p, fluxes.hole, -1.0, references[1]), + ): + drive = sign * np.diff(u[offset : offset + count]) + left_phi, _ = quasi_fermi_potential_tangents(flux, drive, sign, device.thermal_voltage_V) + if transport is not None: + diffusivity = ( + transport.electron_diffusivity_m2_s + if offset == count + else transport.hole_diffusivity_m2_s + ) + d_diffusivity = ( + transport.electron_d_diffusivity_d_field + if offset == count + else transport.hole_d_diffusivity_d_field + ) + left_phi = left_phi + (flux.flux / diffusivity) * d_diffusivity / np.diff(device.nodes_m) + left_z = sign * flux.left_density_derivative * density[:-1] + df = ( + left_phi * (x_vec[: count - 1] - x_vec[1:count]) + + left_z * (x_vec[offset : offset + count - 1] - x_vec[offset + 1 : offset + count]) + + sign + * flux.flux + * ( + x_vec[offset + 1 : offset + count] + + (x_vec[1:count] + reference * voltage_drive) / device.thermal_voltage_V + ) + ) + carrier_df.append(df) + return carrier_df[0], carrier_df[1] + + +def _reabsorption_source_tangent( + reabsorption: ReabsorptionEvaluation | None, + count: int, + dn: Vector, + dp: Vector, +) -> Vector: + out: Vector = np.zeros(count, dtype=float) + if reabsorption is None: + return out + for factor in reabsorption.factors: + if factor.active: + emit = factor.emitter_nodes + d_flux = float( + np.dot(factor.d_emission_flux_dn_m_s, dn[emit]) + + np.dot(factor.d_emission_flux_dp_m_s, dp[emit]) + ) + out[factor.receiver_nodes] += factor.receiver_vector_m1 * d_flux + return out + + +def solve_nonlocal_small_signal_1d( + problem: AssembledNonlocalDC1DProblem, + u: ArrayLike, + frequencies_Hz: Sequence[float] | ArrayLike, + *, + voltage_phasor_V: complex = 1.0 + 0.0j, + thermionic_electron: ThermionicCapDirectionalDerivative | None = None, + thermionic_hole: ThermionicCapDirectionalDerivative | None = None, + field_mobility_electron: FieldMobilityDirectionalDerivative | None = None, + field_mobility_hole: FieldMobilityDirectionalDerivative | None = None, +) -> NonlocalSmallSignal1D: + """Assemble and solve ``(J + i*omega*M) x = -polarity * e_{N-1} * V`` at smooth points.""" + if problem.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_ac_unsupported: WKB tunnelling channels are certified only for quasi-static steady-state DC" + ) + for spec in problem.device.radiative_reabsorption: + if spec.mode == LAGGED_BAKED_GENERATION_V1: + raise CapabilityError( + "lagged_reabsorption_ac_unsupported: lagged baked reabsorption lacks live AC derivatives" + ) + + freqs = frozen_array(frequencies_Hz) + if freqs.ndim != 1 or freqs.size == 0 or np.any(freqs < 0.0): + raise ValueError("frequencies_Hz must be a non-empty 1D array of non-negative frequencies") + v_phasor = complex(voltage_phasor_V) + if not np.isfinite(v_phasor) or v_phasor == 0.0: + raise ValueError("voltage_phasor_V must be finite and nonzero") + + values = np.asarray(u, dtype=float) + ext = evaluate_nonlocal_couplings_1d( + problem.device, + values, + voltage_V=problem.voltage_V, + derivatives=True, + bound_wkb_signature=problem.bound_wkb_signature, + ) + assessment = assess_switching_surfaces( + reabsorption=ext.reabsorption, + thermionic_electron=thermionic_electron, + thermionic_hole=thermionic_hole, + field_mobility_electron=field_mobility_electron, + field_mobility_hole=field_mobility_hole, + ) + try: + require_smooth_ac_surfaces(assessment) + except PhotonRecyclingCapabilityError as exc: + raise CapabilityError(str(exc)) from exc + + comp = problem.device.base + count = comp.node_count + polarity = comp.voltage_polarity + _, n, p = comp.fields(values, voltage_V=problem.voltage_V) + before = comp.carrier_reference_energies(0.0) + after = comp.carrier_reference_energies(1.0) + references = (after[0] - before[0], after[1] - before[1]) + c_ref: Vector = np.r_[ + np.zeros(count, dtype=float), + np.full(count, -references[0] / comp.thermal_voltage_V, dtype=float), + np.full(count, -references[1] / comp.thermal_voltage_V, dtype=float), + ] + lift: Vector = np.zeros(3 * count, dtype=float) + lift[count - 1] = -polarity + for carrier, offset in (("n", count), ("p", 2 * count)): + for side, node in (("left", 0), ("right", count - 1)): + if comp.channel(carrier, side).kind == "fixed_reservoir": + lift[offset + node] = -lift[node] / comp.thermal_voltage_V + c_ref[offset + node] + + rate = problem.recombination_rate(n, p) + assert rate.d_rate_dn is not None and rate.d_rate_dp is not None + dn_lift = n * ((lift[:count] + references[0]) / comp.thermal_voltage_V + lift[count : 2 * count]) + dp_lift = -p * ((lift[:count] + references[1]) / comp.thermal_voltage_V + lift[2 * count :]) + src_lift = -(rate.d_rate_dn * dn_lift + rate.d_rate_dp * dp_lift) + _reabsorption_source_tangent( + ext.reabsorption, count, dn_lift, dp_lift + ) + fn_lift, fp_lift = _particle_perturbations(problem, values, lift, 1.0, references) + partial: Vector = np.zeros(3 * count, dtype=float) + partial[:count] = ( + comp.poisson.jacobian() @ lift[:count] + + comp.poisson.charge_jacobian() * Q * (dp_lift - dn_lift) + ) + partial[count - 1] += polarity + for carrier, offset, d_der, face_flux, sign, ref in ( + ("n", count, dn_lift, np.asarray(fn_lift, dtype=float), 1.0, references[0]), + ("p", 2 * count, dp_lift, np.asarray(fp_lift, dtype=float), -1.0, references[1]), + ): + rows = -np.diff(np.r_[0.0, face_flux, 0.0]) + comp.geometry.cell_measures_m * src_lift + for side, node in (("left", 0), ("right", count - 1)): + ch = comp.channel(carrier, side) + if ch.kind == "fixed_reservoir": + rows[node] = sign * ( + (lift[node] + ref) / comp.thermal_voltage_V + lift[offset + node] + ) + else: + _, slope = problem.base_problem.contact_exchange(values, ch, node) + rows[node] += (1.0 if side == "left" else -1.0) * slope * d_der[node] + partial[offset : offset + count] = rows + + rhs_rate: Vector = np.zeros(3 * count, dtype=float) + for carrier, offset, density, sign, ref in ( + ("n", count, n, 1.0, references[0]), + ("p", 2 * count, p, -1.0, references[1]), + ): + rhs_rate[offset : offset + count] = ( + comp.geometry.cell_measures_m + * sign + * density + * ((lift[:count] + ref) / comp.thermal_voltage_V + lift[offset : offset + count]) + ) + for side, node in (("left", 0), ("right", count - 1)): + if comp.channel(carrier, side).kind == "fixed_reservoir": + rhs_rate[offset + node] = 0.0 + + j_mat = problem.jacobian(values) + m_mat = problem.storage_jacobian(values) + p_lil = eye(3 * count, format="lil") + anchors: list[int] = [] + for carrier, offset, preferred in ( + ("n", count, "right" if polarity > 0.0 else "left"), + ("p", 2 * count, "left" if polarity > 0.0 else "right"), + ): + fixed_sides = [ + side for side in ("left", "right") if comp.channel(carrier, side).kind == "fixed_reservoir" + ] + chosen_side = fixed_sides[0] if fixed_sides else preferred + anc = offset + (0 if chosen_side == "left" else count - 1) + anchors.append(anc) + for r_idx in range(offset, offset + count): + if anc not in p_lil.rows[r_idx]: + p_lil.rows[r_idx].append(anc) + p_lil.data[r_idx].append(1.0) + p_transform = p_lil.tocsc() + solve_j_lil = (j_mat @ p_transform).tolil() + solve_m = (m_mat @ p_transform).tocsc() + fluxes = problem.fluxes(values) + for carrier, anc in zip(("n", "p"), anchors): + dn_u = n if carrier == "n" else np.zeros(count, dtype=float) + dp_u = -p if carrier == "p" else np.zeros(count, dtype=float) + src_u = -(rate.d_rate_dn * dn_u + rate.d_rate_dp * dp_u) + _reabsorption_source_tangent( + ext.reabsorption, count, dn_u, dp_u + ) + unif: Vector = np.zeros(3 * count, dtype=float) + unif[:count] = comp.poisson.charge_jacobian() * Q * (dp_u - dn_u) + for cr, offset, dd, flx, sign in ( + ("n", count, dn_u, fluxes.electron, 1.0), + ("p", 2 * count, dp_u, fluxes.hole, -1.0), + ): + fc = sign * flx.flux if cr == carrier else np.zeros(count - 1, dtype=float) + rws = -np.diff(np.r_[0.0, fc, 0.0]) + comp.geometry.cell_measures_m * src_u + for side, node in (("left", 0), ("right", count - 1)): + ch = comp.channel(cr, side) + if ch.kind == "fixed_reservoir": + rws[node] = sign if cr == carrier else 0.0 + else: + _, slope = problem.base_problem.contact_exchange(values, ch, node) + rws[node] += (1.0 if side == "left" else -1.0) * slope * dd[node] + unif[offset : offset + count] = rws + solve_j_lil[:, anc] = unif[:, None] + solve_j = solve_j_lil.tocsc() + + n_freq = freqs.size + n_faces = count - 1 + x_all: ComplexMatrix = np.empty((n_freq, 3 * count), dtype=np.complex128) + j_cond_all: ComplexMatrix = np.empty((n_freq, n_faces), dtype=np.complex128) + j_disp_all: ComplexMatrix = np.empty((n_freq, n_faces), dtype=np.complex128) + j_tot_all: ComplexMatrix = np.empty((n_freq, n_faces), dtype=np.complex128) + admittance: ComplexVector = np.empty(n_freq, dtype=np.complex128) + spread: Vector = np.empty(n_freq, dtype=float) + + cap = comp.poisson.face_capacitance_F_m2 + for idx, f_hz in enumerate(freqs): + omega = 2.0 * math.pi * float(f_hz) + sys_mat = csc_matrix( + solve_j.astype(np.complex128) + (1j * omega) * solve_m.astype(np.complex128) + ) + rhs_vec: ComplexVector = (-partial + (1j * omega) * rhs_rate) * v_phasor + row_max: Vector = np.zeros(sys_mat.shape[0], dtype=float) + np.maximum.at(row_max, sys_mat.indices, np.abs(sys_mat.data)) + inv_row = 1.0 / np.where(row_max > 0.0, row_max, 1.0) + lu = splu(diags(inv_row).dot(sys_mat).tocsc()) + eta: ComplexVector = np.asarray(lu.solve(inv_row * rhs_vec), dtype=np.complex128) + for _ in range(2): + eta = np.asarray( + eta - lu.solve(inv_row * (sys_mat.dot(eta) - rhs_vec)), + dtype=np.complex128, + ) + moving_x: ComplexVector = np.asarray(p_transform @ eta + lift * v_phasor, dtype=np.complex128) + fixed_x: ComplexVector = np.asarray(moving_x - c_ref * v_phasor, dtype=np.complex128) + x_all[idx] = fixed_x + fn_ac, fp_ac = _particle_perturbations(problem, values, moving_x, v_phasor, references) + jc = np.asarray(-Q * fn_ac + Q * fp_ac, dtype=np.complex128) + jd = np.asarray(-(1j * omega) * cap * (fixed_x[1:count] - fixed_x[: count - 1]), dtype=np.complex128) + jt = jc + jd + j_cond_all[idx] = jc + j_disp_all[idx] = jd + j_tot_all[idx] = jt + mean_jt = complex(np.mean(jt)) + # Positive applied voltage lowers phi_right by polarity*V, driving +polarity current along +x. + admittance[idx] = (polarity * mean_jt) / v_phasor + spread[idx] = float(np.max(np.abs(jt - mean_jt)) / abs(v_phasor)) + + return NonlocalSmallSignal1D( + frequencies_Hz=freqs, + voltage_phasor_V=v_phasor, + admittance_density_S_m2=admittance, + conduction_current_density_A_m2=j_cond_all, + displacement_current_density_A_m2=j_disp_all, + total_current_density_A_m2=j_tot_all, + maxwell_spread_A_m2_V=frozen_array(spread), + fixed_coordinate_perturbation=x_all, + compiled_identity=problem.device.identity, + ) diff --git a/src/solarlab/equations/nonlocal_1d.py b/src/solarlab/equations/nonlocal_1d.py new file mode 100644 index 00000000..cfed3487 --- /dev/null +++ b/src/solarlab/equations/nonlocal_1d.py @@ -0,0 +1,629 @@ +"""Ion-free 1D DC equations extended with nonlocal radiative reabsorption and WKB tunnelling. + +Wraps :class:`~solarlab.equations.dc_1d.CompiledDevice1D` and +:class:`~solarlab.equations.dc_1d.DC1DProblem` without mutating baseline local +operators: + +* When neither ``radiative_reabsorption`` nor ``tunnelling_channels`` is active, + ``residual``, ``jacobian``, ``storage_jacobian``, ``fluxes``, + ``current_density``, and ``contact_current_density`` delegate directly to + :class:`~solarlab.equations.dc_1d.DC1DProblem` and reproduce every array bit + for bit. +* When nonlocal radiative reabsorption is active, each absorber's rank-1 + outer-product coupling ``w_recv * u_recv (x) v_emit`` is assembled into sparse + CSC format on unconstrained carrier balance rows (with constrained contact + reaction fluxes preserved in ``contact_current_density``). +* When WKB intraband electron tunnelling is active, conservative face fluxes + ``F_tun`` and their exact analytical tangents wrt ``(phi, z_n)`` are assembled + under an explicit sparsity-support contract + (``PREALLOCATED_RESERVOIR_SUPERSET_V1`` or ``STRICT_WINDOW_REBIND_V1``). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import hashlib +import json +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import coo_matrix, csc_matrix + +from solarlab.contracts.arrays import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.equations.dc_1d import ( + CapabilityError, + CompiledDevice1D, + DC1DProblem, + State1D, +) +from solarlab.mesh.geometry import ControlVolumeGeometry1D +from solarlab.physics.band_structure.binding import ParameterBinding +from solarlab.physics.contacts import CarrierExchangeChannel +from solarlab.physics.electrostatics import PoissonOperator1D +from solarlab.physics.electrostatics.charge import ChargeLedger +from solarlab.physics.generation.photon_recycling import AbsorberEscapeBinding +from solarlab.physics.generation.radiative_reabsorption import ( + AbsorberReabsorptionSpec, + PhotonRecyclingBudget, + ReabsorptionEvaluation, + evaluate_radiative_reabsorption, +) +from solarlab.physics.recombination.bulk import RecombinationRate +from solarlab.physics.transport.electrochemical_flux import CarrierFaceFluxes +from solarlab.physics.transport.tunneling_channels import ( + PREALLOCATED_RESERVOIR_SUPERSET_V1, + STRICT_WINDOW_REBIND_V1, + WKB_SPARSITY_POLICIES, + CompiledTunnellingChannels, + TunnellingChannelCapabilityError, + TunnellingChannelEvaluation, + WKBWindowSupport, + evaluate_tunnelling_channels, + physical_quasi_fermi_levels_eV, +) + +__all__ = [ + "CompiledNonlocalDevice1D", + "NonlocalCouplingEvaluation1D", + "NonlocalDC1DProblem", + "SparsitySupportChangedError", + "evaluate_device_tunnelling_1d", + "evaluate_nonlocal_couplings_1d", +] + +Vector: TypeAlias = NDArray[np.float64] +Q: float = ELEMENTARY_CHARGE_C + + +class SparsitySupportChangedError(CapabilityError): + """Active WKB turning-point support shifted under ``STRICT_WINDOW_REBIND_V1``.""" + + def __init__(self, message: str, *, state: ArrayLike | None = None) -> None: + super().__init__(message) + self.state: Vector | None = None if state is None else frozen_array(state) + + +@dataclass(frozen=True) +class CompiledNonlocalDevice1D: + """Cold-compiled 1D device with optional nonlocal photon recycling and WKB tunnelling.""" + + base: CompiledDevice1D + escape_bindings: tuple[AbsorberEscapeBinding, ...] = () + radiative_reabsorption: tuple[AbsorberReabsorptionSpec, ...] = () + tunnelling_channels: CompiledTunnellingChannels | None = None + wkb_sparsity_policy: str = PREALLOCATED_RESERVOIR_SUPERSET_V1 + capabilities: tuple[str, ...] = () + sha256: str = field(init=False) + + def __post_init__(self) -> None: + if not isinstance(self.base, CompiledDevice1D): + raise TypeError("base must be a CompiledDevice1D") + if self.wkb_sparsity_policy not in WKB_SPARSITY_POLICIES: + raise CapabilityError( + f"unknown wkb_sparsity_policy {self.wkb_sparsity_policy!r}; expected {WKB_SPARSITY_POLICIES}" + ) + escapes = tuple(self.escape_bindings) + reabs = tuple(self.radiative_reabsorption) + for spec in reabs: + if spec.node_count != self.base.node_count: + raise ValueError( + f"reabsorption spec {spec.layer_id!r} node_count {spec.node_count} != {self.base.node_count}" + ) + tun = self.tunnelling_channels + if tun is not None and tun.node_count != self.base.node_count: + raise ValueError( + f"tunnelling_channels node_count {tun.node_count} != {self.base.node_count}" + ) + + caps = list(self.capabilities) if self.capabilities else list(self.base.capabilities) + if escapes and "photon_recycling_escape" not in caps: + caps.append("photon_recycling_escape") + if reabs and "nonlocal_radiative_reabsorption" not in caps: + caps.append("nonlocal_radiative_reabsorption") + if tun is not None and tun.any_enabled and "wkb_intraband_electron_steady" not in caps: + caps.append("wkb_intraband_electron_steady") + + object.__setattr__(self, "escape_bindings", escapes) + object.__setattr__(self, "radiative_reabsorption", reabs) + object.__setattr__(self, "capabilities", tuple(caps)) + + if not escapes and not reabs and (tun is None or not tun.any_enabled): + object.__setattr__(self, "sha256", self.base.sha256) + else: + payload = { + "schema": "solarlab.compiled_nonlocal_device_1d.v1", + "base_sha256": self.base.sha256, + "escape_sha256": [item.sha256 for item in escapes], + "reabsorption_sha256": [item.sha256 for item in reabs], + "tunnelling_sha256": None if tun is None else tun.digest(), + "wkb_sparsity_policy": self.wkb_sparsity_policy, + } + digest = hashlib.sha256( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("ascii") + ).hexdigest() + object.__setattr__(self, "sha256", digest) + + @property + def has_nonlocal_couplings(self) -> bool: + return bool(self.radiative_reabsorption) or ( + self.tunnelling_channels is not None and self.tunnelling_channels.any_enabled + ) + + @property + def has_wkb_tunnelling(self) -> bool: + return self.tunnelling_channels is not None and self.tunnelling_channels.any_enabled + + @property + def device_id(self) -> str: + return self.base.device_id + + @property + def identity(self) -> str: + return self.sha256 + + @property + def node_count(self) -> int: + return self.base.node_count + + @property + def nodes_m(self) -> Vector: + return self.base.nodes_m + + @property + def geometry(self) -> ControlVolumeGeometry1D: + return self.base.geometry + + @property + def parameters(self) -> ParameterBinding: + return self.base.parameters + + @property + def poisson(self) -> PoissonOperator1D: + return self.base.poisson + + @property + def thermal_voltage_V(self) -> float: + return self.base.thermal_voltage_V + + @property + def voltage_polarity(self) -> float: + return self.base.voltage_polarity + + @property + def generation_limit_A_m2(self) -> float: + return self.base.generation_limit_A_m2 + + def contact_potentials(self, voltage_V: float) -> tuple[float, float]: + return self.base.contact_potentials(voltage_V) + + def channel(self, carrier: str, side: str) -> CarrierExchangeChannel: + return self.base.channel(carrier, side) + + def carrier_reference_energies(self, voltage_V: float) -> tuple[float, float]: + return self.base.carrier_reference_energies(voltage_V) + + def carrier_reference_potentials(self, voltage_V: float) -> tuple[Vector, Vector]: + return self.base.carrier_reference_potentials(voltage_V) + + def rebase_coordinates(self, u: ArrayLike, old_voltage_V: float, new_voltage_V: float) -> Vector: + return self.base.rebase_coordinates(u, old_voltage_V, new_voltage_V) + + def fields(self, u: ArrayLike, *, voltage_V: float = 0.0) -> tuple[Vector, Vector, Vector]: + return self.base.fields(u, voltage_V=voltage_V) + + def state(self, u: ArrayLike, *, voltage_V: float = 0.0) -> State1D: + phi, n, p = self.base.fields(u, voltage_V=voltage_V) + return State1D(np.asarray(u, dtype=float), phi, n, p, self.sha256, voltage_V) + + def charge_ledger(self, n: Vector, p: Vector) -> ChargeLedger: + return self.base.charge_ledger(n, p) + + def require_driver_capability(self, driver: str) -> None: + """Enforce quasi-static driver eligibility pre-solve.""" + if self.has_wkb_tunnelling and driver != "quasi_fermi_steady_state": + raise CapabilityError( + f"wkb_driver_unsupported: WKB tunnelling channels are certified only for " + f"'quasi_fermi_steady_state', not {driver!r}" + ) + + +@dataclass(frozen=True) +class NonlocalCouplingEvaluation1D: + """Evaluated residual, sparse Jacobian, and terminal flux additions of nonlocal terms.""" + + residual_addition: Vector + left_contact_exchange_addition: tuple[float, float] + right_contact_exchange_addition: tuple[float, float] + electron_face_flux_addition_m2_s: Vector + electron_face_current_addition_A_m2: Vector + jacobian_addition: csc_matrix | None + reabsorption: ReabsorptionEvaluation | None + tunnelling: TunnellingChannelEvaluation | None + wkb_support: WKBWindowSupport | None + + +def evaluate_device_tunnelling_1d( + device: CompiledNonlocalDevice1D, + phi: ArrayLike, + n: ArrayLike, + p: ArrayLike, + *, + derivatives: bool = False, +) -> TunnellingChannelEvaluation: + """Evaluate the compiled WKB tunnelling channels on ``device`` at ``(phi, n, p)``.""" + if device.tunnelling_channels is None or not device.tunnelling_channels.any_enabled: + raise CapabilityError("no enabled WKB tunnelling channels are bound on this device") + bands = device.parameters.band_structure + try: + efn, efp = physical_quasi_fermi_levels_eV( + potential_V=phi, + affinity_eV=bands.physical_electron_affinity_eV, + band_gap_eV=bands.physical_band_gap_eV, + electron_density_m3=n, + hole_density_m3=p, + conduction_dos_m3=device.parameters.conduction_dos_m3, + valence_dos_m3=device.parameters.valence_dos_m3, + thermal_voltage_V=device.thermal_voltage_V, + ) + return evaluate_tunnelling_channels( + device.tunnelling_channels, + positions_m=device.nodes_m, + potential_V=phi, + affinity_eV=bands.physical_electron_affinity_eV, + band_gap_eV=bands.physical_band_gap_eV, + electron_quasi_fermi_eV=efn, + hole_quasi_fermi_eV=efp, + thermal_voltage_V=device.thermal_voltage_V, + derivatives=derivatives, + ) + except TunnellingChannelCapabilityError as exc: + raise CapabilityError(str(exc)) from exc + + +def _fixed_reservoir_mask(device: CompiledDevice1D, carrier: str) -> tuple[bool, bool]: + return ( + device.channel(carrier, "left").kind == "fixed_reservoir", + device.channel(carrier, "right").kind == "fixed_reservoir", + ) + + +def evaluate_nonlocal_couplings_1d( + device: CompiledNonlocalDevice1D, + u: ArrayLike, + *, + voltage_V: float, + derivatives: bool, + bound_wkb_signature: str | None = None, +) -> NonlocalCouplingEvaluation1D: + """Evaluate nonlocal radiative reabsorption and WKB path-flux contributions.""" + count = device.node_count + values = np.asarray(u, dtype=float) + phi, n, p = device.fields(values, voltage_V=voltage_V) + widths = device.geometry.cell_measures_m + vt = device.thermal_voltage_V + + res_add: Vector = np.zeros(3 * count, dtype=float) + f_tun_n: Vector = np.zeros(count - 1, dtype=float) + j_tun_n: Vector = np.zeros(count - 1, dtype=float) + left_ex_n = 0.0 + left_ex_p = 0.0 + right_ex_n = 0.0 + right_ex_p = 0.0 + + fixed_n_left, fixed_n_right = _fixed_reservoir_mask(device.base, "n") + fixed_p_left, fixed_p_right = _fixed_reservoir_mask(device.base, "p") + + rows_list: list[NDArray[np.intp]] = [] + cols_list: list[NDArray[np.intp]] = [] + data_list: list[Vector] = [] + + reabs_eval: ReabsorptionEvaluation | None = None + if device.radiative_reabsorption: + reabs_eval = evaluate_radiative_reabsorption( + device.radiative_reabsorption, n, p, derivatives=derivatives + ) + pair_add = widths * reabs_eval.generation_m3_s + n_rows = pair_add.copy() + p_rows = pair_add.copy() + if fixed_n_left: + n_rows[0] = 0.0 + left_ex_n -= float(pair_add[0]) + if fixed_n_right: + n_rows[-1] = 0.0 + right_ex_n += float(pair_add[-1]) + if fixed_p_left: + p_rows[0] = 0.0 + left_ex_p -= float(pair_add[0]) + if fixed_p_right: + p_rows[-1] = 0.0 + right_ex_p += float(pair_add[-1]) + res_add[count : 2 * count] += n_rows + res_add[2 * count : 3 * count] += p_rows + + if derivatives: + for factor in reabs_eval.factors: + if not factor.active: + continue + emit = factor.emitter_nodes + # In quasi-Fermi coordinates: dn/dz_n = +n, dp/dz_p = -p, + # and d(n*p)/dphi = (p*n - n*p)/V_T == 0 (kept explicit via general formula). + vn_z = factor.d_emission_flux_dn_m_s * n[emit] + vp_z = -factor.d_emission_flux_dp_m_s * p[emit] + v_phi = ( + factor.d_emission_flux_dn_m_s * n[emit] + - factor.d_emission_flux_dp_m_s * p[emit] + ) / vt + + for carrier_offset, fixed_l, fixed_r in ( + (count, fixed_n_left, fixed_n_right), + (2 * count, fixed_p_left, fixed_p_right), + ): + keep = np.ones(factor.receiver_nodes.size, dtype=bool) + if fixed_l: + keep &= factor.receiver_nodes != 0 + if fixed_r: + keep &= factor.receiver_nodes != (count - 1) + if not np.any(keep): + continue + recv_kept = factor.receiver_nodes[keep] + u_weighted = widths[recv_kept] * factor.receiver_vector_m1[keep] + + r_grid: NDArray[np.intp] = np.repeat(carrier_offset + recv_kept, emit.size) + c_zn = np.tile(count + emit, recv_kept.size) + c_zp = np.tile(2 * count + emit, recv_kept.size) + rows_list.append(r_grid) + cols_list.append(c_zn) + data_list.append(np.outer(u_weighted, vn_z).ravel()) + rows_list.append(r_grid) + cols_list.append(c_zp) + data_list.append(np.outer(u_weighted, vp_z).ravel()) + if np.any(v_phi != 0.0): + c_phi = np.tile(emit, recv_kept.size) + rows_list.append(r_grid) + cols_list.append(c_phi) + data_list.append(np.outer(u_weighted, v_phi).ravel()) + + tun_eval: TunnellingChannelEvaluation | None = None + wkb_support: WKBWindowSupport | None = None + if device.has_wkb_tunnelling: + tun_eval = evaluate_device_tunnelling_1d(device, phi, n, p, derivatives=derivatives) + assert tun_eval.intraband_path is not None + wkb_support = tun_eval.intraband_path.support + if ( + device.wkb_sparsity_policy == STRICT_WINDOW_REBIND_V1 + and bound_wkb_signature is not None + and wkb_support is not None + and wkb_support.support_signature != bound_wkb_signature + ): + raise SparsitySupportChangedError( + "wkb_support_shifted: turning-point window changed from bound signature " + f"{bound_wkb_signature[:12]} to {wkb_support.support_signature[:12]}; " + "call rebind_for_state(u) or use PREALLOCATED_RESERVOIR_SUPERSET_V1", + state=values, + ) + + f_tun_n = np.asarray(tun_eval.electron_face_flux_m2_s, dtype=float) + j_tun_n = np.asarray(tun_eval.electron_face_current_A_m2, dtype=float) + transfer_n = np.array(tun_eval.electron_nodal_transfer_m2_s, copy=True) + if fixed_n_left: + transfer_n[0] = 0.0 + left_ex_n += float(f_tun_n[0]) + if fixed_n_right: + transfer_n[-1] = 0.0 + right_ex_n += float(f_tun_n[-1]) + res_add[count : 2 * count] += transfer_n + + if derivatives: + assert tun_eval.linearization is not None + assert wkb_support is not None + if device.wkb_sparsity_policy == PREALLOCATED_RESERVOIR_SUPERSET_V1: + f_lo, f_hi = wkb_support.reservoir_face_slice + n_lo, n_hi = wkb_support.reservoir_node_slice + else: + f_lo, f_hi = wkb_support.active_face_bounds + n_lo, n_hi = wkb_support.active_node_bounds + + # Verify zero nonzeros lie outside the declared support slice! + d_bar = tun_eval.linearization.d_face_flux_d_barrier_eV + d_qf = tun_eval.linearization.d_face_flux_d_quasi_fermi_eV + if f_hi > f_lo and n_hi > n_lo: + outside_mask = np.ones(d_bar.shape, dtype=bool) + outside_mask[f_lo:f_hi, n_lo:n_hi] = False + if np.any(d_bar[outside_mask] != 0.0) or np.any(d_qf[outside_mask] != 0.0): + raise SparsitySupportChangedError( + "WKB analytical Jacobian produced nonzero entries outside declared support" + ) + elif np.any(d_bar != 0.0) or np.any(d_qf != 0.0): + raise SparsitySupportChangedError( + "WKB analytical Jacobian produced nonzero entries on an empty support window" + ) + + if f_hi > f_lo and n_hi > n_lo: + # In quasi-Fermi coordinates (phi, z_n): + # U = -phi - chi => dU/dphi = -1, dU/dz_n = 0 + # E_Fn = -phi - chi + V_T*(shift_n + z_n + ln(n_ref/N_c)) => dE_Fn/dphi = 0, dE_Fn/dz_n = V_T. + df_dphi = -d_bar[f_lo:f_hi, n_lo:n_hi] + df_dzn = vt * d_qf[f_lo:f_hi, n_lo:n_hi] + + # Nodal divergence: transfer[node] = sum_{f} (-delta_{node, f} + delta_{node, f+1}) * F[f] + node_span = f_hi - f_lo + 1 + div_dphi: NDArray[np.float64] = np.zeros((node_span, n_hi - n_lo), dtype=float) + div_dzn: NDArray[np.float64] = np.zeros((node_span, n_hi - n_lo), dtype=float) + div_dphi[:-1, :] -= df_dphi + div_dphi[1:, :] += df_dphi + div_dzn[:-1, :] -= df_dzn + div_dzn[1:, :] += df_dzn + + row_nodes: NDArray[np.intp] = np.arange(f_lo, f_hi + 1, dtype=np.intp) + col_nodes: NDArray[np.intp] = np.arange(n_lo, n_hi, dtype=np.intp) + keep_rows: NDArray[np.bool_] = np.ones(row_nodes.size, dtype=bool) + if fixed_n_left: + keep_rows &= row_nodes != 0 + if fixed_n_right: + keep_rows &= row_nodes != (count - 1) + if np.any(keep_rows): + kept_r = count + row_nodes[keep_rows] + r_mat: NDArray[np.intp] = np.repeat(kept_r, col_nodes.size) + c_phi_mat = np.tile(col_nodes, kept_r.size) + c_zn_mat = np.tile(count + col_nodes, kept_r.size) + rows_list.append(r_mat) + cols_list.append(c_phi_mat) + data_list.append(div_dphi[keep_rows, :].ravel()) + rows_list.append(r_mat) + cols_list.append(c_zn_mat) + data_list.append(div_dzn[keep_rows, :].ravel()) + + jac_csc: csc_matrix | None = None + if derivatives: + if rows_list: + all_r = np.concatenate(rows_list) + all_c = np.concatenate(cols_list) + all_d = np.concatenate(data_list) + nz = all_d != 0.0 + jac_csc = coo_matrix( + (all_d[nz], (all_r[nz], all_c[nz])), + shape=(3 * count, 3 * count), + dtype=float, + ).tocsc() + else: + jac_csc = csc_matrix((3 * count, 3 * count), dtype=float) + + return NonlocalCouplingEvaluation1D( + residual_addition=res_add, + left_contact_exchange_addition=(left_ex_n, left_ex_p), + right_contact_exchange_addition=(right_ex_n, right_ex_p), + electron_face_flux_addition_m2_s=f_tun_n, + electron_face_current_addition_A_m2=j_tun_n, + jacobian_addition=jac_csc, + reabsorption=reabs_eval, + tunnelling=tun_eval, + wkb_support=wkb_support, + ) + + +@dataclass(frozen=True) +class NonlocalDC1DProblem: + """Direct 1D steady-state problem with nonlocal photon recycling and WKB tunnelling.""" + + device: CompiledNonlocalDevice1D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + bound_wkb_signature: str | None = None + + def __post_init__(self) -> None: + self.device.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and non-negative") + + @property + def base_problem(self) -> DC1DProblem: + return DC1DProblem(self.device.base, self.voltage_V, self.generation_scale) + + def _require_steady_for_wkb(self, udot: ArrayLike | None, *, alpha: float = 0.0) -> None: + if not self.device.has_wkb_tunnelling: + return + if alpha != 0.0: + raise CapabilityError( + "wkb_transient_unsupported: WKB tunnelling channels are quasi-static steady-state only" + ) + if udot is not None and np.any(np.asarray(udot, dtype=float) != 0.0): + raise CapabilityError( + "wkb_transient_unsupported: WKB tunnelling channels do not admit nonzero udot" + ) + + def fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: + return self.base_problem.fluxes(u) + + def recombination_rate(self, n: Vector, p: Vector, *, derivatives: bool = True) -> RecombinationRate: + return self.base_problem.recombination_rate(n, p, derivatives=derivatives) + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + if self.device.has_wkb_tunnelling: + raise CapabilityError( + "wkb_transient_unsupported: storage_jacobian is unavailable with WKB tunnelling" + ) + return self.base_problem.storage_jacobian(u) + + def residual(self, u: ArrayLike, udot: ArrayLike | None = None) -> Vector: + self._require_steady_for_wkb(udot) + base_f = self.base_problem.residual(u, udot) + if not self.device.has_nonlocal_couplings or not np.all(np.isfinite(base_f)): + return base_f + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=self.bound_wkb_signature, + ) + return base_f + ext.residual_addition + + def jacobian(self, u: ArrayLike, udot: ArrayLike | None = None, *, alpha: float = 0.0) -> csc_matrix: + self._require_steady_for_wkb(udot, alpha=alpha) + base_j = self.base_problem.jacobian(u, udot, alpha=alpha) + if not self.device.has_nonlocal_couplings: + return base_j + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=True, + bound_wkb_signature=self.bound_wkb_signature, + ) + assert ext.jacobian_addition is not None + return csc_matrix(base_j + ext.jacobian_addition) + + def current_density(self, u: ArrayLike) -> Vector: + base_j = self.base_problem.current_density(u) + if not self.device.has_wkb_tunnelling: + return base_j + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=self.bound_wkb_signature, + ) + return base_j + ext.electron_face_current_addition_A_m2 + + def contact_current_density(self, u: ArrayLike) -> Vector: + base_c = self.base_problem.contact_current_density(u) + if not self.device.has_nonlocal_couplings: + return base_c + ext = evaluate_nonlocal_couplings_1d( + self.device, + u, + voltage_V=self.voltage_V, + derivatives=False, + bound_wkb_signature=self.bound_wkb_signature, + ) + dl_n, dl_p = ext.left_contact_exchange_addition + dr_n, dr_p = ext.right_contact_exchange_addition + delta = np.array([-Q * dl_n + Q * dl_p, -Q * dr_n + Q * dr_p], dtype=float) + return base_c + delta + + def photon_recycling_budgets(self, u: ArrayLike) -> tuple[PhotonRecyclingBudget, ...]: + if not self.device.radiative_reabsorption: + return () + ext = evaluate_nonlocal_couplings_1d( + self.device, u, voltage_V=self.voltage_V, derivatives=False + ) + assert ext.reabsorption is not None + return ext.reabsorption.budgets + + def tunnelling_evaluation(self, u: ArrayLike) -> TunnellingChannelEvaluation: + phi, n, p = self.device.fields(u, voltage_V=self.voltage_V) + return evaluate_device_tunnelling_1d(self.device, phi, n, p, derivatives=False) + + def rebind_for_state(self, u: ArrayLike) -> NonlocalDC1DProblem: + """Bind active WKB turning-point support signature at ``u``.""" + if not self.device.has_wkb_tunnelling: + return self + ext = evaluate_nonlocal_couplings_1d( + self.device, u, voltage_V=self.voltage_V, derivatives=False, bound_wkb_signature=None + ) + sig = None if ext.wkb_support is None else ext.wkb_support.support_signature + return NonlocalDC1DProblem(self.device, self.voltage_V, self.generation_scale, sig) diff --git a/src/solarlab/physics/generation/photon_recycling.py b/src/solarlab/physics/generation/photon_recycling.py new file mode 100644 index 00000000..ab247f46 --- /dev/null +++ b/src/solarlab/physics/generation/photon_recycling.py @@ -0,0 +1,399 @@ +"""Escape-probability kernels and optical bindings for radiative photon recycling. + +Models internal photon trapping inside high-index radiative absorbers via two +explicitly labeled escape-probability formulations: + +* ``YABLONOVITCH_INTRINSIC_ALPHA_D_V1``: single-pass optical depth at the band + edge ``OD_gap = alpha(lambda_gap) * d_absorber`` from intrinsic optical + constants ``(n_gap, k_gap)``, yielding ``P_esc = clip(1 / (4 n_gap^2 OD_gap), 0, 1)``. +* ``TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1``: historical stack absorbance + integral ``OD_gap = trapezoid(A(x, lambda_gap), x_absorber)``. +* ``TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1``: discrete control-volume + absorbance integral ``OD_gap = sum(w_absorber * A(x_absorber, lambda_gap))``. + +No mode silently swaps trapezoid and control-volume weights or modifies +non-absorber layers. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.arrays import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.physics.generation.optical_binding import OpticalStackBinding + +__all__ = [ + "C_LIGHT_M_S", + "ESCAPE_PROBABILITY_MODES", + "HC_J_M", + "H_PLANCK_J_S", + "TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1", + "TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1", + "YABLONOVITCH_INTRINSIC_ALPHA_D_V1", + "AbsorberEscapeBinding", + "AbsorberEscapeInput", + "PhotonRecyclingCapabilityError", + "PhotonRecyclingError", + "bind_absorber_escape_from_optical_stack", + "compute_p_esc", + "compute_p_esc_for_absorber", + "effective_radiative_coefficient", + "wavelength_at_gap", +] + +Vector: TypeAlias = NDArray[np.float64] + +H_PLANCK_J_S: float = 6.62607015e-34 +C_LIGHT_M_S: float = 2.99792458e8 +HC_J_M: float = H_PLANCK_J_S * C_LIGHT_M_S +Q: float = ELEMENTARY_CHARGE_C + +YABLONOVITCH_INTRINSIC_ALPHA_D_V1 = "yablonovitch_intrinsic_alpha_d_v1" +TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1 = "tmm_integrated_absorbance_trapezoid_v1" +TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1 = "tmm_integrated_absorbance_control_volume_v1" +ESCAPE_PROBABILITY_MODES: tuple[str, ...] = ( + YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, +) + + +class PhotonRecyclingError(ValueError): + """Invalid input to an escape-probability or photon-recycling kernel.""" + + +class PhotonRecyclingCapabilityError(ValueError): + """Requested photon-recycling mode or AC linearization exceeds capability.""" + + +def wavelength_at_gap(Eg_eV: float) -> float: + """Band-edge photon wavelength ``hc / (q Eg)`` in metres.""" + gap = float(Eg_eV) + if not math.isfinite(gap) or gap <= 0.0: + raise PhotonRecyclingError(f"Eg_eV must be finite and positive, got {Eg_eV!r}") + return HC_J_M / (gap * Q) + + +def compute_p_esc(alpha_gap: float, thickness: float, n_at_gap: float) -> float: + """Yablonovitch single-pass escape probability ``clip(1 / (4 n^2 alpha d), 0, 1)``. + + Transparent, zero-thickness, non-positive-index, or non-finite inputs return + ``1.0`` (every internally emitted photon escapes without reabsorption). + """ + alpha = float(alpha_gap) + width = float(thickness) + index = float(n_at_gap) + if ( + not (math.isfinite(alpha) and math.isfinite(width) and math.isfinite(index)) + or alpha <= 0.0 + or width <= 0.0 + or index <= 0.0 + ): + return 1.0 + optical_depth = alpha * width + if optical_depth <= 0.0: + return 1.0 + p_esc = 1.0 / (4.0 * index * index * optical_depth) + return float(np.clip(p_esc, 0.0, 1.0)) + + +def compute_p_esc_for_absorber( + A_xl: ArrayLike, + wavelengths_m: ArrayLike, + x_absorber: ArrayLike, + Eg_eV: float, + n_at_gap: float, + *, + weights_m: ArrayLike | None = None, + mode: str = TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, +) -> float: + """Escape probability from a TMM local absorbance profile ``A(x, lambda)`` [m^-1]. + + ``mode`` selects the declared spatial quadrature explicitly: + ``TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1`` integrates ``A(x, lambda_gap)`` + with ``np.trapezoid`` over ``x_absorber``, whereas + ``TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1`` integrates with supplied + discrete control-volume measures ``weights_m``. + """ + if mode not in ( + TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + ): + raise PhotonRecyclingCapabilityError( + f"unsupported absorbance escape mode {mode!r}; expected trapezoid or control-volume" + ) + absorbance = np.asarray(A_xl, dtype=float) + wl = np.asarray(wavelengths_m, dtype=float) + x_abs = np.asarray(x_absorber, dtype=float) + index = float(n_at_gap) + if absorbance.ndim != 2 or wl.ndim != 1 or x_abs.ndim != 1: + raise PhotonRecyclingError("A_xl must be 2D (N_x, N_wl) with 1D wavelengths_m and x_absorber") + if absorbance.shape != (x_abs.size, wl.size): + raise PhotonRecyclingError( + f"A_xl shape {absorbance.shape} does not match ({x_abs.size}, {wl.size})" + ) + if wl.size == 0 or x_abs.size < 2 or not math.isfinite(index) or index <= 0.0: + return 1.0 + if not (np.all(np.isfinite(absorbance)) and np.all(np.isfinite(wl)) and np.all(np.isfinite(x_abs))): + raise PhotonRecyclingError("A_xl, wavelengths_m, and x_absorber must be finite") + if np.any(np.diff(wl) <= 0.0): + raise PhotonRecyclingError("wavelengths_m must be strictly increasing") + if np.any(np.diff(x_abs) <= 0.0): + raise PhotonRecyclingError("x_absorber must be strictly increasing") + + lam_gap = float(np.clip(wavelength_at_gap(Eg_eV), float(wl[0]), float(wl[-1]))) + right = int(np.searchsorted(wl, lam_gap)) + if right == 0: + a_gap = absorbance[:, 0] + elif right >= wl.size: + a_gap = absorbance[:, -1] + else: + left = right - 1 + weight = (lam_gap - float(wl[left])) / (float(wl[right]) - float(wl[left])) + a_gap = (1.0 - weight) * absorbance[:, left] + weight * absorbance[:, right] + + if mode == TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1: + if weights_m is not None: + raise PhotonRecyclingError("weights_m cannot be passed in trapezoid absorbance mode") + od_gap = float(np.trapezoid(a_gap, x_abs)) + else: + if weights_m is None: + raise PhotonRecyclingError("control-volume absorbance mode requires explicit weights_m") + w = np.asarray(weights_m, dtype=float) + if w.shape != x_abs.shape or not np.all(np.isfinite(w)) or np.any(w <= 0.0): + raise PhotonRecyclingError("weights_m must be finite positive and match x_absorber") + od_gap = float(np.dot(w, a_gap)) + + if od_gap <= 0.0: + return 1.0 + p_esc = 1.0 / (4.0 * index * index * od_gap) + return float(np.clip(p_esc, 0.0, 1.0)) + + +def effective_radiative_coefficient( + B_rad_m3_s: ArrayLike, + absorber_masks: Sequence[ArrayLike], + absorber_p_esc: Sequence[float], +) -> Vector: + """Local escape-scaled radiative coefficient ``B_rad_eff = B_rad * P_esc``. + + When ``absorber_masks`` is empty or every ``P_esc == 1.0``, returns a copy + bit-identical to ``B_rad_m3_s``. + """ + base = np.array(B_rad_m3_s, dtype=float, copy=True) + if base.ndim != 1 or not np.all(np.isfinite(base)) or np.any(base < 0.0): + raise PhotonRecyclingError("B_rad_m3_s must be a finite non-negative 1D array") + if len(absorber_masks) != len(absorber_p_esc): + raise PhotonRecyclingError("absorber_masks and absorber_p_esc must have equal length") + for raw_mask, raw_p_esc in zip(absorber_masks, absorber_p_esc): + mask = np.asarray(raw_mask, dtype=bool) + if mask.shape != base.shape: + raise PhotonRecyclingError("absorber mask shape must match B_rad_m3_s") + p_esc = float(raw_p_esc) + if not math.isfinite(p_esc) or p_esc < 0.0 or p_esc > 1.0: + raise PhotonRecyclingError(f"P_esc must lie in [0, 1], got {raw_p_esc!r}") + if p_esc != 1.0: + base[mask] = base[mask] * p_esc + return base + + +@dataclass(frozen=True) +class AbsorberEscapeInput: + """Electrical absorber metadata used to derive band-edge optical escape.""" + + layer_id: str + thickness_m: float + band_gap_front_eV: float + band_gap_back_eV: float | None = None + + def __post_init__(self) -> None: + if not isinstance(self.layer_id, str) or not self.layer_id.strip(): + raise PhotonRecyclingError("absorber escape input requires a non-empty layer_id") + thickness = float(self.thickness_m) + gap_front = float(self.band_gap_front_eV) + if not math.isfinite(thickness) or thickness <= 0.0: + raise PhotonRecyclingError(f"{self.layer_id}: thickness_m must be finite positive") + if not math.isfinite(gap_front) or gap_front <= 0.0: + raise PhotonRecyclingError(f"{self.layer_id}: band_gap_front_eV must be finite positive") + object.__setattr__(self, "thickness_m", thickness) + object.__setattr__(self, "band_gap_front_eV", gap_front) + if self.band_gap_back_eV is not None: + gap_back = float(self.band_gap_back_eV) + if not math.isfinite(gap_back) or gap_back <= 0.0: + raise PhotonRecyclingError(f"{self.layer_id}: band_gap_back_eV must be finite positive") + object.__setattr__(self, "band_gap_back_eV", gap_back) + + @property + def effective_emission_gap_eV(self) -> float: + """Emission concentrates near the minimum band gap of a graded absorber.""" + if self.band_gap_back_eV is None: + return self.band_gap_front_eV + return min(self.band_gap_front_eV, self.band_gap_back_eV) + + +@dataclass(frozen=True) +class AbsorberEscapeBinding: + """Resolved optical escape-probability binding for one absorber layer.""" + + layer_id: str + mode: str + band_gap_eV: float + wavelength_gap_m: float + refractive_index_at_gap: float + extinction_at_gap: float + alpha_gap_m1: float + thickness_m: float + optical_depth: float + escape_probability: float + sha256: str = field(init=False) + + def __post_init__(self) -> None: + if self.mode not in ESCAPE_PROBABILITY_MODES: + raise PhotonRecyclingCapabilityError(f"unknown escape mode {self.mode!r}") + p_esc = float(self.escape_probability) + if not math.isfinite(p_esc) or p_esc < 0.0 or p_esc > 1.0: + raise PhotonRecyclingError("escape_probability must lie in [0, 1]") + payload = { + "schema": "solarlab.photon_recycling.escape_binding.v1", + "layer_id": self.layer_id, + "mode": self.mode, + "band_gap_eV": repr(float(self.band_gap_eV)), + "wavelength_gap_m": repr(float(self.wavelength_gap_m)), + "refractive_index_at_gap": repr(float(self.refractive_index_at_gap)), + "extinction_at_gap": repr(float(self.extinction_at_gap)), + "alpha_gap_m1": repr(float(self.alpha_gap_m1)), + "thickness_m": repr(float(self.thickness_m)), + "optical_depth": repr(float(self.optical_depth)), + "escape_probability": repr(p_esc), + } + digest = hashlib.sha256( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("ascii") + ).hexdigest() + object.__setattr__(self, "sha256", digest) + + +def bind_absorber_escape_from_optical_stack( + optical_stack: OpticalStackBinding, + absorbers: Sequence[AbsorberEscapeInput], + *, + mode: str = YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + electrical_nodes_m: ArrayLike | None = None, + absorber_node_masks: Sequence[ArrayLike] | None = None, + absorber_weights_m: Sequence[ArrayLike] | None = None, +) -> tuple[AbsorberEscapeBinding, ...]: + """Derive per-absorber escape probabilities from a frozen TMM optical stack.""" + if not isinstance(optical_stack, OpticalStackBinding): + raise TypeError("optical_stack must be an OpticalStackBinding") + if mode not in ESCAPE_PROBABILITY_MODES: + raise PhotonRecyclingCapabilityError(f"unsupported escape mode {mode!r}") + if not absorbers: + return () + + wl_m = optical_stack.wavelengths_m + slice_lookup = dict(optical_stack.physical_layer_slices) + absorbance_xl: Vector | None = None + nodes: Vector | None = None + if mode != YABLONOVITCH_INTRINSIC_ALPHA_D_V1: + if electrical_nodes_m is None or absorber_node_masks is None: + raise PhotonRecyclingError( + f"{mode} requires electrical_nodes_m and absorber_node_masks" + ) + if len(absorber_node_masks) != len(absorbers): + raise PhotonRecyclingError("absorber_node_masks must match absorbers") + if mode == TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1: + if absorber_weights_m is None or len(absorber_weights_m) != len(absorbers): + raise PhotonRecyclingError( + "control-volume absorbance escape mode requires absorber_weights_m per absorber" + ) + nodes = frozen_array(electrical_nodes_m) + optical_x = nodes + optical_stack.electrical_offset_m + from solarlab.physics.generation.transfer_matrix import tmm_absorption_profile + + absorbance_xl = tmm_absorption_profile( + list(optical_stack.tmm_layers), + wl_m, + optical_x, + optical_stack.boundaries_m, + optical_stack.ambient_index, + optical_stack.exit_index, + ) + + bindings: list[AbsorberEscapeBinding] = [] + for idx, absorber in enumerate(absorbers): + if absorber.layer_id not in slice_lookup: + raise PhotonRecyclingCapabilityError( + f"absorber {absorber.layer_id!r} is missing from OpticalStackBinding" + ) + layer_slice = slice_lookup[absorber.layer_id] + sublayers = optical_stack.layers[layer_slice] + if any(not sub.electrical for sub in sublayers): + raise PhotonRecyclingCapabilityError( + f"absorber {absorber.layer_id!r} must be an electrical layer" + ) + weights = np.array([sub.thickness_m for sub in sublayers], dtype=float) + total_w = float(np.sum(weights)) + n_curve = np.sum([w * sub.n for w, sub in zip(weights, sublayers)], axis=0) / total_w + k_curve = np.sum([w * sub.k for w, sub in zip(weights, sublayers)], axis=0) / total_w + + eg_eff = absorber.effective_emission_gap_eV + lam_gap_raw = wavelength_at_gap(eg_eff) + lam_gap = float(np.clip(lam_gap_raw, float(wl_m[0]), float(wl_m[-1]))) + n_gap = float(np.interp(lam_gap, wl_m, n_curve)) + k_gap = float(np.interp(lam_gap, wl_m, k_curve)) + alpha_gap = 4.0 * math.pi * k_gap / lam_gap if lam_gap > 0.0 else 0.0 + + if mode == YABLONOVITCH_INTRINSIC_ALPHA_D_V1: + od_gap = max(0.0, alpha_gap * absorber.thickness_m) + p_esc = compute_p_esc(alpha_gap, absorber.thickness_m, n_gap) + else: + assert absorbance_xl is not None and nodes is not None and absorber_node_masks is not None + mask = np.asarray(absorber_node_masks[idx], dtype=bool) + x_abs = nodes[mask] + w_abs = None if absorber_weights_m is None else absorber_weights_m[idx] + p_esc = compute_p_esc_for_absorber( + absorbance_xl[mask, :], + wl_m, + x_abs, + eg_eff, + n_gap, + weights_m=w_abs, + mode=mode, + ) + if mode == TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1: + a_interp = np.array( + [np.interp(lam_gap, wl_m, absorbance_xl[row, :]) for row in np.flatnonzero(mask)], + dtype=float, + ) + od_gap = max(0.0, float(np.trapezoid(a_interp, x_abs))) if x_abs.size >= 2 else 0.0 + else: + assert w_abs is not None + a_interp = np.array( + [np.interp(lam_gap, wl_m, absorbance_xl[row, :]) for row in np.flatnonzero(mask)], + dtype=float, + ) + od_gap = max(0.0, float(np.dot(np.asarray(w_abs, dtype=float), a_interp))) + + bindings.append( + AbsorberEscapeBinding( + layer_id=absorber.layer_id, + mode=mode, + band_gap_eV=eg_eff, + wavelength_gap_m=lam_gap, + refractive_index_at_gap=n_gap, + extinction_at_gap=k_gap, + alpha_gap_m1=alpha_gap, + thickness_m=absorber.thickness_m, + optical_depth=od_gap, + escape_probability=p_esc, + ) + ) + return tuple(bindings) diff --git a/src/solarlab/physics/generation/radiative_reabsorption.py b/src/solarlab/physics/generation/radiative_reabsorption.py new file mode 100644 index 00000000..1c930575 --- /dev/null +++ b/src/solarlab/physics/generation/radiative_reabsorption.py @@ -0,0 +1,876 @@ +"""Nonlocal radiative reabsorption kernels, photon budgets, and switching tangents. + +Separates local escape-scaled radiative recombination from nonlocal internal +emission-reabsorption on global emitter-receiver supports: + +* ``CONTROL_VOLUME_CONSERVATIVE_V1`` integrates net radiative emission with + declared emitter control-volume measures ``w_emit`` and redistributes the + trapped photon flux ``(1 - P_esc) * R_tot`` over ``receiver_nodes`` with a + normalized profile ``psi_recv`` satisfying ``sum(w_recv * psi_recv) == 1``, + closing ``emitted == reabsorbed + escaped`` to floating-point round-off on + arbitrary non-uniform meshes. +* ``HISTORICAL_TRAPEZOID_UNIFORM_V1`` preserves the legacy 1D MoL operator: + composite-trapezoid emitter quadrature over ``x_emitter`` divided uniformly + by the declared layer thickness ``thickness_m`` on ``receiver_nodes``. +* ``LAGGED_BAKED_GENERATION_V1`` evaluates ``G_rad`` at an explicitly supplied + frozen state ``(n_lagged, p_lagged)`` with zero live state derivatives, + labeling operator splitting instead of masquerading as self-consistent. + +Analytical derivatives use the exact rank-1 outer-product structure +``dG_rad[receiver] / d(n, p)[emitter] = u_receiver (x) v_emitter`` and declare +non-differentiability across the clamped ``R_tot = 0`` dark-equilibrium surface, +the thermionic ``min(|J_SG|, |J_TE|)`` crossover, and Poole-Frenkel / low-beta +Caughey-Thomas field-mobility cusps. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.arrays import frozen_array, integer_indices +from solarlab.physics.generation.photon_recycling import ( + PhotonRecyclingCapabilityError, + PhotonRecyclingError, +) +from solarlab.physics.transport.field_mobility_tangents import ( + FieldMobilityDirectionalDerivative, + field_mobility_directional_derivative, +) + +__all__ = [ + "CONTROL_VOLUME_CONSERVATIVE_V1", + "HISTORICAL_TRAPEZOID_UNIFORM_V1", + "LAGGED_BAKED_GENERATION_V1", + "REABSORPTION_MODES", + "AbsorberRank1Factor", + "AbsorberReabsorptionSpec", + "PhotonRecyclingBudget", + "ReabsorptionDirectionalDerivative", + "ReabsorptionEvaluation", + "SwitchingSurfaceAssessment", + "ThermionicCapDirectionalDerivative", + "assess_switching_surfaces", + "dense_reabsorption_jacobian", + "evaluate_radiative_reabsorption", + "radiative_reabsorption_directional_derivative", + "require_smooth_ac_surfaces", + "thermionic_cap_directional_derivative", + "thermionic_cap_value", + "trapezoid_quadrature_weights_1d", +] + +Vector: TypeAlias = NDArray[np.float64] +IndexVector: TypeAlias = NDArray[np.intp] +Vector2D: TypeAlias = NDArray[np.float64] + +CONTROL_VOLUME_CONSERVATIVE_V1 = "control_volume_conservative_v1" +HISTORICAL_TRAPEZOID_UNIFORM_V1 = "historical_trapezoid_uniform_v1" +LAGGED_BAKED_GENERATION_V1 = "lagged_baked_generation_v1" +REABSORPTION_MODES: tuple[str, ...] = ( + CONTROL_VOLUME_CONSERVATIVE_V1, + HISTORICAL_TRAPEZOID_UNIFORM_V1, + LAGGED_BAKED_GENERATION_V1, +) + +_DEFAULT_EMISSION_SWITCH_TOL_M2_S = 1.0e-30 + + +def trapezoid_quadrature_weights_1d(x_m: ArrayLike) -> Vector: + """Composite-trapezoid nodal weights ``w`` [m] satisfying ``w . y = trapz(y, x)``.""" + coords = np.asarray(x_m, dtype=float) + if coords.ndim != 1 or coords.size < 2 or not np.all(np.isfinite(coords)): + raise PhotonRecyclingError("trapezoid quadrature requires >= 2 finite 1D coordinates") + dx = np.diff(coords) + if np.any(dx <= 0.0): + raise PhotonRecyclingError("trapezoid quadrature coordinates must be strictly increasing") + weights = np.zeros_like(coords) + weights[:-1] += 0.5 * dx + weights[1:] += 0.5 * dx + return frozen_array(weights) + + +@dataclass(frozen=True) +class AbsorberReabsorptionSpec: + """Nonlocal emission-reabsorption specification for one emitter-receiver pair.""" + + layer_id: str + mode: str + node_count: int + emitter_nodes: IndexVector + receiver_nodes: IndexVector + emitter_weights_m: Vector + receiver_profile_m1: Vector + receiver_weights_m: Vector + escape_probability: float + intrinsic_radiative_B_m3_s: Vector + intrinsic_product_m6: Vector + emitter_coordinates_m: Vector | None = None + lagged_electron_density_m3: Vector | None = None + lagged_hole_density_m3: Vector | None = None + clamp_negative_net_emission: bool = True + switching_tolerance_m2_s: float = _DEFAULT_EMISSION_SWITCH_TOL_M2_S + sha256: str = field(init=False) + + def __post_init__(self) -> None: + if not isinstance(self.layer_id, str) or not self.layer_id.strip(): + raise PhotonRecyclingError("AbsorberReabsorptionSpec requires a non-empty layer_id") + if self.mode not in REABSORPTION_MODES: + raise PhotonRecyclingCapabilityError(f"unsupported reabsorption mode {self.mode!r}") + if type(self.node_count) is not int or self.node_count < 2: + raise PhotonRecyclingError("node_count must be an integer >= 2") + + emit = integer_indices(self.emitter_nodes) + recv = integer_indices(self.receiver_nodes) + if emit.ndim != 1 or emit.size < 1 or recv.ndim != 1 or recv.size < 1: + raise PhotonRecyclingError("emitter_nodes and receiver_nodes must be non-empty 1D index arrays") + if ( + np.any(emit < 0) + or np.any(emit >= self.node_count) + or np.any(recv < 0) + or np.any(recv >= self.node_count) + ): + raise PhotonRecyclingError("emitter_nodes and receiver_nodes must lie in [0, node_count)") + if len(set(emit.tolist())) != emit.size or len(set(recv.tolist())) != recv.size: + raise PhotonRecyclingError("emitter_nodes and receiver_nodes must not contain duplicates") + + w_emit = frozen_array(self.emitter_weights_m) + psi_recv = frozen_array(self.receiver_profile_m1) + w_recv = frozen_array(self.receiver_weights_m) + b_rad = frozen_array(self.intrinsic_radiative_B_m3_s) + ni_sq = frozen_array(self.intrinsic_product_m6) + + if w_emit.shape != emit.shape or np.any(w_emit <= 0.0): + raise PhotonRecyclingError("emitter_weights_m must be finite positive on emitter_nodes") + if psi_recv.shape != recv.shape or np.any(psi_recv < 0.0): + raise PhotonRecyclingError("receiver_profile_m1 must be finite non-negative on receiver_nodes") + if w_recv.shape != recv.shape or np.any(w_recv <= 0.0): + raise PhotonRecyclingError("receiver_weights_m must be finite positive on receiver_nodes") + if b_rad.shape != emit.shape or np.any(b_rad < 0.0): + raise PhotonRecyclingError("intrinsic_radiative_B_m3_s must be finite non-negative on emitter_nodes") + if ni_sq.shape != emit.shape or np.any(ni_sq < 0.0): + raise PhotonRecyclingError("intrinsic_product_m6 must be finite non-negative on emitter_nodes") + + p_esc = float(self.escape_probability) + if not math.isfinite(p_esc) or p_esc < 0.0 or p_esc > 1.0: + raise PhotonRecyclingError(f"escape_probability must lie in [0, 1], got {self.escape_probability!r}") + tol = float(self.switching_tolerance_m2_s) + if not math.isfinite(tol) or tol < 0.0: + raise PhotonRecyclingError("switching_tolerance_m2_s must be finite and non-negative") + + if self.mode == CONTROL_VOLUME_CONSERVATIVE_V1: + norm = float(np.dot(w_recv, psi_recv)) + if not math.isclose(norm, 1.0, rel_tol=1.0e-12, abs_tol=1.0e-12): + raise PhotonRecyclingError( + f"{self.layer_id}: conservative receiver profile must satisfy sum(w_recv * psi_recv) == 1, got {norm}" + ) + + coords: Vector | None = None + if self.emitter_coordinates_m is not None: + coords = frozen_array(self.emitter_coordinates_m) + if coords.shape != emit.shape or coords.size < 2 or np.any(np.diff(coords) <= 0.0): + raise PhotonRecyclingError( + "emitter_coordinates_m must be strictly increasing and match emitter_nodes" + ) + elif self.mode == HISTORICAL_TRAPEZOID_UNIFORM_V1: + raise PhotonRecyclingError( + "HISTORICAL_TRAPEZOID_UNIFORM_V1 requires emitter_coordinates_m" + ) + + n_lag: Vector | None = None + p_lag: Vector | None = None + if self.mode == LAGGED_BAKED_GENERATION_V1: + if self.lagged_electron_density_m3 is None or self.lagged_hole_density_m3 is None: + raise PhotonRecyclingError( + "LAGGED_BAKED_GENERATION_V1 requires explicit lagged_electron_density_m3 and lagged_hole_density_m3" + ) + n_lag = frozen_array(self.lagged_electron_density_m3) + p_lag = frozen_array(self.lagged_hole_density_m3) + if n_lag.shape != (self.node_count,) or p_lag.shape != (self.node_count,): + raise PhotonRecyclingError("lagged densities must have shape (node_count,)") + if np.any(n_lag <= 0.0) or np.any(p_lag <= 0.0): + raise PhotonRecyclingError("lagged densities must be strictly positive") + elif self.lagged_electron_density_m3 is not None or self.lagged_hole_density_m3 is not None: + raise PhotonRecyclingError( + f"lagged densities are only valid for {LAGGED_BAKED_GENERATION_V1}" + ) + + object.__setattr__(self, "emitter_nodes", emit) + object.__setattr__(self, "receiver_nodes", recv) + object.__setattr__(self, "emitter_weights_m", w_emit) + object.__setattr__(self, "receiver_profile_m1", psi_recv) + object.__setattr__(self, "receiver_weights_m", w_recv) + object.__setattr__(self, "escape_probability", p_esc) + object.__setattr__(self, "intrinsic_radiative_B_m3_s", b_rad) + object.__setattr__(self, "intrinsic_product_m6", ni_sq) + object.__setattr__(self, "emitter_coordinates_m", coords) + object.__setattr__(self, "lagged_electron_density_m3", n_lag) + object.__setattr__(self, "lagged_hole_density_m3", p_lag) + object.__setattr__(self, "switching_tolerance_m2_s", tol) + + digest = hashlib.sha256() + meta = { + "schema": "solarlab.radiative_reabsorption.spec.v1", + "layer_id": self.layer_id, + "mode": self.mode, + "node_count": self.node_count, + "emitter_nodes": emit.tolist(), + "receiver_nodes": recv.tolist(), + "escape_probability": repr(p_esc), + "clamp_negative_net_emission": bool(self.clamp_negative_net_emission), + "switching_tolerance_m2_s": repr(tol), + } + digest.update(json.dumps(meta, sort_keys=True, separators=(",", ":")).encode("ascii")) + for arr in (w_emit, psi_recv, w_recv, b_rad, ni_sq): + digest.update(np.ascontiguousarray(arr, dtype=" AbsorberReabsorptionSpec: + """Build a control-volume photon-conserving global emitter-receiver spec.""" + measures = frozen_array(cell_measures_m) + if measures.shape != (node_count,) or np.any(measures <= 0.0): + raise PhotonRecyclingError("cell_measures_m must be finite positive of shape (node_count,)") + emit = integer_indices(emitter_nodes) + recv = emit if receiver_nodes is None else integer_indices(receiver_nodes) + w_emit = measures[emit] + w_recv = measures[recv] + raw_shape = np.ones(recv.size, dtype=float) if receiver_shape is None else np.asarray(receiver_shape, dtype=float) + if raw_shape.shape != recv.shape or not np.all(np.isfinite(raw_shape)) or np.any(raw_shape < 0.0): + raise PhotonRecyclingError("receiver_shape must be finite non-negative on receiver_nodes") + denom = float(np.dot(w_recv, raw_shape)) + if denom <= 0.0: + raise PhotonRecyclingError("receiver_shape must have positive integral over receiver_nodes") + psi_recv = raw_shape / denom + b_full = np.asarray(intrinsic_radiative_B_m3_s, dtype=float) + ni_full = np.asarray(intrinsic_product_m6, dtype=float) + b_emit = b_full[emit] if b_full.shape == (node_count,) else b_full + ni_emit = ni_full[emit] if ni_full.shape == (node_count,) else ni_full + return cls( + layer_id=layer_id, + mode=CONTROL_VOLUME_CONSERVATIVE_V1, + node_count=node_count, + emitter_nodes=emit, + receiver_nodes=recv, + emitter_weights_m=w_emit, + receiver_profile_m1=psi_recv, + receiver_weights_m=w_recv, + escape_probability=escape_probability, + intrinsic_radiative_B_m3_s=b_emit, + intrinsic_product_m6=ni_emit, + clamp_negative_net_emission=clamp_negative_net_emission, + switching_tolerance_m2_s=switching_tolerance_m2_s, + ) + + @classmethod + def historical_trapezoid_uniform( + cls, + *, + layer_id: str, + nodes_m: ArrayLike, + absorber_mask: ArrayLike, + thickness_m: float, + escape_probability: float, + intrinsic_radiative_B_m3_s: ArrayLike, + intrinsic_product_m6: ArrayLike, + clamp_negative_net_emission: bool = True, + switching_tolerance_m2_s: float = _DEFAULT_EMISSION_SWITCH_TOL_M2_S, + ) -> AbsorberReabsorptionSpec: + """Build the historical 1D MoL trapezoid-emission / uniform-thickness spec.""" + coords = frozen_array(nodes_m) + mask = np.asarray(absorber_mask, dtype=bool) + if coords.ndim != 1 or mask.shape != coords.shape: + raise PhotonRecyclingError("absorber_mask must match 1D nodes_m") + idx = np.flatnonzero(mask) + if idx.size < 2: + raise PhotonRecyclingError("historical trapezoid reabsorption requires >= 2 absorber nodes") + width = float(thickness_m) + if not math.isfinite(width) or width <= 0.0: + raise PhotonRecyclingError("thickness_m must be finite and positive") + x_emit = coords[idx] + w_trap = trapezoid_quadrature_weights_1d(x_emit) + psi_uniform: Vector = np.full(idx.size, 1.0 / width, dtype=float) + b_full = np.asarray(intrinsic_radiative_B_m3_s, dtype=float) + ni_full = np.asarray(intrinsic_product_m6, dtype=float) + b_emit = b_full[idx] if b_full.shape == coords.shape else b_full + ni_emit = ni_full[idx] if ni_full.shape == coords.shape else ni_full + return cls( + layer_id=layer_id, + mode=HISTORICAL_TRAPEZOID_UNIFORM_V1, + node_count=coords.size, + emitter_nodes=idx, + receiver_nodes=idx, + emitter_weights_m=w_trap, + receiver_profile_m1=psi_uniform, + receiver_weights_m=w_trap, + escape_probability=escape_probability, + intrinsic_radiative_B_m3_s=b_emit, + intrinsic_product_m6=ni_emit, + emitter_coordinates_m=x_emit, + clamp_negative_net_emission=clamp_negative_net_emission, + switching_tolerance_m2_s=switching_tolerance_m2_s, + ) + + @classmethod + def lagged_baked( + cls, + base_spec: AbsorberReabsorptionSpec, + lagged_electron_density_m3: ArrayLike, + lagged_hole_density_m3: ArrayLike, + ) -> AbsorberReabsorptionSpec: + """Freeze a reabsorption spec at an explicit lagged carrier-density pair.""" + return cls( + layer_id=base_spec.layer_id, + mode=LAGGED_BAKED_GENERATION_V1, + node_count=base_spec.node_count, + emitter_nodes=base_spec.emitter_nodes, + receiver_nodes=base_spec.receiver_nodes, + emitter_weights_m=base_spec.emitter_weights_m, + receiver_profile_m1=base_spec.receiver_profile_m1, + receiver_weights_m=base_spec.receiver_weights_m, + escape_probability=base_spec.escape_probability, + intrinsic_radiative_B_m3_s=base_spec.intrinsic_radiative_B_m3_s, + intrinsic_product_m6=base_spec.intrinsic_product_m6, + emitter_coordinates_m=base_spec.emitter_coordinates_m, + lagged_electron_density_m3=lagged_electron_density_m3, + lagged_hole_density_m3=lagged_hole_density_m3, + clamp_negative_net_emission=base_spec.clamp_negative_net_emission, + switching_tolerance_m2_s=base_spec.switching_tolerance_m2_s, + ) + + +@dataclass(frozen=True) +class AbsorberRank1Factor: + """Rank-1 analytical derivative factor ``u_receiver (x) v_emitter`` for one absorber.""" + + layer_id: str + mode: str + emitter_nodes: IndexVector + receiver_nodes: IndexVector + receiver_vector_m1: Vector + d_emission_flux_dn_m_s: Vector + d_emission_flux_dp_m_s: Vector + active: bool + differentiable: bool + raw_emitted_flux_m2_s: float + clamped_emitted_flux_m2_s: float + + +@dataclass(frozen=True) +class PhotonRecyclingBudget: + """Per-absorber internal photon emission, reabsorption, and escape ledger.""" + + layer_id: str + mode: str + escape_probability: float + raw_emitted_flux_m2_s: float + emitted_flux_m2_s: float + reabsorbed_flux_m2_s: float + escaped_flux_m2_s: float + closure_residual_m2_s: float + + +@dataclass(frozen=True) +class ReabsorptionEvaluation: + """Evaluated nonlocal ``G_rad`` [m^-3 s^-1], low-rank factors, and photon ledger.""" + + generation_m3_s: Vector + factors: tuple[AbsorberRank1Factor, ...] + budgets: tuple[PhotonRecyclingBudget, ...] + differentiable: bool + non_smooth_layers: tuple[str, ...] + + @property + def total_emitted_flux_m2_s(self) -> float: + return float(sum(item.emitted_flux_m2_s for item in self.budgets)) + + @property + def total_reabsorbed_flux_m2_s(self) -> float: + return float(sum(item.reabsorbed_flux_m2_s for item in self.budgets)) + + @property + def total_escaped_flux_m2_s(self) -> float: + return float(sum(item.escaped_flux_m2_s for item in self.budgets)) + + @property + def max_budget_residual_m2_s(self) -> float: + if not self.budgets: + return 0.0 + return float(max(abs(item.closure_residual_m2_s) for item in self.budgets)) + + +def _raw_emission_flux(spec: AbsorberReabsorptionSpec, n_eval: Vector, p_eval: Vector) -> tuple[Vector, float]: + emit = spec.emitter_nodes + net_rate = spec.intrinsic_radiative_B_m3_s * ( + n_eval[emit] * p_eval[emit] - spec.intrinsic_product_m6 + ) + if spec.emitter_coordinates_m is not None: + raw_flux = float(np.trapezoid(net_rate, spec.emitter_coordinates_m)) + else: + raw_flux = float(np.dot(spec.emitter_weights_m, net_rate)) + return net_rate, raw_flux + + +def _effective_switching_tolerance_m2_s(spec: AbsorberReabsorptionSpec) -> float: + thermal_flux_scale = float( + np.dot( + spec.emitter_weights_m, + spec.intrinsic_radiative_B_m3_s * spec.intrinsic_product_m6, + ) + ) + return max(spec.switching_tolerance_m2_s, 1.0e-11 * thermal_flux_scale) + + +def evaluate_radiative_reabsorption( + specs: Sequence[AbsorberReabsorptionSpec], + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + *, + derivatives: bool = True, +) -> ReabsorptionEvaluation: + """Evaluate nonlocal radiative reabsorption ``G_rad`` and exact rank-1 tangents.""" + n = np.asarray(electron_density_m3, dtype=float) + p = np.asarray(hole_density_m3, dtype=float) + if n.ndim != 1 or p.shape != n.shape or not (np.all(np.isfinite(n)) and np.all(np.isfinite(p))): + raise PhotonRecyclingError("carrier densities must be finite 1D arrays of equal length") + node_count = n.size + generation = np.zeros(node_count, dtype=float) + factors: list[AbsorberRank1Factor] = [] + budgets: list[PhotonRecyclingBudget] = [] + non_smooth: list[str] = [] + + for spec in specs: + if spec.node_count != node_count: + raise PhotonRecyclingError( + f"{spec.layer_id}: spec node_count {spec.node_count} != density length {node_count}" + ) + if spec.mode == LAGGED_BAKED_GENERATION_V1: + assert spec.lagged_electron_density_m3 is not None + assert spec.lagged_hole_density_m3 is not None + n_eval = spec.lagged_electron_density_m3 + p_eval = spec.lagged_hole_density_m3 + else: + n_eval = n + p_eval = p + + _, raw_flux = _raw_emission_flux(spec, n_eval, p_eval) + trapped_fraction = 1.0 - spec.escape_probability + has_trapping = trapped_fraction > 0.0 and bool(np.any(spec.intrinsic_radiative_B_m3_s > 0.0)) + + if spec.clamp_negative_net_emission: + active = raw_flux > 0.0 + clamped_flux = raw_flux if active else 0.0 + tol = _effective_switching_tolerance_m2_s(spec) + on_kink = ( + spec.mode != LAGGED_BAKED_GENERATION_V1 + and has_trapping + and abs(raw_flux) <= tol + ) + smooth = not on_kink + else: + active = True + clamped_flux = raw_flux + smooth = True + + if not smooth: + non_smooth.append(spec.layer_id) + + recv = spec.receiver_nodes + u_recv = trapped_fraction * spec.receiver_profile_m1 + if clamped_flux != 0.0 and trapped_fraction > 0.0: + local_gen = u_recv * clamped_flux + generation[recv] += local_gen + reabsorbed_flux = float(np.dot(spec.receiver_weights_m, local_gen)) + else: + reabsorbed_flux = 0.0 + + escaped_flux = spec.escape_probability * clamped_flux + residual_flux = clamped_flux - reabsorbed_flux - escaped_flux + budgets.append( + PhotonRecyclingBudget( + layer_id=spec.layer_id, + mode=spec.mode, + escape_probability=spec.escape_probability, + raw_emitted_flux_m2_s=raw_flux, + emitted_flux_m2_s=clamped_flux, + reabsorbed_flux_m2_s=reabsorbed_flux, + escaped_flux_m2_s=escaped_flux, + closure_residual_m2_s=residual_flux, + ) + ) + + if derivatives: + emit = spec.emitter_nodes + if spec.mode == LAGGED_BAKED_GENERATION_V1 or not active or trapped_fraction == 0.0: + v_n = np.zeros(emit.size, dtype=float) + v_p = np.zeros(emit.size, dtype=float) + u_factor = np.zeros(recv.size, dtype=float) + else: + coeff = spec.emitter_weights_m * spec.intrinsic_radiative_B_m3_s + v_n = coeff * p_eval[emit] + v_p = coeff * n_eval[emit] + u_factor = u_recv + factors.append( + AbsorberRank1Factor( + layer_id=spec.layer_id, + mode=spec.mode, + emitter_nodes=emit, + receiver_nodes=recv, + receiver_vector_m1=frozen_array(u_factor), + d_emission_flux_dn_m_s=frozen_array(v_n), + d_emission_flux_dp_m_s=frozen_array(v_p), + active=active, + differentiable=smooth, + raw_emitted_flux_m2_s=raw_flux, + clamped_emitted_flux_m2_s=clamped_flux, + ) + ) + + return ReabsorptionEvaluation( + generation_m3_s=frozen_array(generation), + factors=tuple(factors), + budgets=tuple(budgets), + differentiable=len(non_smooth) == 0, + non_smooth_layers=tuple(non_smooth), + ) + + +def dense_reabsorption_jacobian( + evaluation: ReabsorptionEvaluation, + node_count: int, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Explicit dense ``(dG_rad/dn, dG_rad/dp)`` matrices for small-grid verification.""" + d_dn: Vector2D = np.zeros((node_count, node_count), dtype=float) + d_dp: Vector2D = np.zeros((node_count, node_count), dtype=float) + for factor in evaluation.factors: + if not factor.active: + continue + rows = factor.receiver_nodes[:, None] + cols = factor.emitter_nodes[None, :] + d_dn[rows, cols] += np.outer(factor.receiver_vector_m1, factor.d_emission_flux_dn_m_s) + d_dp[rows, cols] += np.outer(factor.receiver_vector_m1, factor.d_emission_flux_dp_m_s) + return d_dn, d_dp + + +@dataclass(frozen=True) +class ReabsorptionDirectionalDerivative: + """Value and exact one-sided directional derivative of ``G_rad`` across ``R_tot = 0``.""" + + generation_m3_s: Vector + directional_derivative_m3_s: Vector + smooth: bool + non_smooth_layers: tuple[str, ...] + + +def radiative_reabsorption_directional_derivative( + specs: Sequence[AbsorberReabsorptionSpec], + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + delta_electron_m3: ArrayLike, + delta_hole_m3: ArrayLike, +) -> ReabsorptionDirectionalDerivative: + """Exact one-sided directional derivative ``lim_{h->0+} [G(n+hdn, p+hdp) - G(n,p)] / h``.""" + n = np.asarray(electron_density_m3, dtype=float) + p = np.asarray(hole_density_m3, dtype=float) + dn = np.asarray(delta_electron_m3, dtype=float) + dp = np.asarray(delta_hole_m3, dtype=float) + if ( + n.ndim != 1 + or p.shape != n.shape + or dn.shape != n.shape + or dp.shape != n.shape + or not (np.all(np.isfinite(dn)) and np.all(np.isfinite(dp))) + ): + raise PhotonRecyclingError("densities and directions must be finite 1D arrays of equal length") + + base = evaluate_radiative_reabsorption(specs, n, p, derivatives=False) + slope = np.zeros_like(n) + non_smooth: list[str] = [] + + for spec in specs: + if spec.mode == LAGGED_BAKED_GENERATION_V1: + continue + trapped_fraction = 1.0 - spec.escape_probability + if trapped_fraction <= 0.0 or not np.any(spec.intrinsic_radiative_B_m3_s > 0.0): + continue + _, raw_flux = _raw_emission_flux(spec, n, p) + emit = spec.emitter_nodes + recv = spec.receiver_nodes + coeff = spec.emitter_weights_m * spec.intrinsic_radiative_B_m3_s + d_flux = float(np.dot(coeff, p[emit] * dn[emit] + n[emit] * dp[emit])) + u_recv = trapped_fraction * spec.receiver_profile_m1 + + tol = _effective_switching_tolerance_m2_s(spec) + if not spec.clamp_negative_net_emission: + slope[recv] += u_recv * d_flux + elif raw_flux > tol: + slope[recv] += u_recv * d_flux + elif raw_flux < -tol: + pass + else: + non_smooth.append(spec.layer_id) + if d_flux > 0.0: + slope[recv] += u_recv * d_flux + + return ReabsorptionDirectionalDerivative( + generation_m3_s=base.generation_m3_s, + directional_derivative_m3_s=frozen_array(slope), + smooth=len(non_smooth) == 0, + non_smooth_layers=tuple(non_smooth), + ) + + +def thermionic_cap_value( + j_sg: ArrayLike, + j_te: ArrayLike, + *, + te_softness: float = 0.0, +) -> Vector: + """Direction-preserving thermionic magnitude cap ``copysign(min(|J_sg|, |J_te|), J_sg)``.""" + sg, te = np.broadcast_arrays(np.asarray(j_sg, dtype=float), np.asarray(j_te, dtype=float)) + if not (np.all(np.isfinite(sg)) and np.all(np.isfinite(te))): + raise PhotonRecyclingError("j_sg and j_te must be finite") + soft = float(te_softness) + if not math.isfinite(soft) or soft < 0.0: + raise PhotonRecyclingError("te_softness must be finite and non-negative") + a_sg = np.abs(sg) + a_te = np.abs(te) + if soft == 0.0: + return frozen_array(np.copysign(np.minimum(a_sg, a_te), sg)) + denom = soft * (a_sg + a_te) + 1.0e-300 + t_arg = (a_sg - a_te) / denom + weight = np.where( + t_arg > 40.0, + 1.0, + np.where(t_arg < -40.0, 0.0, 1.0 / (1.0 + np.exp(-np.clip(t_arg, -40.0, 40.0)))), + ) + magnitude = weight * a_te + (1.0 - weight) * a_sg + return frozen_array(np.copysign(magnitude, sg)) + + +@dataclass(frozen=True) +class ThermionicCapDirectionalDerivative: + """Value, one-sided directional derivative, and smoothness mask of the TE cap.""" + + capped_current_A_m2: Vector + directional_derivative_A_m2: Vector + smooth: NDArray[np.bool_] + + +def thermionic_cap_directional_derivative( + j_sg: ArrayLike, + j_te: ArrayLike, + d_j_sg: ArrayLike, + d_j_te: ArrayLike, + *, + te_softness: float = 0.0, + crossover_tolerance_A_m2: float = 1.0e-15, +) -> ThermionicCapDirectionalDerivative: + """Exact one-sided directional derivative across ``|J_sg| == |J_te|`` and ``J_sg == 0``.""" + sg, te, dsg, dte = np.broadcast_arrays( + np.asarray(j_sg, dtype=float), + np.asarray(j_te, dtype=float), + np.asarray(d_j_sg, dtype=float), + np.asarray(d_j_te, dtype=float), + ) + sg_1d = sg.reshape(-1) + te_1d = te.reshape(-1) + dsg_1d = dsg.reshape(-1) + dte_1d = dte.reshape(-1) + if not (np.all(np.isfinite(sg_1d)) and np.all(np.isfinite(te_1d)) and np.all(np.isfinite(dsg_1d)) and np.all(np.isfinite(dte_1d))): + raise PhotonRecyclingError("thermionic currents and perturbations must be finite") + soft = float(te_softness) + if not math.isfinite(soft) or soft < 0.0: + raise PhotonRecyclingError("te_softness must be finite and non-negative") + tol = float(crossover_tolerance_A_m2) + if not math.isfinite(tol) or tol < 0.0: + raise PhotonRecyclingError("crossover_tolerance_A_m2 must be finite and non-negative") + + capped = thermionic_cap_value(sg_1d, te_1d, te_softness=soft) + deriv = np.zeros_like(sg_1d) + smooth = np.ones(sg_1d.shape, dtype=bool) + + for idx in range(sg_1d.size): + s_val = float(sg_1d[idx]) + t_val = float(te_1d[idx]) + ds = float(dsg_1d[idx]) + dt = float(dte_1d[idx]) + a_s = abs(s_val) + a_t = abs(t_val) + da_s = abs(ds) if a_s <= tol else math.copysign(1.0, s_val) * ds + da_t = abs(dt) if a_t <= tol else math.copysign(1.0, t_val) * dt + + if a_s <= tol: + # At J_sg = 0: if |J_te| > 0 and ds == 0, copysign(0, ...) stays 0; + # if a_t == 0 too, copysign(h * min(|ds|, |dt|), ds) has a kink when |dt| < |ds|. + if a_t <= tol: + smooth[idx] = False + sign_dir = 0.0 if ds == 0.0 else math.copysign(1.0, ds) + deriv[idx] = sign_dir * min(abs(ds), abs(dt)) + else: + smooth[idx] = soft == 0.0 + deriv[idx] = ds if soft == 0.0 else ( + math.copysign(1.0, ds) * (1.0 / (1.0 + math.exp(1.0 / soft))) * a_t + if ds != 0.0 + else 0.0 + ) + if soft > 0.0 and a_t > tol: + # Jump discontinuity in copysign(nonzero, J_sg) across J_sg = 0! + smooth[idx] = False + deriv[idx] = math.copysign(math.inf, ds) if ds != 0.0 else 0.0 + continue + + sign_sg = math.copysign(1.0, s_val) + if soft == 0.0: + if abs(a_s - a_t) <= tol: + smooth[idx] = False + deriv[idx] = sign_sg * min(da_s, da_t) + elif a_s < a_t: + smooth[idx] = True + if a_t <= tol: + smooth[idx] = False + deriv[idx] = ds + else: + smooth[idx] = a_t > tol + deriv[idx] = sign_sg * da_t + else: + if a_t <= tol: + smooth[idx] = False + denom = soft * (a_s + a_t) + 1.0e-300 + t_arg = (a_s - a_t) / denom + if t_arg > 40.0: + weight = 1.0 + d_weight = 0.0 + elif t_arg < -40.0: + weight = 0.0 + d_weight = 0.0 + else: + weight = 1.0 / (1.0 + math.exp(-t_arg)) + sig_prime = weight * (1.0 - weight) + dt_arg = ( + (da_s - da_t) * denom - (a_s - a_t) * soft * (da_s + da_t) + ) / (denom * denom) + d_weight = sig_prime * dt_arg + d_mag = d_weight * (a_t - a_s) + weight * da_t + (1.0 - weight) * da_s + deriv[idx] = sign_sg * d_mag + + return ThermionicCapDirectionalDerivative( + capped_current_A_m2=capped, + directional_derivative_A_m2=frozen_array(deriv), + smooth=smooth, + ) + + +@dataclass(frozen=True) +class SwitchingSurfaceAssessment: + """Combined differentiability assessment across reabsorption, TE, and PF surfaces.""" + + smooth: bool + reabsorption_smooth: bool + thermionic_smooth: bool + field_mobility_smooth: bool + reasons: tuple[str, ...] + + +def assess_switching_surfaces( + *, + reabsorption: ReabsorptionEvaluation | None = None, + thermionic_electron: ThermionicCapDirectionalDerivative | None = None, + thermionic_hole: ThermionicCapDirectionalDerivative | None = None, + field_mobility_electron: FieldMobilityDirectionalDerivative | None = None, + field_mobility_hole: FieldMobilityDirectionalDerivative | None = None, + face_fields_V_m: ArrayLike | None = None, + mu0_n: ArrayLike | None = None, + v_sat_n: ArrayLike | None = None, + beta_n: ArrayLike | None = None, + gamma_pf_n: ArrayLike | None = None, + pf_width_V_m: float = 0.0, +) -> SwitchingSurfaceAssessment: + """Evaluate smoothness across declared switching surfaces before linear AC solves.""" + reasons: list[str] = [] + reabs_ok = True + if reabsorption is not None and not reabsorption.differentiable: + reabs_ok = False + layers = ", ".join(reabsorption.non_smooth_layers) + reasons.append( + f"radiative_reabsorption clamped switching surface R_tot == 0 active on ({layers})" + ) + + te_ok = True + for label, te_diag in (("electron", thermionic_electron), ("hole", thermionic_hole)): + if te_diag is not None and not bool(np.all(te_diag.smooth)): + te_ok = False + count = int(np.sum(~te_diag.smooth)) + reasons.append(f"thermionic_cap {label} non-smooth min/sign surface on {count} face(s)") + + fm_ok = True + if ( + field_mobility_electron is None + and face_fields_V_m is not None + and mu0_n is not None + and v_sat_n is not None + and beta_n is not None + and gamma_pf_n is not None + ): + fields = np.asarray(face_fields_V_m, dtype=float) + field_mobility_electron = field_mobility_directional_derivative( + mu0_n, + fields, + np.ones_like(fields), + v_sat_n, + beta_n, + gamma_pf_n, + pf_field_regularization_width_V_m=pf_width_V_m, + ) + for label, fm_diag in (("electron", field_mobility_electron), ("hole", field_mobility_hole)): + if fm_diag is not None and not bool(np.all(fm_diag.smooth)): + fm_ok = False + count = int(np.sum(~fm_diag.smooth)) + infinite = int(np.sum(~fm_diag.finite)) + reasons.append( + f"field_mobility {label} non-smooth surface on {count} face(s) ({infinite} infinite slope)" + ) + + return SwitchingSurfaceAssessment( + smooth=reabs_ok and te_ok and fm_ok, + reabsorption_smooth=reabs_ok, + thermionic_smooth=te_ok, + field_mobility_smooth=fm_ok, + reasons=tuple(reasons), + ) + + +def require_smooth_ac_surfaces(assessment: SwitchingSurfaceAssessment) -> None: + """Refuse linear small-signal AC assembly on non-smooth switching surfaces.""" + if not assessment.smooth: + detail = "; ".join(assessment.reasons) + raise PhotonRecyclingCapabilityError( + "non_smooth_ac_switching_surface: linear AC small-signal operator is undefined at " + f"this operating point ({detail})" + ) diff --git a/src/solarlab/physics/transport/tunneling_channels.py b/src/solarlab/physics/transport/tunneling_channels.py new file mode 100644 index 00000000..a08cc09f --- /dev/null +++ b/src/solarlab/physics/transport/tunneling_channels.py @@ -0,0 +1,1747 @@ +"""Canonical 1D WKB tunnelling-channel contracts, evaluators, and path Jacobians. + +Migrates the four named WKB tunnelling channels under explicit quasi-static +capability gates: + +1. ``band_to_band`` — Zener/Esaki interband two-band Kane tunnelling; +2. ``intraband`` — heterointerface band-spike path-resolved tunnelling; +3. ``interface_defect_assisted`` — trap-assisted tunnelling consuming an explicit + interface occupancy ``f_t`` (refusing algebraically eliminated steady SRH); +4. ``contact`` — Schottky contact field emission. + +For device steady-state coupling, ``intraband_path_flux_and_jacobian`` computes +both the conservative nonlocal face-flux profile ``particle_face_flux_m2_s`` and +its exact analytical Jacobians wrt ``band_edge_eV`` and ``quasi_fermi_eV``, plus +a ``WKBWindowSupport`` descriptor tracking active turning-point face intervals +``(a_k, b_k)`` against the preallocated reservoir superset or strict window +rebind signature. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, replace +from functools import lru_cache +import hashlib +import json +import math +from numbers import Integral, Real +from typing import Any, Literal, Self, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.arrays import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.physics.transport.wkb_tunneling import ( + MINIMUM_MEANINGFUL_ACTION, + WKBTunnellingError, + forbidden_run, + piecewise_linear_wkb_segment_action_derivatives, + piecewise_linear_wkb_segment_actions, + reciprocal_net_flux, + turning_point_levels, + two_band_transmission, + two_band_turning_point_levels, + two_band_validity, + windowed_wkb_transmission, + wkb_validity, +) + +__all__ = [ + "BAND_TO_BAND", + "BOTH_CARRIERS", + "BOTH_SIDES", + "CHANNEL_NAMES", + "CONTACT", + "ELECTRON", + "HOLE", + "INTERFACE_DEFECT_ASSISTED", + "INTRABAND", + "LEFT", + "PREALLOCATED_RESERVOIR_SUPERSET_V1", + "RIGHT", + "STRICT_WINDOW_REBIND_V1", + "TUNNELLING_CHANNEL_DEVICE_VERSION", + "TUNNELLING_CHANNEL_SCHEMA_VERSION", + "WKB_SPARSITY_POLICIES", + "BandToBandTunnellingChannel", + "ChannelFlux", + "CompiledTunnellingChannels", + "ContactTunnellingChannel", + "InterfaceDefectAssistedFlux", + "InterfaceDefectAssistedTunnellingChannel", + "IntrabandBarrierRegion", + "IntrabandPathFlux", + "IntrabandPathLinearization", + "IntrabandTunnellingChannel", + "TunnellingChannelCapabilityError", + "TunnellingChannelDocument", + "TunnellingChannelError", + "TunnellingChannelEvaluation", + "TunnellingChannelSchemaError", + "WKBWindowSupport", + "band_to_band_flux", + "compile_tunnelling_channels", + "conduction_band_eV", + "contact_tunnelling_flux", + "evaluate_tunnelling_channels", + "interface_defect_assisted_rate", + "intraband_flux", + "intraband_path_flux", + "intraband_path_flux_and_jacobian", + "local_barrier_window", + "physical_quasi_fermi_levels_eV", + "tunnelling_channel_document_from_mapping", + "valence_band_eV", +] + +Vector: TypeAlias = NDArray[np.float64] +Matrix: TypeAlias = NDArray[np.float64] +Q: float = ELEMENTARY_CHARGE_C + +TUNNELLING_CHANNEL_SCHEMA_VERSION = "solarlab-wkb-tunnelling-channels-v1" +TUNNELLING_CHANNEL_DEVICE_VERSION = "wkb-tunnelling-channel-device-v2" + +BAND_TO_BAND = "band_to_band" +INTRABAND = "intraband" +INTERFACE_DEFECT_ASSISTED = "interface_defect_assisted" +CONTACT = "contact" +CHANNEL_NAMES = (BAND_TO_BAND, INTRABAND, INTERFACE_DEFECT_ASSISTED, CONTACT) + +ELECTRON = "electron" +HOLE = "hole" +BOTH_CARRIERS = "both" +_CARRIERS = {ELECTRON, HOLE, BOTH_CARRIERS} + +LEFT = "left" +RIGHT = "right" +BOTH_SIDES = "both" +_SIDES = {LEFT, RIGHT, BOTH_SIDES} + +PREALLOCATED_RESERVOIR_SUPERSET_V1 = "preallocated_reservoir_superset_v1" +STRICT_WINDOW_REBIND_V1 = "strict_window_rebind_v1" +WKB_SPARSITY_POLICIES = ( + PREALLOCATED_RESERVOIR_SUPERSET_V1, + STRICT_WINDOW_REBIND_V1, +) + + +class TunnellingChannelSchemaError(ValueError): + """A tunnelling channel document violated the canonical contract.""" + + +class TunnellingChannelError(RuntimeError): + """A channel was asked for a flux outside its declared domain.""" + + +class TunnellingChannelCapabilityError(RuntimeError): + """A tunnelling channel was requested where it is not certified.""" + + +def _finite(value: object, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{field} must be a real number") + result = float(value) + if not math.isfinite(result): + raise TunnellingChannelSchemaError(f"{field} must be finite") + return result + + +def _positive(value: object, field: str) -> float: + result = _finite(value, field) + if result <= 0.0: + raise TunnellingChannelSchemaError(f"{field} must be positive") + return result + + +def _nonnegative(value: object, field: str) -> float: + result = _finite(value, field) + if result < 0.0: + raise TunnellingChannelSchemaError(f"{field} must be non-negative") + return result + + +def _integer(value: object, field: str, *, minimum: int) -> int: + if isinstance(value, bool) or not isinstance(value, Integral): + raise TypeError(f"{field} must be an integer") + result = int(value) + if result < minimum: + raise TunnellingChannelSchemaError(f"{field} must be >= {minimum}") + return result + + +def _boolean(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise TypeError(f"{field} must be a boolean") + return value + + +def _require_exact_keys( + value: Mapping[str, Any], expected: set[str], where: str +) -> None: + actual = set(value) + if actual != expected: + raise TunnellingChannelSchemaError( + f"{where} schema mismatch: missing={sorted(expected - actual)}, " + f"unknown={sorted(actual - expected)}" + ) + + +def _canonical_json(value: Mapping[str, Any]) -> str: + return json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + +def _sha256(value: Mapping[str, Any]) -> str: + return hashlib.sha256(_canonical_json(value).encode("ascii")).hexdigest() + + +@dataclass(frozen=True, slots=True) +class BandToBandTunnellingChannel: + """Zener tunnelling across the gap.""" + + enabled: bool = False + reduced_effective_mass_rel: float = 0.1 + energy_quadrature_order: int = 32 + minimum_field_V_m: float = 1.0e6 + + def __post_init__(self) -> None: + object.__setattr__(self, "enabled", _boolean(self.enabled, "enabled")) + object.__setattr__( + self, + "reduced_effective_mass_rel", + _positive(self.reduced_effective_mass_rel, "reduced_effective_mass_rel"), + ) + object.__setattr__( + self, + "energy_quadrature_order", + _integer(self.energy_quadrature_order, "energy_quadrature_order", minimum=4), + ) + object.__setattr__( + self, + "minimum_field_V_m", + _positive(self.minimum_field_V_m, "minimum_field_V_m"), + ) + + def to_dict(self) -> dict[str, Any]: + return { + "enabled": self.enabled, + "reduced_effective_mass_rel": self.reduced_effective_mass_rel, + "energy_quadrature_order": self.energy_quadrature_order, + "minimum_field_V_m": self.minimum_field_V_m, + } + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> Self: + _require_exact_keys( + value, + { + "enabled", + "reduced_effective_mass_rel", + "energy_quadrature_order", + "minimum_field_V_m", + }, + "band_to_band channel", + ) + return cls(**dict(value)) + + +@dataclass(frozen=True, slots=True) +class IntrabandTunnellingChannel: + """Tunnelling through a heterointerface band spike.""" + + enabled: bool = False + electron_effective_mass_rel: float = 0.2 + hole_effective_mass_rel: float = 0.2 + carrier: str = BOTH_CARRIERS + energy_quadrature_order: int = 32 + + def __post_init__(self) -> None: + object.__setattr__(self, "enabled", _boolean(self.enabled, "enabled")) + for field_name in ("electron_effective_mass_rel", "hole_effective_mass_rel"): + object.__setattr__( + self, field_name, _positive(getattr(self, field_name), field_name) + ) + carrier = str(self.carrier).strip().lower() + if carrier not in _CARRIERS: + raise TunnellingChannelSchemaError(f"unknown carrier {carrier!r}") + object.__setattr__(self, "carrier", carrier) + object.__setattr__( + self, + "energy_quadrature_order", + _integer(self.energy_quadrature_order, "energy_quadrature_order", minimum=4), + ) + + def to_dict(self) -> dict[str, Any]: + return { + "enabled": self.enabled, + "electron_effective_mass_rel": self.electron_effective_mass_rel, + "hole_effective_mass_rel": self.hole_effective_mass_rel, + "carrier": self.carrier, + "energy_quadrature_order": self.energy_quadrature_order, + } + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> Self: + _require_exact_keys( + value, + { + "enabled", + "electron_effective_mass_rel", + "hole_effective_mass_rel", + "carrier", + "energy_quadrature_order", + }, + "intraband channel", + ) + return cls(**dict(value)) + + +@dataclass(frozen=True, slots=True) +class InterfaceDefectAssistedTunnellingChannel: + """Trap-assisted tunnelling requiring an explicit interface occupancy.""" + + enabled: bool = False + electron_effective_mass_rel: float = 0.2 + hole_effective_mass_rel: float = 0.2 + requires_explicit_occupancy: Literal[True] = True + + def __post_init__(self) -> None: + object.__setattr__(self, "enabled", _boolean(self.enabled, "enabled")) + for field_name in ("electron_effective_mass_rel", "hole_effective_mass_rel"): + object.__setattr__( + self, field_name, _positive(getattr(self, field_name), field_name) + ) + if self.requires_explicit_occupancy is not True: + raise TunnellingChannelSchemaError( + "interface-defect-assisted tunnelling may not run against an " + "algebraically eliminated occupancy" + ) + + def to_dict(self) -> dict[str, Any]: + return { + "enabled": self.enabled, + "electron_effective_mass_rel": self.electron_effective_mass_rel, + "hole_effective_mass_rel": self.hole_effective_mass_rel, + "requires_explicit_occupancy": self.requires_explicit_occupancy, + } + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> Self: + _require_exact_keys( + value, + { + "enabled", + "electron_effective_mass_rel", + "hole_effective_mass_rel", + "requires_explicit_occupancy", + }, + "interface_defect_assisted channel", + ) + return cls(**dict(value)) + + +@dataclass(frozen=True, slots=True) +class ContactTunnellingChannel: + """Field emission through a Schottky barrier at an outer contact.""" + + enabled: bool = False + electron_effective_mass_rel: float = 0.2 + hole_effective_mass_rel: float = 0.2 + barrier_height_eV: float = 0.0 + side: str = BOTH_SIDES + energy_quadrature_order: int = 32 + + def __post_init__(self) -> None: + object.__setattr__(self, "enabled", _boolean(self.enabled, "enabled")) + for field_name in ("electron_effective_mass_rel", "hole_effective_mass_rel"): + object.__setattr__( + self, field_name, _positive(getattr(self, field_name), field_name) + ) + object.__setattr__( + self, + "barrier_height_eV", + _nonnegative(self.barrier_height_eV, "barrier_height_eV"), + ) + side = str(self.side).strip().lower() + if side not in _SIDES: + raise TunnellingChannelSchemaError(f"unknown contact side {side!r}") + object.__setattr__(self, "side", side) + object.__setattr__( + self, + "energy_quadrature_order", + _integer(self.energy_quadrature_order, "energy_quadrature_order", minimum=4), + ) + if self.enabled and self.barrier_height_eV <= 0.0: + raise TunnellingChannelSchemaError( + "an enabled contact tunnelling channel needs a positive " + "barrier_height_eV; a zero barrier is an ohmic contact" + ) + + def to_dict(self) -> dict[str, Any]: + return { + "enabled": self.enabled, + "electron_effective_mass_rel": self.electron_effective_mass_rel, + "hole_effective_mass_rel": self.hole_effective_mass_rel, + "barrier_height_eV": self.barrier_height_eV, + "side": self.side, + "energy_quadrature_order": self.energy_quadrature_order, + } + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> Self: + _require_exact_keys( + value, + { + "enabled", + "electron_effective_mass_rel", + "hole_effective_mass_rel", + "barrier_height_eV", + "side", + "energy_quadrature_order", + }, + "contact channel", + ) + return cls(**dict(value)) + + +@dataclass(frozen=True, slots=True) +class TunnellingChannelDocument: + """The four named WKB channels, each independently switchable.""" + + schema_version: str = ( + TUNNELLING_CHANNEL_SCHEMA_VERSION + ) + band_to_band: BandToBandTunnellingChannel = None # type: ignore[assignment] + intraband: IntrabandTunnellingChannel = None # type: ignore[assignment] + interface_defect_assisted: InterfaceDefectAssistedTunnellingChannel = None # type: ignore[assignment] + contact: ContactTunnellingChannel = None # type: ignore[assignment] + + def __post_init__(self) -> None: + if self.schema_version != TUNNELLING_CHANNEL_SCHEMA_VERSION: + raise TunnellingChannelSchemaError( + "unsupported tunnelling channel schema_version" + ) + defaults: dict[str, type] = { + "band_to_band": BandToBandTunnellingChannel, + "intraband": IntrabandTunnellingChannel, + "interface_defect_assisted": InterfaceDefectAssistedTunnellingChannel, + "contact": ContactTunnellingChannel, + } + for field_name, factory in defaults.items(): + value = getattr(self, field_name) + if value is None: + object.__setattr__(self, field_name, factory()) + elif not isinstance(value, factory): + raise TypeError(f"{field_name} must be a {factory.__name__}") + + @property + def enabled_channels(self) -> tuple[str, ...]: + return tuple(name for name in CHANNEL_NAMES if getattr(self, name).enabled) + + @property + def any_enabled(self) -> bool: + return bool(self.enabled_channels) + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + **{name: getattr(self, name).to_dict() for name in CHANNEL_NAMES}, + } + + def canonical_json(self) -> str: + return _canonical_json(self.to_dict()) + + @property + def sha256(self) -> str: + return _sha256(self.to_dict()) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> Self: + if not isinstance(value, Mapping): + raise TunnellingChannelSchemaError( + "tunnelling channel document must be a mapping" + ) + _require_exact_keys( + value, + {"schema_version", *CHANNEL_NAMES}, + "tunnelling channel document", + ) + return cls( + schema_version=value["schema_version"], + band_to_band=BandToBandTunnellingChannel.from_dict(value[BAND_TO_BAND]), + intraband=IntrabandTunnellingChannel.from_dict(value[INTRABAND]), + interface_defect_assisted=InterfaceDefectAssistedTunnellingChannel.from_dict( + value[INTERFACE_DEFECT_ASSISTED] + ), + contact=ContactTunnellingChannel.from_dict(value[CONTACT]), + ) + + +def _coerce_scalars(value: Any) -> Any: + if isinstance(value, Mapping): + return {key: _coerce_scalars(item) for key, item in value.items()} + if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): + return [_coerce_scalars(item) for item in value] + if isinstance(value, str): + try: + return float(value) + except ValueError: + return value + return value + + +def tunnelling_channel_document_from_mapping( + device: Mapping[str, Any], +) -> TunnellingChannelDocument | None: + """Parse optional ``tunnelling_channels`` block (or direct channel mapping).""" + if not isinstance(device, Mapping): + raise TunnellingChannelSchemaError("device configuration must be a mapping") + if "tunnelling_channels" in device: + raw = device.get("tunnelling_channels") + if raw is None: + return None + if not isinstance(raw, Mapping): + raise TunnellingChannelSchemaError("tunnelling_channels must be a mapping") + elif "schema_version" in device or any(name in device for name in CHANNEL_NAMES): + raw = device + else: + return None + + defaults_map: dict[str, dict[str, Any]] = { + BAND_TO_BAND: BandToBandTunnellingChannel().to_dict(), + INTRABAND: IntrabandTunnellingChannel().to_dict(), + INTERFACE_DEFECT_ASSISTED: InterfaceDefectAssistedTunnellingChannel().to_dict(), + CONTACT: ContactTunnellingChannel().to_dict(), + } + payload: dict[str, Any] = { + "schema_version": raw.get("schema_version", TUNNELLING_CHANNEL_SCHEMA_VERSION) + } + extra_top = set(raw.keys()) - {"schema_version", *CHANNEL_NAMES} + if extra_top: + raise TunnellingChannelSchemaError( + f"tunnelling channel document unknown keys: {sorted(extra_top)}" + ) + for name in CHANNEL_NAMES: + channel = raw.get(name) + if channel is None: + payload[name] = dict(defaults_map[name]) + elif isinstance(channel, Mapping): + coerced = _coerce_scalars(channel) + unknown_sub = set(coerced.keys()) - set(defaults_map[name].keys()) + if unknown_sub: + raise TunnellingChannelSchemaError( + f"{name} channel unknown keys: {sorted(unknown_sub)}" + ) + payload[name] = {**defaults_map[name], **coerced} + else: + raise TunnellingChannelSchemaError( + f"tunnelling channel {name!r} must be a mapping" + ) + return TunnellingChannelDocument.from_dict(payload) + + +def _fermi(energy_eV: ArrayLike, level_eV: ArrayLike | float, thermal_voltage_V: float) -> Vector: + reduced = ( + np.asarray(energy_eV, dtype=float) - np.asarray(level_eV, dtype=float) + ) / float(thermal_voltage_V) + out = np.empty_like(reduced, dtype=float) + positive = reduced >= 0.0 + out[positive] = np.exp(-reduced[positive]) / (1.0 + np.exp(-reduced[positive])) + out[~positive] = 1.0 / (1.0 + np.exp(reduced[~positive])) + return out + + +def conduction_band_eV(potential_V: ArrayLike, affinity_eV: ArrayLike) -> Vector: + """``E_C = -(phi + chi)`` [eV].""" + return -(np.asarray(potential_V, dtype=float) + np.asarray(affinity_eV, dtype=float)) + + +def valence_band_eV( + potential_V: ArrayLike, + affinity_eV: ArrayLike, + band_gap_eV: ArrayLike, +) -> Vector: + """``E_V = -(phi + chi + Eg)`` [eV].""" + return -( + np.asarray(potential_V, dtype=float) + + np.asarray(affinity_eV, dtype=float) + + np.asarray(band_gap_eV, dtype=float) + ) + + +def local_barrier_window( + barrier_eV: ArrayLike, + anchor_face: int, + *, + one_sided: bool = False, +) -> tuple[float, float]: + """Peak and base of the barrier feature anchored on ``anchor_face``.""" + barrier = np.asarray(barrier_eV, dtype=float) + face = int(anchor_face) + if face < 0 or face >= barrier.size - 1: + raise WKBTunnellingError("anchor_face is outside the transport faces") + peak_index = face if barrier[face] >= barrier[face + 1] else face + 1 + while peak_index + 1 < barrier.size and barrier[peak_index + 1] > barrier[peak_index]: + peak_index += 1 + while peak_index - 1 >= 0 and barrier[peak_index - 1] > barrier[peak_index]: + peak_index -= 1 + left = peak_index + while left - 1 >= 0 and barrier[left - 1] < barrier[left]: + left -= 1 + right = peak_index + while right + 1 < barrier.size and barrier[right + 1] < barrier[right]: + right += 1 + peak = float(barrier[peak_index]) + if not one_sided: + return peak, float(max(barrier[left], barrier[right])) + return peak, float(min(barrier[left], barrier[right])) + + +def _turning_point_levels( + barrier_eV: Vector, + energies_eV: Vector, + anchor_face: int, + level_profile_eV: ArrayLike, +) -> tuple[Vector, Vector]: + profile = np.asarray(level_profile_eV, dtype=float) + left = np.empty_like(energies_eV) + right = np.empty_like(energies_eV) + for index, energy in enumerate(energies_eV): + left[index], right[index] = turning_point_levels( + barrier_eV, profile, float(energy), anchor_face + ) + return left, right + + +def _two_band_turning_point_levels( + conduction_eV: Vector, + valence_eV: Vector, + energies_eV: Vector, + anchor_face: int, + level_profile_eV: ArrayLike, +) -> tuple[Vector, Vector]: + profile = np.asarray(level_profile_eV, dtype=float) + left = np.empty_like(energies_eV) + right = np.empty_like(energies_eV) + for index, energy in enumerate(energies_eV): + left[index], right[index] = two_band_turning_point_levels( + conduction_eV, valence_eV, profile, float(energy), anchor_face + ) + return left, right + + +@dataclass(frozen=True, slots=True) +class ChannelFlux: + """One channel's net flux plus everything needed to audit it.""" + + channel: str + net_flux_m2_s: float + forward_flux_m2_s: float + reverse_flux_m2_s: float + energies_eV: Vector + transmission: Vector + maximum_transmission: float + minimum_transmission: float + maximum_action: float + valid: bool + notes: tuple[str, ...] + spectral_flux_m2_s_eV: Vector | None = None + left_occupation: Vector | None = None + right_occupation: Vector | None = None + quadrature_weights_eV: Vector | None = None + + +def _channel_flux( + channel: str, + energies: Vector, + transmission: Vector, + left: Vector, + right: Vector, + prefactor: float, + *, + valid: bool, + notes: tuple[str, ...], + quadrature_weights_eV: Vector | None = None, + actions: Vector | None = None, +) -> ChannelFlux: + flux = reciprocal_net_flux( + energies, + transmission, + left, + right, + prefactor, + quadrature_weights_eV=quadrature_weights_eV, + ) + least = float(np.min(flux.transmission)) + return ChannelFlux( + channel=channel, + net_flux_m2_s=flux.net_flux_m2_s, + forward_flux_m2_s=flux.forward_flux_m2_s, + reverse_flux_m2_s=flux.reverse_flux_m2_s, + energies_eV=flux.energies_eV, + transmission=flux.transmission, + maximum_transmission=float(np.max(flux.transmission)), + minimum_transmission=least, + maximum_action=( + float(np.max(actions)) + if actions is not None + else float("inf") if least <= 0.0 else -0.5 * math.log(least) + ), + valid=valid, + notes=notes, + spectral_flux_m2_s_eV=flux.spectral_flux, + left_occupation=flux.left_occupation, + right_occupation=flux.right_occupation, + quadrature_weights_eV=( + frozen_array(quadrature_weights_eV) if quadrature_weights_eV is not None else None + ), + ) + + +@dataclass(frozen=True, slots=True) +class IntrabandBarrierRegion: + """One material barrier and its two adjacent reservoir node ranges.""" + + identity: str + left_start_node: int + core_start_node: int + core_stop_node: int + right_stop_node: int + core_left_m: float + core_right_m: float + + def __post_init__(self) -> None: + if not self.identity: + raise TunnellingChannelError("barrier identity must be non-empty") + if not ( + 0 + <= self.left_start_node + < self.core_start_node + < self.core_stop_node + < self.right_stop_node + ): + raise TunnellingChannelError( + "barrier and reservoir node ranges must be ordered and non-empty" + ) + if ( + not np.isfinite(self.core_left_m) + or not np.isfinite(self.core_right_m) + or self.core_left_m >= self.core_right_m + ): + raise TunnellingChannelError( + "physical barrier boundaries must be finite and ordered" + ) + + +@dataclass(frozen=True, slots=True) +class WKBWindowSupport: + """Active turning-point window vs preallocated reservoir superset.""" + + reservoir_face_slice: tuple[int, int] + reservoir_node_slice: tuple[int, int] + turning_point_face_pairs: tuple[tuple[int, int], ...] + active_face_bounds: tuple[int, int] + active_node_bounds: tuple[int, int] + contained_in_reservoir_superset: bool + support_signature: str + + +@dataclass(frozen=True, slots=True) +class IntrabandPathFlux: + """Path-resolved intraband barrier flux and turning-point support.""" + + region: IntrabandBarrierRegion + flux: ChannelFlux + particle_face_flux_m2_s: Vector + turning_points_m: Matrix + actions: Vector + low_action_supply_fraction: float | None + support: WKBWindowSupport | None = None + + +@dataclass(frozen=True, slots=True) +class IntrabandPathLinearization: + """Exact path flux and analytical Jacobians wrt ``band_edge_eV`` and ``quasi_fermi_eV``.""" + + path: IntrabandPathFlux + d_face_flux_d_barrier_eV: Matrix + d_face_flux_d_quasi_fermi_eV: Matrix + support: WKBWindowSupport + + +@lru_cache(maxsize=32) +def _legendre_energy_rule(order: int) -> tuple[Vector, Vector]: + nodes, weights = np.polynomial.legendre.leggauss(int(order)) + return frozen_array(nodes), frozen_array(weights) + + +def _build_window_support( + region: IntrabandBarrierRegion, + pairs: Sequence[tuple[int, int]], + base_node: int, + peak_node: int, +) -> WKBWindowSupport: + res_faces = (region.left_start_node, region.right_stop_node - 1) + res_nodes = (region.left_start_node, region.right_stop_node) + tup_pairs = tuple((int(a), int(b)) for a, b in pairs) + min_a = min(a for a, _ in tup_pairs) + max_b = max(b for _, b in tup_pairs) + active_faces = (min_a, max_b + 1) + min_node = min(min_a, int(base_node), int(peak_node)) + max_node = max(max_b + 1, int(base_node), int(peak_node)) + 1 + active_nodes = (min_node, max_node) + contained = ( + active_faces[0] >= res_faces[0] + and active_faces[1] <= res_faces[1] + and active_nodes[0] >= res_nodes[0] + and active_nodes[1] <= res_nodes[1] + ) + sig_payload = { + "reservoir_faces": list(res_faces), + "active_faces": list(active_faces), + "active_nodes": list(active_nodes), + "pairs": [list(p) for p in tup_pairs], + } + sig = hashlib.sha256( + json.dumps(sig_payload, separators=(",", ":")).encode("ascii") + ).hexdigest() + return WKBWindowSupport( + reservoir_face_slice=res_faces, + reservoir_node_slice=res_nodes, + turning_point_face_pairs=tup_pairs, + active_face_bounds=active_faces, + active_node_bounds=active_nodes, + contained_in_reservoir_superset=contained, + support_signature=sig, + ) + + +def intraband_path_flux_and_jacobian( + positions_m: ArrayLike, + band_edge_eV: ArrayLike, + channel: IntrabandTunnellingChannel, + *, + region: IntrabandBarrierRegion, + quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + supply_prefactor_m2_s_eV: float = 1.0e24, + compute_jacobian: bool = True, +) -> IntrabandPathLinearization: + """Reciprocal electron transfer across one resolved material barrier + exact Jacobians.""" + if not channel.enabled or channel.carrier != ELECTRON: + raise TunnellingChannelError( + "resolved intraband device transport currently requires one electron channel" + ) + x = np.asarray(positions_m, dtype=float) + barrier = np.asarray(band_edge_eV, dtype=float) + levels = np.asarray(quasi_fermi_eV, dtype=float) + if ( + x.ndim != 1 + or x.size < 3 + or np.any(np.diff(x) <= 0.0) + or barrier.shape != x.shape + or levels.shape != x.shape + or not all(np.all(np.isfinite(value)) for value in (x, barrier, levels)) + ): + raise TunnellingChannelError( + "barrier, physical levels and positions must share a finite increasing grid" + ) + if region.right_stop_node > x.size: + raise TunnellingChannelError("barrier region is outside the electrical grid") + geometry_tolerance = 64.0 * np.finfo(float).eps * max( + float(np.max(np.abs(x))), float(np.ptp(x)) + ) + if ( + abs(float(x[region.core_start_node]) - region.core_left_m) > geometry_tolerance + or abs(float(x[region.core_stop_node]) - region.core_right_m) > geometry_tolerance + ): + raise TunnellingChannelError( + "barrier identity requires its physical boundaries on the nodal grid" + ) + vt = float(thermal_voltage_V) + if not np.isfinite(vt) or vt <= 0.0: + raise TunnellingChannelError("thermal voltage must be finite and positive") + + start, stop = region.core_start_node, region.core_stop_node + peak_node = start + int(np.argmax(barrier[start:stop])) + peak = float(barrier[peak_node]) + left_min_node = region.left_start_node + int( + np.argmin(barrier[region.left_start_node : start]) + ) + right_min_node = stop + int(np.argmin(barrier[stop : region.right_stop_node])) + if float(barrier[left_min_node]) >= float(barrier[right_min_node]): + base_node = left_min_node + else: + base_node = right_min_node + base = float(barrier[base_node]) + if not peak > base: + raise TunnellingChannelError( + "identified barrier has no sub-barrier energy window between its reservoirs" + ) + + nodes_xi, rule_weights = _legendre_energy_rule(channel.energy_quadrature_order) + energies = base + (peak - base) * (nodes_xi + 1.0) / 2.0 + weights = (peak - base) * rule_weights / 2.0 + if np.any(energies >= peak) or np.any(energies <= base): + raise TunnellingChannelError( + "sub-barrier energy interval is below floating-point resolution" + ) + + bounds = np.empty((energies.size, 2), dtype=int) + fractions = np.empty((energies.size, 2), dtype=float) + turning_points = np.empty((energies.size, 2), dtype=float) + left_levels = np.empty(energies.size, dtype=float) + right_levels = np.empty(energies.size, dtype=float) + pairs: list[tuple[int, int]] = [] + + for k, energy in enumerate(energies): + run = forbidden_run(barrier, float(energy), peak_node) + if run is None: + raise TunnellingChannelError( + "turning points do not close inside the declared reservoirs" + ) + low, high = run + if low <= region.left_start_node or high + 1 >= region.right_stop_node: + raise TunnellingChannelError( + "turning points do not close inside the declared reservoirs" + ) + core_forbidden: NDArray[np.intp] = np.flatnonzero(barrier[start:stop] > energy) + start + if np.any((core_forbidden < low) | (core_forbidden > high)): + raise TunnellingChannelError( + "multiple disconnected barriers inside one declared material region" + ) + a, b = low - 1, high + left_fraction = (float(energy) - float(barrier[a])) / float( + barrier[a + 1] - barrier[a] + ) + right_fraction = (float(barrier[b]) - float(energy)) / float( + barrier[b] - barrier[b + 1] + ) + bounds[k] = a, b + pairs.append((a, b)) + fractions[k] = left_fraction, right_fraction + turning_points[k] = ( + float(x[a]) + left_fraction * float(x[a + 1] - x[a]), + float(x[b]) + right_fraction * float(x[b + 1] - x[b]), + ) + left_levels[k] = float(levels[a]) + left_fraction * float( + levels[a + 1] - levels[a] + ) + right_levels[k] = float(levels[b]) + right_fraction * float( + levels[b + 1] - levels[b] + ) + + support = _build_window_support(region, pairs, base_node, peak_node) + if not support.contained_in_reservoir_superset: + raise TunnellingChannelError("active WKB turning-point support escaped reservoir bounds") + + if compute_jacobian: + seg_derivs = piecewise_linear_wkb_segment_action_derivatives( + x, barrier, energies, channel.electron_effective_mass_rel + ) + segment_actions = seg_derivs.segment_actions + else: + seg_derivs = None + segment_actions = piecewise_linear_wkb_segment_actions( + x, barrier, energies, channel.electron_effective_mass_rel + ) + + faces = np.arange(x.size - 1)[None, :] + active = (faces >= bounds[:, :1]) & (faces <= bounds[:, 1:]) + actions = np.sum(np.where(active, segment_actions, 0.0), axis=1) + transmission = np.exp(-2.0 * actions) + left = _fermi(energies, left_levels, vt) + right = _fermi(energies, right_levels, vt) + flux = _channel_flux( + "intraband_electron", + energies, + transmission, + left, + right, + supply_prefactor_m2_s_eV, + valid=bool(np.max(actions) >= MINIMUM_MEANINGFUL_ACTION), + notes=( + "resolved_material_barrier", + "boltzmann_reservoir_levels", + "leading_wkb_exponent", + "supply_prefactor_not_externally_validated", + ), + quadrature_weights_eV=weights, + actions=actions, + ) + assert flux.spectral_flux_m2_s_eV is not None + path_weights = ((faces > bounds[:, :1]) & (faces < bounds[:, 1:])).astype(float) + rows = np.arange(energies.size) + path_weights[rows, bounds[:, 0]] = 1.0 - fractions[:, 0] + path_weights[rows, bounds[:, 1]] = fractions[:, 1] + particle_faces = (weights * flux.spectral_flux_m2_s_eV) @ path_weights + + supply = weights * transmission * (left + right) + denominator = float(np.sum(supply)) + low_action_fraction = ( + float(np.sum(supply[actions < 1.0])) / denominator if denominator > 0.0 else None + ) + + n_nodes = x.size + n_faces = n_nodes - 1 + d_barrier: Matrix = np.zeros((n_faces, n_nodes), dtype=float) if compute_jacobian else np.zeros((0, 0), dtype=float) + d_qf: Matrix = np.zeros((n_faces, n_nodes), dtype=float) if compute_jacobian else np.zeros((0, 0), dtype=float) + + if compute_jacobian: + assert seg_derivs is not None + prefactor = float(supply_prefactor_m2_s_eV) + for k, (a, b) in enumerate(pairs): + fl = float(fractions[k, 0]) + fr = float(fractions[k, 1]) + xi_k = float(nodes_xi[k]) + w_hat_k = float(rule_weights[k]) + w_k = float(weights[k]) + t_k = float(transmission[k]) + f_l = float(left[k]) + f_r = float(right[k]) + delta_occ = f_l - f_r + jk = w_k * prefactor * t_k * delta_occ + + # 1. Energy & weight derivatives wrt U via base_node and peak_node. + de_du = np.zeros(n_nodes, dtype=float) + dw_du = np.zeros(n_nodes, dtype=float) + de_du[base_node] += 0.5 * (1.0 - xi_k) + de_du[peak_node] += 0.5 * (1.0 + xi_k) + dw_du[base_node] -= 0.5 * w_hat_k + dw_du[peak_node] += 0.5 * w_hat_k + + # 2. Active segment action derivatives over faces [a .. b]. + ds_du = np.zeros(n_nodes, dtype=float) + dl_seg = seg_derivs.d_action_d_left_barrier_eV[k, a : b + 1] + dr_seg = seg_derivs.d_action_d_right_barrier_eV[k, a : b + 1] + ds_du[a : b + 1] += dl_seg + ds_du[a + 1 : b + 2] += dr_seg + ds_de = -float(np.sum(dl_seg) + np.sum(dr_seg)) + ds_du += ds_de * de_du + dt_du = -2.0 * t_k * ds_du + + # 3. Crossing-fraction & turning-point Fermi derivatives. + du_l = float(barrier[a + 1] - barrier[a]) + dfl_du = np.zeros(n_nodes, dtype=float) + dfl_du[a] += (fl - 1.0) / du_l + dfl_du[a + 1] -= fl / du_l + dfl_du += de_du / du_l + + du_r = float(barrier[b + 1] - barrier[b]) + dfr_du = np.zeros(n_nodes, dtype=float) + dfr_du[b] += (fr - 1.0) / du_r + dfr_du[b + 1] -= fr / du_r + dfr_du += de_du / du_r + + dmu_l_du = float(levels[a + 1] - levels[a]) * dfl_du + dmu_r_du = float(levels[b + 1] - levels[b]) * dfr_du + + # 4. Occupation derivatives df = f*(1-f)/V_T * (dmu - dE). + df_l_slope = f_l * (1.0 - f_l) / vt + df_r_slope = f_r * (1.0 - f_r) / vt + + ddelta_dqf = np.zeros(n_nodes, dtype=float) + ddelta_dqf[a] += df_l_slope * (1.0 - fl) + ddelta_dqf[a + 1] += df_l_slope * fl + ddelta_dqf[b] -= df_r_slope * (1.0 - fr) + ddelta_dqf[b + 1] -= df_r_slope * fr + + ddelta_du = df_l_slope * (dmu_l_du - de_du) - df_r_slope * (dmu_r_du - de_du) + + djk_dqf = w_k * prefactor * t_k * ddelta_dqf + djk_du = prefactor * ( + dw_du * t_k * delta_occ + + w_k * dt_du * delta_occ + + w_k * t_k * ddelta_du + ) + + # 5. Path-weight scatter across faces a .. b (note b >= a + 1 always). + d_qf[a, :] += (1.0 - fl) * djk_dqf + d_barrier[a, :] += (1.0 - fl) * djk_du - dfl_du * jk + if b > a + 1: + d_qf[a + 1 : b, :] += djk_dqf[None, :] + d_barrier[a + 1 : b, :] += djk_du[None, :] + d_qf[b, :] += fr * djk_dqf + d_barrier[b, :] += fr * djk_du + dfr_du * jk + + path = IntrabandPathFlux( + region=region, + flux=flux, + particle_face_flux_m2_s=frozen_array(particle_faces), + turning_points_m=frozen_array(turning_points), + actions=frozen_array(actions), + low_action_supply_fraction=low_action_fraction, + support=support, + ) + return IntrabandPathLinearization( + path=path, + d_face_flux_d_barrier_eV=frozen_array(d_barrier), + d_face_flux_d_quasi_fermi_eV=frozen_array(d_qf), + support=support, + ) + + +def intraband_path_flux( + positions_m: ArrayLike, + band_edge_eV: ArrayLike, + channel: IntrabandTunnellingChannel, + *, + region: IntrabandBarrierRegion, + quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + supply_prefactor_m2_s_eV: float = 1.0e24, +) -> IntrabandPathFlux: + """Reciprocal electron transfer across one resolved material barrier.""" + return intraband_path_flux_and_jacobian( + positions_m, + band_edge_eV, + channel, + region=region, + quasi_fermi_eV=quasi_fermi_eV, + thermal_voltage_V=thermal_voltage_V, + supply_prefactor_m2_s_eV=supply_prefactor_m2_s_eV, + compute_jacobian=False, + ).path + + +def band_to_band_flux( + positions_m: ArrayLike, + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + channel: BandToBandTunnellingChannel, + *, + anchor_face: int, + quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + supply_prefactor_m2_s_eV: float = 1.0e24, +) -> ChannelFlux: + """Zener tunnelling from the valence band to the conduction band.""" + if not channel.enabled: + raise TunnellingChannelError("band_to_band channel is disabled") + x = np.asarray(positions_m, dtype=float) + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + if conduction.shape != x.shape or valence.shape != x.shape: + raise WKBTunnellingError("band edges must match positions_m") + if np.any(conduction <= valence): + raise TunnellingChannelError( + "band-to-band tunnelling requires a positive gap everywhere" + ) + span = float(x[-1] - x[0]) + if span <= 0.0: + raise WKBTunnellingError("positions_m must span a positive distance") + field_v_m = abs(float(conduction[-1] - conduction[0])) / span + notes: list[str] = [] + if field_v_m < channel.minimum_field_V_m: + notes.append("field_below_channel_minimum") + + lower = float(valence[anchor_face]) + upper = float(conduction[anchor_face]) + energies = np.linspace(lower, upper, channel.energy_quadrature_order + 2)[1:-1] + transmission = np.array( + [ + two_band_transmission( + x, + conduction, + valence, + float(energy), + channel.reduced_effective_mass_rel, + anchor_face, + ) + for energy in energies + ], + dtype=float, + ) + mid = float(energies[len(energies) // 2]) + validity = two_band_validity( + x, + conduction, + valence, + mid, + channel.reduced_effective_mass_rel, + anchor_face, + ) + left_levels, right_levels = _two_band_turning_point_levels( + conduction, valence, energies, anchor_face, quasi_fermi_eV + ) + left = _fermi(energies, left_levels, thermal_voltage_V) + right = _fermi(energies, right_levels, thermal_voltage_V) + if not validity.valid: + notes.append("wkb_action_below_meaningful_barrier") + return _channel_flux( + "band_to_band", + energies, + transmission, + left, + right, + supply_prefactor_m2_s_eV, + valid=validity.valid and not notes, + notes=tuple(notes), + ) + + +def intraband_flux( + positions_m: ArrayLike, + band_edge_eV: ArrayLike, + channel: IntrabandTunnellingChannel, + *, + anchor_face: int, + carrier: str, + quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + supply_prefactor_m2_s_eV: float = 1.0e24, +) -> ChannelFlux: + """Tunnelling through a band-edge spike without changing band.""" + if not channel.enabled: + raise TunnellingChannelError("intraband channel is disabled") + if channel.carrier not in (carrier, "both"): + raise TunnellingChannelError( + f"intraband channel is configured for {channel.carrier!r}, not {carrier!r}" + ) + mass = ( + channel.electron_effective_mass_rel + if carrier == ELECTRON + else channel.hole_effective_mass_rel + ) + x = np.asarray(positions_m, dtype=float) + barrier = np.asarray(band_edge_eV, dtype=float) + if barrier.shape != x.shape: + raise WKBTunnellingError("band edge must match positions_m") + peak, base = local_barrier_window(barrier, anchor_face) + notes: list[str] = [] + if not peak > base: + raise TunnellingChannelError( + "intraband tunnelling requires a local barrier spike at this face" + ) + energies = np.linspace(base, peak, channel.energy_quadrature_order) + transmission = np.array( + [ + windowed_wkb_transmission(x, barrier, float(energy), mass, anchor_face) + for energy in energies + ], + dtype=float, + ) + validity = wkb_validity(x, barrier, float(energies[0]), mass) + if not validity.valid: + notes.append("wkb_action_below_meaningful_barrier") + left_levels, right_levels = _turning_point_levels( + barrier, energies, anchor_face, quasi_fermi_eV + ) + left = _fermi(energies, left_levels, thermal_voltage_V) + right = _fermi(energies, right_levels, thermal_voltage_V) + return _channel_flux( + f"intraband_{carrier}", + energies, + transmission, + left, + right, + supply_prefactor_m2_s_eV, + valid=validity.valid, + notes=tuple(notes), + ) + + +@dataclass(frozen=True, slots=True) +class InterfaceDefectAssistedFlux: + """Trap-assisted tunnelling written against an explicit occupancy.""" + + channel: str + occupancy: float + equilibrium_occupancy: float + electron_transmission: float + hole_transmission: float + electron_net_rate_m2_s: float + hole_net_rate_m2_s: float + net_rate_m2_s: float + occupancy_sensitivity_m2_s: float + stationary_occupancy_residual: float + valid: bool + notes: tuple[str, ...] + + +def interface_defect_assisted_rate( + positions_m: ArrayLike, + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + channel: InterfaceDefectAssistedTunnellingChannel, + *, + anchor_face: int, + trap_energy_eV: float, + occupancy: float | None, + trap_density_m2: float, + electron_capture_velocity_m_s: float, + hole_capture_velocity_m_s: float, + electron_density_m3: float, + hole_density_m3: float, + electron_reference_density_m3: float, + hole_reference_density_m3: float, +) -> InterfaceDefectAssistedFlux: + """Trap-assisted tunnelling consuming the solver's explicit trap occupancy.""" + if not channel.enabled: + raise TunnellingChannelError("interface_defect_assisted channel is disabled") + if occupancy is None: + raise TunnellingChannelCapabilityError( + "interface_defect_assisted requires an explicit interface occupancy; " + "algebraically eliminated steady SRH cannot supply one" + ) + if not 0.0 <= float(occupancy) <= 1.0: + raise TunnellingChannelError("interface occupancy must lie in [0, 1]") + x = np.asarray(positions_m, dtype=float) + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + electron_transmission = windowed_wkb_transmission( + x, + conduction, + float(trap_energy_eV), + channel.electron_effective_mass_rel, + anchor_face, + ) + hole_transmission = windowed_wkb_transmission( + x, + -valence, + -float(trap_energy_eV), + channel.hole_effective_mass_rel, + anchor_face, + ) + notes: list[str] = [] + electron_validity = wkb_validity( + x, conduction, float(trap_energy_eV), channel.electron_effective_mass_rel + ) + if not electron_validity.valid: + notes.append("electron_barrier_below_meaningful_action") + + occupied = float(occupancy) + empty = 1.0 - occupied + electron_net = ( + float(trap_density_m2) + * float(electron_capture_velocity_m_s) + * electron_transmission + * ( + float(electron_density_m3) * empty + - float(electron_reference_density_m3) * occupied + ) + ) + hole_net = ( + float(trap_density_m2) + * float(hole_capture_velocity_m_s) + * hole_transmission + * ( + float(hole_density_m3) * occupied + - float(hole_reference_density_m3) * empty + ) + ) + denominator = float(electron_capture_velocity_m_s) * electron_transmission * ( + float(electron_density_m3) + float(electron_reference_density_m3) + ) + float(hole_capture_velocity_m_s) * hole_transmission * ( + float(hole_density_m3) + float(hole_reference_density_m3) + ) + if denominator <= 0.0: + raise TunnellingChannelError("trap-assisted tunnelling has no active capture leg") + equilibrium = ( + float(electron_capture_velocity_m_s) + * electron_transmission + * float(electron_density_m3) + + float(hole_capture_velocity_m_s) + * hole_transmission + * float(hole_reference_density_m3) + ) / denominator + sensitivity = float(trap_density_m2) * denominator + residual = ( + abs(float(electron_net - hole_net)) / sensitivity + if sensitivity > 0.0 + else math.inf + ) + return InterfaceDefectAssistedFlux( + channel="interface_defect_assisted", + occupancy=occupied, + equilibrium_occupancy=float(equilibrium), + electron_transmission=float(electron_transmission), + hole_transmission=float(hole_transmission), + electron_net_rate_m2_s=float(electron_net), + hole_net_rate_m2_s=float(hole_net), + net_rate_m2_s=float(electron_net - hole_net), + occupancy_sensitivity_m2_s=sensitivity, + stationary_occupancy_residual=residual, + valid=electron_validity.valid, + notes=tuple(notes), + ) + + +def contact_tunnelling_flux( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + channel: ContactTunnellingChannel, + *, + anchor_face: int, + carrier: str, + metal_fermi_eV: float, + quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + richardson_prefactor_m2_s_eV: float = 1.0e24, +) -> ChannelFlux: + """Field emission through a Schottky barrier at an outer contact.""" + if not channel.enabled: + raise TunnellingChannelError("contact channel is disabled") + mass = ( + channel.electron_effective_mass_rel + if carrier == ELECTRON + else channel.hole_effective_mass_rel + ) + x = np.asarray(positions_m, dtype=float) + barrier = np.asarray(barrier_eV, dtype=float) + if barrier.shape != x.shape: + raise WKBTunnellingError("barrier profile must match positions_m") + peak, base = local_barrier_window(barrier, anchor_face, one_sided=True) + if not peak > base: + raise TunnellingChannelError( + "contact tunnelling requires a barrier above the contact level" + ) + energies = np.linspace(base, peak, channel.energy_quadrature_order) + transmission = np.array( + [ + windowed_wkb_transmission(x, barrier, float(energy), mass, anchor_face) + for energy in energies + ], + dtype=float, + ) + validity = wkb_validity(x, barrier, float(energies[0]), mass) + notes: list[str] = [] + if not validity.valid: + notes.append("wkb_action_below_meaningful_barrier") + metal = _fermi(energies, metal_fermi_eV, thermal_voltage_V) + _, semiconductor_levels = _turning_point_levels( + barrier, energies, anchor_face, quasi_fermi_eV + ) + semiconductor = _fermi(energies, semiconductor_levels, thermal_voltage_V) + return _channel_flux( + f"contact_{carrier}", + energies, + transmission, + metal, + semiconductor, + richardson_prefactor_m2_s_eV, + valid=validity.valid, + notes=tuple(notes), + ) + + +@dataclass(frozen=True, slots=True) +class CompiledTunnellingChannels: + """Static part of the tunnelling family bound to one electrical grid.""" + + document: TunnellingChannelDocument + node_count: int + interface_faces: tuple[int, ...] + left_contact_face: int + right_contact_face: int + intraband_barrier: IntrabandBarrierRegion | None = None + + def __post_init__(self) -> None: + if not isinstance(self.document, TunnellingChannelDocument): + raise TypeError("document must be a TunnellingChannelDocument") + if self.node_count < 3: + raise TunnellingChannelCapabilityError( + "tunnelling channels need at least three electrical nodes" + ) + faces = tuple(int(face) for face in self.interface_faces) + if any(face < 0 or face >= self.node_count - 1 for face in faces): + raise TunnellingChannelCapabilityError( + "interface face index is outside the transport faces" + ) + object.__setattr__(self, "interface_faces", faces) + + @property + def any_enabled(self) -> bool: + return self.document.any_enabled + + @property + def enabled_channels(self) -> tuple[str, ...]: + return self.document.enabled_channels + + @property + def identity_sha256(self) -> str: + return self.document.sha256 + + def digest(self) -> str: + payload = { + "version": TUNNELLING_CHANNEL_DEVICE_VERSION, + "document_sha256": self.document.sha256, + "node_count": self.node_count, + "interface_faces": list(self.interface_faces), + "intraband_barrier": ( + None + if self.intraband_barrier is None + else { + "identity": self.intraband_barrier.identity, + "left_start_node": self.intraband_barrier.left_start_node, + "core_start_node": self.intraband_barrier.core_start_node, + "core_stop_node": self.intraband_barrier.core_stop_node, + "right_stop_node": self.intraband_barrier.right_stop_node, + "core_left_m": repr(self.intraband_barrier.core_left_m), + "core_right_m": repr(self.intraband_barrier.core_right_m), + } + ), + } + return _sha256(payload) + + +def compile_tunnelling_channels( + document: TunnellingChannelDocument | None, + *, + node_count: int, + interface_nodes: tuple[int, ...], + positions_m: ArrayLike | None = None, + physical_affinity_eV: ArrayLike | None = None, + layer_names: tuple[str, ...] | None = None, + layer_boundaries_m: ArrayLike | None = None, + driver: str = "quasi_fermi_steady_state", +) -> CompiledTunnellingChannels | None: + """Bind a channel document to an electrical grid, enforcing scope pre-solve.""" + if document is None or not document.any_enabled: + return None + if driver != "quasi_fermi_steady_state": + raise TunnellingChannelCapabilityError( + f"WKB tunnelling channels are certified only for driver='quasi_fermi_steady_state', got {driver!r}" + ) + if document.enabled_channels != (INTRABAND,) or document.intraband.carrier != ELECTRON: + raise TunnellingChannelCapabilityError( + "device tunnelling v2 supports one intraband electron channel; " + "hole, contact, band-to-band and defect-assisted occupancy coupling " + "require their own conservative device validation" + ) + faces = tuple(int(node) - 1 for node in interface_nodes) + if not faces: + raise TunnellingChannelCapabilityError( + "interface-bound tunnelling channels need at least one heterointerface on this stack" + ) + compiled = CompiledTunnellingChannels( + document=document, + node_count=int(node_count), + interface_faces=faces, + left_contact_face=0, + right_contact_face=int(node_count) - 2, + ) + if positions_m is not None: + if any(value is None for value in (physical_affinity_eV, layer_names, layer_boundaries_m)): + raise TunnellingChannelCapabilityError( + "material barrier identity needs layer geometry and physical affinity" + ) + assert physical_affinity_eV is not None + assert layer_names is not None + assert layer_boundaries_m is not None + x = np.asarray(positions_m, dtype=float) + affinity = np.asarray(physical_affinity_eV, dtype=float) + boundaries = np.asarray(layer_boundaries_m, dtype=float) + if ( + x.shape != (node_count,) + or affinity.shape != x.shape + or not np.all(np.isfinite(affinity)) + or np.any(np.diff(x) <= 0.0) + or len(layer_names) != len(interface_nodes) + 1 + or boundaries.shape != (len(layer_names) + 1,) + ): + raise TunnellingChannelCapabilityError( + "barrier geometry does not match the layer grid" + ) + nodes = (0, *interface_nodes, node_count) + if any(left_i >= right_i for left_i, right_i in zip(nodes[:-1], nodes[1:])): + raise TunnellingChannelCapabilityError( + "material layer node ranges must be strictly ordered" + ) + candidates: list[IntrabandBarrierRegion] = [] + for layer_index in range(1, len(layer_names) - 1): + start, stop = nodes[layer_index], nodes[layer_index + 1] + if affinity[start] < affinity[start - 1] and affinity[stop - 1] < affinity[stop]: + if stop - start < 3: + raise TunnellingChannelCapabilityError( + "resolved intraband barrier requires at least three barrier nodes" + ) + candidates.append( + IntrabandBarrierRegion( + identity=f"electrical_layer[{layer_index}]:{layer_names[layer_index]}", + left_start_node=nodes[layer_index - 1], + core_start_node=start, + core_stop_node=stop, + right_stop_node=nodes[layer_index + 2], + core_left_m=float(boundaries[layer_index]), + core_right_m=float(boundaries[layer_index + 1]), + ) + ) + if len(candidates) != 1: + raise TunnellingChannelCapabilityError( + "intraband device transport requires one isolated material conduction-band spike; " + f"found {len(candidates)}" + ) + compiled = replace(compiled, intraband_barrier=candidates[0]) + return compiled + + +@dataclass(frozen=True, slots=True) +class TunnellingChannelEvaluation: + """Per-face tunnelling currents plus per-channel diagnostics and linearization.""" + + identity_sha256: str + electron_face_flux_m2_s: Vector + electron_face_current_A_m2: Vector + hole_face_current_A_m2: Vector + electron_nodal_transfer_m2_s: Vector + channel_names: tuple[str, ...] + channel_net_flux_m2_s: tuple[float, ...] + channel_maximum_transmission: tuple[float, ...] + channel_minimum_transmission: tuple[float, ...] + channel_valid: tuple[bool, ...] + channel_notes: tuple[tuple[str, ...], ...] + defect_assisted_occupancy: float | None = None + defect_assisted_residual: float | None = None + intraband_path: IntrabandPathFlux | None = None + linearization: IntrabandPathLinearization | None = None + implementation_version: str = TUNNELLING_CHANNEL_DEVICE_VERSION + + +def physical_quasi_fermi_levels_eV( + *, + potential_V: ArrayLike, + affinity_eV: ArrayLike, + band_gap_eV: ArrayLike, + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + conduction_dos_m3: ArrayLike | None, + valence_dos_m3: ArrayLike | None, + thermal_voltage_V: float, +) -> tuple[Vector, Vector]: + """Physical ``(E_Fn, E_Fp)`` [eV] for Boltzmann carrier populations.""" + if conduction_dos_m3 is None or valence_dos_m3 is None: + raise TunnellingChannelCapabilityError( + "physical Nc/Nv are required for tunnelling occupations" + ) + arrays = tuple( + np.asarray(value, dtype=float) + for value in ( + potential_V, + affinity_eV, + band_gap_eV, + electron_density_m3, + hole_density_m3, + conduction_dos_m3, + valence_dos_m3, + ) + ) + potential, affinity, gap, electrons, holes, nc, nv = arrays + if ( + potential.ndim != 1 + or not potential.size + or any(value.shape != potential.shape for value in arrays) + ): + raise TunnellingChannelCapabilityError( + "physical level inputs must share one nodal grid" + ) + if not all(np.all(np.isfinite(value)) for value in arrays): + raise TunnellingChannelCapabilityError( + "physical bands, densities and Nc/Nv must be finite" + ) + if any(np.any(value <= 0.0) for value in (electrons, holes, nc, nv)): + raise TunnellingChannelCapabilityError( + "positive carrier densities and Nc/Nv are required" + ) + thermal = float(thermal_voltage_V) + if not math.isfinite(thermal) or thermal <= 0.0: + raise TunnellingChannelCapabilityError("thermal voltage must be finite and positive") + conduction = -(potential + affinity) + electron_level = conduction + thermal * (np.log(electrons) - np.log(nc)) + hole_level = conduction - gap - thermal * (np.log(holes) - np.log(nv)) + return electron_level, hole_level + + +def evaluate_tunnelling_channels( + compiled: CompiledTunnellingChannels, + *, + positions_m: ArrayLike, + potential_V: ArrayLike, + affinity_eV: ArrayLike, + band_gap_eV: ArrayLike, + electron_quasi_fermi_eV: ArrayLike, + hole_quasi_fermi_eV: ArrayLike, + thermal_voltage_V: float, + derivatives: bool = False, +) -> TunnellingChannelEvaluation: + """Evaluate the resolved electron path; other device couplings fail explicitly.""" + document = compiled.document + if document.enabled_channels != (INTRABAND,) or document.intraband.carrier != ELECTRON: + raise TunnellingChannelCapabilityError( + "device tunnelling v2 supports one intraband electron channel; " + "hole, contact, band-to-band and defect-assisted occupancy coupling " + "require their own conservative device validation" + ) + if compiled.intraband_barrier is None: + raise TunnellingChannelCapabilityError( + "intraband channel requires compiled material and reservoir geometry" + ) + x = np.asarray(positions_m, dtype=float) + potential = np.asarray(potential_V, dtype=float) + affinity = np.asarray(affinity_eV, dtype=float) + gap = np.asarray(band_gap_eV, dtype=float) + qfn = np.asarray(electron_quasi_fermi_eV, dtype=float) + qfp = np.asarray(hole_quasi_fermi_eV, dtype=float) + if x.shape != (compiled.node_count,) or any( + value.shape != x.shape for value in (potential, affinity, gap, qfn, qfp) + ): + raise TunnellingChannelCapabilityError( + "physical tunnelling inputs must share the compiled electrical grid" + ) + if not all(np.all(np.isfinite(value)) for value in (potential, affinity, gap, qfn, qfp)): + raise TunnellingChannelCapabilityError( + "physical tunnelling bands and levels must be finite" + ) + try: + lin = intraband_path_flux_and_jacobian( + x, + -(potential + affinity), + document.intraband, + region=compiled.intraband_barrier, + quasi_fermi_eV=qfn, + thermal_voltage_V=thermal_voltage_V, + compute_jacobian=derivatives, + ) + except TunnellingChannelError as exc: + raise TunnellingChannelCapabilityError( + f"resolved intraband channel failed: {exc}" + ) from exc + path = lin.path + flux = path.flux + if not flux.valid: + raise TunnellingChannelCapabilityError( + "identified barrier has no meaningful WKB action" + ) + face_flux = path.particle_face_flux_m2_s + electron_current = -Q * face_flux + if not np.all(np.isfinite(electron_current)): + raise TunnellingChannelCapabilityError( + "tunnelling produced a non-finite face current" + ) + nodal_transfer = np.zeros(x.size, dtype=float) + nodal_transfer[:-1] -= face_flux + nodal_transfer[1:] += face_flux + return TunnellingChannelEvaluation( + identity_sha256=compiled.identity_sha256, + electron_face_flux_m2_s=face_flux, + electron_face_current_A_m2=frozen_array(electron_current), + hole_face_current_A_m2=frozen_array(np.zeros(x.size - 1)), + electron_nodal_transfer_m2_s=frozen_array(nodal_transfer), + channel_names=(flux.channel,), + channel_net_flux_m2_s=(flux.net_flux_m2_s,), + channel_maximum_transmission=(flux.maximum_transmission,), + channel_minimum_transmission=(flux.minimum_transmission,), + channel_valid=(flux.valid,), + channel_notes=(flux.notes,), + defect_assisted_occupancy=None, + defect_assisted_residual=None, + intraband_path=path, + linearization=lin if derivatives else None, + ) diff --git a/src/solarlab/physics/transport/wkb_tunneling.py b/src/solarlab/physics/transport/wkb_tunneling.py new file mode 100644 index 00000000..34bb09cf --- /dev/null +++ b/src/solarlab/physics/transport/wkb_tunneling.py @@ -0,0 +1,744 @@ +"""One-dimensional WKB barrier integrals, analytical tangents, and TFE scaling. + +Provides two distinct, explicitly separated quantum-tunnelling primitives: + +1. ``tfe_gamma``: static Padovani-Stratton thermionic-field-emission (TFE) + Richardson-constant enhancement ``Gamma >= 1`` built once from geometry and + doping (never representing nonlocal WKB barrier transmission). +2. Resolved 1D WKB and two-band Kane action / transmission / turning-point / + reciprocal-flux kernels, together with cancellation-free analytical + derivatives ``piecewise_linear_wkb_segment_action_derivatives`` of every + piecewise-linear segment action wrt the nodal barrier potential. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.arrays import frozen_array +from solarlab.contracts.units import ELEMENTARY_CHARGE_C + +__all__ = [ + "ELECTRON_MASS_KG", + "HBAR_J_S", + "MINIMUM_MEANINGFUL_ACTION", + "VACUUM_PERMITTIVITY_F_M", + "ReciprocalFlux", + "WKBSegmentActionDerivatives", + "WKBTunnellingError", + "WKBValidity", + "decay_constant_per_m", + "forbidden_run", + "kane_uniform_field_action", + "piecewise_linear_wkb_segment_action_derivatives", + "piecewise_linear_wkb_segment_actions", + "reciprocal_net_flux", + "tfe_gamma", + "triangular_barrier_action", + "turning_point_levels", + "turning_point_nodes", + "two_band_action", + "two_band_decay_constant_per_m", + "two_band_transmission", + "two_band_turning_point_levels", + "two_band_turning_point_nodes", + "two_band_validity", + "windowed_wkb_action", + "windowed_wkb_transmission", + "wkb_action", + "wkb_transmission", + "wkb_validity", +] + +Vector: TypeAlias = NDArray[np.float64] +Matrix: TypeAlias = NDArray[np.float64] + +Q: float = ELEMENTARY_CHARGE_C +HBAR_J_S: float = 1.054571817e-34 +ELECTRON_MASS_KG: float = 9.1093837015e-31 +VACUUM_PERMITTIVITY_F_M: float = 8.854187817e-12 +MINIMUM_MEANINGFUL_ACTION: float = 1.0e-3 + + +class WKBTunnellingError(ValueError): + """A barrier profile or effective mass was outside the WKB domain.""" + + +def _positive(value: object, field: str) -> float: + if isinstance(value, bool): + raise TypeError(f"{field} must be a real number") + try: + result = float(value) # type: ignore[arg-type] + except (TypeError, ValueError) as exc: + raise TypeError(f"{field} must be a real number") from exc + if not math.isfinite(result) or result <= 0.0: + raise WKBTunnellingError(f"{field} must be finite and positive") + return result + + +def _coth_positive(z: float) -> float: + if z > 40.0: + return 1.0 + if z < 1.0e-8: + return 1.0 / z + return 1.0 / math.tanh(z) + + +def tfe_gamma( + delta_E_eV: float, + N_iface: float, + m_eff_rel: float, + eps_r: float, + V_T: float, +) -> float: + """Static Padovani-Stratton TFE Richardson enhancement ``Gamma >= 1``.""" + d_e = abs(float(delta_E_eV)) + n_if = float(N_iface) + m_rel = float(m_eff_rel) + eps = float(eps_r) + vt = float(V_T) + if n_if <= 0.0 or m_rel <= 0.0 or eps <= 0.0 or d_e <= 0.0 or vt <= 0.0: + return 1.0 + eps_s = eps * VACUUM_PERMITTIVITY_F_M + e00_j = (Q * HBAR_J_S / 2.0) * math.sqrt(n_if / (m_rel * ELECTRON_MASS_KG * eps_s)) + e00 = e00_j / Q + e0 = e00 * _coth_positive(e00 / vt) + delta_tun = d_e * (1.0 - vt / e0) + if delta_tun <= 0.0: + return 1.0 + if delta_tun >= d_e: + delta_tun = d_e * (1.0 - 1.0e-9) + return math.exp(delta_tun / vt) + + +def decay_constant_per_m( + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, +) -> Vector: + """Return ``kappa(x)`` in 1/m, zero where the carrier is not forbidden.""" + mass = _positive(effective_mass_rel, "effective_mass_rel") + barrier = np.asarray(barrier_eV, dtype=float) + if not np.all(np.isfinite(barrier)): + raise WKBTunnellingError("barrier profile must be finite") + if not math.isfinite(float(energy_eV)): + raise WKBTunnellingError("energy_eV must be finite") + forbidden = np.maximum(barrier - float(energy_eV), 0.0) + return np.sqrt(2.0 * mass * ELECTRON_MASS_KG * forbidden * Q) / HBAR_J_S + + +def piecewise_linear_wkb_segment_actions( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energies_eV: ArrayLike, + effective_mass_rel: float, +) -> Matrix: + """Exact actions per energy/segment for the linearly interpolated band.""" + x = np.asarray(positions_m, dtype=float) + barrier = np.asarray(barrier_eV, dtype=float) + energies = np.asarray(energies_eV, dtype=float) + if ( + x.ndim != 1 + or x.size < 2 + or not np.all(np.isfinite(x)) + or np.any(np.diff(x) <= 0.0) + or not np.all(np.isfinite(np.diff(x))) + ): + raise WKBTunnellingError("positions_m must be finite and strictly increase on a 1-D grid") + if barrier.shape != x.shape or not np.all(np.isfinite(barrier)): + raise WKBTunnellingError("finite barrier profile must match positions_m") + if energies.ndim != 1 or not np.all(np.isfinite(energies)): + raise WKBTunnellingError("energies_eV must be a finite 1-D vector") + mass = _positive(effective_mass_rel, "effective_mass_rel") + left = barrier[:-1][None, :] - energies[:, None] + right = barrier[1:][None, :] - energies[:, None] + if not np.all(np.isfinite(left)) or not np.all(np.isfinite(right)): + raise WKBTunnellingError("barrier-energy differences must be finite") + root_left = np.sqrt(np.maximum(left, 0.0)) + root_right = np.sqrt(np.maximum(right, 0.0)) + root_sum = root_left + root_right + ratio = np.divide(root_right, root_sum, out=np.zeros_like(root_sum), where=root_sum > 0.0) + mean_root = (2.0 / 3.0) * (root_sum - root_left * ratio) + crossing = ((left < 0.0) & (right > 0.0)) | ((left > 0.0) & (right < 0.0)) + positive = np.maximum(left[crossing], right[crossing]) + negative = -np.minimum(left[crossing], right[crossing]) + with np.errstate(over="ignore"): + forbidden_fraction = 1.0 / (1.0 + negative / positive) + mean_root[crossing] *= forbidden_fraction + prefactor = math.sqrt(2.0 * mass * ELECTRON_MASS_KG * Q) / HBAR_J_S + return prefactor * mean_root * np.diff(x)[None, :] + + +@dataclass(frozen=True) +class WKBSegmentActionDerivatives: + """Segment actions ``I_{k,m}`` and exact partials ``dI_{k,m}/dU_m``, ``dI_{k,m}/dU_{m+1}`` [eV^-1].""" + + segment_actions: Matrix + d_action_d_left_barrier_eV: Matrix + d_action_d_right_barrier_eV: Matrix + + +def piecewise_linear_wkb_segment_action_derivatives( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energies_eV: ArrayLike, + effective_mass_rel: float, +) -> WKBSegmentActionDerivatives: + """Exact cancellation-free segment actions and derivatives wrt nodal ``barrier_eV``.""" + actions = piecewise_linear_wkb_segment_actions( + positions_m, barrier_eV, energies_eV, effective_mass_rel + ) + x = np.asarray(positions_m, dtype=float) + barrier = np.asarray(barrier_eV, dtype=float) + energies = np.asarray(energies_eV, dtype=float) + mass = _positive(effective_mass_rel, "effective_mass_rel") + + prefactor = math.sqrt(2.0 * mass * ELECTRON_MASS_KG * Q) / HBAR_J_S + scale = np.broadcast_to((prefactor * np.diff(x))[None, :], actions.shape) + u_left = barrier[:-1][None, :] - energies[:, None] + u_right = barrier[1:][None, :] - energies[:, None] + + d_left: Matrix = np.zeros_like(actions) + d_right: Matrix = np.zeros_like(actions) + + both = (u_left > 0.0) & (u_right > 0.0) + if np.any(both): + a = np.sqrt(u_left[both]) + b = np.sqrt(u_right[both]) + apb = a + b + inv_denom = 1.0 / (3.0 * apb * apb) + d_left[both] = scale[both] * (a + 2.0 * b) * inv_denom + d_right[both] = scale[both] * (b + 2.0 * a) * inv_denom + + left_cross = (u_left <= 0.0) & (u_right > 0.0) + if np.any(left_cross): + l_val = u_left[left_cross] + r_val = u_right[left_cross] + b = np.sqrt(r_val) + rml = r_val - l_val + inv_sq = 1.0 / (3.0 * rml * rml) + d_left[left_cross] = 2.0 * scale[left_cross] * (r_val * b) * inv_sq + d_right[left_cross] = scale[left_cross] * b * (r_val - 3.0 * l_val) * inv_sq + + right_cross = (u_left > 0.0) & (u_right <= 0.0) + if np.any(right_cross): + l_val = u_left[right_cross] + r_val = u_right[right_cross] + a = np.sqrt(l_val) + lmr = l_val - r_val + inv_sq = 1.0 / (3.0 * lmr * lmr) + d_left[right_cross] = scale[right_cross] * a * (l_val - 3.0 * r_val) * inv_sq + d_right[right_cross] = 2.0 * scale[right_cross] * (l_val * a) * inv_sq + + return WKBSegmentActionDerivatives(actions, d_left, d_right) + + +def wkb_action( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, +) -> float: + """Integrate ``kappa`` over the classically forbidden region.""" + actions = piecewise_linear_wkb_segment_actions( + positions_m, barrier_eV, np.array([float(energy_eV)]), effective_mass_rel + ) + return float(np.sum(actions[0])) + + +def forbidden_run( + barrier_eV: ArrayLike, + energy_eV: float, + anchor_face: int, +) -> tuple[int, int] | None: + """Return the connected forbidden interval ``(low, high)`` containing ``anchor_face``.""" + barrier = np.asarray(barrier_eV, dtype=float) + if barrier.ndim != 1 or barrier.size < 2: + raise WKBTunnellingError("barrier profile must be a 1-D grid") + face = int(anchor_face) + if face < 0 or face >= barrier.size - 1: + raise WKBTunnellingError("anchor_face is outside the transport faces") + forbidden = barrier > float(energy_eV) + if not (forbidden[face] or forbidden[face + 1]): + return None + start = face if forbidden[face] else face + 1 + low = start + while low - 1 >= 0 and forbidden[low - 1]: + low -= 1 + high = start + while high + 1 < barrier.size and forbidden[high + 1]: + high += 1 + return low, high + + +def turning_point_nodes( + barrier_eV: ArrayLike, + energy_eV: float, + anchor_face: int, +) -> tuple[int, int]: + """Allowed nodes flanking the forbidden run containing ``anchor_face``.""" + barrier = np.asarray(barrier_eV, dtype=float) + face = int(anchor_face) + bounds = forbidden_run(barrier, energy_eV, face) + if bounds is None: + return face, face + 1 + low, high = bounds + return max(low - 1, 0), min(high + 1, barrier.size - 1) + + +def two_band_turning_point_nodes( + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + energy_eV: float, + anchor_face: int, +) -> tuple[int, int]: + """Allowed nodes flanking the in-gap run containing ``anchor_face``.""" + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + if conduction.shape != valence.shape: + raise WKBTunnellingError("band edges must share one grid") + face = int(anchor_face) + if face < 0 or face >= conduction.size - 1: + raise WKBTunnellingError("anchor_face is outside the transport faces") + energy = float(energy_eV) + inside = (conduction > energy) & (valence < energy) + if not (inside[face] or inside[face + 1]): + return face, face + 1 + start = face if inside[face] else face + 1 + low = start + while low - 1 >= 0 and inside[low - 1]: + low -= 1 + high = start + while high + 1 < conduction.size and inside[high + 1]: + high += 1 + return max(low - 1, 0), min(high + 1, conduction.size - 1) + + +def _interpolate_at_crossing( + barrier: Vector, + profile: Vector, + energy: float, + allowed: int, + forbidden: int, +) -> float: + low_value = float(barrier[allowed]) + high_value = float(barrier[forbidden]) + span = high_value - low_value + if not math.isfinite(span) or span == 0.0: + return float(profile[allowed]) + fraction = min(max((float(energy) - low_value) / span, 0.0), 1.0) + return float(profile[allowed] + fraction * (profile[forbidden] - profile[allowed])) + + +def turning_point_levels( + barrier_eV: ArrayLike, + profile_eV: ArrayLike, + energy_eV: float, + anchor_face: int, +) -> tuple[float, float]: + """``profile_eV`` linearly interpolated at the two turning points of ``anchor_face``.""" + barrier = np.asarray(barrier_eV, dtype=float) + profile = np.asarray(profile_eV, dtype=float) + if barrier.shape != profile.shape: + raise WKBTunnellingError("profile must share the barrier grid") + face = int(anchor_face) + bounds = forbidden_run(barrier, energy_eV, face) + if bounds is None: + return float(profile[face]), float(profile[face + 1]) + low, high = bounds + energy = float(energy_eV) + left = ( + _interpolate_at_crossing(barrier, profile, energy, low - 1, low) + if low - 1 >= 0 + else float(profile[low]) + ) + right = ( + _interpolate_at_crossing(barrier, profile, energy, high + 1, high) + if high + 1 < barrier.size + else float(profile[high]) + ) + return left, right + + +def two_band_turning_point_levels( + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + profile_eV: ArrayLike, + energy_eV: float, + anchor_face: int, +) -> tuple[float, float]: + """``profile_eV`` interpolated at the opposite-band turning points of ``anchor_face``.""" + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + profile = np.asarray(profile_eV, dtype=float) + if not (conduction.shape == valence.shape == profile.shape): + raise WKBTunnellingError("band edges and profile must share one grid") + low, high = two_band_turning_point_nodes(conduction, valence, energy_eV, anchor_face) + energy = float(energy_eV) + left = ( + _interpolate_at_crossing(conduction, profile, energy, low, min(low + 1, conduction.size - 1)) + if low + 1 < conduction.size + else float(profile[low]) + ) + right = ( + _interpolate_at_crossing(valence, profile, energy, high, max(high - 1, 0)) + if high - 1 >= 0 + else float(profile[high]) + ) + return left, right + + +def windowed_wkb_action( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, + anchor_face: int, +) -> float: + """WKB action over the forbidden run containing ``anchor_face`` only.""" + bounds = forbidden_run(barrier_eV, energy_eV, anchor_face) + if bounds is None: + return 0.0 + low, high = bounds + x = np.asarray(positions_m, dtype=float) + low = max(low - 1, 0) + high = min(high + 1, x.size - 1) + return wkb_action( + x[low : high + 1], + np.asarray(barrier_eV, dtype=float)[low : high + 1], + energy_eV, + effective_mass_rel, + ) + + +def two_band_decay_constant_per_m( + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + energy_eV: float, + reduced_effective_mass_rel: float, +) -> Vector: + """Kane two-band decay constant inside the forbidden gap.""" + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + if conduction.shape != valence.shape: + raise WKBTunnellingError("band edges must share one grid") + mass = _positive(reduced_effective_mass_rel, "reduced_effective_mass_rel") + gap = conduction - valence + if np.any(gap <= 0.0): + raise WKBTunnellingError("the gap must be positive on the whole grid") + energy = float(energy_eV) + inside = (conduction > energy) & (valence < energy) + kappa = np.zeros_like(conduction) + if not np.any(inside): + return kappa + numerator = (conduction[inside] - energy) * (energy - valence[inside]) / gap[inside] + kappa[inside] = np.sqrt(2.0 * mass * ELECTRON_MASS_KG * numerator * Q) / HBAR_J_S + return kappa + + +def two_band_action( + positions_m: ArrayLike, + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + energy_eV: float, + reduced_effective_mass_rel: float, + anchor_face: int, +) -> float: + """Kane action over the in-gap run containing ``anchor_face``.""" + conduction = np.asarray(conduction_edge_eV, dtype=float) + valence = np.asarray(valence_edge_eV, dtype=float) + x = np.asarray(positions_m, dtype=float) + if conduction.shape != x.shape or valence.shape != x.shape: + raise WKBTunnellingError("band edges must match positions_m") + if x.ndim != 1 or x.size < 2: + raise WKBTunnellingError("positions_m must be a 1-D grid") + if np.any(np.diff(x) <= 0.0): + raise WKBTunnellingError("positions_m must strictly increase") + face = int(anchor_face) + if face < 0 or face >= x.size - 1: + raise WKBTunnellingError("anchor_face is outside the transport faces") + energy = float(energy_eV) + inside = (conduction > energy) & (valence < energy) + if not (inside[face] or inside[face + 1]): + return 0.0 + start = face if inside[face] else face + 1 + low = start + while low - 1 >= 0 and inside[low - 1]: + low -= 1 + high = start + while high + 1 < x.size and inside[high + 1]: + high += 1 + if high - low < 1: + return 0.0 + kappa = two_band_decay_constant_per_m( + conduction[low : high + 1], + valence[low : high + 1], + energy, + reduced_effective_mass_rel, + ) + return float(np.trapezoid(kappa, x[low : high + 1])) + + +def two_band_transmission( + positions_m: ArrayLike, + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + energy_eV: float, + reduced_effective_mass_rel: float, + anchor_face: int, +) -> float: + """Two-band transmission ``exp(-2 S)`` for band-to-band tunnelling.""" + return math.exp( + -2.0 + * two_band_action( + positions_m, + conduction_edge_eV, + valence_edge_eV, + energy_eV, + reduced_effective_mass_rel, + anchor_face, + ) + ) + + +def kane_uniform_field_action( + band_gap_eV: float, + field_V_m: float, + reduced_effective_mass_rel: float, +) -> float: + """Closed-form Kane action ``pi sqrt(2 m_r) E_g^{3/2} / (8 hbar q F)``.""" + gap = _positive(band_gap_eV, "band_gap_eV") + field = _positive(field_V_m, "field_V_m") + mass = _positive(reduced_effective_mass_rel, "reduced_effective_mass_rel") + gap_j = gap * Q + return ( + math.pi + * math.sqrt(2.0 * mass * ELECTRON_MASS_KG) + * gap_j**1.5 + / (8.0 * HBAR_J_S * Q * field) + ) + + +def windowed_wkb_transmission( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, + anchor_face: int, +) -> float: + """Transmission through the forbidden run containing ``anchor_face``.""" + action = windowed_wkb_action( + positions_m, barrier_eV, energy_eV, effective_mass_rel, anchor_face + ) + return math.exp(-2.0 * action) + + +def wkb_transmission( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, +) -> float: + """Transmission ``exp(-2 S)`` for one energy, bounded in ``(0, 1]``.""" + action = wkb_action(positions_m, barrier_eV, energy_eV, effective_mass_rel) + if not math.isfinite(action) or action < 0.0: + raise WKBTunnellingError("WKB action must be finite and non-negative") + return math.exp(-2.0 * action) + + +def triangular_barrier_action( + height_eV: float, + width_m: float, + effective_mass_rel: float, + energy_eV: float = 0.0, +) -> float: + """Closed-form Fowler-Nordheim action for ``U(x) = U0 (1 - x / w)``.""" + height = _positive(height_eV, "height_eV") + width = _positive(width_m, "width_m") + mass = _positive(effective_mass_rel, "effective_mass_rel") + energy = float(energy_eV) + if not math.isfinite(energy) or energy >= height: + raise WKBTunnellingError("energy_eV must be finite and below the barrier") + prefactor = math.sqrt(2.0 * mass * ELECTRON_MASS_KG * Q) / HBAR_J_S + return (2.0 / 3.0) * prefactor * (height - energy) ** 1.5 / height * width + + +@dataclass(frozen=True, slots=True) +class WKBValidity: + """Diagnostics describing whether WKB is meaningful for this barrier.""" + + action: float + transmission: float + maximum_wavelength_gradient: float + forbidden_width_m: float + meaningful_barrier: bool + slowly_varying: bool + + @property + def valid(self) -> bool: + return bool(self.meaningful_barrier) + + +def _validity_from_kappa( + positions_m: ArrayLike, + kappa: Vector, + action: float, + *, + maximum_wavelength_gradient: float, + turning_point_fraction: float, +) -> WKBValidity: + x = np.asarray(positions_m, dtype=float) + forbidden = kappa > 0.0 + width = float(np.sum(np.diff(x)[forbidden[:-1] & forbidden[1:]])) + gradient = 0.0 + peak = float(np.max(kappa)) if kappa.size else 0.0 + if peak > 0.0: + fraction = float(turning_point_fraction) + if not 0.0 < fraction < 1.0: + raise WKBTunnellingError("turning_point_fraction must lie in (0, 1)") + core = kappa >= fraction * peak + interior = core[:-1] & core[1:] + if np.any(interior): + wavelength = np.zeros_like(kappa) + wavelength[core] = 1.0 / kappa[core] + gradient = float( + np.max(np.abs(np.diff(wavelength)[interior] / np.diff(x)[interior])) + ) + return WKBValidity( + action=float(action), + transmission=math.exp(-2.0 * float(action)), + maximum_wavelength_gradient=gradient, + forbidden_width_m=width, + meaningful_barrier=bool(action >= MINIMUM_MEANINGFUL_ACTION), + slowly_varying=bool(gradient <= float(maximum_wavelength_gradient)), + ) + + +def wkb_validity( + positions_m: ArrayLike, + barrier_eV: ArrayLike, + energy_eV: float, + effective_mass_rel: float, + *, + maximum_wavelength_gradient: float = 1.0, + turning_point_fraction: float = 0.1, +) -> WKBValidity: + """Semiclassical validity diagnostics for a single-band barrier.""" + kappa = decay_constant_per_m(barrier_eV, energy_eV, effective_mass_rel) + action = wkb_action(positions_m, barrier_eV, energy_eV, effective_mass_rel) + return _validity_from_kappa( + positions_m, + kappa, + action, + maximum_wavelength_gradient=maximum_wavelength_gradient, + turning_point_fraction=turning_point_fraction, + ) + + +def two_band_validity( + positions_m: ArrayLike, + conduction_edge_eV: ArrayLike, + valence_edge_eV: ArrayLike, + energy_eV: float, + reduced_effective_mass_rel: float, + anchor_face: int, + *, + maximum_wavelength_gradient: float = 1.0, + turning_point_fraction: float = 0.1, +) -> WKBValidity: + """Semiclassical validity diagnostics for the two-band Kane decay constant.""" + kappa = two_band_decay_constant_per_m( + conduction_edge_eV, valence_edge_eV, energy_eV, reduced_effective_mass_rel + ) + action = two_band_action( + positions_m, + conduction_edge_eV, + valence_edge_eV, + energy_eV, + reduced_effective_mass_rel, + anchor_face, + ) + return _validity_from_kappa( + positions_m, + kappa, + action, + maximum_wavelength_gradient=maximum_wavelength_gradient, + turning_point_fraction=turning_point_fraction, + ) + + +@dataclass(frozen=True, slots=True) +class ReciprocalFlux: + """One channel's net flux plus the pieces that make it reciprocal.""" + + energies_eV: Vector + transmission: Vector + left_occupation: Vector + right_occupation: Vector + spectral_flux: Vector + net_flux_m2_s: float + forward_flux_m2_s: float + reverse_flux_m2_s: float + + +def reciprocal_net_flux( + energies_eV: ArrayLike, + transmission: ArrayLike, + left_occupation: ArrayLike, + right_occupation: ArrayLike, + prefactor_m2_s_eV: float, + *, + quadrature_weights_eV: ArrayLike | None = None, +) -> ReciprocalFlux: + """Combine one transmission with two occupations in detailed-balance form.""" + energies = np.asarray(energies_eV, dtype=float) + values = [ + np.asarray(item, dtype=float) + for item in (transmission, left_occupation, right_occupation) + ] + if energies.ndim != 1 or energies.size < 2: + raise WKBTunnellingError("energies_eV must be a 1-D grid with >= 2 points") + if np.any(np.diff(energies) <= 0.0): + raise WKBTunnellingError("energies_eV must strictly increase") + for name, array in zip( + ("transmission", "left_occupation", "right_occupation"), values, strict=True + ): + if array.shape != energies.shape: + raise WKBTunnellingError(f"{name} must match energies_eV") + if not np.all(np.isfinite(array)): + raise WKBTunnellingError(f"{name} must be finite") + transmission_values, left, right = values + if np.any(transmission_values < 0.0) or np.any(transmission_values > 1.0): + raise WKBTunnellingError("transmission must lie in [0, 1]") + prefactor = float(prefactor_m2_s_eV) + if not math.isfinite(prefactor) or prefactor < 0.0: + raise WKBTunnellingError("prefactor_m2_s_eV must be finite and non-negative") + if quadrature_weights_eV is None: + def integrate(arr: Vector) -> float: + return float(np.trapezoid(arr, energies)) + else: + weights = np.asarray(quadrature_weights_eV, dtype=float) + if weights.shape != energies.shape or not np.all(np.isfinite(weights)) or np.any(weights < 0.0): + raise WKBTunnellingError( + "quadrature weights must be finite, nonnegative and match energies" + ) + + def integrate(arr: Vector) -> float: + return float(np.dot(weights, arr)) + + spectral = prefactor * transmission_values * (left - right) + return ReciprocalFlux( + energies_eV=frozen_array(energies), + transmission=frozen_array(transmission_values), + left_occupation=frozen_array(left), + right_occupation=frozen_array(right), + spectral_flux=frozen_array(spectral), + net_flux_m2_s=integrate(spectral), + forward_flux_m2_s=integrate(prefactor * transmission_values * left), + reverse_flux_m2_s=integrate(prefactor * transmission_values * right), + ) diff --git a/tests/integration/test_photon_recycling_and_wkb_parity.py b/tests/integration/test_photon_recycling_and_wkb_parity.py new file mode 100644 index 00000000..0d016fb9 --- /dev/null +++ b/tests/integration/test_photon_recycling_and_wkb_parity.py @@ -0,0 +1,580 @@ +"""Live numerical parity tests (T4) for photon recycling & bounded WKB tunnelling (P04-12). + +Verifies end-to-end numerical and structural parity between new-core ``solarlab`` and +legacy ``perovskite_sim`` across: +1. Optical escape probability primitives (``wavelength_at_gap``, ``compute_p_esc``, + ``compute_p_esc_for_absorber``) and static thermionic-field emission ``tfe_gamma``. +2. Nonlocal radiative reabsorption operator parity against ``perovskite_sim.solver.mol``, + coherent spectral TMM escape-probability binding, photon-budget closure, and + radiative-limit ``V_oc(P_esc)`` enhancement ``V_T * ln(1 / P_esc)``. +3. Live WKB compilation identity, path-flux operator parity, and end-to-end steady-state + device solves on ``perovskite-sim/tests/fixtures/configs/wkb_resolved_electron_barrier.yaml`` + under both ``PREALLOCATED_RESERVOIR_SUPERSET_V1`` and ``STRICT_WINDOW_REBIND_V1``. +""" + +from __future__ import annotations + +from collections.abc import Iterator +import dataclasses +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from numpy.typing import NDArray +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.constants import K_B, Q +from perovskite_sim.discretization.grid import Layer as LegacyLayer, multilayer_grid as legacy_grid +from perovskite_sim.experiments.quasi_fermi_steady_state import solve_quasi_fermi_steady_state +from perovskite_sim.models.config_loader import load_device_from_yaml +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.parameters import MaterialParams +from perovskite_sim.physics import photon_recycling as legacy_pr +from perovskite_sim.physics import tunneling as legacy_tun +from perovskite_sim.physics.tunneling_channel_device import ( + evaluate_tunnelling_channels as legacy_evaluate_tunnelling, + physical_quasi_fermi_levels_eV as legacy_ef_levels, +) +from perovskite_sim.solver.mol import StateVec, assemble_rhs, build_material_arrays + +from examples.research_1d.steady import load_device +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_nonlocal_1d import ( + CompiledNonlocalDevice1D, + PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED, + compile_nonlocal_device_1d, + solve_nonlocal_steady_state_1d, +) +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.equations.assembly.nonlocal_1d import AssembledNonlocalDC1DProblem +from solarlab.equations.nonlocal_1d import ( + evaluate_device_tunnelling_1d, + physical_quasi_fermi_levels_eV, +) +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.physics.generation.photon_recycling import ( + TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + compute_p_esc, + compute_p_esc_for_absorber, + wavelength_at_gap, +) +from solarlab.physics.generation.radiative_reabsorption import ( + CONTROL_VOLUME_CONSERVATIVE_V1, + AbsorberReabsorptionSpec, + evaluate_radiative_reabsorption, +) +from solarlab.physics.transport.tunneling_channels import ( + PREALLOCATED_RESERVOIR_SUPERSET_V1, + STRICT_WINDOW_REBIND_V1, +) +from solarlab.physics.transport.wkb_tunneling import tfe_gamma + +ROOT = Path(__file__).resolve().parents[2] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +WKB_FIXTURE_YAML = ROOT / "perovskite-sim" / "tests" / "fixtures" / "configs" / "wkb_resolved_electron_barrier.yaml" + +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) +LEGACY_MODEL_SOURCES = ( + "physics/cigs_optics.py", + "models/tunneling_channels.py", +) + +Vector = NDArray[np.float64] + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def legacy_catalog() -> DefaultCatalog: + sources = tuple( + SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_DEFAULTS + ) + model_sources = tuple( + SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_MODEL_SOURCES + ) + return read_legacy_default_catalog(sources, model_sources=model_sources) + + +def _find_voc(dev: CompiledNonlocalDevice1D, v_lo: float, v_max: float) -> tuple[float, Any]: + """Stepped bracket + secant/bisection root find for illuminated open-circuit voltage.""" + s_lo = solve_nonlocal_steady_state_1d(dev, voltage_V=v_lo, generation_scale=1.0) + j_lo = float(np.mean(s_lo.current_density_A_m2)) + v_cur = v_lo + s_hi = s_lo + j_hi = j_lo + while v_cur < v_max and j_lo * j_hi > 0.0: + v_next = min(v_max, v_cur + 0.02) + s_next = solve_nonlocal_steady_state_1d( + dev, initial_state=s_hi.state, voltage_V=v_next, generation_scale=1.0 + ) + j_next = float(np.mean(s_next.current_density_A_m2)) + if j_lo * j_next <= 0.0: + v_hi = v_next + s_hi = s_next + j_hi = j_next + break + v_lo, s_lo, j_lo = v_next, s_next, j_next + v_cur = v_next + s_hi, j_hi = s_next, j_next + else: + v_hi = v_cur + assert j_lo * j_hi <= 0.0, f"V_oc not bracketed up to {v_max}: J=({j_lo}, {j_hi})" + + state_seed = s_lo.state + a, b = v_lo, v_hi + fa, fb = j_lo, j_hi + best = s_lo + for _ in range(14): + if abs(fb - fa) > 0.0: + v_sec = b - fb * (b - a) / (fb - fa) + margin = 0.05 * (b - a) + v_mid = v_sec if (a + margin) < v_sec < (b - margin) else 0.5 * (a + b) + else: + v_mid = 0.5 * (a + b) + sol = solve_nonlocal_steady_state_1d( + dev, initial_state=state_seed, voltage_V=v_mid, generation_scale=1.0 + ) + state_seed = sol.state + best = sol + fm = float(np.mean(sol.current_density_A_m2)) + if abs(fm) <= 1.0e-7 or abs(b - a) <= 1.0e-7: + return v_mid, sol + if fa * fm <= 0.0: + b, fb = v_mid, fm + else: + a, fa = v_mid, fm + return float(best.voltage_V), best + + +# --------------------------------------------------------------------------- +# 1. Optical escape & static TFE primitives parity vs perovskite_sim +# --------------------------------------------------------------------------- + + +def test_optical_escape_and_tfe_primitives_match_legacy_bit_for_bit() -> None: + for eg in (1.12, 1.50, 1.60, 2.10): + assert wavelength_at_gap(eg) == pytest.approx(legacy_pr.wavelength_at_gap(eg), rel=1e-15) + + for alpha in (0.0, 2.0e4, 1.5e6, 8.0e6): + for d_m in (50.0e-9, 450.0e-9, 1.2e-6): + for n_r in (1.5, 2.4, 2.6, 3.5): + p_new = compute_p_esc(alpha, d_m, n_r) + p_leg = legacy_pr.compute_p_esc(alpha, d_m, n_r) + assert p_new == pytest.approx(p_leg, rel=1e-15, abs=0.0) + + x_abs = np.linspace(0.0, 500.0e-9, 65) + wl_m = np.linspace(400.0e-9, 900.0e-9, 41) + for k_gap, n_gap in ((0.0, 2.5), (0.015, 2.55), (0.12, 2.65)): + alpha_wl = 4.0 * math.pi * k_gap / wl_m + a_xl = alpha_wl[None, :] * np.exp(-0.7 * x_abs[:, None] * alpha_wl[None, :]) + p_new = compute_p_esc_for_absorber( + a_xl, + wl_m, + x_abs, + 1.60, + n_gap, + mode=TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + ) + p_leg = legacy_pr.compute_p_esc_for_absorber(a_xl, wl_m, x_abs, 1.60, n_gap) + assert p_new == pytest.approx(p_leg, rel=1e-15, abs=0.0) + + vt_300 = K_B * 300.0 / Q + for delta_e in (-0.05, 0.0, 0.08, 0.25, 0.45): + for doping in (0.0, 1.0e22, 5.0e23, 2.0e24): + for m_rel, eps_r in ((0.15, 10.0), (0.25, 24.0)): + g_new = tfe_gamma(delta_e, doping, m_rel, eps_r, vt_300) + g_leg = legacy_tun.tfe_gamma(delta_e, doping, m_rel, eps_r, vt_300) + assert g_new == pytest.approx(g_leg, rel=1e-15, abs=0.0) + + +# --------------------------------------------------------------------------- +# 2. Radiative reabsorption operator parity vs mol.py & steady-state V_oc(P_esc) +# --------------------------------------------------------------------------- + + +def test_radiative_reabsorption_operator_parity_with_legacy_mol_and_voc_enhancement() -> None: + # (a) Live operator parity against perovskite_sim.solver.mol.assemble_rhs + vt = K_B * 300.0 / Q + nc, nv = 1.0e24, 1.0e24 + ni_htl = math.sqrt(nc * nv * math.exp(-1.8 / vt)) + ni_abs = math.sqrt(nc * nv * math.exp(-1.6 / vt)) + ni_etl = math.sqrt(nc * nv * math.exp(-2.0 / vt)) + + def _mp(eg: float, chi: float, ni_val: float, **kw: Any) -> MaterialParams: + base = dict( + eps_r=20.0, + mu_n=1.0e-4, + mu_p=1.0e-4, + D_ion=0.0, + P_lim=1.0e30, + P0=0.0, + ni=ni_val, + tau_n=2.0e-6, + tau_p=2.0e-6, + n1=ni_val, + p1=ni_val, + B_rad=0.0, + C_n=0.0, + C_p=0.0, + alpha=0.0, + N_A=0.0, + N_D=0.0, + chi=chi, + Eg=eg, + Nc300=nc, + Nv300=nv, + ) + base.update(kw) + return MaterialParams(**base) + + stack_off = DeviceStack( + layers=( + LayerSpec("htl", 100.0e-9, _mp(1.8, 3.6, ni_htl, N_A=1.0e23), "HTL"), + LayerSpec("absorber", 450.0e-9, _mp(1.6, 3.9, ni_abs, B_rad=2.5e-15, alpha=2.0e6), "absorber"), + LayerSpec("etl", 100.0e-9, _mp(2.0, 4.0, ni_etl, N_D=1.0e23), "ETL"), + ), + V_bi=1.0, + Phi=1.0e21, + interfaces=((0.0, 0.0), (0.0, 0.0)), + mode="full", + ) + x_grid = legacy_grid([LegacyLayer(layer.thickness, 12) for layer in stack_off.layers], alpha=3.0) + n_nodes = x_grid.size + + mat_off = build_material_arrays(x_grid, stack_off) + abs_mask = (x_grid > 100.0e-9 - 1.0e-15) & (x_grid <= 550.0e-9 - 1.0e-15) + mat_on = dataclasses.replace( + mat_off, + has_radiative_reabsorption=True, + absorber_masks=(abs_mask,), + absorber_p_esc=(0.14,), + absorber_thicknesses=(450.0e-9,), + ) + + rng = np.random.default_rng(20260412) + n_prof = 1.0e20 * np.exp(0.6 * np.sin(np.linspace(0.0, 2.5, n_nodes))) + rng.uniform(1e18, 5e19, n_nodes) + p_prof = 1.5e20 * np.exp(0.5 * np.cos(np.linspace(0.0, 2.0, n_nodes))) + rng.uniform(1e18, 5e19, n_nodes) + n_prof[0] = mat_off.n_L + n_prof[-1] = mat_off.n_R + p_prof[0] = mat_off.p_L + p_prof[-1] = mat_off.p_R + y_state = StateVec.pack(n_prof, p_prof, np.zeros(n_nodes, dtype=float)) + + rhs_off = assemble_rhs(0.0, y_state, x_grid, stack_off, mat_off, illuminated=False, V_app=0.5) + rhs_on = assemble_rhs(0.0, y_state, x_grid, stack_off, mat_on, illuminated=False, V_app=0.5) + dn_dt_diff = rhs_on[1 : n_nodes - 1] - rhs_off[1 : n_nodes - 1] + dp_dt_diff = rhs_on[n_nodes + 1 : 2 * n_nodes - 1] - rhs_off[n_nodes + 1 : 2 * n_nodes - 1] + + spec_hist = AbsorberReabsorptionSpec.historical_trapezoid_uniform( + layer_id="absorber", + nodes_m=x_grid, + absorber_mask=mat_on.absorber_masks[0], + thickness_m=mat_on.absorber_thicknesses[0], + intrinsic_radiative_B_m3_s=mat_on.B_rad, + intrinsic_product_m6=mat_on.ni_sq, + escape_probability=0.14, + ) + ev_hist = evaluate_radiative_reabsorption([spec_hist], n_prof, p_prof, derivatives=False) + # Near heterointerface clustered faces, subtracting ~1e34 s^-1 drift-diffusion divergences + # in (rhs_on - rhs_off) has ~6e-9 IEEE-754 cancellation; interior absorber nodes match < 1e-12. + np.testing.assert_allclose(ev_hist.generation_m3_s[1:-1], dn_dt_diff, rtol=1e-8, atol=0.0) + np.testing.assert_allclose(ev_hist.generation_m3_s[1:-1], dp_dt_diff, rtol=1e-8, atol=0.0) + np.testing.assert_allclose( + ev_hist.generation_m3_s[15:22], dn_dt_diff[14:21], rtol=1e-12, atol=0.0 + ) + + # (b) Coherent spectral TMM escape binding + steady-state V_oc(P_esc) enhancement + base = load_device() + tdoc_defaults = base.defaults + from solarlab.physics.transport.tunneling_channels import TunnellingChannelDocument + + tdoc = TunnellingChannelDocument() + defaults = dataclasses.replace( + tdoc_defaults, + complex_defaults=( + ("cigs_graded_optics", (("model", "minoura_2015"), ("slices", 12), ("kk_quadrature_order", 160))), + ("band_to_band", tuple(tdoc.band_to_band.to_dict().items())), + ("intraband", tuple(tdoc.intraband.to_dict().items())), + ("interface_defect_assisted", tuple(tdoc.interface_defect_assisted.to_dict().items())), + ("contact", tuple(tdoc.contact.to_dict().items())), + ), + ) + + wavelengths = (400, 450, 500, 550, 600, 650, 700, 750, 800, 850) + photon_csv = "wavelength_nm,spectral_flux_m-2_s-1_m-1\n" + "".join( + f"{wl},{6.0e27 if wl <= 760 else 0.0}\n" for wl in wavelengths + ) + nk_csv = "wavelength_nm,n,k\n" + "".join( + f"{wl},2.55,{0.18 if wl <= 780 else 0.02}\n" for wl in wavelengths + ) + tables = ( + ResourceTable( + "pr_test_photons", + "spectrum", + SourceDocument("pr_test_photons.csv", photon_csv.encode()), + ), + ResourceTable( + "pr_test_absorber_nk", + "nk", + SourceDocument("pr_test_absorber_nk.csv", nk_csv.encode()), + ), + ) + decl = base.to_input().editing_data() + decl["spectrum"] = tables[0].name + decl["settings"]["Phi"] = 0.0 + for layer in decl["layers"]: + p = layer["parameters"] + p.update(alpha=0.0, incoherent=False, tau_n=1.0e-3, tau_p=1.0e-3, C_n=0.0, C_p=0.0) + if layer["role"] == "absorber": + abs_id = layer["id"] + p.update(optical_material=tables[1].name, n_optical=None, B_rad=5.0e-15) + else: + p.update(optical_material=None, n_optical=2.0, B_rad=0.0) + raw_decl = json.dumps(decl, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + src_decl = SourceDocument("pr_test.declaration", raw_decl) + prep_tmm = resolve_device( + DeviceInput.model_validate(decl), + defaults, + ResourceLibrary(tables), + sources=(*base.sources, src_decl), + ) + + # Compile with live coherent spectral TMM escape binding across all 3 modes! + dev_tmm_yab = compile_nonlocal_device_1d( + prep_tmm, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + escape_probability_mode=YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + ) + dev_tmm_trap = compile_nonlocal_device_1d( + prep_tmm, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + escape_probability_mode=TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + ) + dev_tmm_cv = compile_nonlocal_device_1d( + prep_tmm, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + escape_probability_mode=TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + ) + assert 0.0 < dev_tmm_yab.escape_bindings[0].escape_probability < 1.0 + assert 0.0 < dev_tmm_trap.escape_bindings[0].escape_probability < 1.0 + assert 0.0 < dev_tmm_cv.escape_bindings[0].escape_probability < 1.0 + + # Sweep P_esc in (1.0, 0.3, 0.05) and verify radiative-limit V_oc enhancement! + voc_map: dict[float, float] = {} + for p_esc in (1.0, 0.3, 0.05): + dev_cv = compile_nonlocal_device_1d( + prep_tmm, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + explicit_escape_probabilities={abs_id: p_esc}, + ) + voc_cv, sol_cv = _find_voc(dev_cv, 1.00, 1.32) + voc_map[p_esc] = voc_cv + + prob_cv = AssembledNonlocalDC1DProblem(dev_cv, voc_cv, 1.0) + budgets = prob_cv.photon_recycling_budgets(sol_cv.state.u) + assert len(budgets) == 1 + budget = budgets[0] + assert budget.emitted_flux_m2_s > 0.0 + assert abs(budget.closure_residual_m2_s) <= 1.0e-14 * budget.emitted_flux_m2_s + + dev_loc = compile_nonlocal_device_1d( + prep_tmm, + intervals_per_layer=8, + photon_recycling_mode=PHOTON_RECYCLING_LOCAL_ESCAPE_SCALED, + explicit_escape_probabilities={abs_id: p_esc}, + ) + voc_loc, _ = _find_voc(dev_loc, 1.00, 1.32) + assert abs(voc_cv - voc_loc) <= 2.5e-3 + + assert voc_map[0.05] > voc_map[0.3] > voc_map[1.0] + vt_dev = dev_tmm_cv.thermal_voltage_V + for p_esc in (0.3, 0.05): + expected_shift = vt_dev * math.log(1.0 / p_esc) + actual_shift = voc_map[p_esc] - voc_map[1.0] + assert abs(actual_shift - expected_shift) <= 3.0e-3 + + +# --------------------------------------------------------------------------- +# 3. Live WKB compilation, operator, and steady-state parity on fixture YAML +# --------------------------------------------------------------------------- + + +def test_wkb_resolved_electron_barrier_live_operator_and_steady_state_parity( + legacy_catalog: DefaultCatalog, +) -> None: + stack = load_device_from_yaml(WKB_FIXTURE_YAML) + counts = (10, 10, 10) + x_leg = legacy_grid([LegacyLayer(layer.thickness, c) for layer, c in zip(stack.layers, counts)], alpha=3.0) + mat_leg = build_material_arrays(x_leg, stack) + assert mat_leg.tunnelling_channels is not None + + src_yaml = SourceDocument("wkb_resolved_electron_barrier.yaml", WKB_FIXTURE_YAML.read_bytes()) + dev_input = import_standard_device( + src_yaml, id="wkb_resolved_electron_barrier", defaults=legacy_catalog + ) + prepared = resolve_device(dev_input, legacy_catalog, ResourceLibrary(()), sources=(src_yaml,)) + + dev_sup = compile_nonlocal_device_1d( + prepared, + intervals_per_layer=counts, + grid_alpha=3.0, + wkb_sparsity_policy=PREALLOCATED_RESERVOIR_SUPERSET_V1, + ) + dev_strict = compile_nonlocal_device_1d( + prepared, + intervals_per_layer=counts, + grid_alpha=3.0, + wkb_sparsity_policy=STRICT_WINDOW_REBIND_V1, + ) + assert dev_sup.tunnelling_channels is not None + + # Exact grid & SHA-256 compiled tunnelling identity parity! + np.testing.assert_array_equal(dev_sup.nodes_m, x_leg) + assert dev_sup.tunnelling_channels.identity_sha256 == mat_leg.tunnelling_channels.identity_sha256 + assert dev_sup.tunnelling_channels.enabled_channels == mat_leg.tunnelling_channels.enabled_channels + + # Live WKB path-flux operator parity at an explicit non-equilibrium state! + s_probe = solve_nonlocal_steady_state_1d(dev_sup, voltage_V=0.05, generation_scale=0.0) + phi_p = s_probe.state.potential_V + n_p = s_probe.state.electron_density_m3 + p_p = s_probe.state.hole_density_m3 + tun_new = evaluate_device_tunnelling_1d(dev_sup, phi_p, n_p, p_p, derivatives=False) + chi_leg = mat_leg.chi_phys if mat_leg.chi_phys is not None else mat_leg.chi + eg_leg = mat_leg.Eg_phys if mat_leg.Eg_phys is not None else mat_leg.Eg + assert mat_leg.N_C_physical is not None and mat_leg.N_V_physical is not None + efn_leg, efp_leg = legacy_ef_levels( + potential_V=phi_p, + affinity_eV=chi_leg, + band_gap_eV=eg_leg, + electron_density_m3=n_p, + hole_density_m3=p_p, + conduction_dos_m3=mat_leg.N_C_physical, + valence_dos_m3=mat_leg.N_V_physical, + thermal_voltage_V=mat_leg.V_T_device, + ) + tun_leg = legacy_evaluate_tunnelling( + mat_leg.tunnelling_channels, + positions_m=x_leg, + potential_V=phi_p, + affinity_eV=chi_leg, + band_gap_eV=eg_leg, + electron_quasi_fermi_eV=efn_leg, + hole_quasi_fermi_eV=efp_leg, + thermal_voltage_V=mat_leg.V_T_device, + ) + assert tun_new is not None and tun_new.intraband_path is not None + assert tun_leg.intraband_path is not None + + np.testing.assert_allclose( + tun_new.intraband_path.actions, tun_leg.intraband_path.actions, rtol=1e-14, atol=0.0 + ) + np.testing.assert_allclose( + tun_new.intraband_path.particle_face_flux_m2_s, + tun_leg.intraband_path.particle_face_flux_m2_s, + rtol=1e-14, + atol=0.0, + ) + np.testing.assert_allclose( + tun_new.electron_face_current_A_m2, tun_leg.electron_face_current_A_m2, rtol=1e-14, atol=0.0 + ) + np.testing.assert_allclose( + tun_new.channel_net_flux_m2_s, + tun_leg.channel_net_flux_m2_s, + rtol=1e-14, + atol=0.0, + ) + assert abs(float(np.sum(tun_new.electron_nodal_transfer_m2_s))) <= 1.0e-12 * float( + np.max(np.abs(tun_new.electron_nodal_transfer_m2_s)) + ) + + # Channel-disabled reference device to verify observable WKB tunnelling enhancement! + doc_no_wkb = prepared.to_input().editing_data() + doc_no_wkb["tunnelling_channels"]["intraband"]["enabled"] = False + prep_no_wkb = resolve_device( + DeviceInput.model_validate(doc_no_wkb), legacy_catalog, ResourceLibrary(()) + ) + dev_no_wkb = compile_nonlocal_device_1d( + prep_no_wkb, intervals_per_layer=counts, grid_alpha=3.0 + ) + + # End-to-end steady-state parity across reverse, equilibrium, and forward biases! + for v_app in (-0.02, 0.0, 0.02, 0.10): + leg_res = solve_quasi_fermi_steady_state(x_leg, stack, V_app=v_app, illuminated=False) + sol_sup = solve_nonlocal_steady_state_1d(dev_sup, voltage_V=v_app, generation_scale=0.0) + sol_str = solve_nonlocal_steady_state_1d(dev_strict, voltage_V=v_app, generation_scale=0.0) + + # Superset vs strict rebind policies agree to machine precision! + np.testing.assert_allclose( + sol_str.current_density_A_m2, sol_sup.current_density_A_m2, rtol=1e-10, atol=1e-12 + ) + + # Electrostatic potential and terminal current parity against perovskite_sim! + np.testing.assert_allclose(sol_sup.state.potential_V, leg_res.phi, rtol=0.0, atol=1e-7) + + j_term_new = -float(np.mean(sol_sup.current_density_A_m2)) + if v_app == 0.0: + assert abs(j_term_new) <= 1.0e-10 + assert abs(leg_res.current_A_m2) <= 1.0e-10 + else: + assert j_term_new == pytest.approx(leg_res.current_A_m2, rel=1e-6) + + prob_v = AssembledNonlocalDC1DProblem(dev_sup, v_app, 0.0) + tun_v = prob_v.tunnelling_evaluation(sol_sup.state.u) + assert tun_v is not None + assert leg_res.tunnelling_channel_diagnostics is not None + np.testing.assert_allclose( + tun_v.electron_face_current_A_m2, + leg_res.tunnelling_channel_diagnostics.electron_face_current_A_m2, + rtol=1e-6, + atol=1e-10, + ) + + # Strictly dissipative WKB chemical work! + bands = dev_sup.parameters.band_structure + efn_eV, _ = physical_quasi_fermi_levels_eV( + potential_V=sol_sup.state.potential_V, + affinity_eV=bands.physical_electron_affinity_eV, + band_gap_eV=bands.physical_band_gap_eV, + electron_density_m3=sol_sup.state.electron_density_m3, + hole_density_m3=sol_sup.state.hole_density_m3, + conduction_dos_m3=dev_sup.parameters.conduction_dos_m3, + valence_dos_m3=dev_sup.parameters.valence_dos_m3, + thermal_voltage_V=dev_sup.thermal_voltage_V, + ) + chem_work = float(np.dot(efn_eV, tun_v.electron_nodal_transfer_m2_s)) + assert chem_work < 0.0 + + # Observable WKB current enhancement over channel-disabled barrier! + sol_no_wkb = solve_nonlocal_steady_state_1d( + dev_no_wkb, voltage_V=v_app, generation_scale=0.0 + ) + j_no_wkb = -float(np.mean(sol_no_wkb.current_density_A_m2)) + assert abs(j_term_new) > abs(j_no_wkb) + assert abs(j_term_new) - abs(j_no_wkb) > 1.0e-3 diff --git a/tests/unit/equations/test_nonlocal_assembly_1d.py b/tests/unit/equations/test_nonlocal_assembly_1d.py new file mode 100644 index 00000000..d7925a93 --- /dev/null +++ b/tests/unit/equations/test_nonlocal_assembly_1d.py @@ -0,0 +1,513 @@ +"""T2 unit tests for 1D nonlocal equation assembly, WKB sparsity support, and AC gates.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Any + +import numpy as np +from numpy.typing import NDArray +import pytest +from scipy.sparse import csc_matrix +from threadpoolctl import threadpool_limits + +from examples.research_1d.steady import load_device +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_nonlocal_1d import ( + PHOTON_RECYCLING_OFF, + compile_nonlocal_device_1d, + solve_nonlocal_steady_state_1d, +) +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.assembly.nonlocal_1d import ( + AssembledNonlocalDC1DProblem, + SparsitySupportChangedError, + nonlocal_classical_dc_1d, + solve_nonlocal_small_signal_1d, +) +from solarlab.equations.dc_1d import CapabilityError, DC1DProblem +from solarlab.equations.nonlocal_1d import NonlocalDC1DProblem, evaluate_nonlocal_couplings_1d +from solarlab.materials.resources import ResourceLibrary +from solarlab.physics.generation.radiative_reabsorption import ( + CONTROL_VOLUME_CONSERVATIVE_V1, + HISTORICAL_TRAPEZOID_UNIFORM_V1, + LAGGED_BAKED_GENERATION_V1, + dense_reabsorption_jacobian, + evaluate_radiative_reabsorption, + thermionic_cap_directional_derivative, +) +from solarlab.physics.transport.field_mobility_tangents import ( + field_mobility_directional_derivative, +) +from solarlab.physics.transport.tunneling_channels import ( + PREALLOCATED_RESERVOIR_SUPERSET_V1, + STRICT_WINDOW_REBIND_V1, + TunnellingChannelDocument, +) +from solarlab.solvers.nonlinear.steady_1d import solve_steady_state + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +def _csc_dense(mat: csc_matrix) -> np.ndarray: + out = np.zeros(mat.shape, dtype=mat.dtype) + for col in range(mat.shape[1]): + start, stop = int(mat.indptr[col]), int(mat.indptr[col + 1]) + out[mat.indices[start:stop], col] = mat.data[start:stop] + return out + + +def _central_fd_jacobian( + problem: AssembledNonlocalDC1DProblem | NonlocalDC1DProblem, + u0: np.ndarray, + *, + step: float = 1.0e-6, +) -> np.ndarray: + n_dof = u0.size + j_fd: NDArray[np.float64] = np.zeros((n_dof, n_dof), dtype=float) + for col in range(n_dof): + h = step * max(1.0, abs(float(u0[col]))) + up = u0.copy() + um = u0.copy() + up[col] += h + um[col] -= h + fp = problem.residual(up) + fm = problem.residual(um) + j_fd[:, col] = (fp - fm) / (2.0 * h) + return j_fd + + +def _with_tunnelling_defaults(defaults: DefaultCatalog) -> DefaultCatalog: + doc = TunnellingChannelDocument() + channel_defaults = ( + ( + "cigs_graded_optics", + ( + ("model", "minoura_2015"), + ("slices", 12), + ("kk_quadrature_order", 160), + ), + ), + ("band_to_band", tuple(doc.band_to_band.to_dict().items())), + ("intraband", tuple(doc.intraband.to_dict().items())), + ("interface_defect_assisted", tuple(doc.interface_defect_assisted.to_dict().items())), + ("contact", tuple(doc.contact.to_dict().items())), + ) + return replace(defaults, complex_defaults=channel_defaults) + + +@pytest.fixture(scope="module") +def radiative_prepared() -> PreparedDevice: + base = load_device() + defaults = _with_tunnelling_defaults(base.defaults) + doc: dict[str, Any] = base.to_input().editing_data() + for layer in doc["layers"]: + if layer["role"] == "absorber": + layer["parameters"]["B_rad"] = 2.5e-15 + layer["parameters"]["tau_n"] = 5.0e-6 + layer["parameters"]["tau_p"] = 5.0e-6 + return resolve_device( + DeviceInput.model_validate(doc), + defaults, + base.resources, + sources=base.sources, + ) + + +@pytest.fixture(scope="module") +def wkb_prepared() -> PreparedDevice: + base = load_device() + defaults = _with_tunnelling_defaults(base.defaults) + common_params: dict[str, Any] = { + "eps_r": 20.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e30, + "P0": 0.0, + "ni": 2.2495700957e11, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": 2.2495700957e11, + "p1": 2.2495700957e11, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 1.0e22, + "chi": 4.0, + "Eg": 1.5, + "Nc300": 1.0e24, + "Nv300": 8.0e23, + } + barrier_params = { + **common_params, + "mu_n": 2.0e-5, + "mu_p": 2.0e-5, + "N_D": 0.0, + "chi": 3.7, + "Eg": 2.1, + "ni": 2.0526804442e6, + "n1": 2.0526804442e6, + "p1": 2.0526804442e6, + } + right_params = {**common_params, "N_D": 2.0e22} + doc: dict[str, Any] = { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": "wkb_resolved_electron_barrier_unit", + "settings": { + "Phi": 1.0e21, + "mode": "legacy", + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + }, + "tunnelling_channels": { + "schema_version": "solarlab-wkb-tunnelling-channels-v1", + "intraband": { + "enabled": True, + "electron_effective_mass_rel": 0.2, + "hole_effective_mass_rel": 0.2, + "carrier": "electron", + "energy_quadrature_order": 96, + }, + }, + "layers": [ + { + "id": "left_reservoir", + "name": "left_reservoir", + "role": "ETL", + "thickness": 150.0e-9, + "parameters": common_params, + }, + { + "id": "electron_barrier", + "name": "electron_barrier", + "role": "ETL", + "thickness": 3.0e-9, + "parameters": barrier_params, + }, + { + "id": "right_reservoir", + "name": "right_reservoir", + "role": "ETL", + "thickness": 100.0e-9, + "parameters": right_params, + }, + ], + } + return resolve_device(DeviceInput.model_validate(doc), defaults, ResourceLibrary(())) + + +# --------------------------------------------------------------------------- +# 1. Zero-coupling & all-disabled bitwise identity +# --------------------------------------------------------------------------- + + +def test_disabled_nonlocal_and_inert_tunnelling_are_bit_identical_to_classical( + radiative_prepared: PreparedDevice, +) -> None: + local_dev = compile_device_1d(radiative_prepared, intervals_per_layer=8) + nonlocal_off = compile_nonlocal_device_1d( + radiative_prepared, intervals_per_layer=8, photon_recycling_mode=PHOTON_RECYCLING_OFF + ) + assert nonlocal_off.sha256 == local_dev.sha256 + assert nonlocal_classical_dc_1d(nonlocal_off).identity == AssembledDC1DProblem(local_dev).binding.identity + + # Also test an explicit all-disabled tunnelling_channels block in configuration! + doc = radiative_prepared.to_input().editing_data() + doc["tunnelling_channels"] = { + "schema_version": "solarlab-wkb-tunnelling-channels-v1", + "intraband": {"enabled": False, "carrier": "electron", "energy_quadrature_order": 16}, + } + prep_inert = resolve_device( + DeviceInput.model_validate(doc), + radiative_prepared.defaults, + radiative_prepared.resources, + sources=radiative_prepared.sources, + ) + nonlocal_inert = compile_nonlocal_device_1d(prep_inert, intervals_per_layer=8) + assert nonlocal_inert.tunnelling_channels is None + assert nonlocal_inert.has_nonlocal_couplings is False + + steady_local = solve_steady_state(local_dev, voltage_V=0.45, generation_scale=1.0) + u = steady_local.state.u + + p_loc_asm = AssembledDC1DProblem(local_dev, 0.45, 1.0) + p_nl_asm = AssembledNonlocalDC1DProblem(nonlocal_off, 0.45, 1.0) + p_inert_asm = AssembledNonlocalDC1DProblem(nonlocal_inert, 0.45, 1.0) + p_loc_dir = DC1DProblem(local_dev, 0.45, 1.0) + p_nl_dir = NonlocalDC1DProblem(nonlocal_off, 0.45, 1.0) + + assert np.array_equal(p_nl_asm.residual(u), p_loc_asm.residual(u)) + assert np.array_equal(p_inert_asm.residual(u), p_loc_asm.residual(u)) + assert np.array_equal(p_nl_dir.residual(u), p_loc_dir.residual(u)) + + j_loc = p_loc_asm.jacobian(u) + j_nl = p_nl_asm.jacobian(u) + j_inert = p_inert_asm.jacobian(u) + assert np.array_equal(j_nl.data, j_loc.data) + assert np.array_equal(j_inert.data, j_loc.data) + assert np.array_equal(j_nl.indices, j_loc.indices) + assert np.array_equal(j_nl.indptr, j_loc.indptr) + + m_loc = p_loc_asm.storage_jacobian(u) + m_nl = p_nl_asm.storage_jacobian(u) + assert np.array_equal(m_nl.data, m_loc.data) + assert np.array_equal(m_nl.indices, m_loc.indices) + assert np.array_equal(m_nl.indptr, m_loc.indptr) + + assert np.array_equal(p_nl_asm.current_density(u), p_loc_asm.current_density(u)) + assert np.array_equal(p_nl_asm.contact_current_density(u), p_loc_asm.contact_current_density(u)) + + +# --------------------------------------------------------------------------- +# 2. Sparse rank-1 reabsorption Jacobian vs FD & dense reference +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "mode,cross_region", + [ + (CONTROL_VOLUME_CONSERVATIVE_V1, False), + (CONTROL_VOLUME_CONSERVATIVE_V1, True), + (HISTORICAL_TRAPEZOID_UNIFORM_V1, False), + ], +) +def test_nonlocal_reabsorption_sparse_jacobian_matches_fd_and_rank1_reference( + radiative_prepared: PreparedDevice, + mode: str, + cross_region: bool, +) -> None: + abs_id = next(layer.id for layer in radiative_prepared.layers if layer.role == "absorber") + # For cross_region=True, route reabsorbed photons into a distinct downstream node subset! + overrides: dict[str, NDArray[np.intp]] | None = ( + {abs_id: np.arange(10, 20, dtype=np.intp)} if cross_region else None + ) + dev = compile_nonlocal_device_1d( + radiative_prepared, + intervals_per_layer=(6, 10, 6), + photon_recycling_mode=mode, + explicit_escape_probabilities={abs_id: 0.12}, + receiver_node_overrides=overrides, + ) + solved = solve_nonlocal_steady_state_1d(dev, voltage_V=0.55, generation_scale=1.0) + u = solved.state.u + + prob_asm = AssembledNonlocalDC1DProblem(dev, 0.55, 1.0) + prob_dir = NonlocalDC1DProblem(dev, 0.55, 1.0) + np.testing.assert_allclose(prob_asm.residual(u), prob_dir.residual(u), rtol=0.0, atol=1e-22) + + j_asm = _csc_dense(prob_asm.jacobian(u)) + j_dir = _csc_dense(prob_dir.jacobian(u)) + np.testing.assert_allclose(j_asm, j_dir, rtol=1e-14, atol=1e-22) + + j_fd = _central_fd_jacobian(prob_asm, u, step=1.0e-6) + rel_frob = np.linalg.norm(j_asm - j_fd) / np.linalg.norm(j_fd) + assert rel_frob <= 1e-8 + + # Also check the pure nonlocal Jacobian addition against dense_reabsorption_jacobian! + ext = evaluate_nonlocal_couplings_1d(dev, u, voltage_V=0.55, derivatives=True) + assert ext.jacobian_addition is not None + j_add_sparse = _csc_dense(ext.jacobian_addition) + + count = dev.node_count + _, n, p = dev.fields(u, voltage_V=0.55) + ev = evaluate_radiative_reabsorption(dev.radiative_reabsorption, n, p, derivatives=True) + dn_dense, dp_dense = dense_reabsorption_jacobian(ev, count) + widths = dev.geometry.cell_measures_m + j_add_ref: NDArray[np.float64] = np.zeros((3 * count, 3 * count), dtype=float) + for row_offset in (count, 2 * count): + # Rows 1..count-2 are unconstrained interior carrier rows under ohmic contacts. + j_add_ref[row_offset + 1 : row_offset + count - 1, count : 2 * count] = ( + widths[1:-1, None] * dn_dense[1:-1, :] * n[None, :] + ) + j_add_ref[row_offset + 1 : row_offset + count - 1, 2 * count : 3 * count] = ( + -widths[1:-1, None] * dp_dense[1:-1, :] * p[None, :] + ) + rel_ref = np.linalg.norm(j_add_sparse - j_add_ref) / np.linalg.norm(j_add_ref) + assert rel_ref <= 1e-14 + + +# --------------------------------------------------------------------------- +# 3. WKB intraband sparse Jacobian & turning-point support-window shift test +# --------------------------------------------------------------------------- + + +def test_wkb_sparse_jacobian_and_support_window_shift_policies( + wkb_prepared: PreparedDevice, +) -> None: + counts = (8, 8, 8) + dev_superset = compile_nonlocal_device_1d( + wkb_prepared, + intervals_per_layer=counts, + wkb_sparsity_policy=PREALLOCATED_RESERVOIR_SUPERSET_V1, + ) + dev_strict = compile_nonlocal_device_1d( + wkb_prepared, + intervals_per_layer=counts, + wkb_sparsity_policy=STRICT_WINDOW_REBIND_V1, + ) + + s_low = solve_nonlocal_steady_state_1d( + dev_superset, voltage_V=-0.02, generation_scale=0.0 + ) + s_high = solve_nonlocal_steady_state_1d( + dev_superset, voltage_V=0.22, generation_scale=0.0 + ) + + p_low = AssembledNonlocalDC1DProblem(dev_superset, -0.02, 0.0) + p_high = AssembledNonlocalDC1DProblem(dev_superset, 0.22, 0.0) + + # Confirm the WKB turning-point support window actually shifts across grid cells! + ext_low = evaluate_nonlocal_couplings_1d( + dev_superset, s_low.state.u, voltage_V=-0.02, derivatives=True + ) + ext_high = evaluate_nonlocal_couplings_1d( + dev_superset, s_high.state.u, voltage_V=0.22, derivatives=True + ) + assert ext_low.wkb_support is not None and ext_high.wkb_support is not None + assert ext_low.wkb_support.support_signature != ext_high.wkb_support.support_signature + assert ext_low.wkb_support.turning_point_face_pairs != ext_high.wkb_support.turning_point_face_pairs + assert ext_low.wkb_support.contained_in_reservoir_superset is True + assert ext_high.wkb_support.contained_in_reservoir_superset is True + + # Under PREALLOCATED_RESERVOIR_SUPERSET_V1, 0 nonzeros are dropped at BOTH windows! + for prob, state_u in ((p_low, s_low.state.u), (p_high, s_high.state.u)): + j_ana = _csc_dense(prob.jacobian(state_u)) + j_fd = _central_fd_jacobian(prob, state_u, step=1.0e-6) + rel_err = np.linalg.norm(j_ana - j_fd) / np.linalg.norm(j_fd) + assert rel_err <= 1e-8 + + # Under STRICT_WINDOW_REBIND_V1, a shifted turning-point window raises SparsitySupportChangedError + # until explicitly rebound via .rebind_for_state(u)! + strict_prob = AssembledNonlocalDC1DProblem(dev_strict, 0.22, 0.0).rebind_for_state( + dev_strict.rebase_coordinates(s_low.state.u, -0.02, 0.22) + ) + with pytest.raises(SparsitySupportChangedError, match="wkb_support_shifted"): + strict_prob.jacobian(s_high.state.u) + + rebound_prob = strict_prob.rebind_for_state(s_high.state.u) + j_strict = _csc_dense(rebound_prob.jacobian(s_high.state.u)) + j_superset_high = _csc_dense(p_high.jacobian(s_high.state.u)) + np.testing.assert_allclose(j_strict, j_superset_high, rtol=1e-14, atol=0.0) + + # Full solve under STRICT_WINDOW_REBIND_V1 succeeds by rebinding across continuation stages! + s_strict_solved = solve_nonlocal_steady_state_1d( + dev_strict, voltage_V=0.22, generation_scale=0.0 + ) + np.testing.assert_allclose( + s_strict_solved.current_density_A_m2, s_high.current_density_A_m2, rtol=1e-12, atol=1e-15 + ) + + +# --------------------------------------------------------------------------- +# 4. Small-signal AC capability gates, Maxwell spread & DC conductance limit +# --------------------------------------------------------------------------- + + +def test_small_signal_ac_refuses_wkb_lagged_and_nonsmooth_surfaces_and_matches_dc_slope( + radiative_prepared: PreparedDevice, + wkb_prepared: PreparedDevice, +) -> None: + # (a) WKB is refused in transient storage, nonzero alpha/udot, non-QF driver, and AC! + with pytest.raises(CapabilityError, match="quasi_fermi_steady_state"): + compile_nonlocal_device_1d(wkb_prepared, intervals_per_layer=6, driver="mol_transient") + + wkb_dev = compile_nonlocal_device_1d(wkb_prepared, intervals_per_layer=(8, 8, 8)) + wkb_eq = solve_nonlocal_steady_state_1d(wkb_dev, voltage_V=0.0, generation_scale=0.0) + wkb_prob = AssembledNonlocalDC1DProblem(wkb_dev, 0.0, 0.0) + + with pytest.raises(CapabilityError, match="wkb_transient_unsupported"): + wkb_prob.storage(wkb_eq.state.u) + with pytest.raises(CapabilityError, match="wkb_transient_unsupported"): + wkb_prob.storage_jacobian(wkb_eq.state.u) + with pytest.raises(CapabilityError, match="wkb_transient_unsupported"): + wkb_prob.jacobian(wkb_eq.state.u, alpha=1.0) + with pytest.raises(CapabilityError, match="wkb_transient_unsupported"): + wkb_prob.residual(wkb_eq.state.u, np.ones_like(wkb_eq.state.u)) + with pytest.raises(CapabilityError, match="wkb_ac_unsupported"): + solve_nonlocal_small_signal_1d(wkb_prob, wkb_eq.state.u, [100.0]) + + # (b) Radiative reabsorption at dark equilibrium (R_tot == 0 clamp surface) is refused in AC! + abs_id = next(layer.id for layer in radiative_prepared.layers if layer.role == "absorber") + reabs_dev = compile_nonlocal_device_1d( + radiative_prepared, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + explicit_escape_probabilities={abs_id: 0.08}, + ) + reabs_dark = solve_nonlocal_steady_state_1d(reabs_dev, voltage_V=0.0, generation_scale=0.0) + dark_prob = AssembledNonlocalDC1DProblem(reabs_dev, 0.0, 0.0) + with pytest.raises(CapabilityError, match="non_smooth_ac_switching_surface"): + solve_nonlocal_small_signal_1d(dark_prob, reabs_dark.state.u, [10.0]) + + # (c) Lagged baked reabsorption is refused in AC! + reabs_light = solve_nonlocal_steady_state_1d(reabs_dev, voltage_V=0.55, generation_scale=1.0) + _, n_light, p_light = reabs_dev.fields(reabs_light.state.u, voltage_V=0.55) + lagged_dev = compile_nonlocal_device_1d( + radiative_prepared, + intervals_per_layer=8, + photon_recycling_mode=LAGGED_BAKED_GENERATION_V1, + explicit_escape_probabilities={abs_id: 0.08}, + lagged_carrier_densities_m3=(n_light, p_light), + ) + lagged_prob = AssembledNonlocalDC1DProblem(lagged_dev, 0.55, 1.0) + with pytest.raises(CapabilityError, match="lagged_reabsorption_ac_unsupported"): + solve_nonlocal_small_signal_1d(lagged_prob, reabs_light.state.u, [10.0]) + + # (d) Active TE crossover & PF cusp surfaces passed to AC are refused! + smooth_prob = AssembledNonlocalDC1DProblem(reabs_dev, 0.55, 1.0) + te_kink = thermionic_cap_directional_derivative([5.0], [5.0], [1.0], [0.2]) + with pytest.raises(CapabilityError, match="thermionic_cap"): + solve_nonlocal_small_signal_1d( + smooth_prob, reabs_light.state.u, [10.0], thermionic_electron=te_kink + ) + pf_cusp = field_mobility_directional_derivative([1e-4], [0.0], [1e4], [0.0], [2.0], [1e-4]) + with pytest.raises(CapabilityError, match="field_mobility"): + solve_nonlocal_small_signal_1d( + smooth_prob, reabs_light.state.u, [10.0], field_mobility_electron=pf_cusp + ) + + # (e) Smooth illuminated point passes AC, conserves total Maxwell current, and matches DC dJ/dV! + freqs = [0.0, 10.0, 1.0e4, 1.0e7] + ac = solve_nonlocal_small_signal_1d(smooth_prob, reabs_light.state.u, freqs) + ac_scale = np.max(np.abs(ac.total_current_density_A_m2), axis=1) + assert np.all(ac.maxwell_spread_A_m2_V <= 1.0e-8 + 1.0e-10 * ac_scale) + + dv = 1.0e-5 + s_plus = solve_nonlocal_steady_state_1d( + reabs_dev, initial_state=reabs_light.state, voltage_V=0.55 + dv, generation_scale=1.0 + ) + s_minus = solve_nonlocal_steady_state_1d( + reabs_dev, initial_state=reabs_light.state, voltage_V=0.55 - dv, generation_scale=1.0 + ) + j_plus = float(np.mean(s_plus.current_density_A_m2)) + j_minus = float(np.mean(s_minus.current_density_A_m2)) + g_dc_fd = reabs_dev.voltage_polarity * (j_plus - j_minus) / (2.0 * dv) + assert float(np.real(ac.admittance_density_S_m2[0])) == pytest.approx(g_dc_fd, rel=5e-6) + assert abs(float(np.imag(ac.admittance_density_S_m2[0]))) == 0.0 + + # Confirm nonlocal reabsorption visibly alters AC admittance vs P_esc = 1.0 (no trapping)! + no_trap_dev = compile_nonlocal_device_1d( + radiative_prepared, + intervals_per_layer=8, + photon_recycling_mode=CONTROL_VOLUME_CONSERVATIVE_V1, + explicit_escape_probabilities={abs_id: 1.0}, + ) + no_trap_light = solve_nonlocal_steady_state_1d(no_trap_dev, voltage_V=0.55, generation_scale=1.0) + ac_no_trap = solve_nonlocal_small_signal_1d( + AssembledNonlocalDC1DProblem(no_trap_dev, 0.55, 1.0), no_trap_light.state.u, [0.0] + ) + assert abs(ac.admittance_density_S_m2[0] - ac_no_trap.admittance_density_S_m2[0]) > 1.0e-3 * abs( + ac_no_trap.admittance_density_S_m2[0] + ) diff --git a/tests/unit/physics/test_photon_recycling_and_wkb.py b/tests/unit/physics/test_photon_recycling_and_wkb.py new file mode 100644 index 00000000..d010c00c --- /dev/null +++ b/tests/unit/physics/test_photon_recycling_and_wkb.py @@ -0,0 +1,549 @@ +"""T1 unit tests for photon recycling, radiative reabsorption, and WKB tunnelling.""" + +from __future__ import annotations + +import math + +import numpy as np +from numpy.typing import NDArray +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.physics.generation.optical_binding import ( + OpticalLayerSpec, + OpticalStackBinding, + constant_index_optical_constants, +) +from solarlab.physics.generation.photon_recycling import ( + TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + YABLONOVITCH_INTRINSIC_ALPHA_D_V1, + AbsorberEscapeInput, + PhotonRecyclingCapabilityError, + bind_absorber_escape_from_optical_stack, + compute_p_esc, + compute_p_esc_for_absorber, + effective_radiative_coefficient, + wavelength_at_gap, +) +from solarlab.physics.generation.radiative_reabsorption import ( + AbsorberReabsorptionSpec, + assess_switching_surfaces, + dense_reabsorption_jacobian, + evaluate_radiative_reabsorption, + radiative_reabsorption_directional_derivative, + require_smooth_ac_surfaces, + thermionic_cap_directional_derivative, + thermionic_cap_value, +) +from solarlab.physics.generation.spectrum import SpectralPhotonFlux +from solarlab.physics.transport.field_mobility_tangents import ( + field_mobility_directional_derivative, +) +from solarlab.physics.transport.tunneling_channels import ( + BandToBandTunnellingChannel, + ContactTunnellingChannel, + InterfaceDefectAssistedTunnellingChannel, + IntrabandBarrierRegion, + IntrabandTunnellingChannel, + TunnellingChannelCapabilityError, + TunnellingChannelDocument, + TunnellingChannelSchemaError, + band_to_band_flux, + compile_tunnelling_channels, + conduction_band_eV, + contact_tunnelling_flux, + interface_defect_assisted_rate, + intraband_flux, + intraband_path_flux, + intraband_path_flux_and_jacobian, + valence_band_eV, +) +from solarlab.physics.transport.wkb_tunneling import ( + kane_uniform_field_action, + piecewise_linear_wkb_segment_action_derivatives, + tfe_gamma, + triangular_barrier_action, + two_band_action, + wkb_action, +) + + +@pytest.fixture(scope="module", autouse=True) +def blas1() -> object: + with threadpool_limits(limits=1): + yield + + +# --------------------------------------------------------------------------- +# 1. Escape probability limits & explicit TMM absorbance modes +# --------------------------------------------------------------------------- + + +def test_escape_probability_asymptotic_limits_and_guardrails() -> None: + assert wavelength_at_gap(1.55) == pytest.approx(7.99898014e-7, rel=1e-6) + with pytest.raises(ValueError, match="Eg_eV"): + wavelength_at_gap(0.0) + + # Non-positive inputs clamp cleanly to 1.0 (no trapping). + assert compute_p_esc(0.0, 500e-9, 2.5) == 1.0 + assert compute_p_esc(1e5, 0.0, 2.5) == 1.0 + assert compute_p_esc(1e5, 500e-9, 0.0) == 1.0 + + # Optically thin limit (OD -> 0) clamps to 1.0 rather than > 1.0. + assert compute_p_esc(1.0, 1.0e-9, 2.5) == 1.0 + + # Optically thick limit (OD >> 1) follows 1 / (4 n_r^2 alpha d). + alpha = 1.0e7 + d = 1.0e-5 + n_r = 2.6 + expected = 1.0 / (4.0 * n_r * n_r * alpha * d) + assert compute_p_esc(alpha, d, n_r) == pytest.approx(expected, rel=1e-15) + + +def test_absorber_escape_modes_separate_intrinsic_trapezoid_and_control_volume() -> None: + wl_nm = np.linspace(400.0, 950.0, 56) + wl_m = wl_nm * 1e-9 + n_arr, k_arr = constant_index_optical_constants( + wl_nm, absorption_coefficient_m1=2.0e6, refractive_index=2.5 + ) + spectrum = SpectralPhotonFlux(wl_nm, np.full_like(wl_nm, 1.0e27), "synthetic_flat") + stack = OpticalStackBinding( + (OpticalLayerSpec("abs", 400.0e-9, n_arr, k_arr, incoherent=False, electrical=True),), + spectrum, + ) + inp = (AbsorberEscapeInput("abs", 400.0e-9, band_gap_front_eV=1.6, band_gap_back_eV=1.55),) + + b_intr = bind_absorber_escape_from_optical_stack( + stack, inp, mode=YABLONOVITCH_INTRINSIC_ALPHA_D_V1 + )[0] + assert b_intr.band_gap_eV == 1.55 + assert 0.0 < b_intr.escape_probability < 1.0 + + # Non-uniform grid distinguishes trapezoid vs control-volume weights explicitly. + x_abs = np.array([0.0, 20e-9, 90e-9, 240e-9, 400e-9]) + mask = np.ones(x_abs.size, dtype=bool) + # Deliberately distinct positive control-volume weights summing to 400 nm. + cv_weights = np.array([15e-9, 60e-9, 125e-9, 130e-9, 70e-9]) + assert math.isclose(float(np.sum(cv_weights)), 400.0e-9, rel_tol=1e-15) + + b_trap = bind_absorber_escape_from_optical_stack( + stack, + inp, + mode=TMM_INTEGRATED_ABSORBANCE_TRAPEZOID_V1, + electrical_nodes_m=x_abs, + absorber_node_masks=(mask,), + )[0] + b_cv = bind_absorber_escape_from_optical_stack( + stack, + inp, + mode=TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + electrical_nodes_m=x_abs, + absorber_node_masks=(mask,), + absorber_weights_m=(cv_weights,), + )[0] + assert b_trap.sha256 != b_cv.sha256 + assert b_trap.escape_probability != b_cv.escape_probability + + # Direct compute_p_esc_for_absorber refuses CV mode without weights. + absorbance_dummy = np.full((x_abs.size, wl_m.size), 1.0e5) + with pytest.raises(ValueError, match="weights_m"): + compute_p_esc_for_absorber( + absorbance_dummy, + wl_m, + x_abs, + 1.55, + 2.5, + mode=TMM_INTEGRATED_ABSORBANCE_CONTROL_VOLUME_V1, + ) + + +# --------------------------------------------------------------------------- +# 2. Radiative reabsorption conservation, uniform equivalence & rank-1 Jacobian +# --------------------------------------------------------------------------- + + +def test_reabsorption_photon_conservation_and_uniform_limit_equivalence() -> None: + rng = np.random.default_rng(20261113) + node_count = 18 + # Non-uniform control volumes across 3 regions: [0..4], [5..12], [13..17]. + dx = rng.uniform(5e-9, 45e-9, size=node_count) + emit_nodes: NDArray[np.intp] = np.arange(5, 13, dtype=np.intp) + # Cross-region receiver support (partially overlapping + downstream region). + recv_nodes: NDArray[np.intp] = np.arange(8, 17, dtype=np.intp) + recv_shape = np.exp(-0.25 * np.arange(recv_nodes.size, dtype=float)) + + b_rad = np.full(node_count, 4.5e-16) + ni_sq = np.full(node_count, 1.0e20) + p_esc = 0.14 + + spec_cross = AbsorberReabsorptionSpec.control_volume_conservative( + layer_id="abs_cross", + node_count=node_count, + emitter_nodes=emit_nodes, + cell_measures_m=dx, + escape_probability=p_esc, + intrinsic_radiative_B_m3_s=b_rad, + intrinsic_product_m6=ni_sq, + receiver_nodes=recv_nodes, + receiver_shape=recv_shape, + ) + n = rng.uniform(1e18, 5e21, size=node_count) + p = rng.uniform(1e18, 5e21, size=node_count) + + ev = evaluate_radiative_reabsorption((spec_cross,), n, p, derivatives=True) + budget = ev.budgets[0] + assert ev.factors[0].active is True + assert budget.emitted_flux_m2_s > 0.0 + assert abs(budget.closure_residual_m2_s) <= 1e-14 * budget.emitted_flux_m2_s + # Explicit cell-weighted integral check: sum(dx * G_rad) == (1 - P_esc) * emitted + integrated_reabs = float(np.dot(dx, ev.generation_m3_s)) + assert integrated_reabs == pytest.approx((1.0 - p_esc) * budget.emitted_flux_m2_s, rel=1e-14) + + # Spatially uniform n*p equivalence on self-reabsorbing uniform receiver: + spec_self = AbsorberReabsorptionSpec.control_volume_conservative( + layer_id="abs_self", + node_count=node_count, + emitter_nodes=emit_nodes, + cell_measures_m=dx, + escape_probability=p_esc, + intrinsic_radiative_B_m3_s=b_rad, + intrinsic_product_m6=ni_sq, + ) + np_const = 2.5e38 + n_uni = np.linspace(1.0e19, 5.0e19, node_count) + p_uni = np_const / n_uni + ev_uni = evaluate_radiative_reabsorption((spec_self,), n_uni, p_uni, derivatives=False) + net_full_minus_reabs = b_rad[emit_nodes] * (n_uni[emit_nodes] * p_uni[emit_nodes] - ni_sq[emit_nodes]) - ev_uni.generation_m3_s[emit_nodes] + b_eff = effective_radiative_coefficient( + b_rad, (np.isin(np.arange(node_count), emit_nodes),), (p_esc,) + ) + local_scaled = b_eff[emit_nodes] * (n_uni[emit_nodes] * p_uni[emit_nodes] - ni_sq[emit_nodes]) + np.testing.assert_allclose(net_full_minus_reabs, local_scaled, rtol=1e-14, atol=0.0) + + +def test_reabsorption_rank1_jacobian_matches_central_fd() -> None: + rng = np.random.default_rng(42) + node_count = 14 + x: NDArray[np.float64] = np.cumsum(np.r_[0.0, rng.uniform(8e-9, 30e-9, size=node_count - 1)]) + dx = np.empty(node_count) + dx[0] = 0.5 * (x[1] - x[0]) + dx[-1] = 0.5 * (x[-1] - x[-2]) + dx[1:-1] = 0.5 * (x[2:] - x[:-2]) + + spec_cv = AbsorberReabsorptionSpec.control_volume_conservative( + layer_id="abs_cv", + node_count=node_count, + emitter_nodes=np.arange(2, 9), + cell_measures_m=dx, + escape_probability=0.22, + intrinsic_radiative_B_m3_s=np.full(node_count, 3.0e-16), + intrinsic_product_m6=np.full(node_count, 1.0e20), + receiver_nodes=np.arange(5, 12), + ) + mask_hist: NDArray[np.bool_] = np.zeros(node_count, dtype=bool) + mask_hist[3:11] = True + spec_hist = AbsorberReabsorptionSpec.historical_trapezoid_uniform( + layer_id="abs_hist", + nodes_m=x, + absorber_mask=mask_hist, + thickness_m=float(x[10] - x[3]), + escape_probability=0.35, + intrinsic_radiative_B_m3_s=np.full(node_count, 2.0e-16), + intrinsic_product_m6=np.full(node_count, 1.0e20), + ) + + n0 = rng.uniform(2e19, 8e20, size=node_count) + p0 = rng.uniform(2e19, 8e20, size=node_count) + specs = (spec_cv, spec_hist) + ev = evaluate_radiative_reabsorption(specs, n0, p0, derivatives=True) + dn_ana, dp_ana = dense_reabsorption_jacobian(ev, node_count) + + dn_fd = np.zeros_like(dn_ana) + dp_fd = np.zeros_like(dp_ana) + for j in range(node_count): + hn = 1e-4 * n0[j] + np_plus = n0.copy() + np_minus = n0.copy() + np_plus[j] += hn + np_minus[j] -= hn + g_p = evaluate_radiative_reabsorption(specs, np_plus, p0, derivatives=False).generation_m3_s + g_m = evaluate_radiative_reabsorption(specs, np_minus, p0, derivatives=False).generation_m3_s + dn_fd[:, j] = (g_p - g_m) / (2.0 * hn) + + hp = 1e-4 * p0[j] + pp_plus = p0.copy() + pp_minus = p0.copy() + pp_plus[j] += hp + pp_minus[j] -= hp + gp_p = evaluate_radiative_reabsorption(specs, n0, pp_plus, derivatives=False).generation_m3_s + gp_m = evaluate_radiative_reabsorption(specs, n0, pp_minus, derivatives=False).generation_m3_s + dp_fd[:, j] = (gp_p - gp_m) / (2.0 * hp) + + rel_n = np.linalg.norm(dn_ana - dn_fd) / np.linalg.norm(dn_fd) + rel_p = np.linalg.norm(dp_ana - dp_fd) / np.linalg.norm(dp_fd) + assert rel_n <= 1e-10 + assert rel_p <= 1e-10 + + +# --------------------------------------------------------------------------- +# 3. Switching-surface directional derivatives (reabsorption, TE cap, PF cusp) +# --------------------------------------------------------------------------- + + +def test_switching_surfaces_expose_both_side_directional_derivatives_and_gate_ac() -> None: + node_count = 6 + dx = np.full(node_count, 50e-9) + ni_sq = np.full(node_count, 1.0e20) + spec = AbsorberReabsorptionSpec.control_volume_conservative( + layer_id="abs", + node_count=node_count, + emitter_nodes=np.arange(1, 5), + cell_measures_m=dx, + escape_probability=0.1, + intrinsic_radiative_B_m3_s=np.full(node_count, 5.0e-16), + intrinsic_product_m6=ni_sq, + ) + # Exact dark equilibrium: n * p == ni^2 => R_tot == 0 on clamp surface! + n_eq = np.full(node_count, 1.0e10) + p_eq = np.full(node_count, 1.0e10) + dn = np.full(node_count, 1.0e9) + dp = np.full(node_count, 1.0e9) + + dd_fwd = radiative_reabsorption_directional_derivative((spec,), n_eq, p_eq, dn, dp) + dd_rev = radiative_reabsorption_directional_derivative((spec,), n_eq, p_eq, -dn, -dp) + assert dd_fwd.smooth is False + assert dd_rev.smooth is False + assert dd_fwd.non_smooth_layers == ("abs",) + assert np.any(dd_fwd.directional_derivative_m3_s > 0.0) + assert np.all(dd_rev.directional_derivative_m3_s == 0.0) + + # Verify directional derivative against one-sided FD along +d and -d. + eps = 1.0e-4 + g_fwd = evaluate_radiative_reabsorption((spec,), n_eq + eps * dn, p_eq + eps * dp).generation_m3_s + g_rev = evaluate_radiative_reabsorption((spec,), n_eq - eps * dn, p_eq - eps * dp).generation_m3_s + np.testing.assert_allclose(g_fwd / eps, dd_fwd.directional_derivative_m3_s, rtol=2e-4) + np.testing.assert_array_equal(g_rev, 0.0) + + # Thermionic hard-cap crossover |J_sg| == |J_te|: + j_sg = np.array([10.0, -5.0]) + j_te = np.array([10.0, 20.0]) + dj_sg = np.array([2.0, 1.0]) + dj_te = np.array([0.5, 0.5]) + dd_te_fwd = thermionic_cap_directional_derivative(j_sg, j_te, dj_sg, dj_te) + dd_te_rev = thermionic_cap_directional_derivative(j_sg, j_te, -dj_sg, -dj_te) + assert bool(dd_te_fwd.smooth[0]) is False + assert bool(dd_te_fwd.smooth[1]) is True + assert dd_te_fwd.directional_derivative_A_m2[0] == pytest.approx(0.5) # +eps -> |J_te| smaller -> dJ_te + assert dd_te_rev.directional_derivative_A_m2[0] == pytest.approx(-2.0) # -eps -> |J_sg| smaller -> -dJ_sg + val_plus = thermionic_cap_value(j_sg + 1e-6 * dj_sg, j_te + 1e-6 * dj_te) + val_0 = thermionic_cap_value(j_sg, j_te) + assert (val_plus[0] - val_0[0]) / 1e-6 == pytest.approx( + dd_te_fwd.directional_derivative_A_m2[0], rel=1e-6 + ) + + # Poole-Frenkel cusp at E == 0: + dd_pf = field_mobility_directional_derivative( + np.array([1.0e-4]), + np.array([0.0]), + np.array([1.0e5]), + np.array([0.0]), + np.array([2.0]), + np.array([1.0e-4]), + ) + assert bool(dd_pf.smooth[0]) is False + assert bool(dd_pf.finite[0]) is False + + ev_eq = evaluate_radiative_reabsorption((spec,), n_eq, p_eq, derivatives=True) + assessment = assess_switching_surfaces( + reabsorption=ev_eq, + thermionic_electron=dd_te_fwd, + field_mobility_electron=dd_pf, + ) + assert assessment.smooth is False + assert len(assessment.reasons) == 3 + with pytest.raises(PhotonRecyclingCapabilityError, match="non_smooth_ac_switching_surface"): + require_smooth_ac_surfaces(assessment) + + +# --------------------------------------------------------------------------- +# 4. WKB closed-form actions, segment derivatives & intraband path Jacobian +# --------------------------------------------------------------------------- + + +def test_wkb_closed_form_fowler_nordheim_and_kane_zener_benchmarks() -> None: + # Fowler-Nordheim linear triangular barrier: piecewise-linear WKB is exact! + width = 6.0e-9 + height = 0.45 + mass = 0.25 + x = np.linspace(0.0, width, 25) + barrier = height * (1.0 - x / width) + s_num = wkb_action(x, barrier, 0.0, mass) + s_ref = triangular_barrier_action(height, width, mass, 0.0) + assert s_num == pytest.approx(s_ref, rel=1e-14) + + # Uniform-field Kane two-band Zener action: + gap_eV = 1.2 + field_V_m = 8.0e7 + span = 40.0e-9 + x_z = np.linspace(0.0, span, 4001) + ec = gap_eV / 2.0 - field_V_m * (x_z - 0.5 * span) + ev = ec - gap_eV + s_two = two_band_action(x_z, ec, ev, 0.0, 0.15, anchor_face=2000) + s_kane = kane_uniform_field_action(gap_eV, field_V_m, 0.15) + assert s_two == pytest.approx(s_kane, rel=1e-4) + + # Static TFE factor limits: + assert tfe_gamma(0.0, 1.0e24, 0.2, 10.0, 0.02585) == 1.0 + g_pos = tfe_gamma(0.35, 2.0e24, 0.2, 10.0, 0.02585) + assert g_pos > 1.0 + assert tfe_gamma(-0.35, 2.0e24, 0.2, 10.0, 0.02585) == g_pos + + +def test_wkb_segment_action_derivatives_and_intraband_path_jacobian_vs_fd() -> None: + x = np.array([0.0, 1.2e-9, 2.5e-9, 4.1e-9, 6.0e-9, 8.3e-9]) + # Include both sloped, flat (U_L == U_R), and crossing segments! + barrier = np.array([-0.10, 0.25, 0.25, 0.42, 0.12, -0.08]) + energies = np.array([0.0, 0.15, 0.28]) + mass = 0.22 + + derivs = piecewise_linear_wkb_segment_action_derivatives(x, barrier, energies, mass) + eps = 1.0e-6 + for j in range(x.size): + bp = barrier.copy() + bm = barrier.copy() + bp[j] += eps + bm[j] -= eps + sp = piecewise_linear_wkb_segment_action_derivatives(x, bp, energies, mass).segment_actions + sm = piecewise_linear_wkb_segment_action_derivatives(x, bm, energies, mass).segment_actions + fd_j = (sp - sm) / (2.0 * eps) + ana_j = np.zeros_like(fd_j) + if j < x.size - 1: + ana_j[:, j] += derivs.d_action_d_left_barrier_eV[:, j] + if j > 0: + ana_j[:, j - 1] += derivs.d_action_d_right_barrier_eV[:, j - 1] + np.testing.assert_allclose(ana_j, fd_j, rtol=1e-9, atol=1e-12) + + # Full intraband_path_flux_and_jacobian FD verification wrt BOTH barrier & quasi_fermi! + pts = 37 + x_bar = np.linspace(0.0, 12.0e-9, pts) + u_bar = 0.32 * np.maximum(1.0 - np.abs(x_bar - 6.0e-9) / 2.2e-9, 0.0) + 0.015 * ( + x_bar / x_bar[-1] + ) + start, stop = 12, 25 + region = IntrabandBarrierRegion( + "resolved_spike", 0, start, stop, pts, float(x_bar[start]), float(x_bar[stop]) + ) + qf = -0.22 - 0.035 * (x_bar / x_bar[-1]) + 0.004 * np.sin(2.0 * math.pi * x_bar / x_bar[-1]) + ch = IntrabandTunnellingChannel( + enabled=True, electron_effective_mass_rel=0.2, carrier="electron", energy_quadrature_order=32 + ) + vt = 0.02585 + lin = intraband_path_flux_and_jacobian( + x_bar, u_bar, ch, region=region, quasi_fermi_eV=qf, thermal_voltage_V=vt + ) + + fd_u = np.zeros_like(lin.d_face_flux_d_barrier_eV) + fd_qf = np.zeros_like(lin.d_face_flux_d_quasi_fermi_eV) + h = 1.0e-7 + for j in range(pts): + up = u_bar.copy() + um = u_bar.copy() + up[j] += h + um[j] -= h + fp = intraband_path_flux( + x_bar, up, ch, region=region, quasi_fermi_eV=qf, thermal_voltage_V=vt + ).particle_face_flux_m2_s + fm = intraband_path_flux( + x_bar, um, ch, region=region, quasi_fermi_eV=qf, thermal_voltage_V=vt + ).particle_face_flux_m2_s + fd_u[:, j] = (fp - fm) / (2.0 * h) + + qp = qf.copy() + qm = qf.copy() + qp[j] += h + qm[j] -= h + fqp = intraband_path_flux( + x_bar, u_bar, ch, region=region, quasi_fermi_eV=qp, thermal_voltage_V=vt + ).particle_face_flux_m2_s + fqm = intraband_path_flux( + x_bar, u_bar, ch, region=region, quasi_fermi_eV=qm, thermal_voltage_V=vt + ).particle_face_flux_m2_s + fd_qf[:, j] = (fqp - fqm) / (2.0 * h) + + rel_u = np.linalg.norm(lin.d_face_flux_d_barrier_eV - fd_u) / np.linalg.norm(fd_u) + rel_qf = np.linalg.norm(lin.d_face_flux_d_quasi_fermi_eV - fd_qf) / np.linalg.norm(fd_qf) + assert rel_u <= 1e-9 + assert rel_qf <= 1e-9 + + +# --------------------------------------------------------------------------- +# 5. Structural equilibrium reciprocity & explicit capability refusals +# --------------------------------------------------------------------------- + + +def test_all_four_wkb_channels_have_zero_net_flux_at_equilibrium_and_fail_closed() -> None: + x = np.linspace(0.0, 20.0e-9, 81) + phi = 0.6 * (x / x[-1]) + chi = np.where((x >= 8e-9) & (x <= 12e-9), 3.65, 4.0) + eg = np.where((x >= 8e-9) & (x <= 12e-9), 2.0, 1.1) + ec = conduction_band_eV(phi, chi) + ev = valence_band_eV(phi, chi, eg) + ef_eq = np.full_like(x, -4.25) + vt = 0.02585 + + # 1) Intraband local & path flux at flat E_F == 0 net flux: + ch_intra = IntrabandTunnellingChannel(enabled=True, carrier="electron", energy_quadrature_order=24) + f_intra = intraband_flux(x, ec, ch_intra, anchor_face=32, carrier="electron", quasi_fermi_eV=ef_eq, thermal_voltage_V=vt) + assert f_intra.net_flux_m2_s == 0.0 + + # 2) Band-to-band Zener at flat E_F == 0 net flux: + x_btbt = np.linspace(0.0, 30.0e-9, 121) + ec_btbt = 0.8 - 1.0e8 * x_btbt + ev_btbt = ec_btbt - 1.0 + ch_btbt = BandToBandTunnellingChannel(enabled=True, energy_quadrature_order=24) + f_btbt = band_to_band_flux( + x_btbt, ec_btbt, ev_btbt, ch_btbt, anchor_face=60, quasi_fermi_eV=np.full_like(x_btbt, -0.5), thermal_voltage_V=vt + ) + assert f_btbt.net_flux_m2_s == 0.0 + + # 3) Contact Schottky tunnelling at E_Fm == E_Fs == 0 net flux: + x_c = np.linspace(0.0, 15.0e-9, 61) + bar_c = 0.4 * np.exp(-x_c / 4.0e-9) + ch_c = ContactTunnellingChannel(enabled=True, barrier_height_eV=0.4, side="left", energy_quadrature_order=24) + f_c = contact_tunnelling_flux( + x_c, bar_c, ch_c, anchor_face=0, carrier="electron", metal_fermi_eV=-0.1, quasi_fermi_eV=np.full_like(x_c, -0.1), thermal_voltage_V=vt + ) + assert f_c.net_flux_m2_s == 0.0 + + # 4) Interface defect-assisted rate: refuses None occupancy; vanishes at equilibrium occupancy! + ch_tat = InterfaceDefectAssistedTunnellingChannel(enabled=True) + with pytest.raises(TunnellingChannelCapabilityError, match="explicit interface occupancy"): + interface_defect_assisted_rate( + x, ec, ev, ch_tat, + anchor_face=32, trap_energy_eV=float(ec[32]) - 0.35, occupancy=None, + trap_density_m2=1e16, electron_capture_velocity_m_s=1e3, hole_capture_velocity_m_s=1e3, + electron_density_m3=1e20, hole_density_m3=1e18, + electron_reference_density_m3=1e19, hole_reference_density_m3=1e19, + ) + # Detailed-balance equilibrium where n*p == n1*p1 => f_eq gives electron_net == hole_net == 0! + tat_eq = interface_defect_assisted_rate( + x, ec, ev, ch_tat, + anchor_face=32, trap_energy_eV=float(ec[32]) - 0.35, occupancy=0.5, + trap_density_m2=1e16, electron_capture_velocity_m_s=1e3, hole_capture_velocity_m_s=1e3, + electron_density_m3=1e19, hole_density_m3=1e19, + electron_reference_density_m3=1e19, hole_reference_density_m3=1e19, + ) + assert tat_eq.electron_net_rate_m2_s == 0.0 + assert tat_eq.hole_net_rate_m2_s == 0.0 + assert tat_eq.net_rate_m2_s == 0.0 + + # Schema & device capability refusals: + with pytest.raises(TunnellingChannelSchemaError, match="algebraically eliminated"): + InterfaceDefectAssistedTunnellingChannel(enabled=True, requires_explicit_occupancy=False) # type: ignore[arg-type] + with pytest.raises(TunnellingChannelSchemaError, match="barrier_height_eV"): + ContactTunnellingChannel(enabled=True, barrier_height_eV=0.0) + + doc_intra = TunnellingChannelDocument(intraband=ch_intra) + with pytest.raises(TunnellingChannelCapabilityError, match="quasi_fermi_steady_state"): + compile_tunnelling_channels(doc_intra, node_count=20, interface_nodes=(8,), driver="mol_transient") From 44aa8f6204308560b446177671b51036b4b69e19 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sun, 15 Nov 2026 14:04:40 +0800 Subject: [PATCH 15/46] N(physics,experiments): migrate dynamic, distributed, multivalent, and metastable 1D defects plus defect/ion AC, C-f, and transients onto unified assembly (P04-10, P05-03b, P05-04b) --- .../device/compile_dynamic_defect_1d.py | 1728 ++++++++++ .../equations/assembly/dynamic_defects_1d.py | 2859 +++++++++++++++++ src/solarlab/equations/dynamic_defect_1d.py | 955 ++++++ .../experiments/capacitance_frequency.py | 379 +++ .../experiments/defect_ion_impedance.py | 297 ++ .../experiments/dynamic_defect_impedance.py | 567 ++++ .../experiments/dynamic_defect_transient.py | 871 +++++ .../experiments/metastable_transient.py | 749 +++++ src/solarlab/physics/defects/__init__.py | 173 + src/solarlab/physics/defects/distributions.py | 531 +++ .../physics/defects/dynamic_single_level.py | 1357 ++++++++ src/solarlab/physics/defects/metastable.py | 644 ++++ src/solarlab/physics/defects/multivalent.py | 540 ++++ .../physics/interface_transport/__init__.py | 4 + .../physics/interface_transport/two_sided.py | 451 +++ .../test_defect_ion_impedance_parity.py | 435 +++ .../test_dynamic_defect_parity_1d.py | 1026 ++++++ .../equations/test_defect_ion_coupled_ac.py | 516 +++ .../test_dynamic_defect_experiments.py | 662 ++++ tests/unit/physics/test_dynamic_defects.py | 990 ++++++ 20 files changed, 15734 insertions(+) create mode 100644 src/solarlab/device/compile_dynamic_defect_1d.py create mode 100644 src/solarlab/equations/assembly/dynamic_defects_1d.py create mode 100644 src/solarlab/equations/dynamic_defect_1d.py create mode 100644 src/solarlab/experiments/capacitance_frequency.py create mode 100644 src/solarlab/experiments/defect_ion_impedance.py create mode 100644 src/solarlab/experiments/dynamic_defect_impedance.py create mode 100644 src/solarlab/experiments/dynamic_defect_transient.py create mode 100644 src/solarlab/experiments/metastable_transient.py create mode 100644 src/solarlab/physics/defects/__init__.py create mode 100644 src/solarlab/physics/defects/distributions.py create mode 100644 src/solarlab/physics/defects/dynamic_single_level.py create mode 100644 src/solarlab/physics/defects/metastable.py create mode 100644 src/solarlab/physics/defects/multivalent.py create mode 100644 tests/integration/test_defect_ion_impedance_parity.py create mode 100644 tests/integration/test_dynamic_defect_parity_1d.py create mode 100644 tests/unit/equations/test_defect_ion_coupled_ac.py create mode 100644 tests/unit/experiments/test_dynamic_defect_experiments.py create mode 100644 tests/unit/physics/test_dynamic_defects.py diff --git a/src/solarlab/device/compile_dynamic_defect_1d.py b/src/solarlab/device/compile_dynamic_defect_1d.py new file mode 100644 index 00000000..506704bd --- /dev/null +++ b/src/solarlab/device/compile_dynamic_defect_1d.py @@ -0,0 +1,1728 @@ +"""Bind a PreparedDevice to the unified dynamic-defect and metastable 1D models (P04-10). + +Supported (everything else raises :class:`CapabilityError` before any solve): + +* explicit monovalent bulk defects (charged, neutral, distributed, spatially graded) + and legacy ``bulk_trap_distribution`` declarations as stationary quasi-steady + inventories (``dynamic_bulk_defects=False``) or as explicit trap-occupancy + storage DOFs on interior active nodes (``dynamic_bulk_defects=True``); +* explicit multivalent / amphoteric bulk defects (``solarlab-explicit-bulk-defects-v4``) + in stationary grand-partition closure (``dynamic_bulk_defects=False``); +* contact-layer equilibrium charge-neutrality rebinding when an outer electrical + layer carries explicit charged/distributed/multivalent bulk defects; +* dynamic two-sided heterointerface single-level traps with equilibrium-referenced + or off sheet-charge closure (``dynamic_interface_defects=True``), including + stacks mixing microscopic defect interfaces with passive interfaces; +* mobile finite-site ions coupled to bulk and/or interface defects on both the + deduplicated topology (:class:`CompiledIonicDevice1D`) and the two-sided trace + topology (:class:`TwoSidedIonicComponent1D`); +* two-configuration metastable bulk-defect inventories compiled via + :func:`compile_metastable_device_1d` into :class:`CompiledMetastableDevice1D`. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import replace +import hashlib +import json +import math +from typing import Any, Literal, cast + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import ION_INPUTS, compile_ionic_device_1d +from solarlab.device.defects import ( + LegacyBulkTrapInput, + MetastableDocumentInput, + MetastablePreparationInput, +) +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice, PreparedLayer, PreparedMultivalentDefect +from solarlab.equations.dc_1d import ( + CapabilityError, + CompiledDevice1D, + CompiledInterfaceModel1D, + TERegularizationName, + TwoSidedInterfaceBindingSpec, +) +from solarlab.equations.dynamic_defect_1d import ( + CompiledDynamicDefectDevice1D, + CompiledMetastableDevice1D, + DynamicInterfaceTrapBinding1D, + StationaryDefectModel1D, + TwoSidedIonicComponent1D, +) +from solarlab.equations.ionic_1d import CompiledIonicDevice1D +from solarlab.mesh import RIGHT_LAYER_WINS +from solarlab.mesh.geometry import ( + ControlVolumeGeometry1D, + NO_SHARED_NODES, + TWO_SIDED_TRACE_V1, +) +from solarlab.mesh.grid import layer_node_masks +from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature +from solarlab.physics.contacts.exchange import ( + STATISTICS_CLOSURE, + CarrierExchangeChannel, +) +from solarlab.physics.defects import ( + DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + DefectDistributionSpec, + DynamicInterfaceTrapSpec, + FrozenMetastableRegion, + MetastableConversionKineticsSpec, + MetastableDefectSpec, + MonovalentDefectRegion, + MonovalentSpeciesSpec, + MultivalentConfigurationSpec, + MultivalentDefectRegion, + MultivalentSpeciesSpec, + MultivalentTransitionKineticsSpec, + SpatialDensityProfileSpec, + SpatialProfileKnot, + WIDTH_GAUSSIAN_SIGMA, + WIDTH_NOT_APPLICABLE, + compile_dynamic_bulk_trap_layout, + quasi_steady_bulk_trap_logit, + solve_monovalent_defect_charge_neutrality, + solve_multivalent_defect_charge_neutrality, + validate_defect_energy_quadrature_order, +) +from solarlab.physics.electrostatics.interface_traces import sheet_charge_row_weights +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + solve_two_sided_interface_qss, +) +from solarlab.physics.ions import ( + DIFFUSION_ONLY_STERIC_V1, + HISTORICAL_OCCUPANCY_CLIP, + HISTORICAL_STERIC_FLOOR, + WHOLE_FLUX_STERIC_V1, +) +from solarlab.physics.recombination import ( + BulkRecombinationCoefficients, + BulkRecombinationReaction, +) + +__all__ = [ + "CapabilityError", + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "compile_dynamic_defect_device_1d", + "compile_metastable_device_1d", +] + +BINDING_SCHEMA = "solarlab.dynamic_defect_1d.binding.v2" +METASTABLE_BINDING_SCHEMA = "solarlab.metastable_defect_1d.binding.v1" +InterfaceTopologyName = Literal["deduplicated", "two_sided_trace"] + + +def _canonical(payload: object) -> str: + return hashlib.sha256( + json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False, default=str + ).encode() + ).hexdigest() + + +def _mask_lifetime_srh( + component: CompiledDevice1D, explicit_srh_nodes: NDArray[np.bool_] +) -> CompiledDevice1D: + """Disable lifetime-form SRH on nodes owned by explicit bulk/metastable defects.""" + owned = np.asarray(explicit_srh_nodes, dtype=bool) + if not np.any(owned): + return component + coeff = component.recombination.coefficients + new_coeff = BulkRecombinationCoefficients( + node_count=coeff.node_count, + ni_sq_m6=coeff.ni_sq_m6, + tau_n_s=np.where(owned, np.inf, coeff.tau_n_s), + tau_p_s=np.where(owned, np.inf, coeff.tau_p_s), + n1_m3=np.where(owned, np.maximum(coeff.n1_m3, 1.0), coeff.n1_m3), + p1_m3=np.where(owned, np.maximum(coeff.p1_m3, 1.0), coeff.p1_m3), + radiative_m3_s=coeff.radiative_m3_s, + auger_n_m6_s=coeff.auger_n_m6_s, + auger_p_m6_s=coeff.auger_p_m6_s, + ) + new_recomb = BulkRecombinationReaction( + new_coeff, component.recombination.explicit_defects + ) + new_sha = _canonical( + ["explicit_srh_mask_v1", component.identity, np.flatnonzero(owned).tolist()] + ) + return replace(component, sha256=new_sha, recombination=new_recomb) + + +def _logit(value: float) -> float: + if not 0.0 < value < 1.0: + raise CapabilityError( + f"interface reference occupancy {value!r} saturated outside (0, 1)" + ) + return math.log(value) - math.log1p(-value) + + +def _species_from_item(layer_id: str, item: dict[str, Any]) -> MonovalentSpeciesSpec: + where = f"layers.{layer_id}.bulk_defects.{item['id']}" + distribution = item["distribution"] + kinetics = item["kinetics"] + if item["charge_transition"] not in ("acceptor", "donor", "neutral"): + raise CapabilityError( + f"{where}: charge_transition must be acceptor, donor, or neutral" + ) + if float(item["degeneracy"]) != 1.0: + raise CapabilityError(f"{where}: monovalent defects require unit degeneracy") + center = distribution["center_eV_above_vb"] + if center is None: + raise CapabilityError( + f"{where}: a resolved energy above the valence band is required" + ) + try: + spec = DefectDistributionSpec( + kind=str(distribution["kind"]), + center_eV_above_vb=float(center), + total_density_m3=float(distribution["total_density_m3"]), + width_eV=( + 0.0 + if distribution.get("width_eV") is None + else float(distribution["width_eV"]) + ), + width_convention=( + "not_applicable" + if distribution.get("width_convention") in (None, "not_applicable") + else str(distribution["width_convention"]) + ), + support_width_multiplier=( + None + if distribution.get("support_width_multiplier") is None + else float(distribution["support_width_multiplier"]) + ), + ) + profile = item.get("spatial_profile") + spatial = None + if profile is not None: + spatial = SpatialDensityProfileSpec( + tuple( + SpatialProfileKnot( + float(knot["position_fraction"]), + float(knot["density_multiplier"]), + ) + for knot in profile["knots"] + ) + ) + return MonovalentSpeciesSpec( + identifier=f"{layer_id}/{item['id']}", + charge_transition=str(item["charge_transition"]), + distribution=spec, + sigma_n_m2=float(kinetics["sigma_n_m2"]), + sigma_p_m2=float(kinetics["sigma_p_m2"]), + thermal_velocity_n_m_s=float(kinetics["thermal_velocity_n_m_s"]), + thermal_velocity_p_m_s=float(kinetics["thermal_velocity_p_m_s"]), + spatial_profile=spatial, + ) + except ValueError as error: + raise CapabilityError(f"{where}: {error}") from error + + +def _species_from_legacy_bulk_trap( + layer_id: str, trap_data: Mapping[str, Any] +) -> MonovalentSpeciesSpec: + where = f"layers.{layer_id}.bulk_trap_distribution" + kind = str(trap_data["distribution"]) + try: + spec = DefectDistributionSpec( + kind=kind, + center_eV_above_vb=float(trap_data["center_eV_above_vb"]), + total_density_m3=float(trap_data["total_density_m3"]), + width_eV=( + 0.0 + if kind == "single_level" + else float(trap_data["energy_sigma_eV"]) + ), + width_convention=( + WIDTH_NOT_APPLICABLE if kind == "single_level" else WIDTH_GAUSSIAN_SIGMA + ), + support_width_multiplier=None, + ) + v_th = float(trap_data["thermal_velocity_m_s"]) + return MonovalentSpeciesSpec( + identifier=f"{layer_id}/bulk_trap_distribution", + charge_transition=str(trap_data["charge_transition"]), + distribution=spec, + sigma_n_m2=float(trap_data["sigma_n_m2"]), + sigma_p_m2=float(trap_data["sigma_p_m2"]), + thermal_velocity_n_m_s=v_th, + thermal_velocity_p_m_s=v_th, + ) + except ValueError as error: + raise CapabilityError(f"{where}: {error}") from error + + +def _multivalent_config_from_mapping( + where: str, cfg: Mapping[str, Any] +) -> MultivalentConfigurationSpec: + try: + kinetics = tuple( + MultivalentTransitionKineticsSpec( + sigma_n_m2=float(kin["sigma_n_m2"]), + sigma_p_m2=float(kin["sigma_p_m2"]), + thermal_velocity_n_m_s=float(kin["thermal_velocity_n_m_s"]), + thermal_velocity_p_m_s=float(kin["thermal_velocity_p_m_s"]), + ) + for kin in cfg["transition_kinetics"] + ) + return MultivalentConfigurationSpec( + family=str(cfg["family"]), + charge_states_e=tuple(int(c) for c in cfg["charge_states_e"]), + degeneracy_convention=str(cfg["degeneracy_convention"]), + state_degeneracies=tuple(float(g) for g in cfg["state_degeneracies"]), + transition_energies_eV_above_vb=tuple( + float(e) for e in cfg["transition_energies_eV_above_vb"] + ), + transition_kinetics=kinetics, + ) + except ValueError as error: + raise CapabilityError(f"{where}: {error}") from error + + +def _multivalent_from_item( + layer_id: str, item: Mapping[str, Any] +) -> MultivalentSpeciesSpec: + where = f"layers.{layer_id}.bulk_defects.{item['id']}" + cfg = _multivalent_config_from_mapping(where, item["configuration"]) + try: + return MultivalentSpeciesSpec( + identifier=f"{layer_id}/{item['id']}", + total_density_m3=float(item["total_density_m3"]), + configuration=cfg, + ) + except ValueError as error: + raise CapabilityError(f"{where}: {error}") from error + + +def _metastable_from_item( + layer_id: str, item: Mapping[str, Any] +) -> MetastableDefectSpec: + where = f"layers.{layer_id}.metastable_defects.{item['id']}" + donor_cfg = _multivalent_config_from_mapping( + f"{where}.donor_configuration", item["donor_configuration"] + ) + acceptor_cfg = _multivalent_config_from_mapping( + f"{where}.acceptor_configuration", item["acceptor_configuration"] + ) + kin = item["conversion_kinetics"] + try: + conv = MetastableConversionKineticsSpec( + transition_energy_eV_above_vb=float(kin["transition_energy_eV_above_vb"]), + electron_capture_activation_eV=float(kin["electron_capture_activation_eV"]), + electron_emission_activation_eV=float( + kin["electron_emission_activation_eV"] + ), + hole_capture_activation_eV=float(kin["hole_capture_activation_eV"]), + hole_emission_activation_eV=float(kin["hole_emission_activation_eV"]), + electron_capture_path=str(kin["electron_capture_path"]), + hole_capture_path=str(kin["hole_capture_path"]), + capture_n_m3_s=float(kin["capture_n_m3_s"]), + capture_p_m3_s=float(kin["capture_p_m3_s"]), + phonon_frequency_Hz=float(kin["phonon_frequency_Hz"]), + ) + return MetastableDefectSpec( + identifier=f"{layer_id}/{item['id']}", + total_density_m3=float(item["total_density_m3"]), + donor_configuration=donor_cfg, + acceptor_configuration=acceptor_cfg, + donor_conversion_state_index=int(item["donor_conversion_state_index"]), + acceptor_conversion_state_index=int(item["acceptor_conversion_state_index"]), + conversion_kinetics=conv, + ) + except ValueError as error: + raise CapabilityError(f"{where}: {error}") from error + + +def _compile_two_sided_ionic_component( + *, + original_prepared: PreparedDevice, + component_prepared: PreparedDevice, + component: CompiledDevice1D, + projection_changes: list[dict[str, object]], + layers: tuple[PreparedLayer, ...], + ion_domain_layer: str | None, + ion_domain_endpoints: tuple[str, str] | None, +) -> TwoSidedIonicComponent1D: + """Bind a single-layer blocking finite-site ion domain onto TWO_SIDED_TRACE_V1.""" + data = original_prepared.to_mapping() + if ion_domain_layer is None: + mobile_layers = [ + layer + for layer in layers + if any( + float(cast(float, dict(layer.parameters)[name])) != 0.0 + for name in ("D_ion", "D_ion_neg") + ) + ] + active_layers = mobile_layers or [ + layer + for layer in layers + if any( + float(cast(float, dict(layer.parameters)[name])) != 0.0 + for name in ("P0", "D_ion", "P0_neg", "D_ion_neg") + ) + ] + if len(layers) == 1: + domain_layer = layers[0] + elif len(active_layers) == 1 and ion_domain_endpoints == ("blocking", "blocking"): + domain_layer = active_layers[0] + else: + raise CapabilityError( + "two_sided_ionic_1d: multilayer device requires explicit ion_domain_layer and blocking endpoints" + ) + else: + selected = [layer for layer in layers if layer.id == ion_domain_layer] + if len(selected) != 1: + raise CapabilityError( + "two_sided_ionic_1d: ion_domain_layer must name one electrical layer" + ) + domain_layer = selected[0] + + if ion_domain_endpoints is None: + if len(layers) != 1: + raise CapabilityError( + "two_sided_ionic_1d: multilayer ion domain requires explicit ('blocking', 'blocking') endpoints" + ) + elif ion_domain_endpoints != ("blocking", "blocking"): + raise CapabilityError( + "two_sided_ionic_1d: ion interface exchange is unsupported; declare ('blocking', 'blocking')" + ) + + shared = bool(data["settings"]["ion_steric_shared_site"]) + if shared and not data["settings"]["ion_steric_diffusion_only"]: + raise CapabilityError( + "shared-site ions require the original diffusion-only crowding law" + ) + for layer in original_prepared.layers: + params = dict(layer.parameters) + if layer.role == "substrate" and any( + params[name] != 0.0 for name in ("P0", "D_ion", "P0_neg", "D_ion_neg") + ): + raise CapabilityError("two_sided_ionic_1d: substrate ion domains are unsupported") + if layer.id != domain_layer.id and any( + params[name] != 0.0 for name in ("D_ion", "D_ion_neg") + ): + raise CapabilityError( + "two_sided_ionic_1d: multiple active ion layers are unsupported" + ) + + parameters = dict(domain_layer.parameters) + reference = float(cast(float, parameters["P0"])) + capacity = float(cast(float, parameters["P_lim"])) + diffusion = float(cast(float, parameters["D_ion"])) + activation = float(cast(float, parameters["E_a_ion"])) + if not all(math.isfinite(v) for v in (reference, capacity, diffusion, activation)): + raise CapabilityError("two_sided_ionic_1d: finite ionic parameters are required") + if not 0.0 < reference < capacity: + raise CapabilityError( + "two_sided_ionic_1d: a strictly positive, unsaturated finite-site reference is required" + ) + if diffusion < 0.0 or activation < 0.0: + raise CapabilityError( + "two_sided_ionic_1d: diffusivity/activation energy must be non-negative" + ) + + negative_reference = float(cast(float, parameters["P0_neg"])) + negative_capacity = float(cast(float, parameters["P_lim_neg"])) + negative_diffusion = float(cast(float, parameters["D_ion_neg"])) + dual = negative_reference != 0.0 or negative_diffusion != 0.0 + if dual: + if not all( + math.isfinite(v) + for v in (negative_reference, negative_capacity, negative_diffusion) + ): + raise CapabilityError( + "two_sided_ionic_1d: finite negative-ion parameters are required" + ) + if not 0.0 < negative_reference < negative_capacity: + raise CapabilityError( + "two_sided_ionic_1d: a positive unsaturated negative-ion reference is required" + ) + if negative_diffusion < 0.0: + raise CapabilityError( + "two_sided_ionic_1d: negative-ion diffusivity must be non-negative" + ) + if shared: + if not dual: + raise CapabilityError( + "shared-site ions require both declared positive and negative references" + ) + if capacity != negative_capacity: + raise CapabilityError( + "shared-site ions require one exactly common site capacity" + ) + if ( + not math.isfinite(reference + negative_reference) + or reference + negative_reference >= capacity + ): + raise CapabilityError( + "shared-site reference summed occupancy must be below the common capacity" + ) + + domain_index = layers.index(domain_layer) + planes = component.geometry.interfaces + left = 0 if domain_index == 0 else int(planes[domain_index - 1].right_node) + right = ( + component.node_count - 1 + if domain_index == len(layers) - 1 + else int(planes[domain_index].left_node) + ) + indices: np.ndarray = np.arange(left, right + 1, dtype=np.intp) + if indices.size < 3: + raise CapabilityError( + "two_sided_ionic_1d: ion domain requires at least 3 trace nodes" + ) + ion_geometry = ControlVolumeGeometry1D( + TWO_SIDED_TRACE_V1, + component.geometry.nodes_m[indices], + component.geometry.cell_measures_m[indices], + component.geometry.cell_faces_m[left : right + 2], + (), + NO_SHARED_NODES, + NO_SHARED_NODES, + ) + count = ion_geometry.node_count + scaled_diffusion = ion_diffusivity_at_temperature( + diffusion, component.parameters.temperature_K, activation + ) + if not math.isfinite(scaled_diffusion) or scaled_diffusion < 0.0: + raise CapabilityError( + "two_sided_ionic_1d: temperature-scaled ion diffusivity is outside the finite envelope" + ) + occ = reference / capacity + logit = math.log(occ) - math.log1p(-occ) + steric_model = ( + DIFFUSION_ONLY_STERIC_V1 + if data["settings"]["ion_steric_diffusion_only"] + else WHOLE_FLUX_STERIC_V1 + ) + ref_arr: np.ndarray = np.full(count, reference, dtype=np.float64) + lim_arr: np.ndarray = np.full(count, capacity, dtype=np.float64) + faces: np.ndarray = np.full(count - 1, scaled_diffusion, dtype=np.float64) + pos_logit_arr: np.ndarray = np.full(count, logit, dtype=np.float64) + neg_arrays: dict[str, np.ndarray] = {} + if dual: + scaled_neg = ion_diffusivity_at_temperature( + negative_diffusion, component.parameters.temperature_K, activation + ) + if not math.isfinite(scaled_neg) or scaled_neg < 0.0: + raise CapabilityError( + "two_sided_ionic_1d: temperature-scaled negative diffusivity is outside the finite envelope" + ) + neg_occ = negative_reference / negative_capacity + neg_logit = math.log(neg_occ) - math.log1p(-neg_occ) + neg_arrays = { + "negative_ion_reference_m3": np.full(count, negative_reference, dtype=np.float64), + "negative_ion_site_limit_m3": np.full(count, negative_capacity, dtype=np.float64), + "negative_ion_logit_reference": np.full(count, neg_logit, dtype=np.float64), + "negative_ion_diffusivity_faces_m2_s": np.full( + count - 1, scaled_neg, dtype=np.float64 + ), + } + if shared: + vacancy = ( + 1.0 + - (ref_arr + neg_arrays["negative_ion_reference_m3"]) / lim_arr + ) + pos_logit_arr = np.log(ref_arr / lim_arr) - np.log(vacancy) + neg_arrays["negative_ion_logit_reference"] = np.log( + neg_arrays["negative_ion_reference_m3"] / lim_arr + ) - np.log(vacancy) + + declarations = [ + { + "layer": lyr.id, + **{name: dict(lyr.parameters)[name] for name in ION_INPUTS}, + } + for lyr in original_prepared.layers + ] + manifest: dict[str, Any] = { + "binding": ( + "two_sided_shared_site_dual_ion_1d_v1" + if shared + else ( + "two_sided_independent_dual_ion_1d_v1" + if dual + else "two_sided_single_positive_ion_1d_v1" + ) + ), + "original_prepared_sha256": original_prepared.content_sha256, + "original_ionic_inputs": declarations, + "electronic_component": { + "prepared_sha256": component_prepared.content_sha256, + "compiled_sha256": component.identity, + "projection": projection_changes, + "geometry": component.geometry.name, + }, + "ion_domain": { + "layer": domain_layer.id, + "electrical_node_indices": indices.tolist(), + "geometry": ion_geometry.name, + "contacts": ["blocking", "blocking"], + "reference_inventory_m2": math.fsum( + (ion_geometry.cell_measures_m * ref_arr).tolist() + ), + }, + "ion_model": { + "steric_model": steric_model, + "occupancy_clip": HISTORICAL_OCCUPANCY_CLIP, + "steric_floor": HISTORICAL_STERIC_FLOOR, + "activation_energy_eV": activation, + "temperature_K": component.parameters.temperature_K, + "face_diffusivity_m2_s": faces.tolist(), + }, + } + encoded = json.dumps(manifest, sort_keys=True, separators=(",", ":"), allow_nan=False) + identity = hashlib.sha256(encoded.encode()).hexdigest() + return TwoSidedIonicComponent1D( + device_id=str(data["id"]), + sha256=identity, + original_prepared_sha256=original_prepared.content_sha256, + electronic_component=component, + ion_geometry=ion_geometry, + domain_layer_id=domain_layer.id, + positive_ion_reference_m3=ref_arr, + positive_ion_site_limit_m3=lim_arr, + positive_ion_logit_reference=pos_logit_arr, + positive_ion_diffusivity_faces_m2_s=faces, + steric_model=steric_model, + binding_manifest_json=encoded, + ion_node_indices=indices, + negative_ion_reference_m3=neg_arrays.get("negative_ion_reference_m3", np.empty(0)), + negative_ion_site_limit_m3=neg_arrays.get("negative_ion_site_limit_m3", np.empty(0)), + negative_ion_logit_reference=neg_arrays.get( + "negative_ion_logit_reference", np.empty(0) + ), + negative_ion_diffusivity_faces_m2_s=neg_arrays.get( + "negative_ion_diffusivity_faces_m2_s", np.empty(0) + ), + ion_site_contract="shared_finite_sites" if shared else "independent_finite_sites", + ) + + +def _rebind_contact_neutrality( + component: CompiledDevice1D, + *, + last_layer_index: int, + layer_species: Mapping[int, Sequence[MonovalentSpeciesSpec]], + layer_multivalent: Mapping[int, Sequence[MultivalentSpeciesSpec]], + energy_quadrature_order: int, +) -> CompiledDevice1D: + """Re-solve contact equilibrium neutrality when outer layers carry bulk defects.""" + left_has = 0 in layer_species or 0 in layer_multivalent + right_has = last_layer_index in layer_species or last_layer_index in layer_multivalent + if not left_has and not right_has: + return component + + parameters = component.parameters + bands = parameters.band_structure + temp = float(parameters.temperature_K) + vt = float(parameters.thermal_voltage_V) + + def solve_endpoint( + layer_idx: int, node: int, position: float + ) -> tuple[float, tuple[float, float]]: + gap = float(bands.physical_band_gap_eV[node]) + chi = float(bands.physical_electron_affinity_eV[node]) + nc = float(parameters.conduction_dos_m3[node]) + nv = float(parameters.valence_dos_m3[node]) + nd = float(parameters.donor_density_m3[node]) + na = float(parameters.acceptor_density_m3[node]) + if layer_idx in layer_species: + st = solve_monovalent_defect_charge_neutrality( + temperature_K=temp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=nd, + acceptor_density_m3=na, + species=layer_species[layer_idx], + electron_affinity_eV=chi, + energy_quadrature_order=energy_quadrature_order, + normalized_layer_position=position, + ) + assert st.work_function_eV is not None + return float(st.work_function_eV), ( + float(st.electron_density_m3), + float(st.hole_density_m3), + ) + st_mv = solve_multivalent_defect_charge_neutrality( + temperature_K=temp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=nd, + acceptor_density_m3=na, + species=layer_multivalent[layer_idx], + electron_affinity_eV=chi, + ) + assert st_mv.work_function_eV is not None + return float(st_mv.work_function_eV), ( + float(st_mv.electron_density_m3), + float(st_mv.hole_density_m3), + ) + + base_work_left = -component.fermi_level_eV - component.phi_left_V + base_work_right = base_work_left - component.built_in_potential_V + if left_has: + work_left, res_left = solve_endpoint(0, 0, 0.0) + else: + work_left = base_work_left + res_left = ( + float(component.reference_electron_density_m3[0]), + float(component.reference_hole_density_m3[0]), + ) + if right_has: + work_right, res_right = solve_endpoint(last_layer_index, -1, 1.0) + else: + work_right = base_work_right + res_right = ( + float(component.reference_electron_density_m3[-1]), + float(component.reference_hole_density_m3[-1]), + ) + + phi_left = component.phi_left_V + built_in = work_left - work_right + fermi = -work_left - phi_left + nodes = component.nodes_m + ref_phi = phi_left + built_in * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + ref_n = parameters.conduction_dos_m3 * np.exp( + (fermi + ref_phi + bands.physical_electron_affinity_eV) / vt + ) + ref_p = parameters.valence_dos_m3 * np.exp( + -( + fermi + + ref_phi + + bands.physical_electron_affinity_eV + + bands.physical_band_gap_eV + ) + / vt + ) + ref_n[0], ref_p[0] = res_left + ref_n[-1], ref_p[-1] = res_right + reservoirs = (res_left, res_right) + rebound_sides = {"left": left_has, "right": right_has} + new_channels = tuple( + CarrierExchangeChannel( + ch.carrier, + ch.side, + ch.velocity_m_s, + reservoirs[0 if ch.side == "left" else 1][0 if ch.carrier == "n" else 1], + reservoir_source=( + STATISTICS_CLOSURE if rebound_sides[ch.side] else ch.reservoir_source + ), + ) + for ch in component.channels + ) + rebound_sha = _canonical( + [ + "defect_contact_neutrality_v1", + component.identity, + work_left, + work_right, + res_left, + res_right, + ] + ) + return replace( + component, + sha256=rebound_sha, + built_in_potential_V=built_in, + fermi_level_eV=fermi, + reference_potential_V=ref_phi, + reference_electron_density_m3=ref_n, + reference_hole_density_m3=ref_p, + channels=new_channels, + ) + + +def compile_dynamic_defect_device_1d( + prepared: PreparedDevice, + *, + intervals_per_layer: int | Sequence[int] = 24, + dynamic_bulk_defects: bool = False, + dynamic_interface_defects: bool = False, + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + interface_topology: InterfaceTopologyName | None = None, + ion_domain_layer: str | None = None, + ion_domain_endpoints: tuple[str, str] | None = None, + te_softness: float = 0.02, + te_regularization_mode: TERegularizationName = "legacy_logistic", + interface_transmission: float = 1.0, +) -> CompiledDynamicDefectDevice1D: + """Compile stationary/dynamic bulk defects, dynamic interface traps, and ions.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("compile_dynamic_defect_device_1d requires an existing PreparedDevice") + try: + quad_order = validate_defect_energy_quadrature_order(energy_quadrature_order) + except ValueError as error: + raise CapabilityError(f"unsupported_dynamic_defect_1d: {error}") from error + if interface_topology is not None and interface_topology not in ( + "deduplicated", + "two_sided_trace", + ): + raise ValueError( + "interface_topology must be 'deduplicated', 'two_sided_trace', or None" + ) + + data = prepared.to_mapping() + settings = data["settings"] + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + refusals: list[str] = [] + + layer_species: dict[int, list[MonovalentSpeciesSpec]] = {} + layer_multivalent: dict[int, list[MultivalentSpeciesSpec]] = {} + handled_ids: dict[str, set[str]] = {} + cleared_legacy_traps: set[str] = set() + + for index, layer in enumerate(layers): + if layer.metastable_document_json is not None: + refusals.append( + f"layers.{layer.id}: metastable inventories use compile_metastable_device_1d" + ) + continue + if layer.bulk_trap_distribution_json is not None: + trap_data = LegacyBulkTrapInput.model_validate( + json.loads(layer.bulk_trap_distribution_json.decode()) + ).resolved_data(dict(layer.parameters)["Eg"]) + layer_species.setdefault(index, []).append( + _species_from_legacy_bulk_trap(layer.id, trap_data) + ) + cleared_legacy_traps.add(layer.id) + if layer.defects and layer.defect_model != "explicit_quasi_steady": + refusals.append( + f"layers.{layer.id}.bulk_defects: an explicit inventory requires explicit_quasi_steady" + ) + continue + for item_obj in layer.defects: + if isinstance(item_obj, PreparedMultivalentDefect): + if dynamic_bulk_defects: + refusals.append( + f"layers.{layer.id}.bulk_defects.{item_obj.values['id']}: " + "dynamic trap storage DOFs are not bound for multivalent v4 species" + ) + continue + item = item_obj.to_mapping() + layer_multivalent.setdefault(index, []).append( + _multivalent_from_item(layer.id, item) + ) + handled_ids.setdefault(layer.id, set()).add(str(item["id"])) + continue + + item = item_obj.to_mapping() + neutral_simple = ( + not dynamic_bulk_defects + and item["charge_transition"] == "neutral" + and item["distribution"]["kind"] == "single_level" + and item.get("spatial_profile") is None + ) + if neutral_simple: + continue + layer_species.setdefault(index, []).append(_species_from_item(layer.id, item)) + handled_ids.setdefault(layer.id, set()).add(str(item["id"])) + + if refusals: + raise CapabilityError("unsupported_dynamic_defect_1d: " + "; ".join(refusals)) + if dynamic_bulk_defects and not layer_species: + raise CapabilityError( + "unsupported_dynamic_defect_1d: dynamic_bulk_defects=True requires explicit monovalent/distributed bulk defects" + ) + + closure = str(settings["interface_charge_closure"]) + if closure not in ("off", "equilibrium_referenced"): + raise CapabilityError( + f"unsupported_dynamic_defect_1d: unsupported interface_charge_closure={closure!r}" + ) + if closure == "equilibrium_referenced" and not settings[ + "interface_charge_rebaseline_acknowledged" + ]: + raise CapabilityError( + "unsupported_dynamic_defect_1d: equilibrium_referenced requires interface_charge_rebaseline_acknowledged=True" + ) + if dynamic_interface_defects and interface_topology == "deduplicated": + raise CapabilityError( + "unsupported_dynamic_defect_1d: dynamic_interface_defects requires two_sided_trace topology" + ) + use_two_sided = bool( + dynamic_interface_defects + or interface_topology == "two_sided_trace" + or closure == "equilibrium_referenced" + ) + if use_two_sided and ( + settings["interface_shared_occupancy"] + or settings["interface_plane_projection"] + or settings["interface_plane_closure"] + or settings["interface_plane_generation"] + ): + raise CapabilityError( + "unsupported_dynamic_defect_1d: shared-occupancy/plane flags are refused on two_sided_trace" + ) + + ion_active = any( + float(cast(float, dict(layer.parameters)[name])) != 0.0 + for layer in prepared.layers + for name in ("P0", "D_ion", "P0_neg", "D_ion_neg") + ) + + # ---- electronic projection ---------------------------------------------------- + projection = prepared.to_input().editing_data() + changes: list[dict[str, object]] = [] + for layer_doc in projection["layers"]: + lid = str(layer_doc["id"]) + removed = handled_ids.get(lid) + if removed: + kept = [ + entry + for entry in layer_doc.get("bulk_defects", ()) + if entry["id"] not in removed + ] + layer_doc["bulk_defects"] = kept + if not kept: + layer_doc["defect_model"] = None + layer_doc["defect_schema_version"] = None + for identifier in sorted(removed): + changes.append( + { + "path": f"layers.{lid}.bulk_defects.{identifier}", + "component_value": "removed", + } + ) + if lid in cleared_legacy_traps: + layer_doc["bulk_trap_distribution"] = None + changes.append( + { + "path": f"layers.{lid}.bulk_trap_distribution", + "component_value": None, + } + ) + if closure != "off": + projection.setdefault("settings", {})["interface_charge_closure"] = "off" + projection["settings"]["interface_charge_rebaseline_acknowledged"] = False + changes.append( + {"path": "settings.interface_charge_closure", "component_value": "off"} + ) + + ionic: CompiledIonicDevice1D | TwoSidedIonicComponent1D | None = None + if ion_active and not use_two_sided: + if ion_domain_layer is not None: + for layer_doc in projection["layers"]: + lid_cand = str(layer_doc["id"]) + if lid_cand == ion_domain_layer or layer_doc.get("role") == "substrate": + continue + p_map = layer_doc.setdefault("parameters", {}) + if float(p_map.get("D_ion", 0.0) or 0.0) == 0.0 and float( + p_map.get("D_ion_neg", 0.0) or 0.0 + ) == 0.0: + for p_key in ("P0", "P0_neg"): + if float(p_map.get(p_key, 0.0) or 0.0) != 0.0: + p_map[p_key] = 0.0 + changes.append( + { + "path": f"layers.{lid_cand}.{p_key}", + "component_value": 0.0, + } + ) + component_prepared = resolve_device( + DeviceInput.model_validate(projection), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + ionic_dedup = compile_ionic_device_1d( + component_prepared, + intervals_per_layer=intervals_per_layer, + ion_domain_layer=ion_domain_layer, + ion_domain_endpoints=ion_domain_endpoints, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + ) + component: CompiledDevice1D = _rebind_contact_neutrality( + ionic_dedup.electronic_component, + last_layer_index=len(layers) - 1, + layer_species=layer_species, + layer_multivalent=layer_multivalent, + energy_quadrature_order=quad_order, + ) + if component is not ionic_dedup.electronic_component: + ionic_dedup = replace(ionic_dedup, electronic_component=component) + ionic = ionic_dedup + else: + ion_proj_changes = list(changes) + if ion_active: + for layer_doc in projection["layers"]: + for name in ("P0", "P0_neg", "D_ion", "D_ion_neg"): + layer_doc.setdefault("parameters", {})[name] = 0.0 + ion_proj_changes.append( + { + "path": f"layers.{layer_doc['id']}.{name}", + "component_value": 0.0, + } + ) + for name in ("ion_steric_diffusion_only", "ion_steric_shared_site"): + projection.setdefault("settings", {})[name] = False + ion_proj_changes.append( + {"path": f"settings.{name}", "component_value": False} + ) + component_prepared = resolve_device( + DeviceInput.model_validate(projection), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + base_component = compile_device_1d( + component_prepared, + intervals_per_layer=intervals_per_layer, + interface_topology="two_sided_trace" if use_two_sided else interface_topology, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + interface_transmission=interface_transmission, + ) + component = _rebind_contact_neutrality( + base_component, + last_layer_index=len(layers) - 1, + layer_species=layer_species, + layer_multivalent=layer_multivalent, + energy_quadrature_order=quad_order, + ) + if ion_active: + ionic = _compile_two_sided_ionic_component( + original_prepared=prepared, + component_prepared=component_prepared, + component=component, + projection_changes=ion_proj_changes, + layers=layers, + ion_domain_layer=ion_domain_layer, + ion_domain_endpoints=ion_domain_endpoints, + ) + + # ---- bulk defect regions ------------------------------------------------------ + node_count = component.node_count + parameters = component.parameters + bands = parameters.band_structure + nodes = component.nodes_m + thicknesses = [float(layer.thickness) for layer in layers] + masks = layer_node_masks(nodes, thicknesses, RIGHT_LAYER_WINS) + edges = np.concatenate(([0.0], np.cumsum(thicknesses))) + + mono_regions: list[MonovalentDefectRegion] = [] + boundary_mono_regions: list[MonovalentDefectRegion] = [] + interior_mask: np.ndarray = np.ones(node_count, dtype=bool) + interior_mask[0] = False + interior_mask[-1] = False + + for index, species in sorted(layer_species.items()): + layer = layers[index] + mask = np.asarray(masks[index], dtype=bool) + gap = np.asarray(bands.physical_band_gap_eV, dtype=float)[mask] + conduction = np.asarray(parameters.conduction_dos_m3, dtype=float)[mask] + valence = np.asarray(parameters.valence_dos_m3, dtype=float)[mask] + position = np.clip( + (nodes[mask] - edges[index]) / (edges[index + 1] - edges[index]), 0.0, 1.0 + ) + document_digest = _canonical([layer.id, quad_order, [s.identifier for s in species]]) + try: + region = MonovalentDefectRegion( + identifier=f"layer[{index}]/{layer.id}", + document_sha256=document_digest, + active_nodes=mask, + band_gap_eV=gap, + effective_conduction_dos_m3=conduction, + effective_valence_dos_m3=valence, + temperature_K=float(parameters.temperature_K), + species=tuple(species), + energy_quadrature_order=quad_order, + normalized_layer_positions=position, + ) + except ValueError as error: + raise CapabilityError(f"layers.{layer.id}: {error}") from error + mono_regions.append(region) + + if dynamic_bulk_defects: + bmask = mask & ~interior_mask + if np.any(bmask): + bpos = np.clip( + (nodes[bmask] - edges[index]) / (edges[index + 1] - edges[index]), + 0.0, + 1.0, + ) + boundary_mono_regions.append( + MonovalentDefectRegion( + identifier=f"layer[{index}]/{layer.id}:contact_boundary", + document_sha256=document_digest, + active_nodes=bmask, + band_gap_eV=np.asarray(bands.physical_band_gap_eV, dtype=float)[ + bmask + ], + effective_conduction_dos_m3=np.asarray( + parameters.conduction_dos_m3, dtype=float + )[bmask], + effective_valence_dos_m3=np.asarray( + parameters.valence_dos_m3, dtype=float + )[bmask], + temperature_K=float(parameters.temperature_K), + species=tuple(species), + energy_quadrature_order=quad_order, + normalized_layer_positions=bpos, + ) + ) + + mv_regions: list[MultivalentDefectRegion] = [] + for index, mv_species in sorted(layer_multivalent.items()): + layer = layers[index] + mask = np.asarray(masks[index], dtype=bool) + gap = np.asarray(bands.physical_band_gap_eV, dtype=float)[mask] + conduction = np.asarray(parameters.conduction_dos_m3, dtype=float)[mask] + valence = np.asarray(parameters.valence_dos_m3, dtype=float)[mask] + doc_digest = _canonical([layer.id, [s.identifier for s in mv_species]]) + try: + mv_regions.append( + MultivalentDefectRegion( + identifier=f"layer[{index}]/{layer.id}:multivalent", + document_sha256=doc_digest, + active_nodes=mask, + band_gap_eV=gap, + effective_conduction_dos_m3=conduction, + effective_valence_dos_m3=valence, + temperature_K=float(parameters.temperature_K), + species=tuple(mv_species), + ) + ) + except ValueError as error: + raise CapabilityError(f"layers.{layer.id}: {error}") from error + + explicit_srh_mask: NDArray[np.bool_] = np.zeros(node_count, dtype=bool) + for r_mono in mono_regions: + explicit_srh_mask |= r_mono.active_nodes + for r_mv in mv_regions: + explicit_srh_mask |= r_mv.active_nodes + if np.any(explicit_srh_mask): + component = _mask_lifetime_srh(component, explicit_srh_mask) + if ionic is not None: + ionic = replace(ionic, electronic_component=component) + + # ---- validate interface defects before dark equilibrium solve ----------------- + elec_interfaces = [ + iface.to_mapping() for iface in prepared.interfaces if iface.electrical + ] + by_pair = {(str(e["left"]), str(e["right"])): e for e in elec_interfaces} + ordered_iface_entries: list[dict[str, Any]] = [] + for k in range(len(layers) - 1): + pair = (layers[k].id, layers[k + 1].id) + if pair not in by_pair: + raise CapabilityError( + f"unsupported_dynamic_defect_1d: missing electrical interface {pair[0]}->{pair[1]}" + ) + ordered_iface_entries.append(by_pair[pair]) + + if dynamic_interface_defects or closure == "equilibrium_referenced": + model_check = component.interface_model + if ( + model_check is None + or model_check.topology != "two_sided_trace" + or not model_check.two_sided + ): + raise CapabilityError( + "unsupported_dynamic_defect_1d: two-sided interfaces are required" + ) + has_defect_iface = False + for tspec in model_check.two_sided: + entry = ordered_iface_entries[tspec.interface_index] + defect = entry.get("defect") + if defect is None: + continue + has_defect_iface = True + cal = float(defect["calibration_factor"]) + state_cal = float(defect["iface_state_calibration_factor"]) + if (dynamic_interface_defects or closure == "equilibrium_referenced") and ( + cal != 1.0 or state_cal != 1.0 + ): + raise CapabilityError( + f"interfaces.{entry['id']}: empirical calibration factors are refused for dynamic/charged interface closure" + ) + raw_vn = entry.get("v_n") + raw_vp = entry.get("v_p") + micro_pair = tuple( + float(v) for v in entry["microscopic_capture_velocities_m_s"] + ) + if ( + (dynamic_interface_defects or closure == "equilibrium_referenced") + and raw_vn is not None + and raw_vp is not None + and not ( + math.isclose(float(raw_vn), micro_pair[0], rel_tol=1.0e-12, abs_tol=0.0) + and math.isclose( + float(raw_vp), micro_pair[1], rel_tol=1.0e-12, abs_tol=0.0 + ) + ) + ): + raise CapabilityError( + f"interfaces.{entry['id']}: compatibility SRV {(raw_vn, raw_vp)!r} disagrees with microscopic capture {micro_pair!r}" + ) + if not has_defect_iface: + raise CapabilityError( + "unsupported_dynamic_defect_1d: at least one microscopic interface defect is required" + ) + + def build_device( + comp_arg: CompiledDevice1D, + ionic_arg: CompiledIonicDevice1D | TwoSidedIonicComponent1D | None, + stationary_model: StationaryDefectModel1D | None, + layout: Any, + ref_logit: np.ndarray, + traps: Sequence[DynamicInterfaceTrapBinding1D], + caps: Sequence[str], + dark_seed: np.ndarray | None = None, + ) -> CompiledDynamicDefectDevice1D: + manifest: dict[str, Any] = { + "binding": BINDING_SCHEMA, + "original_prepared_sha256": prepared.content_sha256, + "electronic_component": { + "prepared_sha256": component_prepared.content_sha256, + "compiled_sha256": comp_arg.identity, + "projection": changes, + }, + "dynamic_bulk_defects": bool(dynamic_bulk_defects), + "dynamic_interface_defects": bool(dynamic_interface_defects), + "energy_quadrature_order": quad_order, + "interface_charge_closure": closure, + "ions": None if ionic_arg is None else ionic_arg.identity, + "monovalent_regions": [r.identifier for r in mono_regions], + "multivalent_regions": [r.identifier for r in mv_regions], + "scope": "assembled residual, derivatives, steady, AC and BDF; scientific qualification remains open", + } + text = json.dumps( + manifest, sort_keys=True, separators=(",", ":"), allow_nan=False, default=str + ) + identity = _canonical( + [ + text, + None if stationary_model is None else stationary_model.identity_sha256, + None if layout is None else layout.identity_sha256, + [(t.interface_id, t.reference_logit) for t in traps], + ] + ) + return CompiledDynamicDefectDevice1D( + device_id=str(data["id"]), + sha256=identity, + original_prepared_sha256=prepared.content_sha256, + electronic_component=comp_arg, + ionic_component=ionic_arg, + stationary_defects=stationary_model, + dynamic_bulk_traps=layout, + bulk_trap_reference_logit=ref_logit, + dynamic_interface_traps=tuple(traps), + binding_manifest_json=text, + capabilities=tuple(caps), + dark_equilibrium_seed=( + np.empty(0, dtype=np.float64) if dark_seed is None else dark_seed + ), + ) + + # ---- unified dark V=0, G=0 reference solve (if needed) ------------------------ + need_dark_reference = bool( + dynamic_bulk_defects + or dynamic_interface_defects + or closure == "equilibrium_referenced" + ) + dynamic_layout = ( + compile_dynamic_bulk_trap_layout(mono_regions, node_count=node_count) + if dynamic_bulk_defects + else None + ) + reference_logit: NDArray[np.float64] = np.empty(0, dtype=np.float64) + eq_occ_by_iface: dict[int, float] = {} + eq_logit_by_iface: dict[int, float] = {} + probe_eq_u: NDArray[np.float64] | None = None + + if need_dark_reference: + from solarlab.equations.assembly.dynamic_defects_1d import ( + solve_dynamic_defect_steady_1d, + ) + + probe_stationary: StationaryDefectModel1D | None = None + if mono_regions or mv_regions: + probe_stationary = StationaryDefectModel1D( + node_count=node_count, + identity_sha256=_canonical( + [ + "dark_probe", + *(r.document_sha256 for r in mono_regions), + *(r.document_sha256 for r in mv_regions), + ] + ), + monovalent_regions=tuple(mono_regions), + multivalent_regions=tuple(mv_regions), + ) + probe = build_device( + component, + ionic, + probe_stationary, + None, + np.empty(0, dtype=np.float64), + (), + ("unified_assembly", "dynamic_defect_1d_probe"), + ) + equilibrium = solve_dynamic_defect_steady_1d( + probe, voltage_V=0.0, generation_scale=0.0 + ) + if not equilibrium.converged: + raise CapabilityError( + "dynamic defect dark equilibrium reference failed to converge" + ) + probe_eq_u = np.array(equilibrium.state.u, dtype=np.float64, copy=True) + elec_eq = equilibrium.state.electronic_state + n_eq = np.asarray(elec_eq.electron_density_m3, dtype=np.float64) + p_eq = np.asarray(elec_eq.hole_density_m3, dtype=np.float64) + phi_eq = np.asarray(elec_eq.potential_V, dtype=np.float64) + zn_eq = np.asarray(elec_eq.u[node_count : 2 * node_count], dtype=np.float64) + zp_eq = np.asarray(elec_eq.u[2 * node_count : 3 * node_count], dtype=np.float64) + + if dynamic_layout is not None: + reference_logit = quasi_steady_bulk_trap_logit(n_eq, p_eq, dynamic_layout) + + if ( + component.interface_model is not None + and component.interface_model.topology == "two_sided_trace" + ): + for tspec in component.interface_model.two_sided: + entry = ordered_iface_entries[tspec.interface_index] + if entry.get("defect") is None: + continue + l_node = tspec.left_node + r_node = tspec.right_node + dark_qss = solve_two_sided_interface_qss( + tspec.trace_electrostatics, + tspec.physics, + TwoSidedBulkState( + phi_left_V=float(phi_eq[l_node]), + phi_right_V=float(phi_eq[r_node]), + n_left_m3=float(n_eq[l_node]), + p_left_m3=float(p_eq[l_node]), + n_right_m3=float(n_eq[r_node]), + p_right_m3=float(p_eq[r_node]), + electron_electrochemical_step=float( + zn_eq[r_node] - zn_eq[l_node] + ), + hole_electrochemical_step=float( + -(zp_eq[r_node] - zp_eq[l_node]) + ), + ), + ) + if dark_qss.occupancy is None: + raise CapabilityError( + f"interfaces.{entry['id']}: microscopic interface defect produced zero dark QSS occupancy" + ) + eq_occ_by_iface[tspec.interface_index] = float(dark_qss.occupancy) + n_tl, p_tl, n_tr, p_tr = (float(v) for v in dark_qss.state_m3) + vn_i = float(tspec.physics.surface_recombination_velocity_n_m_s) + vp_i = float(tspec.physics.surface_recombination_velocity_p_m_s) + filled_eq = vn_i * (n_tl + n_tr) + vp_i * ( + float(tspec.physics.p1_left_m3) + float(tspec.physics.p1_right_m3) + ) + empty_eq = vn_i * ( + float(tspec.physics.n1_left_m3) + float(tspec.physics.n1_right_m3) + ) + vp_i * (p_tl + p_tr) + eq_logit_by_iface[tspec.interface_index] = ( + math.log(filled_eq) - math.log(empty_eq) + if filled_eq > 0.0 and empty_eq > 0.0 + else _logit(float(dark_qss.occupancy)) + ) + + # ---- finalize stationary bulk model, interface bindings, and capabilities ----- + capabilities = ["unified_assembly", "dynamic_defect_1d"] + stationary: StationaryDefectModel1D | None = None + if dynamic_bulk_defects: + capabilities.append("dynamic_bulk_traps") + if boundary_mono_regions or mv_regions: + stationary = StationaryDefectModel1D( + node_count=node_count, + identity_sha256=_canonical( + [ + *(r.document_sha256 for r in boundary_mono_regions), + *(r.document_sha256 for r in mv_regions), + ] + ), + monovalent_regions=tuple(boundary_mono_regions), + multivalent_regions=tuple(mv_regions), + ) + elif mono_regions or mv_regions: + stationary = StationaryDefectModel1D( + node_count=node_count, + identity_sha256=_canonical( + [ + *(r.document_sha256 for r in mono_regions), + *(r.document_sha256 for r in mv_regions), + ] + ), + monovalent_regions=tuple(mono_regions), + multivalent_regions=tuple(mv_regions), + ) + if mono_regions: + capabilities.append("stationary_charged_defects") + if mv_regions: + capabilities.append("stationary_multivalent_defects") + + interface_traps: list[DynamicInterfaceTrapBinding1D] = [] + if dynamic_interface_defects: + assert component.interface_model is not None + for tspec in component.interface_model.two_sided: + entry = ordered_iface_entries[tspec.interface_index] + defect = entry.get("defect") + if defect is None: + continue + f_eq = eq_occ_by_iface[tspec.interface_index] + trap_nt = float(defect["total_density_m2"]) + wl = wr = 0.0 + if closure == "equilibrium_referenced": + wl, wr = sheet_charge_row_weights( + tspec.trace_electrostatics.eps_r_left, + tspec.trace_electrostatics.left_distance_m, + tspec.trace_electrostatics.eps_r_right, + tspec.trace_electrostatics.right_distance_m, + ) + trap_spec = DynamicInterfaceTrapSpec( + interface_id=str(entry["id"]), + left_node=tspec.left_node, + right_node=tspec.right_node, + charge_type="acceptor", + sheet_density_m2=trap_nt, + v_n_m_s=float(tspec.physics.surface_recombination_velocity_n_m_s), + v_p_m_s=float(tspec.physics.surface_recombination_velocity_p_m_s), + n1_left_m3=float(tspec.physics.n1_left_m3), + p1_left_m3=float(tspec.physics.p1_left_m3), + n1_right_m3=float(tspec.physics.n1_right_m3), + p1_right_m3=float(tspec.physics.p1_right_m3), + equilibrium_occupancy=f_eq, + equilibrium_referenced_charge=(closure == "equilibrium_referenced"), + ) + interface_traps.append( + DynamicInterfaceTrapBinding1D( + interface_index=tspec.interface_index, + interface_id=str(entry["id"]), + face=tspec.face, + left_node=tspec.left_node, + right_node=tspec.right_node, + trace_electrostatics=tspec.trace_electrostatics, + physics=tspec.physics, + trap_spec=trap_spec, + reference_logit=eq_logit_by_iface[tspec.interface_index], + weight_left=float(wl), + weight_right=float(wr), + ) + ) + capabilities.append("dynamic_interface_traps") + elif closure == "equilibrium_referenced": + assert component.interface_model is not None + updated_specs: list[TwoSidedInterfaceBindingSpec] = [] + for tspec in component.interface_model.two_sided: + entry = ordered_iface_entries[tspec.interface_index] + defect = entry.get("defect") + if defect is None: + updated_specs.append(tspec) + continue + f_eq = eq_occ_by_iface[tspec.interface_index] + trap_nt = float(defect["total_density_m2"]) + wl, wr = sheet_charge_row_weights( + tspec.trace_electrostatics.eps_r_left, + tspec.trace_electrostatics.left_distance_m, + tspec.trace_electrostatics.eps_r_right, + tspec.trace_electrostatics.right_distance_m, + ) + updated_specs.append( + replace( + tspec, + charge=EquilibriumReferencedSheetCharge( + equilibrium_occupancy=f_eq, + trap_density_m2=trap_nt, + ), + weight_left=float(wl), + weight_right=float(wr), + ) + ) + charged_model = CompiledInterfaceModel1D( + topology="two_sided_trace", + identity_sha256=_canonical( + [ + "charged_two_sided_v1", + component.interface_model.identity_sha256, + sorted(eq_occ_by_iface.items()), + ] + ), + two_sided=tuple(updated_specs), + ) + component = replace( + component, + sha256=_canonical([component.identity, charged_model.identity_sha256]), + interface_model=charged_model, + ) + if ionic is not None: + ionic = replace(ionic, electronic_component=component) + capabilities.append("equilibrium_referenced_interface_charge") + + if ionic is not None: + capabilities.append("mobile_ions") + + dark_seed: NDArray[np.float64] | None = None + if probe_eq_u is not None: + extra_dofs = (0 if dynamic_layout is None else dynamic_layout.size) + 2 * len( + interface_traps + ) + dark_seed = np.r_[probe_eq_u, np.zeros(extra_dofs, dtype=np.float64)] + + return build_device( + component, + ionic, + stationary, + dynamic_layout, + reference_logit, + interface_traps, + capabilities, + dark_seed, + ) + + +def compile_metastable_device_1d( + prepared: PreparedDevice, + *, + intervals_per_layer: int | Sequence[int] = 24, + te_softness: float = 0.02, + te_regularization_mode: TERegularizationName = "legacy_logistic", + interface_transmission: float = 1.0, +) -> CompiledMetastableDevice1D: + """Compile a single-layer metastable defect declaration into a freeze-ready model.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("compile_metastable_device_1d requires an existing PreparedDevice") + layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") + meta_layers = [ + (idx, layer) + for idx, layer in enumerate(layers) + if layer.metastable_document_json is not None + ] + if len(meta_layers) != 1: + raise CapabilityError( + "unsupported_metastable_1d: exactly one electrical layer must declare metastable_document" + ) + for layer in layers: + if layer.defects or layer.bulk_trap_distribution_json is not None: + raise CapabilityError( + f"layers.{layer.id}: metastable compilation refuses additional explicit bulk defect inventories" + ) + params = dict(layer.parameters) + if any(params[name] != 0.0 for name in ("P0", "D_ion", "P0_neg", "D_ion_neg")): + raise CapabilityError( + f"layers.{layer.id}: coupled mobile ions and metastable configurations are not bound" + ) + + meta_idx, meta_layer = meta_layers[0] + eg_nominal = float(cast(float, dict(meta_layer.parameters)["Eg"])) + doc_raw = json.loads(cast(bytes, meta_layer.metastable_document_json).decode()) + doc_resolved = MetastableDocumentInput.model_validate(doc_raw).resolved_data( + eg_nominal + ) + specs = tuple( + _metastable_from_item(meta_layer.id, item) + for item in doc_resolved["metastable_defects"] + ) + preparation: MetastablePreparationInput | None = None + if meta_layer.metastable_preparation_json is not None: + prep_raw = json.loads(meta_layer.metastable_preparation_json.decode()) + preparation = MetastablePreparationInput.model_validate(prep_raw) + + intervals_stored: int | tuple[int, ...] = ( + intervals_per_layer + if isinstance(intervals_per_layer, int) + else tuple(int(c) for c in intervals_per_layer) + ) + + def _compile_electronic_at_temperature(temp_override: float | None) -> CompiledDevice1D: + proj = prepared.to_input().editing_data() + for ldoc in proj["layers"]: + if ldoc["id"] == meta_layer.id: + ldoc.pop("metastable_document", None) + ldoc.pop("metastable_preparation", None) + ldoc["defect_model"] = None + ldoc["defect_schema_version"] = None + if temp_override is not None: + proj.setdefault("settings", {})["T"] = float(temp_override) + proj_prepared = resolve_device( + DeviceInput.model_validate(proj), + prepared.defaults, + prepared.resources, + sources=prepared.sources, + ) + return compile_device_1d( + proj_prepared, + intervals_per_layer=intervals_stored, + te_softness=te_softness, + te_regularization_mode=te_regularization_mode, + interface_transmission=interface_transmission, + ) + + base_comp = _compile_electronic_at_temperature(None) + nodes = base_comp.nodes_m + thicknesses = [float(layer.thickness) for layer in layers] + edges = np.concatenate(([0.0], np.cumsum(thicknesses))) + left_edge, right_edge = float(edges[meta_idx]), float(edges[meta_idx + 1]) + mask = (nodes >= left_edge) & (nodes <= right_edge) + # Never own outer contact nodes 0 / N-1 (matches metastable_preparation.py). + mask[[0, -1]] = False + if not np.any(mask): + raise CapabilityError( + f"layers.{meta_layer.id}: metastable layer has no interior grid nodes" + ) + base_comp = _mask_lifetime_srh(base_comp, mask) + + def _extract_region_arrays( + comp_obj: CompiledDevice1D, + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, float]: + b = comp_obj.parameters.band_structure + gap = np.asarray(b.physical_band_gap_eV, dtype=np.float64)[mask] + nc = np.asarray(comp_obj.parameters.conduction_dos_m3, dtype=np.float64)[mask] + nv = np.asarray(comp_obj.parameters.valence_dos_m3, dtype=np.float64)[mask] + for label, vals in (("band gap", gap), ("conduction DOS", nc), ("valence DOS", nv)): + if ( + vals.size == 0 + or not np.all(np.isfinite(vals)) + or np.any(vals <= 0.0) + or not np.all(vals == vals[0]) + ): + raise CapabilityError( + f"layers.{meta_layer.id}: metastable closure requires uniform positive {label}" + ) + for sp in specs: + try: + sp.validate_band_gap(float(gap[0])) + except ValueError as err: + raise CapabilityError(f"layers.{meta_layer.id}: {err}") from err + return gap, nc, nv, float(comp_obj.parameters.temperature_K) + + base_gap, base_nc, base_nv, base_temp = _extract_region_arrays(base_comp) + active_count = int(np.count_nonzero(mask)) + data = prepared.to_mapping() + doc_sha = _canonical([meta_layer.id, doc_resolved]) + + def _freeze_builder( + donor_fractions: Mapping[str, ArrayLike] | Sequence[ArrayLike], + temperature_K: float | None = None, + ) -> CompiledDynamicDefectDevice1D: + comp_f = ( + base_comp + if temperature_K is None + or math.isclose(float(temperature_K), base_temp, rel_tol=0.0, abs_tol=1e-15) + else _mask_lifetime_srh( + _compile_electronic_at_temperature(float(temperature_K)), mask + ) + ) + gap_f, nc_f, nv_f, temp_f = ( + (base_gap, base_nc, base_nv, base_temp) + if comp_f is base_comp + else _extract_region_arrays(comp_f) + ) + y_mat: NDArray[np.float64] = np.empty((len(specs), active_count), dtype=np.float64) + if isinstance(donor_fractions, Mapping): + for s_idx, sp in enumerate(specs): + short_id = sp.identifier.split("/", 1)[-1] + if sp.identifier in donor_fractions: + raw_y = donor_fractions[sp.identifier] + elif short_id in donor_fractions: + raw_y = donor_fractions[short_id] + else: + raise ValueError( + f"missing donor_fraction entry for metastable species {sp.identifier!r}" + ) + y_mat[s_idx] = np.broadcast_to( + np.asarray(raw_y, dtype=np.float64), (active_count,) + ) + else: + if len(donor_fractions) != len(specs): + raise ValueError( + "donor_fractions sequence length must match metastable_specs" + ) + for s_idx, raw_y in enumerate(donor_fractions): + y_mat[s_idx] = np.broadcast_to( + np.asarray(raw_y, dtype=np.float64), (active_count,) + ) + + f_region = FrozenMetastableRegion( + identifier=f"layer[{meta_idx}]/{meta_layer.id}", + document_sha256=doc_sha, + active_nodes=mask, + band_gap_eV=gap_f, + effective_conduction_dos_m3=nc_f, + effective_valence_dos_m3=nv_f, + temperature_K=temp_f, + species=specs, + donor_fractions=y_mat, + ) + y_digest = hashlib.sha256(y_mat.tobytes()).hexdigest() + stat_model = StationaryDefectModel1D( + node_count=comp_f.node_count, + identity_sha256=_canonical(["frozen_metastable", doc_sha, temp_f, y_digest]), + metastable_regions=(f_region,), + ) + manifest_obj = { + "binding": METASTABLE_BINDING_SCHEMA, + "original_prepared_sha256": prepared.content_sha256, + "electronic_compiled_sha256": comp_f.identity, + "layer_id": meta_layer.id, + "temperature_K": temp_f, + "donor_fractions_sha256": y_digest, + } + manifest_txt = json.dumps( + manifest_obj, sort_keys=True, separators=(",", ":"), allow_nan=False + ) + dev_sha = _canonical([manifest_txt, stat_model.identity_sha256]) + return CompiledDynamicDefectDevice1D( + device_id=str(data["id"]), + sha256=dev_sha, + original_prepared_sha256=prepared.content_sha256, + electronic_component=comp_f, + ionic_component=None, + stationary_defects=stat_model, + dynamic_bulk_traps=None, + bulk_trap_reference_logit=np.empty(0, dtype=np.float64), + dynamic_interface_traps=(), + binding_manifest_json=manifest_txt, + capabilities=( + "unified_assembly", + "dynamic_defect_1d", + "frozen_metastable_defects", + ), + ) + + meta_sha = _canonical( + [ + METASTABLE_BINDING_SCHEMA, + prepared.content_sha256, + base_comp.identity, + doc_sha, + None if preparation is None else preparation.normalized_data(), + ] + ) + return CompiledMetastableDevice1D( + device_id=str(data["id"]), + sha256=meta_sha, + prepared=prepared, + metastable_layer_id=meta_layer.id, + metastable_layer_index=meta_idx, + metastable_specs=specs, + preparation=preparation, + intervals_per_layer=intervals_stored, + base_electronic_device=base_comp, + active_nodes=mask, + band_gap_eV=base_gap, + conduction_dos_m3=base_nc, + valence_dos_m3=base_nv, + temperature_K=base_temp, + freeze_builder=_freeze_builder, + ) diff --git a/src/solarlab/equations/assembly/dynamic_defects_1d.py b/src/solarlab/equations/assembly/dynamic_defects_1d.py new file mode 100644 index 00000000..84b47378 --- /dev/null +++ b/src/solarlab/equations/assembly/dynamic_defects_1d.py @@ -0,0 +1,2859 @@ +"""Unified 1D dynamic-defect, two-sided interface-trap, and coupled defect-ion assembly. + +All physics equations, storages, constraints, steady solves, BDF transient steps, +and small-signal AC linearizations share ONE :class:`~solarlab.equations.assembly.Assembler` +binding per compiled device. Nothing is assembled twice. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from hashlib import sha256 +import json +import math +from typing import Any, TypeAlias, cast + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix, diags +from scipy.sparse.linalg import splu + +from solarlab.contracts import Geometry +from solarlab.contracts.units import ( + AREA, + COULOMB, + ELEMENTARY_CHARGE_C as Q, + LENGTH, + ONE, + PARTICLE, + SECOND, + VOLUME, + Unit, +) +from solarlab.equations.assembly.assembler import ( + AssembledSystem, + Assembler, + Mesh, + Port, + SupportGeometry, +) +from solarlab.equations.assembly.classical_1d import ( + ClassicalDC1D, + classical_dc_1d, + populate_interface_fields, +) +from solarlab.equations.assembly.ionic_1d import ( + INVENTORY_UNIT, + ImmobileProfile, + InventoryReduction, + IonDomain, + IonStorage, + IonTransport, + K1, +) +from solarlab.equations.assembly.layout import ( + Block, + ConstraintRows, + NodeSet, + SystemLayout, +) +from solarlab.equations.assembly.quasi_fermi import ( + ELECTRODE_QUASI_FERMI_1D_V1, + quasi_fermi_potential_tangents, +) +from solarlab.equations.assembly.terms import ( + CELL_SOURCE, + CONSTRAINT, + FACE_FLUX, + PORT_FLUX, + STORAGE, + Contribution, + EvaluationState, + FaceValue, + FieldValues, + LocalValue, + OperatingInputs, + ReductionValue, + Term, + TermValue, +) +from solarlab.equations.assembly.weighted import MEASURE +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dynamic_defect_1d import ( + CompiledDynamicDefectDevice1D, + DynamicDefectState1D, + DynamicInterfaceTrapBinding1D, + StationaryDefectEvaluation1D, + TwoSidedIonicComponent1D, +) +from solarlab.equations.ionic_1d import CompiledIonicDevice1D +from solarlab.equations.ionic_closure import declared_immobile_profiles, ion_mobility_partition +from solarlab.physics.contacts.boundary_flux import boundary_particle_flux +from solarlab.physics.defects import ( + DynamicBulkTrapEvaluation, + DynamicBulkTrapMode, + evaluate_dynamic_bulk_traps, + logit_occupancy_secant, +) +from solarlab.physics.electrostatics import contact_displacement +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + solve_charged_two_sided_interface_qss, + solve_fixed_occupancy_two_sided_interface, + solve_two_sided_interface_qss, +) +from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, ion_face_flux, ion_face_flux_jacobian +from solarlab.physics.transport.electrochemical_flux import ( + CarrierFaceFluxes, + carrier_particle_fluxes, +) +from solarlab.solvers.linear import FrequencyOptions, FrequencySolution, solve_frequency_systems +from solarlab.solvers.nonlinear.problem import Matrix +from solarlab.solvers.time.bdf import BDFStep, HistoryPoint, StorageProblem + +Vector: TypeAlias = NDArray[np.float64] +ComplexVector: TypeAlias = NDArray[np.complex128] + +NODES = "nodes" +POTENTIAL, ELECTRON, HOLE = "potential", "electron", "hole" +DISPLACEMENT_UNIT = COULOMB / AREA +CHARGE_UNIT = COULOMB / VOLUME +FLUX_UNIT = PARTICLE / (AREA * SECOND) +SOURCE_UNIT = PARTICLE / (VOLUME * SECOND) +DENSITY_UNIT = PARTICLE / VOLUME +TERM_SCHEMA = "solarlab.dynamic_defects_1d.terms.v1" + +__all__ = [ + "AssembledDynamicDefect1DProblem", + "DynamicBulkCarrierCaptureTerm", + "DynamicBulkTrapRateTerm", + "DynamicBulkTrapStorageTerm", + "DynamicDefectACSweepPoint", + "DynamicDefectACSweepResult", + "DynamicDefectFields", + "DynamicDefectSmallSignal1D", + "DynamicDefectSpaceCharge", + "DynamicDefectSteadyOptions", + "DynamicDefectSteadyResult", + "DynamicDefectStorage1D", + "DynamicDefectSystem1D", + "DynamicInterfaceTrapRateTerm", + "DynamicInterfaceTrapStorageTerm", + "DynamicInterfaceTrapTieTerm", + "StationaryDefectRecombinationTerm", + "dynamic_defect_step_accounting", + "dynamic_defect_system_1d", + "solve_dynamic_defect_steady_1d", +] + + +def _identity(*parts: object) -> str: + return sha256(json.dumps((TERM_SCHEMA, *parts), separators=(",", ":")).encode()).hexdigest() + + +def _scatter_two_sided_tangent( + face: int, + g_ll: float, + g_lr: float, + g_rl: float, + g_rr: float, + face_left: Vector, + face_right: Vector, + port_diag: Vector, +) -> None: + """Set 2x2 carrier Jacobian ``[[-g_ll, -g_lr], [-g_rl, -g_rr]]`` on ``(L, R)``.""" + face_left[face] = -g_rl + face_right[face] = g_lr + port_diag[face - 1] -= g_ll + g_rl + port_diag[face] -= g_rr + g_lr + + +def _scatter_three_node_tangent( + idx: int, + g_left: float, + g_mid: float, + g_right: float, + face_left: Vector, + face_right: Vector, + port_diag: Vector, +) -> None: + if g_left != 0.0: + face_left[idx - 1] += g_left + port_diag[idx - 1] += g_left + if g_mid != 0.0: + port_diag[idx] += g_mid + if g_right != 0.0: + face_right[idx] -= g_right + port_diag[idx] += g_right + + +def _populate_interfaces_with_dynamic_traps( + dyn_device: CompiledDynamicDefectDevice1D, + full_u: Vector, + elec_u: Vector, + phi: Vector, + n: Vector, + p: Vector, + iface_occ: Vector, + iface_omf: Vector, + fields: dict[str, Any], +) -> bool: + """Evaluate all static and dynamic heterointerfaces in one pass.""" + device = dyn_device.electronic_component + model = device.interface_model + if model is None and not dyn_device.dynamic_interface_traps: + return True + if not dyn_device.dynamic_interface_traps: + return populate_interface_fields(device, elec_u, phi, n, p, fields) + + count = device.node_count + thermal = device.thermal_voltage_V + electron_diffusivity = device.electron_diffusivity_faces_m2_s + hole_diffusivity = device.hole_diffusivity_faces_m2_s + transport = None if device.field_transport is None else device.field_transport.evaluate(phi) + if transport is not None: + electron_diffusivity = transport.electron_diffusivity_m2_s + hole_diffusivity = transport.hole_diffusivity_m2_s + + zn = elec_u[count : 2 * count] + zp = elec_u[2 * count : 3 * count] + base = carrier_particle_fluxes( + device.nodes_m, + phi, + n, + p, + electron_diffusivity, + hole_diffusivity, + thermal, + device.parameters.band_structure, + electron_electrochemical_step=np.diff(zn), + hole_electrochemical_step=-np.diff(zp), + ) + e_flux = np.array(base.electron.flux, dtype=float, copy=True) + e_ld = np.array(base.electron.left_density_derivative, dtype=float, copy=True) + e_rd = np.array(base.electron.right_density_derivative, dtype=float, copy=True) + h_flux = np.array(base.hole.flux, dtype=float, copy=True) + h_ld = np.array(base.hole.left_density_derivative, dtype=float, copy=True) + h_rd = np.array(base.hole.right_density_derivative, dtype=float, copy=True) + + face_count = count - 1 + interior_count = count - 2 + e_port_val: Vector = np.zeros(interior_count, dtype=float) + h_port_val: Vector = np.zeros(interior_count, dtype=float) + g_port_val: Vector = np.zeros(interior_count, dtype=float) + + e_left_phi, e_right_phi = quasi_fermi_potential_tangents(base.electron, np.diff(zn), 1.0, thermal) + h_left_phi, h_right_phi = quasi_fermi_potential_tangents(base.hole, -np.diff(zp), -1.0, thermal) + e_left_phi = np.array(e_left_phi, dtype=float, copy=True) + e_right_phi = np.array(e_right_phi, dtype=float, copy=True) + h_left_phi = np.array(h_left_phi, dtype=float, copy=True) + h_right_phi = np.array(h_right_phi, dtype=float, copy=True) + if transport is not None: + dx = np.diff(device.nodes_m) + e_chain = (e_flux / transport.electron_diffusivity_m2_s) * transport.electron_d_diffusivity_d_field / dx + h_chain = (h_flux / transport.hole_diffusivity_m2_s) * transport.hole_d_diffusivity_d_field / dx + e_left_phi = e_left_phi + e_chain + e_right_phi = e_right_phi - e_chain + h_left_phi = h_left_phi + h_chain + h_right_phi = h_right_phi - h_chain + + e_left_zn = np.array(e_ld * n[:-1], dtype=float, copy=True) + e_right_zn = np.array(e_rd * n[1:], dtype=float, copy=True) + e_left_zp: Vector = np.zeros(face_count, dtype=float) + e_right_zp: Vector = np.zeros(face_count, dtype=float) + h_left_zn: Vector = np.zeros(face_count, dtype=float) + h_right_zn: Vector = np.zeros(face_count, dtype=float) + h_left_zp = np.array(-h_ld * p[:-1], dtype=float, copy=True) + h_right_zp = np.array(-h_rd * p[1:], dtype=float, copy=True) + g_left_phi = np.array(device.poisson.face_capacitance_F_m2, dtype=float, copy=True) + g_right_phi = -np.array(device.poisson.face_capacitance_F_m2, dtype=float, copy=True) + + e_port_phi: Vector = np.zeros(interior_count, dtype=float) + e_port_zn: Vector = np.zeros(interior_count, dtype=float) + e_port_zp: Vector = np.zeros(interior_count, dtype=float) + h_port_phi: Vector = np.zeros(interior_count, dtype=float) + h_port_zn: Vector = np.zeros(interior_count, dtype=float) + h_port_zp: Vector = np.zeros(interior_count, dtype=float) + g_port_phi: Vector = np.zeros(interior_count, dtype=float) + g_port_zn: Vector = np.zeros(interior_count, dtype=float) + g_port_zp: Vector = np.zeros(interior_count, dtype=float) + g_left_zn: Vector = np.zeros(face_count, dtype=float) + g_right_zn: Vector = np.zeros(face_count, dtype=float) + g_left_zp: Vector = np.zeros(face_count, dtype=float) + g_right_zp: Vector = np.zeros(face_count, dtype=float) + + dyn_by_idx = { + itrap.interface_index: (pos, itrap) + for pos, itrap in enumerate(dyn_device.dynamic_interface_traps) + } + + try: + if model is not None and model.topology == "two_sided_trace": + for tspec in model.two_sided: + k = tspec.interface_index + f = tspec.face + l_node = tspec.left_node + r_node = tspec.right_node + bulk = TwoSidedBulkState( + phi_left_V=float(phi[l_node]), + phi_right_V=float(phi[r_node]), + n_left_m3=float(n[l_node]), + p_left_m3=float(p[l_node]), + n_right_m3=float(n[r_node]), + p_right_m3=float(p[r_node]), + electron_electrochemical_step=float(zn[r_node] - zn[l_node]), + hole_electrochemical_step=float(-(zp[r_node] - zp[l_node])), + ) + if k in dyn_by_idx: + pos, itrap = dyn_by_idx[k] + occ_val = float(iface_occ[pos]) + omf_val = float(iface_omf[pos]) + inc_val = float(full_u[dyn_device.interface_trap_slices[pos].start]) + df_eq_val = itrap.occupancy_minus_equilibrium_from_increment(inc_val) + eq_charge = EquilibriumReferencedSheetCharge( + equilibrium_occupancy=itrap.trap_spec.equilibrium_occupancy, + trap_density_m2=( + itrap.trap_density_m2 if itrap.has_sheet_charge else 0.0 + ), + ) + fixed_res = solve_fixed_occupancy_two_sided_interface( + itrap.trace_electrostatics, + itrap.physics, + bulk, + eq_charge, + occupancy=occ_val, + one_minus_occupancy=omf_val, + occupancy_minus_equilibrium=df_eq_val, + ) + fields[f"dyn_iface:{k}"] = fixed_res + bflux = fixed_res.bulk_flux_m2_s + j_bulk = fixed_res.bulk_flux_jacobian_bulk + if itrap.has_sheet_charge: + sigma = fixed_res.incremental_sheet_charge_C_m2 + g_port_val[l_node - 1] += itrap.weight_left * sigma + g_port_val[r_node - 1] += itrap.weight_right * sigma + elif tspec.charge is not None: + charged = solve_charged_two_sided_interface_qss( + tspec.trace_electrostatics, + tspec.physics, + bulk, + tspec.charge, + ) + bflux = charged.bulk_flux_m2_s + j_bulk = charged.bulk_flux_jacobian_bulk + sigma = charged.incremental_sheet_charge_C_m2 + j_sigma = charged.sheet_charge_jacobian_bulk + g_port_val[l_node - 1] += tspec.weight_left * sigma + g_port_val[r_node - 1] += tspec.weight_right * sigma + s_phi_l = float(j_sigma[0] + (j_sigma[2] - j_sigma[3]) / thermal) + s_phi_r = float(j_sigma[1] + (j_sigma[4] - j_sigma[5]) / thermal) + s_zn_l = float(j_sigma[2]) + s_zn_r = float(j_sigma[4]) + s_zp_l = float(-j_sigma[3]) + s_zp_r = float(-j_sigma[5]) + wl, wr = tspec.weight_left, tspec.weight_right + w_sum = wl + wr + g_left_phi[f] += wr * s_phi_l + g_right_phi[f] -= wl * s_phi_r + g_port_phi[l_node - 1] += w_sum * s_phi_l + g_port_phi[r_node - 1] += w_sum * s_phi_r + g_left_zn[f] += wr * s_zn_l + g_right_zn[f] -= wl * s_zn_r + g_port_zn[l_node - 1] += w_sum * s_zn_l + g_port_zn[r_node - 1] += w_sum * s_zn_r + g_left_zp[f] += wr * s_zp_l + g_right_zp[f] -= wl * s_zp_r + g_port_zp[l_node - 1] += w_sum * s_zp_l + g_port_zp[r_node - 1] += w_sum * s_zp_r + else: + uncharged = solve_two_sided_interface_qss( + tspec.trace_electrostatics, + tspec.physics, + bulk, + ) + bflux = uncharged.bulk_flux_m2_s + j_bulk = uncharged.bulk_flux_jacobian_bulk + + e_flux[f] = float(bflux[0]) + h_flux[f] = float(bflux[1]) + e_ld[f] = float(j_bulk[0, 2]) / float(n[l_node]) + e_rd[f] = float(j_bulk[0, 4]) / float(n[r_node]) + h_ld[f] = float(j_bulk[1, 3]) / float(p[l_node]) + h_rd[f] = float(j_bulk[1, 5]) / float(p[r_node]) + e_port_val[r_node - 1] -= float(bflux[0] + bflux[2]) + h_port_val[r_node - 1] -= float(bflux[1] + bflux[3]) + + for row_l, row_r, fl_phi, fr_phi, pd_phi, fl_zn, fr_zn, pd_zn, fl_zp, fr_zp, pd_zp in ( + (0, 2, e_left_phi, e_right_phi, e_port_phi, e_left_zn, e_right_zn, e_port_zn, e_left_zp, e_right_zp, e_port_zp), + (1, 3, h_left_phi, h_right_phi, h_port_phi, h_left_zn, h_right_zn, h_port_zn, h_left_zp, h_right_zp, h_port_zp), + ): + gl_phi = float(j_bulk[row_l, 0] + (j_bulk[row_l, 2] - j_bulk[row_l, 3]) / thermal) + gr_phi = float(j_bulk[row_l, 1] + (j_bulk[row_l, 4] - j_bulk[row_l, 5]) / thermal) + hl_phi = float(j_bulk[row_r, 0] + (j_bulk[row_r, 2] - j_bulk[row_r, 3]) / thermal) + hr_phi = float(j_bulk[row_r, 1] + (j_bulk[row_r, 4] - j_bulk[row_r, 5]) / thermal) + _scatter_two_sided_tangent(f, gl_phi, gr_phi, hl_phi, hr_phi, fl_phi, fr_phi, pd_phi) + _scatter_two_sided_tangent( + f, + float(j_bulk[row_l, 2]), + float(j_bulk[row_l, 4]), + float(j_bulk[row_r, 2]), + float(j_bulk[row_r, 4]), + fl_zn, fr_zn, pd_zn, + ) + _scatter_two_sided_tangent( + f, + float(-j_bulk[row_l, 3]), + float(-j_bulk[row_l, 5]), + float(-j_bulk[row_r, 3]), + float(-j_bulk[row_r, 5]), + fl_zp, fr_zp, pd_zp, + ) + except (RuntimeError, FloatingPointError, ValueError): + return False + + ef = replace( + base.electron, + flux=e_flux, + left_density_derivative=e_ld, + right_density_derivative=e_rd, + ) + hf = replace( + base.hole, + flux=h_flux, + left_density_derivative=h_ld, + right_density_derivative=h_rd, + ) + fields.update({ + "iface:e_flux": ef.flux, + "iface:e_ld": ef.left_density_derivative, + "iface:e_rd": ef.right_density_derivative, + "iface:e_lpot": ef.left_potential_derivative, + "iface:e_rpot": ef.right_potential_derivative, + "iface:e_step": ef.energy_step, + "iface:e_coeff": ef.coefficient, + "iface:h_flux": hf.flux, + "iface:h_ld": hf.left_density_derivative, + "iface:h_rd": hf.right_density_derivative, + "iface:h_lpot": hf.left_potential_derivative, + "iface:h_rpot": hf.right_potential_derivative, + "iface:h_step": hf.energy_step, + "iface:h_coeff": hf.coefficient, + "iface:e_left_phi": e_left_phi, + "iface:e_right_phi": e_right_phi, + "iface:e_left_zn": e_left_zn, + "iface:e_right_zn": e_right_zn, + "iface:e_left_zp": e_left_zp, + "iface:e_right_zp": e_right_zp, + "iface:h_left_phi": h_left_phi, + "iface:h_right_phi": h_right_phi, + "iface:h_left_zn": h_left_zn, + "iface:h_right_zn": h_right_zn, + "iface:h_left_zp": h_left_zp, + "iface:h_right_zp": h_right_zp, + "iface:e_port_val": e_port_val, + "iface:e_port_phi": e_port_phi, + "iface:e_port_zn": e_port_zn, + "iface:e_port_zp": e_port_zp, + "iface:h_port_val": h_port_val, + "iface:h_port_phi": h_port_phi, + "iface:h_port_zn": h_port_zn, + "iface:h_port_zp": h_port_zp, + "iface:g_port_val": g_port_val, + "iface:g_port_phi": g_port_phi, + "iface:g_port_zn": g_port_zn, + "iface:g_port_zp": g_port_zp, + "iface:g_left_phi": g_left_phi, + "iface:g_right_phi": g_right_phi, + "iface:g_left_zn": g_left_zn, + "iface:g_right_zn": g_right_zn, + "iface:g_left_zp": g_left_zp, + "iface:g_right_zp": g_right_zp, + }) + return True + + +@dataclass(frozen=True) +class DynamicDefectFields: + """Single-pass constitutive evaluation for all active electronic, ionic, and defect physics.""" + + device: CompiledDynamicDefectDevice1D + + @property + def identity(self) -> str: + return _identity("dynamic_defect_fields_v1", self.device.identity) + + def evaluate(self, layout: SystemLayout, u: Vector, inputs: OperatingInputs) -> FieldValues: + dev = self.device + comp = dev.electronic_component + elec_u = u[dev.electronic_slice] + + try: + if dev.ionic_component is not None: + ion_u = u[: dev.ionic_component.state_size] + phi, n, p, single = dev.ionic_component.fields_by_species( + ion_u, voltage_V=inputs.voltage_V + ) + else: + phi, n, p = comp.fields(elec_u, voltage_V=inputs.voltage_V) + single = () + except (ValueError, FloatingPointError): + return FieldValues({}, False) + + admissible = bool( + np.all(np.isfinite(phi)) + and np.all(np.isfinite(n)) + and np.all(np.isfinite(p)) + and not np.any(n <= 0.0) + and not np.any(p <= 0.0) + ) + fields: dict[str, Any] = { + "potential_V": phi, + "electron_density_m3": n, + "hole_density_m3": p, + } + if not admissible: + return FieldValues(fields, False) + + if dev.ionic_component is not None: + domain = IonDomain(cast(CompiledIonicDevice1D, dev.ionic_component)) + fields.update(zip(domain.blocks, single)) + fields[domain.mass_field] = domain.coordinate_jacobian(single) + + if dev.stationary_defects is not None: + try: + fields["stationary_defects"] = dev.stationary_defects.evaluate(n, p) + except (ValueError, FloatingPointError): + return FieldValues(fields, False) + + if dev.dynamic_bulk_traps is not None: + try: + bulk_occ = dev.bulk_trap_occupancies(u) + bulk_omf = dev.bulk_trap_one_minus_occupancies(u) + fields["dynamic_bulk_traps"] = evaluate_dynamic_bulk_traps( + n, + p, + bulk_occ, + dev.dynamic_bulk_traps, + one_minus_occupancy=bulk_omf, + ) + except (ValueError, FloatingPointError): + return FieldValues(fields, False) + + iface_occ = dev.interface_trap_occupancies(u) + iface_omf = dev.interface_trap_one_minus_occupancies(u) + if dev.dynamic_interface_traps: + fields["iface_trap_occ"] = iface_occ + + if comp.interface_model is not None or dev.dynamic_interface_traps: + ok = _populate_interfaces_with_dynamic_traps( + dev, u, elec_u, phi, n, p, iface_occ, iface_omf, fields + ) + if not ok: + return FieldValues(fields, False) + + return FieldValues(fields, True) + + +@dataclass(frozen=True) +class DynamicDefectSpaceCharge: + """Total Gauss space charge folding carriers, dopants, ions, stationary defects, and bulk traps.""" + + device: CompiledDynamicDefectDevice1D + id: str = "potential.space_charge" + kind: str = CELL_SOURCE + support: str = NODES + equations: tuple[str, ...] = (POTENTIAL,) + unit: Unit = CHARGE_UNIT + port: str | None = None + + @property + def dependencies(self) -> tuple[str, ...]: + deps: list[str] = [POTENTIAL, ELECTRON, HOLE] + if self.device.ionic_component is not None: + deps.extend(IonDomain(cast(CompiledIonicDevice1D, self.device.ionic_component)).blocks) + if self.device.dynamic_bulk_traps is not None: + deps.extend( + f"trap:{idx}" for idx in range(len(self.device.dynamic_bulk_traps.modes)) + ) + return tuple(deps) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, ELECTRODE_QUASI_FERMI_1D_V1) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + dev = self.device + comp = dev.electronic_component + n = state.field("electron_density_m3") + p = state.field("hole_density_m3") + thermal = comp.thermal_voltage_V + + if dev.ionic_component is not None: + domain = IonDomain(cast(CompiledIonicDevice1D, dev.ionic_component)) + pops = tuple(state.field(blk) for blk in domain.blocks) + base_rho = dev.ionic_component.charge_ledger( + n, p, pops[0], pops[1] if len(pops) == 2 else None + ).space_charge_C_m3() + else: + base_rho = comp.charge_ledger(n, p).space_charge_C_m3() + + rho = np.array(base_rho, dtype=np.float64, copy=True) + stat_ev: StationaryDefectEvaluation1D | None = None + if dev.stationary_defects is not None: + stat_ev = cast(StationaryDefectEvaluation1D, state.field("stationary_defects")) + rho = rho + stat_ev.charge_density_C_m3 + + trap_ev: DynamicBulkTrapEvaluation | None = None + if dev.dynamic_bulk_traps is not None: + trap_ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + rho = rho + trap_ev.total_charge_density_C_m3 + + if not derivatives: + return {POTENTIAL: LocalValue(rho)} + + d_phi: Vector = -Q * (n + p) / thermal + d_zn: Vector = -Q * n + d_zp: Vector = -Q * p + + if stat_ev is not None: + d_phi = d_phi + stat_ev.d_charge_dphi_fixed_qf_C_m3_V + d_zn = d_zn + stat_ev.d_charge_dn_C * n + d_zp = d_zp - stat_ev.d_charge_dp_C * p + + tangents: dict[str, Contribution] = { + POTENTIAL: d_phi * MEASURE, + ELECTRON: d_zn * MEASURE, + HOLE: d_zp * MEASURE, + } + + if dev.ionic_component is not None: + domain = IonDomain(cast(CompiledIonicDevice1D, dev.ionic_component)) + ion_nodes = domain.device.ion_node_indices + ratio = np.zeros(n.size, dtype=np.float64) + ratio[ion_nodes] = state.embedding_ratio(domain.node_set) + mass = state.field(domain.mass_field) + for col, blk in enumerate(domain.blocks): + partial = np.zeros(n.size, dtype=np.float64) + if domain.shared: + partial[ion_nodes] = mass[:, 0, col] - mass[:, 1, col] + tangents[blk] = (Q * ratio * partial) * MEASURE + else: + partial[ion_nodes] = mass[:, col, col] + sign = 1.0 if domain.species[col] == "positive" else -1.0 + tangents[blk] = (sign * Q * ratio * partial) * MEASURE + + if dev.dynamic_bulk_traps is not None: + assert trap_ev is not None + f = trap_ev.occupancy + omf = trap_ev.one_minus_occupancy + df_du = f * omf + for idx, mode in enumerate(dev.dynamic_bulk_traps.modes): + sl = mode.flat_slice + t_vec = np.zeros(n.size, dtype=np.float64) + t_vec[mode.device_node_indices] = trap_ev.d_charge_df_C_m3[sl] * df_du[sl] + tangents[f"trap:{idx}"] = t_vec + + return {POTENTIAL: LocalValue(rho, tangents)} + + +@dataclass(frozen=True) +class StationaryDefectRecombinationTerm: + """Net recombination ``-R_stat(n, p)`` [m^-3 s^-1] from stationary QSS bulk defects.""" + + device: CompiledDynamicDefectDevice1D + id: str = "carrier.stationary_defect_recombination" + kind: str = CELL_SOURCE + support: str = NODES + equations: tuple[str, ...] = (ELECTRON, HOLE) + dependencies: tuple[str, ...] = (POTENTIAL, ELECTRON, HOLE) + unit: Unit = SOURCE_UNIT + port: str | None = None + + @property + def identity(self) -> str: + assert self.device.stationary_defects is not None + return _identity(self.id, self.device.stationary_defects.identity_sha256) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + stat_ev = cast(StationaryDefectEvaluation1D, state.field("stationary_defects")) + loss = -stat_ev.recombination_rate_m3_s + if not derivatives: + return {ELECTRON: LocalValue(loss), HOLE: LocalValue(loss)} + n = state.field("electron_density_m3") + p = state.field("hole_density_m3") + thermal = self.device.thermal_voltage_V + sn = -stat_ev.d_recombination_dn_s1 * n + sp = stat_ev.d_recombination_dp_s1 * p + sphi = (sn + sp) / thermal + tangents: dict[str, Contribution] = {POTENTIAL: sphi, ELECTRON: sn, HOLE: sp} + return {ELECTRON: LocalValue(loss, tangents), HOLE: LocalValue(loss, tangents)} + + +@dataclass(frozen=True) +class DynamicBulkCarrierCaptureTerm: + """Non-equilibrium carrier capture ``(-C_n, -C_p)`` [m^-3 s^-1] into dynamic bulk traps.""" + + device: CompiledDynamicDefectDevice1D + id: str = "carrier.dynamic_bulk_trap_capture" + kind: str = CELL_SOURCE + support: str = NODES + equations: tuple[str, ...] = (ELECTRON, HOLE) + unit: Unit = SOURCE_UNIT + port: str | None = None + + @property + def dependencies(self) -> tuple[str, ...]: + assert self.device.dynamic_bulk_traps is not None + trap_blocks = tuple( + f"trap:{idx}" for idx in range(len(self.device.dynamic_bulk_traps.modes)) + ) + return (POTENTIAL, ELECTRON, HOLE) + trap_blocks + + @property + def identity(self) -> str: + assert self.device.dynamic_bulk_traps is not None + return _identity(self.id, self.device.dynamic_bulk_traps.model_identity_sha256) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + layout_bt = self.device.dynamic_bulk_traps + assert layout_bt is not None + ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + loss_n = -ev.total_electron_capture_rate_m3_s + loss_p = -ev.total_hole_capture_rate_m3_s + if not derivatives: + return {ELECTRON: LocalValue(loss_n), HOLE: LocalValue(loss_p)} + + n = state.field("electron_density_m3") + p = state.field("hole_density_m3") + thermal = self.device.thermal_voltage_V + N = n.size + + dn_tot = np.zeros(N, dtype=np.float64) + dp_tot = np.zeros(N, dtype=np.float64) + np.add.at(dn_tot, layout_bt.device_node_indices, -ev.d_electron_capture_dn_s1) + np.add.at(dp_tot, layout_bt.device_node_indices, -ev.d_hole_capture_dp_s1) + + e_zn = dn_tot * n + e_phi = e_zn / thermal + h_zp = -dp_tot * p + h_phi = h_zp / thermal + + e_tan: dict[str, Contribution] = { + POTENTIAL: e_phi, + ELECTRON: e_zn, + HOLE: np.zeros(N, dtype=np.float64), + } + h_tan: dict[str, Contribution] = { + POTENTIAL: h_phi, + ELECTRON: np.zeros(N, dtype=np.float64), + HOLE: h_zp, + } + + df_du = ev.occupancy * ev.one_minus_occupancy + for idx, mode in enumerate(layout_bt.modes): + sl = mode.flat_slice + te = np.zeros(N, dtype=np.float64) + th = np.zeros(N, dtype=np.float64) + te[mode.device_node_indices] = -ev.d_electron_capture_df_m3_s[sl] * df_du[sl] + th[mode.device_node_indices] = -ev.d_hole_capture_df_m3_s[sl] * df_du[sl] + blk = f"trap:{idx}" + e_tan[blk] = te + h_tan[blk] = th + + return { + ELECTRON: LocalValue(loss_n, e_tan), + HOLE: LocalValue(loss_p, h_tan), + } + + +@dataclass(frozen=True) +class DynamicBulkTrapRateTerm: + """Net trap capture-minus-emission rate ``C_n - C_p`` [m^-3 s^-1] for one trap mode.""" + + device: CompiledDynamicDefectDevice1D + mode_index: int + mode: DynamicBulkTrapMode + kind: str = CELL_SOURCE + unit: Unit = SOURCE_UNIT + port: str | None = None + + @property + def block(self) -> str: + return f"trap:{self.mode_index}" + + @property + def id(self) -> str: + return f"{self.block}.rate" + + @property + def support(self) -> str: + return self.block + + @property + def equations(self) -> tuple[str, ...]: + return (self.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (POTENTIAL, ELECTRON, HOLE, self.block) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.mode.mode_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + sl = self.mode.flat_slice + rate = ev.trap_storage_rate_m3_s[sl] + if not derivatives: + return {self.block: LocalValue(rate)} + + nodes = self.mode.device_node_indices + n_loc = state.field("electron_density_m3")[nodes] + p_loc = state.field("hole_density_m3")[nodes] + thermal = self.device.thermal_voltage_V + + t_zn = ev.d_trap_storage_rate_dn_s1[sl] * n_loc + t_zp = -ev.d_trap_storage_rate_dp_s1[sl] * p_loc + t_phi = (t_zn + t_zp) / thermal + df_du = ev.occupancy[sl] * ev.one_minus_occupancy[sl] + t_u = ev.d_trap_storage_rate_df_m3_s[sl] * df_du + + return { + self.block: LocalValue( + rate, + { + POTENTIAL: t_phi, + ELECTRON: t_zn, + HOLE: t_zp, + self.block: t_u, + }, + ) + } + + +@dataclass(frozen=True) +class DynamicBulkTrapStorageTerm: + """Occupied trap storage ``N_t * f`` [m^-3] and cancellation-free logit secant.""" + + device: CompiledDynamicDefectDevice1D + mode_index: int + mode: DynamicBulkTrapMode + kind: str = STORAGE + unit: Unit = DENSITY_UNIT + port: str | None = None + + @property + def block(self) -> str: + return f"trap:{self.mode_index}" + + @property + def id(self) -> str: + return f"{self.block}.storage" + + @property + def support(self) -> str: + return self.block + + @property + def equations(self) -> tuple[str, ...]: + return (self.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.mode.mode_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + sl = self.mode.flat_slice + stored = ev.occupied_storage_m3[sl] + if not derivatives: + return {self.block: LocalValue(stored)} + df_du = ev.occupancy[sl] * ev.one_minus_occupancy[sl] + return { + self.block: LocalValue( + stored, + {self.block: self.mode.population_density_m3 * df_du}, + ) + } + + def increment(self, state: EvaluationState, previous: EvaluationState) -> Mapping[str, Contribution]: + sl = self.mode.flat_slice + ref = self.device.bulk_trap_reference_logit[sl] + l_new = ref + state.block(self.block) + l_old = ref + previous.block(self.block) + df = logit_occupancy_secant(l_new, l_old) + return {self.block: self.mode.population_density_m3 * df} + + +@dataclass(frozen=True) +class DynamicInterfaceTrapRateTerm: + """Two-sided interface trap rate ``+(C_n - C_p)`` [m^-2 s^-1] on Row 0 of ``iface_trap:{k}``.""" + + device: CompiledDynamicDefectDevice1D + binding: DynamicInterfaceTrapBinding1D + kind: str = FACE_FLUX + unit: Unit = FLUX_UNIT + port: str | None = None + + @property + def id(self) -> str: + return f"{self.binding.block}.rate" + + @property + def support(self) -> str: + return self.binding.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (POTENTIAL, ELECTRON, HOLE, self.binding.block) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.binding.interface_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + res = state.field(f"dyn_iface:{self.binding.interface_index}") + flux = np.array([-float(res.trap_storage_rate_m2_s)], dtype=np.float64) + if not derivatives: + return {self.binding.block: FaceValue(flux)} + + thermal = self.device.thermal_voltage_V + j_b = res.trap_storage_rate_jacobian_bulk + sr_df = float(res.trap_storage_rate_derivative_occupancy) + f_occ = float(res.occupancy) + df_du = f_occ * float(res.one_minus_occupancy) + + # Face divergence scatters -flux to node 0 (left) and +flux to node 1 (right, constraint-dropped). + # Thus -left_tangent lands in Row 0 vs left_node columns, and -right_tangent lands in Row 0 vs right_node columns! + d_phi_l = float(j_b[0] + (j_b[2] - j_b[3]) / thermal) + d_phi_r = float(j_b[1] + (j_b[4] - j_b[5]) / thermal) + d_zn_l = float(j_b[2]) + d_zn_r = float(j_b[4]) + d_zp_l = float(-j_b[3]) + d_zp_r = float(-j_b[5]) + d_u_l = sr_df * df_du + + left: dict[str, Contribution] = { + POTENTIAL: np.array([-d_phi_l]), + ELECTRON: np.array([-d_zn_l]), + HOLE: np.array([-d_zp_l]), + self.binding.block: np.array([-d_u_l]), + } + right: dict[str, Contribution] = { + POTENTIAL: np.array([-d_phi_r]), + ELECTRON: np.array([-d_zn_r]), + HOLE: np.array([-d_zp_r]), + self.binding.block: np.array([0.0]), + } + return {self.binding.block: FaceValue(flux, left, right)} + + +@dataclass(frozen=True) +class DynamicInterfaceTrapTieTerm: + """Constraint ``u_L - u_R == 0`` on Row 1 of ``iface_trap:{k}``.""" + + device: CompiledDynamicDefectDevice1D + binding: DynamicInterfaceTrapBinding1D + kind: str = CONSTRAINT + unit: Unit = ONE + port: str | None = None + + @property + def id(self) -> str: + return f"{self.binding.block}.tie" + + @property + def support(self) -> str: + return self.binding.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.binding.interface_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + blk_u = state.block(self.binding.block) + summand = np.array([blk_u[0], -blk_u[1]], dtype=np.float64) + tangents: dict[str, Contribution] = ( + {self.binding.block: np.array([1.0, -1.0], dtype=np.float64)} + if derivatives + else {} + ) + return {self.binding.block: ReductionValue(summand, None, tangents)} + + +@dataclass(frozen=True) +class DynamicInterfaceTrapStorageTerm: + """Areal trap storage ``N_it * f`` [m^-2] on Row 0 of ``iface_trap:{k}``.""" + + device: CompiledDynamicDefectDevice1D + binding: DynamicInterfaceTrapBinding1D + kind: str = STORAGE + unit: Unit = DENSITY_UNIT + port: str | None = None + + @property + def id(self) -> str: + return f"{self.binding.block}.storage" + + @property + def support(self) -> str: + return self.binding.node_set + + @property + def equations(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.binding.interface_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + res = state.field(f"dyn_iface:{self.binding.interface_index}") + f_occ = float(res.occupancy) + nt = self.binding.trap_density_m2 + # Support volumes on iface_trap:{k} are [1.0, 1.0] m, so [nt * f, 0.0] integrates to [nt * f, 0.0] m^-2. + val = np.array([nt * f_occ, 0.0], dtype=np.float64) + if not derivatives: + return {self.binding.block: LocalValue(val)} + df_du = f_occ * float(res.one_minus_occupancy) + return { + self.binding.block: LocalValue( + val, + {self.binding.block: np.array([nt * df_du, 0.0], dtype=np.float64)}, + ) + } + + def increment(self, state: EvaluationState, previous: EvaluationState) -> Mapping[str, Contribution]: + ref = self.binding.reference_logit + l_new = np.array([ref + float(state.block(self.binding.block)[0])]) + l_old = np.array([ref + float(previous.block(self.binding.block)[0])]) + df = float(logit_occupancy_secant(l_new, l_old)[0]) + nt = self.binding.trap_density_m2 + return {self.binding.block: np.array([nt * df, 0.0], dtype=np.float64)} + + +@dataclass(frozen=True) +class DynamicInterfaceCarrierFaceTangentTerm: + """Deposits right-node bulk carrier tangent wrt ``u_L`` (and ``-right`` on ``l_node``).""" + + device: CompiledDynamicDefectDevice1D + id: str = "carrier.dyn_iface_face_tangents" + kind: str = FACE_FLUX + support: str = NODES + equations: tuple[str, ...] = (ELECTRON, HOLE) + unit: Unit = FLUX_UNIT + port: str | None = None + + @property + def dependencies(self) -> tuple[str, ...]: + return tuple(itrap.block for itrap in self.device.dynamic_interface_traps) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + face_count = self.device.node_count - 1 + zero: Vector = np.zeros(face_count, dtype=np.float64) + if not derivatives: + return {ELECTRON: FaceValue(zero), HOLE: FaceValue(zero)} + + e_left: dict[str, Contribution] = {} + e_right: dict[str, Contribution] = {} + h_left: dict[str, Contribution] = {} + h_right: dict[str, Contribution] = {} + + for itrap in self.device.dynamic_interface_traps: + res = state.field(f"dyn_iface:{itrap.interface_index}") + f_occ = float(res.occupancy) + df_du = f_occ * float(res.one_minus_occupancy) + dbf = res.bulk_flux_derivative_occupancy + # Target derivatives on (l_node, r_node) wrt u_L are (A, B) = (-dbf_L * df_du, -dbf_R * df_du). + # Face f=l_node scatters -left_val to l_node and +left_val to r_node in col(u_L)! + b_e = -float(dbf[2]) * df_du + b_h = -float(dbf[3]) * df_du + ve: Vector = np.zeros(face_count, dtype=np.float64) + vh: Vector = np.zeros(face_count, dtype=np.float64) + ve[itrap.face] = b_e + vh[itrap.face] = b_h + e_left[itrap.block] = ve + e_right[itrap.block] = zero + h_left[itrap.block] = vh + h_right[itrap.block] = zero + + return { + ELECTRON: FaceValue(zero, e_left, e_right), + HOLE: FaceValue(zero, h_left, h_right), + } + + +@dataclass(frozen=True) +class DynamicInterfaceCarrierLeftPortTerm: + """Completes ``A + B`` tangent on ``l_node`` wrt ``u_L`` so net tangent is ``(A, B)``.""" + + device: CompiledDynamicDefectDevice1D + binding: DynamicInterfaceTrapBinding1D + block_name: str + kind: str = PORT_FLUX + support: str = NODES + unit: Unit = FLUX_UNIT + + @property + def id(self) -> str: + return f"{self.block_name}.dyn_iface_left.{self.binding.interface_index}" + + @property + def port(self) -> str: + return self.binding.left_port + + @property + def equations(self) -> tuple[str, ...]: + return (self.block_name,) + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.binding.interface_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + zero: Vector = np.zeros(1, dtype=np.float64) + if not derivatives: + return {self.block_name: LocalValue(zero)} + res = state.field(f"dyn_iface:{self.binding.interface_index}") + f_occ = float(res.occupancy) + df_du = f_occ * float(res.one_minus_occupancy) + dbf = res.bulk_flux_derivative_occupancy + if self.block_name == ELECTRON: + a_plus_b = (-float(dbf[0]) - float(dbf[2])) * df_du + else: + a_plus_b = (-float(dbf[1]) - float(dbf[3])) * df_du + return { + self.block_name: LocalValue( + zero, + {self.binding.block: np.array([a_plus_b], dtype=np.float64)}, + ) + } + + +@dataclass(frozen=True) +class DynamicInterfaceGaussPortTerm: + """Deposits ``g_port_val`` onto interior Gauss rows via ``interfaces`` port.""" + + device: CompiledDynamicDefectDevice1D + id: str = "potential.interfaces" + kind: str = PORT_FLUX + support: str = NODES + port: str = "interfaces" + equations: tuple[str, ...] = (POTENTIAL,) + dependencies: tuple[str, ...] = (POTENTIAL, ELECTRON, HOLE) + unit: Unit = DISPLACEMENT_UNIT + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, ELECTRODE_QUASI_FERMI_1D_V1) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + val = state.field("iface:g_port_val") + if not derivatives: + return {POTENTIAL: LocalValue(val)} + return { + POTENTIAL: LocalValue( + val, + { + POTENTIAL: state.field("iface:g_port_phi"), + ELECTRON: state.field("iface:g_port_zn"), + HOLE: state.field("iface:g_port_zp"), + }, + ) + } + + +@dataclass(frozen=True) +class DynamicInterfaceGaussFaceTangentTerm: + """Deposits right-node Gauss sheet-charge tangent ``w_R * d_sigma/du_L`` in ``col(u_L)``.""" + + device: CompiledDynamicDefectDevice1D + id: str = "potential.dyn_iface_face_tangents" + kind: str = FACE_FLUX + support: str = NODES + equations: tuple[str, ...] = (POTENTIAL,) + unit: Unit = DISPLACEMENT_UNIT + port: str | None = None + + @property + def dependencies(self) -> tuple[str, ...]: + return tuple( + itrap.block + for itrap in self.device.dynamic_interface_traps + if itrap.has_sheet_charge + ) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + face_count = self.device.node_count - 1 + zero: Vector = np.zeros(face_count, dtype=np.float64) + if not derivatives: + return {POTENTIAL: FaceValue(zero)} + left: dict[str, Contribution] = {} + right: dict[str, Contribution] = {} + for itrap in self.device.dynamic_interface_traps: + if not itrap.has_sheet_charge: + continue + res = state.field(f"dyn_iface:{itrap.interface_index}") + f_occ = float(res.occupancy) + d_sigma_du = float(res.d_sheet_charge_df_C_m2) * f_occ * float(res.one_minus_occupancy) + b_phi = itrap.weight_right * d_sigma_du + vg: Vector = np.zeros(face_count, dtype=np.float64) + vg[itrap.face] = b_phi + left[itrap.block] = vg + right[itrap.block] = zero + return {POTENTIAL: FaceValue(zero, left, right)} + + +@dataclass(frozen=True) +class DynamicInterfaceGaussLeftPortTerm: + """Completes ``(w_L + w_R) * d_sigma/du_L`` on ``l_node`` so net is ``(w_L, w_R) * d_sigma/du_L``.""" + + device: CompiledDynamicDefectDevice1D + binding: DynamicInterfaceTrapBinding1D + kind: str = PORT_FLUX + support: str = NODES + equations: tuple[str, ...] = (POTENTIAL,) + unit: Unit = DISPLACEMENT_UNIT + + @property + def id(self) -> str: + return f"potential.dyn_iface_left.{self.binding.interface_index}" + + @property + def port(self) -> str: + return self.binding.left_port + + @property + def dependencies(self) -> tuple[str, ...]: + return (self.binding.block,) + + @property + def identity(self) -> str: + return _identity(self.id, self.device.identity, self.binding.interface_id) + + def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: + zero: Vector = np.zeros(1, dtype=np.float64) + if not derivatives: + return {POTENTIAL: LocalValue(zero)} + res = state.field(f"dyn_iface:{self.binding.interface_index}") + f_occ = float(res.occupancy) + d_sigma_du = float(res.d_sheet_charge_df_C_m2) * f_occ * float(res.one_minus_occupancy) + a_plus_b = (self.binding.weight_left + self.binding.weight_right) * d_sigma_du + return { + POTENTIAL: LocalValue( + zero, + {self.binding.block: np.array([a_plus_b], dtype=np.float64)}, + ) + } + + +@dataclass(frozen=True) +class DynamicDefectSystem1D: + """Unified ``Assembler`` binding for CompiledDynamicDefectDevice1D.""" + + device: CompiledDynamicDefectDevice1D + inventory_row_node: int | None = None + assembler: Assembler = field(init=False, repr=False, compare=False) + electronic: ClassicalDC1D = field(init=False, repr=False, compare=False) + closure_rows: NDArray[np.bool_] = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + dev = self.device + comp = dev.electronic_component + electronic = classical_dc_1d(comp) + + base_layout = electronic.assembler.layout + node_sets = list(base_layout.node_sets) + blocks = list(base_layout.blocks) + constraints = list(base_layout.constraints) + + nodes_support = electronic.assembler.mesh.support(NODES) + nodes_ports = list(nodes_support.ports) + existing_port_ids = {pt.id for pt in nodes_ports} + if (comp.interface_model is not None or dev.dynamic_interface_traps) and ( + "interfaces" not in existing_port_ids + ): + interior = tuple(range(1, comp.node_count - 1)) + nodes_ports.append(Port("interfaces", interior, -1, np.ones(len(interior)), ONE)) + + for itrap in dev.dynamic_interface_traps: + nodes_ports.append( + Port(itrap.left_port, (itrap.left_node,), -1, np.ones(1), ONE) + ) + + supports: list[SupportGeometry] = [ + SupportGeometry(NODES, nodes_support.geometry, tuple(nodes_ports)) + ] + + closure_terms: list[ImmobileProfile | InventoryReduction] = [] + ion_transports: list[Term] = [] + ion_storages: list[Term] = [] + + if dev.ionic_component is not None: + domain = IonDomain(cast(CompiledIonicDevice1D, dev.ionic_component)) + ion = domain.device + node_sets.append( + NodeSet( + domain.node_set, + ion.ion_node_count, + NODES, + tuple(int(nd) for nd in ion.ion_node_indices), + ) + ) + blocks.extend(Block(blk, domain.node_set, ONE, FLUX_UNIT) for blk in domain.blocks) + supports.append( + SupportGeometry( + domain.node_set, + ion.ion_geometry.to_contract_geometry( + cell_support=domain.node_set, + face_support=domain.node_set + ".faces", + ), + ) + ) + for sp in domain.species: + ion_transports.append(IonTransport(domain, sp)) + ion_storages.append(IonStorage(domain)) + if self.inventory_row_node is not None: + immobile = ion_mobility_partition(ion)[1] + for sp in domain.species: + cterm: ImmobileProfile | InventoryReduction + if sp in immobile: + cterm, crows = ImmobileProfile(domain, sp), tuple(range(ion.ion_node_count)) + else: + cterm, crows = InventoryReduction(domain, sp, K1), (self.inventory_row_node,) + constraints.append(ConstraintRows(cterm.block, crows, cterm.id, INVENTORY_UNIT)) + closure_terms.append(cterm) + + trap_terms: list[Term] = [] + if dev.dynamic_bulk_traps is not None: + cell_w = comp.geometry.cell_measures_m + empty_pairs: NDArray[np.int64] = np.empty((0, 2), dtype=np.int64) + empty_faces: Vector = np.empty(0, dtype=np.float64) + for idx, mode in enumerate(dev.dynamic_bulk_traps.modes): + ns_id = f"trap:{idx}" + dev_indices = tuple(int(nd) for nd in mode.device_node_indices) + node_sets.append(NodeSet(ns_id, len(dev_indices), NODES, dev_indices)) + blocks.append(Block(ns_id, ns_id, ONE, FLUX_UNIT)) + supports.append( + SupportGeometry( + ns_id, + Geometry( + volumes=cell_w[mode.device_node_indices], + pairs=empty_pairs, + face_measures=empty_faces, + volume_unit=LENGTH, + face_unit=ONE, + cell_support=ns_id, + face_support=ns_id + ".faces", + ), + ) + ) + trap_terms.append(DynamicBulkTrapRateTerm(dev, idx, mode)) + trap_terms.append(DynamicBulkTrapStorageTerm(dev, idx, mode)) + + iface_terms: list[Term] = [] + if dev.dynamic_interface_traps: + iface_terms.append(DynamicInterfaceCarrierFaceTangentTerm(dev)) + has_any_dyn_sheet = any(it.has_sheet_charge for it in dev.dynamic_interface_traps) + if has_any_dyn_sheet: + iface_terms.append(DynamicInterfaceGaussFaceTangentTerm(dev)) + pair_01 = np.array([[0, 1]], dtype=np.int64) + unit_face: Vector = np.ones(1, dtype=np.float64) + unit_vols: Vector = np.ones(2, dtype=np.float64) + for itrap in dev.dynamic_interface_traps: + ns_id = itrap.node_set + node_sets.append( + NodeSet(ns_id, 2, NODES, (itrap.left_node, itrap.right_node)) + ) + blocks.append(Block(itrap.block, ns_id, ONE, FLUX_UNIT)) + constraints.append( + ConstraintRows(itrap.block, (1,), f"{itrap.block}.tie", ONE) + ) + supports.append( + SupportGeometry( + ns_id, + Geometry( + volumes=unit_vols, + pairs=pair_01, + face_measures=unit_face, + volume_unit=LENGTH, + face_unit=ONE, + cell_support=ns_id, + face_support=ns_id + ".faces", + ), + ) + ) + iface_terms.append(DynamicInterfaceTrapRateTerm(dev, itrap)) + iface_terms.append(DynamicInterfaceTrapTieTerm(dev, itrap)) + iface_terms.append(DynamicInterfaceTrapStorageTerm(dev, itrap)) + iface_terms.append(DynamicInterfaceCarrierLeftPortTerm(dev, itrap, ELECTRON)) + iface_terms.append(DynamicInterfaceCarrierLeftPortTerm(dev, itrap, HOLE)) + if itrap.has_sheet_charge: + iface_terms.append(DynamicInterfaceGaussLeftPortTerm(dev, itrap)) + + layout = SystemLayout(tuple(node_sets), tuple(blocks), tuple(constraints)) + if layout.size != dev.state_size: + raise CapabilityError("assembled dynamic-defect layout size disagrees with compiled device") + + terms: list[Term] = [] + has_gauss_port = False + for term in electronic.assembler.terms: + if term.id == "potential.space_charge": + terms.append(DynamicDefectSpaceCharge(dev)) + else: + if term.id == "potential.interfaces": + has_gauss_port = True + terms.append(term) + + if not has_gauss_port and any(it.has_sheet_charge for it in dev.dynamic_interface_traps): + terms.append(DynamicInterfaceGaussPortTerm(dev)) + + if dev.stationary_defects is not None: + terms.append(StationaryDefectRecombinationTerm(dev)) + if dev.dynamic_bulk_traps is not None: + terms.append(DynamicBulkCarrierCaptureTerm(dev)) + + terms.extend(ion_transports) + terms.extend(ion_storages) + terms.extend(closure_terms) + terms.extend(trap_terms) + terms.extend(iface_terms) + + assembler = Assembler(layout, Mesh(tuple(supports)), DynamicDefectFields(dev), terms) + closure_mask: NDArray[np.bool_] = np.zeros(layout.size, dtype=bool) + for cterm in closure_terms: + owned = layout.constraint_rows(cterm.id) + closure_mask[layout.rows(owned.block, owned.nodes)] = True + closure_mask.setflags(write=False) + + object.__setattr__(self, "assembler", assembler) + object.__setattr__(self, "electronic", electronic) + object.__setattr__(self, "closure_rows", closure_mask) + + @property + def layout(self) -> SystemLayout: + return self.assembler.layout + + @property + def identity(self) -> str: + return self.assembler.identity + + +def dynamic_defect_system_1d( + device: CompiledDynamicDefectDevice1D, + *, + inventory_row_node: int | None = None, +) -> DynamicDefectSystem1D: + """Build unified Assembler system for ``device``.""" + if not isinstance(device, CompiledDynamicDefectDevice1D): + raise TypeError("dynamic_defect_system_1d requires CompiledDynamicDefectDevice1D") + return DynamicDefectSystem1D(device, inventory_row_node) + + +@dataclass(frozen=True) +class AssembledDynamicDefect1DProblem: + """Assembled residual, Jacobian, physical storage, and current observations.""" + + device: CompiledDynamicDefectDevice1D + voltage_V: float = 0.0 + generation_scale: float = 0.0 + inventory_row_node: int | None = None + system: DynamicDefectSystem1D | None = field(default=None, repr=False, compare=False) + + def __post_init__(self) -> None: + self.device.electronic_component.contact_potentials(self.voltage_V) + if not math.isfinite(self.generation_scale) or self.generation_scale < 0.0: + raise ValueError("generation_scale must be finite and non-negative") + if self.system is None: + object.__setattr__( + self, + "system", + dynamic_defect_system_1d( + self.device, inventory_row_node=self.inventory_row_node + ), + ) + + @property + def binding(self) -> DynamicDefectSystem1D: + assert self.system is not None + return self.system + + @property + def inputs(self) -> OperatingInputs: + return OperatingInputs(self.voltage_V, self.generation_scale) + + def assemble( + self, u: ArrayLike, *, derivatives: bool = True, storage: bool = False + ) -> AssembledSystem: + return self.binding.assembler.evaluate( + u, self.inputs, derivatives=derivatives, storage=storage + ) + + def residual(self, u: ArrayLike) -> Vector: + assembled = self.assemble(u, derivatives=False) + if not assembled.admissible or not np.all(np.isfinite(assembled.F)): + raise FloatingPointError("dynamic-defect residual outside finite domain") + return np.array(assembled.F, copy=True) + + def jacobian(self, u: ArrayLike) -> csc_matrix: + assembled = self.assemble(u, derivatives=True) + if not assembled.admissible or assembled.J is None or not np.all(np.isfinite(assembled.J.data)): + raise FloatingPointError("dynamic-defect Jacobian outside finite domain") + return assembled.J + + def storage(self, u: ArrayLike) -> Vector: + s, _ = self.binding.assembler.storage(u, self.inputs, derivatives=False) + return np.array(s, copy=True) + + def storage_tangent(self, u: ArrayLike) -> csc_matrix: + _, su = self.binding.assembler.storage(u, self.inputs, derivatives=True) + assert su is not None + return su + + def storage_jacobian(self, u: ArrayLike) -> csc_matrix: + """Signed DAE mass ``M = -S_u``.""" + return csc_matrix(-self.storage_tangent(u)) + + def storage_increment( + self, + u: ArrayLike, + old_problem: AssembledDynamicDefect1DProblem, + old_u: ArrayLike, + ) -> Vector: + return self.binding.assembler.storage_increment( + u, self.inputs, old_u, old_problem.inputs + ) + + def physical_storage(self, u: ArrayLike) -> Vector: + return self.binding.assembler.physical_storage(u, self.inputs) + + def physical_increment( + self, + u: ArrayLike, + old_problem: AssembledDynamicDefect1DProblem, + old_u: ArrayLike, + ) -> Vector: + return self.binding.assembler.storage_increment( + u, self.inputs, old_u, old_problem.inputs, physical=True + ) + + def carrier_face_fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: + state = self.binding.assembler.state(u, self.inputs) + if state is None: + raise FloatingPointError("state outside admissible domain") + return self.binding.electronic.transport.fluxes(state) + + def ion_face_fluxes(self, u: ArrayLike) -> dict[str, Vector]: + if self.device.ionic_component is None: + return {} + state = self.binding.assembler.state(u, self.inputs) + if state is None: + raise FloatingPointError("state outside admissible domain") + domain = IonDomain(cast(CompiledIonicDevice1D, self.device.ionic_component)) + ion = domain.device + phi = state.field("potential_V")[ion.ion_node_indices] + dx = np.diff(ion.ion_geometry.nodes_m) + pops = tuple(state.field(blk) for blk in domain.blocks) + steric = ion.steric_model == DIFFUSION_ONLY_STERIC_V1 + out: dict[str, Vector] = {} + for idx, sp in enumerate(domain.species): + cap = domain.capacity(sp) + partner = pops[1 - idx] if domain.shared else None + sign = 1.0 if sp == "positive" else -1.0 + out[sp] = ion_face_flux( + phi, + pops[idx], + dx, + getattr(ion, sp + "_ion_diffusivity_faces_m2_s"), + self.device.thermal_voltage_V, + cap[:-1], + steric_diffusion_only=steric, + P_lim_node=cap, + P_other_node=partner, + drift_sign=sign, + ) + return out + + def dc_current_density_A_m2(self, u: ArrayLike) -> Vector: + """All-face ``(N + 1,)`` DC conduction current density [A m^-2] along +x.""" + values = np.asarray(u, dtype=np.float64) + comp = self.device.electronic_component + N = comp.node_count + state = self.binding.assembler.state(values, self.inputs) + if state is None: + raise FloatingPointError("state outside admissible domain") + fluxes = self.binding.electronic.transport.fluxes(state) + fn = fluxes.electron.flux + fp = fluxes.hole.flux + interior = -Q * fn + Q * fp + + n = state.field("electron_density_m3") + p = state.field("hole_density_m3") + rec = self.binding.electronic.recombination.rate(n, p, derivatives=False).rate + gen = self.generation_scale * comp.generation.source_m3_s + net_source_n = np.array(gen - rec, dtype=np.float64) + net_source_p = np.array(gen - rec, dtype=np.float64) + if self.device.stationary_defects is not None: + stat_ev = cast(StationaryDefectEvaluation1D, state.field("stationary_defects")) + net_source_n -= stat_ev.recombination_rate_m3_s + net_source_p -= stat_ev.recombination_rate_m3_s + if self.device.dynamic_bulk_traps is not None: + trap_ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + net_source_n -= trap_ev.total_electron_capture_rate_m3_s + net_source_p -= trap_ev.total_hole_capture_rate_m3_s + + w = comp.geometry.cell_measures_m + terminals: list[float] = [] + for side, node, face, orient in (("left", 0, 0, -1.0), ("right", N - 1, -1, 1.0)): + j_term = 0.0 + for carrier, c_dens, c_flux, src, q_sign in ( + ("n", n, fn, net_source_n, -Q), + ("p", p, fp, net_source_p, Q), + ): + ch = comp.channel(carrier, side) + if ch.kind == "fixed_reservoir": + exch = float(c_flux[face]) + orient * float(w[node] * src[node]) + else: + exch_term = self.binding.electronic.exchanges[(carrier, side)] + offset = N if carrier == "n" else 2 * N + raw_exch, _ = exch_term.exchange( + float(values[node]), float(values[offset + node]), self.voltage_V + ) + # CarrierExchange returns outward particle flux; orient along +x: + exch = -raw_exch if side == "left" else raw_exch + j_term += q_sign * exch + terminals.append(j_term) + + all_faces: Vector = np.r_[terminals[0], interior, terminals[1]] + all_faces.setflags(write=False) + return all_faces + + def terminal_current_density_A_m2(self, u: ArrayLike) -> float: + """Signed terminal current density [A m^-2] in SolarLab passive/active J-V convention.""" + j_all = self.dc_current_density_A_m2(u) + pos_idx = 0 if self.device.voltage_polarity > 0.0 else -1 + return float(self.device.voltage_polarity * j_all[pos_idx]) + + +@dataclass(frozen=True) +class DynamicDefectStorage1D: + """``StorageProblem`` adapter for BDF1/2 time integration of dynamic defects and ions.""" + + problem: AssembledDynamicDefect1DProblem + + def __post_init__(self) -> None: + if not isinstance(self.problem, AssembledDynamicDefect1DProblem): + raise TypeError("DynamicDefectStorage1D requires AssembledDynamicDefect1DProblem") + if self.problem.inventory_row_node is not None: + raise ValueError("transient storage problem must not carry steady inventory constraints") + + @property + def device(self) -> CompiledDynamicDefectDevice1D: + return self.problem.device + + @property + def voltage_V(self) -> float: + return self.problem.voltage_V + + @property + def generation_scale(self) -> float: + return self.problem.generation_scale + + def residual(self, u: Vector) -> Vector: + return self.problem.residual(u) + + def jacobian(self, u: Vector) -> Matrix: + return self.problem.jacobian(u) + + def storage(self, u: Vector) -> Vector: + return self.problem.storage(u) + + def storage_tangent(self, u: Vector) -> Matrix: + return self.problem.storage_tangent(u) + + def mass_matrix(self, u: Vector) -> Matrix: + return self.problem.storage_jacobian(u) + + def storage_jacobian(self, u: Vector) -> Matrix: + return self.mass_matrix(u) + + def _previous(self, old_problem: StorageProblem) -> AssembledDynamicDefect1DProblem: + if not isinstance(old_problem, DynamicDefectStorage1D): + raise TypeError("dynamic-defect storage history requires DynamicDefectStorage1D") + old = old_problem.problem + if old.binding.identity != self.problem.binding.identity: + raise ValueError("dynamic-defect storage history requires identical bound system") + return old + + def storage_increment(self, u: Vector, old_problem: StorageProblem, old_u: Vector) -> Vector: + return self.problem.storage_increment(u, self._previous(old_problem), old_u) + + def physical_storage(self, u: Vector) -> Vector: + return self.problem.physical_storage(u) + + def physical_increment(self, u: Vector, old_problem: StorageProblem, old_u: Vector) -> Vector: + return self.problem.physical_increment(u, self._previous(old_problem), old_u) + + +def _displacement_profile_C_m2( + device: CompiledDynamicDefectDevice1D, u: Vector, voltage_V: float +) -> Vector: + """All-face ``(N + 1,)`` displacement profile [C m^-2], using ``D_left`` at two-sided planes.""" + comp = device.electronic_component + N = comp.node_count + phi, n, p = comp.fields(u[: 3 * N], voltage_V=voltage_V) + rho = device.space_charge_density_C_m3(n, p, u) + d_series = np.array(comp.poisson.face_displacement(phi), dtype=np.float64, copy=True) + + sheets = device.interface_sheet_charges_C_m2(u, voltage_V=voltage_V) + w = comp.geometry.cell_measures_m + cell_charge = np.array(rho * w, dtype=np.float64, copy=True) + + # Fold eliminated two-sided sheet charges into adjacent cells for contact_displacement + # while recording D_left = D_series - w_L * sigma on the interface face itself! + if comp.interface_model is not None and comp.interface_model.topology == "two_sided_trace": + dyn_map = {it.interface_index: it for it in device.dynamic_interface_traps} + for tspec in comp.interface_model.two_sided: + k = tspec.interface_index + sigma = float(sheets[k]) + if k in dyn_map: + wl, wr = dyn_map[k].weight_left, dyn_map[k].weight_right + else: + wl, wr = tspec.weight_left, tspec.weight_right + if wl != 0.0 or wr != 0.0: + cell_charge[tspec.left_node] += wl * sigma + cell_charge[tspec.right_node] += wr * sigma + d_series[tspec.face] -= wl * sigma + + d_left_port = float(d_series[0] - cell_charge[0]) + d_right_port = float(d_series[-1] + cell_charge[-1]) + # Wait: if face 0 were a two-sided interface (never, since l_node >= 1), d_series[0] already has -wl*sigma. + # On right port, face N-2: if face N-2 were a two-sided interface, D_right_side = D_series_orig + wr * sigma + # = (d_series[N-2] + wl * sigma) + wr * sigma! Let's compute ports from original D_series + folded cell_charge! + orig_series = comp.poisson.face_displacement(phi) + ports = contact_displacement(orig_series, cell_charge / w, w) + _ = (d_left_port, d_right_port) + return np.r_[ports[0], d_series, ports[1]] + + +def dynamic_defect_step_accounting(step: BDFStep, u: ArrayLike) -> dict[str, Any]: + """Conservative all-face Maxwell current accounting ``J_cond + J_ion + dD/dt`` on a BDFStep.""" + if not isinstance(step.endpoint, DynamicDefectStorage1D): + raise TypeError("dynamic_defect_step_accounting requires DynamicDefectStorage1D") + adapter = step.endpoint + prob = adapter.problem + dev = prob.device + comp = dev.electronic_component + N = comp.node_count + values = np.asarray(u, dtype=np.float64) + + old = step.history[0] + assert isinstance(old.problem, DynamicDefectStorage1D) + coeffs = step.coefficients + h = step.dt_s + + phys_rate = coeffs[0] * adapter.physical_increment(values, old.problem, old.u) / h + if step.order == 2: + older = step.history[1] + assert isinstance(old.problem, DynamicDefectStorage1D) + phys_rate = phys_rate - coeffs[2] * old.problem.physical_increment(old.u, older.problem, older.u) / h + + state = prob.binding.assembler.state(values, prob.inputs) + if state is None: + raise FloatingPointError("state outside admissible domain") + fluxes = prob.binding.electronic.transport.fluxes(state) + fn = fluxes.electron.flux + fp = fluxes.hole.flux + j_elec_interior = -Q * fn + Q * fp + + n = state.field("electron_density_m3") + p = state.field("hole_density_m3") + rec = prob.binding.electronic.recombination.rate(n, p, derivatives=False).rate + gen = prob.generation_scale * comp.generation.source_m3_s + net_src_n = np.array(gen - rec, dtype=np.float64) + net_src_p = np.array(gen - rec, dtype=np.float64) + if dev.stationary_defects is not None: + stat_ev = cast(StationaryDefectEvaluation1D, state.field("stationary_defects")) + net_src_n -= stat_ev.recombination_rate_m3_s + net_src_p -= stat_ev.recombination_rate_m3_s + if dev.dynamic_bulk_traps is not None: + trap_ev = cast(DynamicBulkTrapEvaluation, state.field("dynamic_bulk_traps")) + net_src_n -= trap_ev.total_electron_capture_rate_m3_s + net_src_p -= trap_ev.total_hole_capture_rate_m3_s + + dn_dt_area = phys_rate[N : 2 * N] + dp_dt_area = phys_rate[2 * N : 3 * N] + w = comp.geometry.cell_measures_m + + terminals: list[float] = [] + for side, node, face, orient in (("left", 0, 0, -1.0), ("right", N - 1, -1, 1.0)): + j_term = 0.0 + for carrier, c_flux, src, dstorage_dt, q_sign in ( + ("n", fn, net_src_n, dn_dt_area, -Q), + ("p", fp, net_src_p, dp_dt_area, Q), + ): + ch = comp.channel(carrier, side) + if ch.kind == "fixed_reservoir": + exch = float(c_flux[face]) + orient * float(w[node] * src[node] - dstorage_dt[node]) + else: + exch_term = prob.binding.electronic.exchanges[(carrier, side)] + offset = N if carrier == "n" else 2 * N + raw_exch, _ = exch_term.exchange( + float(values[node]), float(values[offset + node]), prob.voltage_V + ) + exch = -raw_exch if side == "left" else raw_exch + j_term += q_sign * exch + terminals.append(j_term) + + j_cond: Vector = np.r_[terminals[0], j_elec_interior, terminals[1]] + j_ion: Vector = np.zeros(N + 1, dtype=np.float64) + if dev.ionic_component is not None: + ion_fluxes = prob.ion_face_fluxes(values) + ion_indices = dev.ionic_component.ion_node_indices + for idx, sp in enumerate(dev.ionic_component.ion_species_names): + sign = 1.0 if idx == 0 else -1.0 + j_ion[ion_indices[:-1] + 1] += sign * Q * ion_fluxes[sp] + + d_new = _displacement_profile_C_m2(dev, values, prob.voltage_V) + d_old = _displacement_profile_C_m2(dev, old.u, old.problem.voltage_V) + if step.order == 1: + j_disp = coeffs[0] * (d_new - d_old) / h + else: + older = step.history[1] + assert isinstance(older.problem, DynamicDefectStorage1D) + d_older = _displacement_profile_C_m2(dev, older.u, older.problem.voltage_V) + j_disp = (coeffs[0] * (d_new - d_old) - coeffs[2] * (d_old - d_older)) / h + + j_total = j_cond + j_ion + j_disp + pos_idx = 0 if dev.voltage_polarity > 0.0 else -1 + j_terminal = float(dev.voltage_polarity * j_total[pos_idx]) + spread = float(np.ptp(j_total)) + return { + "conduction_current_density_A_m2": j_cond, + "ionic_current_density_A_m2": j_ion, + "displacement_current_density_A_m2": j_disp, + "total_current_density_A_m2": j_total, + "terminal_current_density_A_m2": j_terminal, + "maxwell_spread_A_m2": spread, + } + + +@dataclass(frozen=True, slots=True) +class DynamicDefectSteadyOptions: + """Damped/equilibrated Newton + continuation controls for steady dynamic-defect solves.""" + + max_iterations: int = 80 + residual_tolerance: float = 1.0e-10 + step_tolerance: float = 1.0e-8 + max_logit_step: float = 2.0 + max_potential_step_V: float = 0.5 + inventory_row_node: int = 0 + + +@dataclass(frozen=True) +class DynamicDefectSteadyResult: + """Certified steady state of ``CompiledDynamicDefectDevice1D``.""" + + state: DynamicDefectState1D + problem: AssembledDynamicDefect1DProblem = field(repr=False) + converged: bool + iterations: int + residual_inf_norm: float + scaled_step_norm: float + terminal_current_density_A_m2: float + all_face_current_density_A_m2: Vector + maxwell_spread_A_m2: float + + +def _damped_newton_solve( + problem: AssembledDynamicDefect1DProblem, + u_init: Vector, + options: DynamicDefectSteadyOptions, +) -> tuple[Vector, bool, int, float, float]: + N = problem.device.node_count + u = np.array(u_init, dtype=np.float64, copy=True) + + # Enforce exact Dirichlet potential contacts on initial seed: + phi_l, phi_r = problem.device.electronic_component.contact_potentials(problem.voltage_V) + u[0] = phi_l + u[N - 1] = phi_r + + res_norm = math.inf + step_norm = math.inf + for iteration in range(1, options.max_iterations + 1): + sys = problem.assemble(u, derivatives=True) + if not sys.admissible or sys.J is None or not np.all(np.isfinite(sys.F)): + raise FloatingPointError("steady Newton encountered inadmissible initial/trial state") + F = sys.F + J = sys.J + + row_max = np.asarray(np.abs(J).max(axis=1).todense()).ravel() + row_scale = np.where(row_max > 0.0, 1.0 / row_max, 1.0) + f_scaled = row_scale * F + res_norm = float(np.max(np.abs(f_scaled))) + if res_norm <= options.residual_tolerance and ( + iteration == 1 + or step_norm <= options.step_tolerance + or res_norm <= 1.0e-2 * options.residual_tolerance + ): + return u, True, iteration - 1, res_norm, (0.0 if iteration == 1 else step_norm) + + j_row = diags(row_scale) @ J + col_max = np.asarray(np.abs(j_row).max(axis=0).todense()).ravel() + col_scale = np.where(col_max > 0.0, 1.0 / col_max, 1.0) + try: + factor = splu((j_row @ diags(col_scale)).tocsc()) + du = -col_scale * factor.solve(f_scaled) + except RuntimeError: + return u, False, iteration, res_norm, step_norm + if not np.all(np.isfinite(du)): + raise FloatingPointError("steady Newton linear step is nonfinite") + + # Clip giant initial potential / logit jumps gently before line search: + max_dphi = float(np.max(np.abs(du[:N]))) + max_dlog = float(np.max(np.abs(du[N:]))) if du.size > N else 0.0 + clip = 1.0 + if max_dphi > options.max_potential_step_V: + clip = min(clip, options.max_potential_step_V / max_dphi) + if max_dlog > options.max_logit_step: + clip = min(clip, options.max_logit_step / max_dlog) + + merit_0 = float(np.linalg.norm(f_scaled)) + alpha = clip + accepted_u: Vector | None = None + for _ in range(18): + u_try = u + alpha * du + try: + sys_try = problem.assemble(u_try, derivatives=False) + except FloatingPointError: + alpha *= 0.5 + continue + if not sys_try.admissible or not np.all(np.isfinite(sys_try.F)): + alpha *= 0.5 + continue + f_try_scaled = row_scale * sys_try.F + merit_try = float(np.linalg.norm(f_try_scaled)) + if merit_try <= (1.0 - 1.0e-4 * alpha) * merit_0 or merit_try <= options.residual_tolerance: + accepted_u = u_try + break + alpha *= 0.5 + + if accepted_u is None: + return u, False, iteration, res_norm, step_norm + step_norm = float(np.max(np.abs(accepted_u - u))) + u = accepted_u + + try: + sys_end = problem.assemble(u, derivatives=True) + except FloatingPointError: + return u, False, iteration, res_norm, step_norm + if sys_end.admissible and sys_end.J is not None and np.all(np.isfinite(sys_end.F)): + rm = np.asarray(np.abs(sys_end.J).max(axis=1).todense()).ravel() + rs = np.where(rm > 0.0, 1.0 / rm, 1.0) + res_norm = float(np.max(np.abs(rs * sys_end.F))) + if res_norm <= options.residual_tolerance and ( + step_norm <= options.step_tolerance or res_norm <= 1.0e-2 * options.residual_tolerance + ): + return u, True, iteration, res_norm, step_norm + + return u, False, options.max_iterations, res_norm, step_norm + + +def _scaled_newton( + step: Any, + u_init: Vector, + *, + tolerance: float = 1.0e-10, + max_iterations: int = 40, +) -> tuple[Vector, bool, int]: + """Row/column-equilibrated damped Newton on any object exposing ``residual`` / ``jacobian``.""" + u = np.array(u_init, dtype=np.float64, copy=True) + for iteration in range(max_iterations + 1): + try: + f = np.asarray(step.residual(u), dtype=np.float64) + jac = csc_matrix(step.jacobian(u)) + except (FloatingPointError, ValueError): + return u, False, iteration + row_max = np.asarray(np.abs(jac).max(axis=1).todense()).ravel() + row_scale = np.where(row_max > 0.0, 1.0 / row_max, 1.0) + fs = row_scale * f + if float(np.max(np.abs(fs))) <= tolerance: + return u, True, iteration + if iteration == max_iterations: + break + j_row = diags(row_scale) @ jac + col_max = np.asarray(np.abs(j_row).max(axis=0).todense()).ravel() + col_scale = np.where(col_max > 0.0, 1.0 / col_max, 1.0) + try: + du = -col_scale * splu((j_row @ diags(col_scale)).tocsc()).solve(fs) + except RuntimeError: + return u, False, iteration + if not np.all(np.isfinite(du)): + return u, False, iteration + merit = float(np.linalg.norm(fs)) + alpha = 1.0 + accepted: Vector | None = None + for _ in range(24): + u_try = u + alpha * du + try: + trial = row_scale * np.asarray(step.residual(u_try), dtype=np.float64) + except (FloatingPointError, ValueError): + alpha *= 0.5 + continue + if np.all(np.isfinite(trial)) and float(np.linalg.norm(trial)) < merit: + accepted = u_try + break + alpha *= 0.5 + if accepted is None: + return u, False, iteration + u = accepted + return u, False, max_iterations + + +def _pseudo_transient_solve( + problem: AssembledDynamicDefect1DProblem, + u_init: Vector, + options: DynamicDefectSteadyOptions, +) -> tuple[Vector, bool, int]: + """Backward-Euler pseudo-time continuation to a steady state of ``problem``.""" + unconstrained_prob = ( + problem + if problem.inventory_row_node is None + else AssembledDynamicDefect1DProblem( + problem.device, + problem.voltage_V, + problem.generation_scale, + None, + dynamic_defect_system_1d(problem.device, inventory_row_node=None), + ) + ) + adapter = DynamicDefectStorage1D(unconstrained_prob) + u = np.array(u_init, dtype=np.float64, copy=True) + phi_l, phi_r = problem.device.electronic_component.contact_potentials(problem.voltage_V) + u[0] = phi_l + u[problem.device.node_count - 1] = phi_r + try: + _ = adapter.storage(u) + except (FloatingPointError, ValueError): + u = problem.device.initial_equilibrium_seed(voltage_V=problem.voltage_V) + time_s = 0.0 + dt = 1.0e-12 + steps = 0 + while dt < 1.0e18 and steps < 400: + previous = HistoryPoint(time_s, u, adapter.storage(u), adapter) + step = BDFStep(adapter, (previous,), time_s + dt, 1) + candidate, ok, _ = _scaled_newton(step, u, tolerance=1.0e-9, max_iterations=25) + steps += 1 + if not ok: + dt *= 0.25 + if dt < 1.0e-18: + break + continue + u = candidate + time_s += dt + dt *= 3.0 + try: + probe = problem.assemble(u, derivatives=True) + except FloatingPointError: + continue + if probe.admissible and probe.J is not None and np.all(np.isfinite(probe.F)): + row_max = np.asarray(np.abs(probe.J).max(axis=1).todense()).ravel() + if float(np.max(np.abs(np.where(row_max > 0, 1.0 / row_max, 1.0) * probe.F))) <= 1.0e-8: + return u, True, steps + return u, False, steps + + +def _newton_or_pseudo_transient( + problem: AssembledDynamicDefect1DProblem, + u_init: Vector, + options: DynamicDefectSteadyOptions, +) -> tuple[Vector, bool, int, float, float]: + """Direct damped Newton first; pseudo-transient continuation and Newton polish on failure.""" + try: + result = _damped_newton_solve(problem, u_init, options) + except FloatingPointError: + result = (np.array(u_init, dtype=np.float64, copy=True), False, 0, math.inf, math.inf) + if result[1]: + return result + seed, reached, steps = _pseudo_transient_solve(problem, u_init, options) + try: + polished = _damped_newton_solve(problem, seed, options) + except FloatingPointError: + return seed, False, steps, math.inf, math.inf + return polished[0], polished[1], steps + polished[2], polished[3], polished[4] + + +def solve_dynamic_defect_steady_1d( + device: CompiledDynamicDefectDevice1D, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + initial_u: ArrayLike | None = None, + options: DynamicDefectSteadyOptions | None = None, + voltage_step_max_V: float = 0.04, +) -> DynamicDefectSteadyResult: + """Solve steady DC working point (with automatic dark -> light -> bias continuation if needed).""" + controls = DynamicDefectSteadyOptions() if options is None else options + inv_row = controls.inventory_row_node if device.has_ions else None + sys_binding = dynamic_defect_system_1d(device, inventory_row_node=inv_row) + + target_v = float(voltage_V) + target_g = float(generation_scale) + if not math.isfinite(target_v) or not math.isfinite(target_g) or target_g < 0.0: + raise ValueError("voltage_V must be finite and generation_scale >= 0") + + def _advance_bias_interval( + u_left: Vector, v_left: float, v_right: float, depth: int = 0 + ) -> tuple[Vector, bool, int, float, float]: + u_seed = device.rebase_coordinates(u_left, v_left, v_right) + phi_l, phi_r = device.electronic_component.contact_potentials(v_right) + dv_contact = (phi_r - phi_l) - (u_seed[device.node_count - 1] - u_seed[0]) + nodes = device.nodes_m + u_seed[: device.node_count] += dv_contact * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + prob_v = AssembledDynamicDefect1DProblem( + device, v_right, target_g, inv_row, sys_binding + ) + u_out, ok, step_iters, r_val, s_val = _newton_or_pseudo_transient(prob_v, u_seed, controls) + if ok or depth >= 6 or abs(v_right - v_left) <= 1.0e-3: + return u_out, ok, step_iters, r_val, s_val + v_mid = 0.5 * (v_left + v_right) + u_mid, ok1, it1, r1, s1 = _advance_bias_interval(u_left, v_left, v_mid, depth + 1) + if not ok1: + return u_mid, False, step_iters + it1, r1, s1 + u_end, ok2, it2, r2, s2 = _advance_bias_interval(u_mid, v_mid, v_right, depth + 1) + return u_end, ok2, step_iters + it1 + it2, r2, s2 + + total_iters = 0 + if initial_u is not None: + u_curr = np.array(initial_u, dtype=np.float64, copy=True) + prob_target = AssembledDynamicDefect1DProblem( + device, target_v, target_g, inv_row, sys_binding + ) + u_sol, conv, iters, r_norm, s_norm = _newton_or_pseudo_transient(prob_target, u_curr, controls) + total_iters += iters + else: + u_curr = device.initial_equilibrium_seed(voltage_V=0.0) + prob_eq = AssembledDynamicDefect1DProblem(device, 0.0, 0.0, inv_row, sys_binding) + u_curr, conv, iters, r_norm, s_norm = _newton_or_pseudo_transient(prob_eq, u_curr, controls) + total_iters += iters + if not conv: + raise RuntimeError(f"dark 0 V equilibrium failed to converge (res={r_norm:.3e})") + + if target_g > 0.0: + for g_frac in (1.0e-3, 1.0e-1, 1.0) if target_g >= 0.1 else (1.0,): + g_val = target_g * g_frac + prob_g = AssembledDynamicDefect1DProblem(device, 0.0, g_val, inv_row, sys_binding) + u_curr, conv, iters, r_norm, s_norm = _newton_or_pseudo_transient(prob_g, u_curr, controls) + total_iters += iters + if not conv: + raise RuntimeError(f"illumination continuation failed at G={g_val:.3g}") + + if abs(target_v) > 0.0: + n_steps = max(1, int(math.ceil(abs(target_v) / max(voltage_step_max_V, 1.0e-3)))) + v_prev = 0.0 + for k in range(1, n_steps + 1): + v_next = target_v * (k / n_steps) + u_curr, conv, iters, r_norm, s_norm = _advance_bias_interval(u_curr, v_prev, v_next) + total_iters += iters + if not conv: + raise RuntimeError(f"voltage continuation failed at V={v_next:.4f} V") + v_prev = v_next + u_sol = u_curr + prob_target = AssembledDynamicDefect1DProblem( + device, target_v, target_g, inv_row, sys_binding + ) + + if not conv: + raise RuntimeError( + f"steady dynamic-defect solve did not converge: residual_inf_norm={r_norm:.3e}" + ) + + state_obj = device.state(u_sol, voltage_V=target_v) + j_all = prob_target.dc_current_density_A_m2(u_sol) + j_term = prob_target.terminal_current_density_A_m2(u_sol) + spread = float(np.ptp(j_all)) + return DynamicDefectSteadyResult( + state=state_obj, + problem=prob_target, + converged=True, + iterations=total_iters, + residual_inf_norm=r_norm, + scaled_step_norm=s_norm, + terminal_current_density_A_m2=j_term, + all_face_current_density_A_m2=j_all, + maxwell_spread_A_m2=spread, + ) + + +@dataclass(frozen=True) +class DynamicDefectACSweepPoint: + """Single-frequency small-signal response and Maxwell/conservation diagnostics.""" + + frequency_Hz: float + linear_solution: FrequencySolution + admittance_density_S_m2: complex + impedance_area_ohm_m2: complex + electronic_conduction_current_A_m2: ComplexVector + ionic_conduction_current_A_m2: ComplexVector + displacement_current_A_m2: ComplexVector + total_current_A_m2: ComplexVector + maxwell_spread_A_m2_V: float + potential_perturbation_V: ComplexVector + electron_density_perturbation_m3: ComplexVector + hole_density_perturbation_m3: ComplexVector + bulk_trap_occupancy_perturbation_per_V: ComplexVector + bulk_trap_charge_perturbation_C_m3_per_V: ComplexVector + interface_trap_occupancy_perturbation_per_V: ComplexVector + interface_sheet_charge_perturbation_C_m2_per_V: ComplexVector + ion_density_perturbation_m3: Mapping[str, ComplexVector] + ion_inventory_perturbation_m2: Mapping[str, complex] + ion_inventory_relative_per_V: Mapping[str, float] + + +@dataclass(frozen=True) +class DynamicDefectACSweepResult: + """Frequency-sweep small-signal AC result on ``CompiledDynamicDefectDevice1D``.""" + + frequencies_Hz: Vector + voltage_phasor_V: complex + admittance_density_S_m2: ComplexVector + impedance_area_ohm_m2: ComplexVector + maxwell_spread_A_m2_V: Vector + points: tuple[DynamicDefectACSweepPoint, ...] + active_species: tuple[str, ...] + frozen_species: tuple[str, ...] + operating_voltage_V: float + generation_scale: float + working_state_digest: str + + +@dataclass(frozen=True) +class DynamicDefectSmallSignal1D: + """Exact small-signal AC linearization ``(J + i * omega * K) x = b`` about steady state.""" + + device: CompiledDynamicDefectDevice1D + operating_state: DynamicDefectState1D + generation_scale: float = 0.0 + problem: AssembledDynamicDefect1DProblem = field(init=False, repr=False) + jacobian: csc_matrix = field(init=False, repr=False) + storage_jacobian: csc_matrix = field(init=False, repr=False) + working_state_digest: str = field(init=False) + + def __post_init__(self) -> None: + if self.operating_state.device_sha256 != self.device.sha256: + raise ValueError("operating_state belongs to a different compiled device") + # Unconstrained rows (inventory_row_node=None) so K = -S_u has full ion storage! + prob = AssembledDynamicDefect1DProblem( + self.device, + voltage_V=self.operating_state.voltage_V, + generation_scale=self.generation_scale, + inventory_row_node=None, + ) + u0 = self.operating_state.u + object.__setattr__(self, "problem", prob) + object.__setattr__(self, "jacobian", prob.jacobian(u0)) + object.__setattr__(self, "storage_jacobian", prob.storage_jacobian(u0)) + object.__setattr__( + self, + "working_state_digest", + sha256(np.ascontiguousarray(u0, dtype=np.float64).tobytes()).hexdigest(), + ) + + def species_partition( + self, + *, + freeze_ions: bool = False, + freeze_bulk_traps: bool = False, + freeze_interface_traps: bool = False, + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return ``(active_species, frozen_species)`` ledger for diagnostic transparency.""" + active: list[str] = ["electrons", "holes"] + frozen: list[str] = [] + if self.device.ionic_component is not None: + immobile = set( + declared_immobile_profiles(cast(CompiledIonicDevice1D, self.device.ionic_component)) + ) + for sp in self.device.ionic_component.ion_species_names: + label = f"ion:{sp}" + if freeze_ions or sp in immobile: + frozen.append(label) + else: + active.append(label) + if self.device.dynamic_bulk_traps is not None: + for mode in self.device.dynamic_bulk_traps.modes: + label = f"bulk_trap:{mode.mode_id}" + if freeze_bulk_traps: + frozen.append(label) + else: + active.append(label) + for itrap in self.device.dynamic_interface_traps: + label = f"interface_trap:{itrap.interface_id}" + if freeze_interface_traps: + frozen.append(label) + else: + active.append(label) + return tuple(active), tuple(frozen) + + def solve_sweep( + self, + frequencies_Hz: ArrayLike, + *, + voltage_phasor_V: complex = 1.0, + options: FrequencyOptions | None = None, + freeze_ions: bool = False, + freeze_bulk_traps: bool = False, + freeze_interface_traps: bool = False, + ) -> DynamicDefectACSweepResult: + """Solve complex sparse small-signal AC sweep with selective species freezing.""" + controls = FrequencyOptions() if options is None else options + freqs = np.asarray(frequencies_Hz, dtype=np.float64) + if ( + freqs.ndim != 1 + or freqs.size == 0 + or not np.all(np.isfinite(freqs)) + or np.any(freqs < 0.0) + or np.unique(freqs).size != freqs.size + ): + raise ValueError("frequencies_Hz must be 1D distinct finite non-negative Hz") + if freqs.size > controls.max_frequencies: + controls = FrequencyOptions( + max_frequencies=int(freqs.size), + relative_tolerance=controls.relative_tolerance, + max_refinements=controls.max_refinements, + ) + + voltage = complex(voltage_phasor_V) + if not np.isfinite(voltage) or voltage == 0.0: + raise ValueError("voltage_phasor_V must be finite and nonzero") + + dev = self.device + comp = dev.electronic_component + N = dev.node_count + + # Build base J, K with any frozen species pinned to 0 perturbation: + j_base = self.jacobian.copy().tolil() + k_base = self.storage_jacobian.copy().tolil() + + rhs: ComplexVector = np.zeros(dev.state_size, dtype=np.complex128) + phi_right = complex(-comp.voltage_polarity * voltage) + rhs[N - 1] = phi_right + + known: dict[int, complex] = {0: 0.0j, N - 1: phi_right} + for carrier, offset in (("n", N), ("p", 2 * N)): + if comp.channel(carrier, "left").kind == "fixed_reservoir": + known[offset] = 0.0j + if comp.channel(carrier, "right").kind == "fixed_reservoir": + known[offset + N - 1] = -phi_right / comp.thermal_voltage_V + + frozen_indices: list[int] = [] + if dev.ionic_component is not None and freeze_ions: + sl_ion = dev.ion_slice + frozen_indices.extend(range(sl_ion.start, sl_ion.stop)) + if dev.dynamic_bulk_traps is not None and freeze_bulk_traps: + sl_bt = dev.bulk_trap_slice + frozen_indices.extend(range(sl_bt.start, sl_bt.stop)) + if dev.dynamic_interface_traps and freeze_interface_traps: + sl_it = dev.interface_trap_slice + frozen_indices.extend(range(sl_it.start, sl_it.stop)) + + for idx in frozen_indices: + j_base.rows[idx], j_base.data[idx] = [idx], [1.0] + k_base.rows[idx], k_base.data[idx] = [], [] + known[idx] = 0.0j + rhs[idx] = 0.0j + + j_csc = j_base.tocsc() + k_csc = k_base.tocsc() + + # Split 0 Hz (if mobile ions are active, 0 Hz needs inventory constraint rows) vs f > 0 Hz: + has_mobile_ions = dev.ionic_component is not None and not freeze_ions + if has_mobile_ions: + ion_dev: CompiledIonicDevice1D | TwoSidedIonicComponent1D | None = dev.ionic_component + assert ion_dev is not None + immobile_profiles = declared_immobile_profiles(cast(CompiledIonicDevice1D, ion_dev)) + for sp, blk_sl in zip(ion_dev.ion_species_names, ion_dev.ion_species_slices): + if sp in immobile_profiles: + for row in range(cast(int, blk_sl.start), cast(int, blk_sl.stop)): + grad = -self.storage_jacobian[row, :].toarray()[0] + nz = np.flatnonzero(grad) + j_base.rows[row], j_base.data[row] = nz.tolist(), grad[nz].tolist() + k_base.rows[row], k_base.data[row] = [], [] + rhs[row] = 0.0j + else: + diff_faces = getattr(ion_dev, sp + "_ion_diffusivity_faces_m2_s") + if np.all(diff_faces > 0.0): + row0 = cast(int, blk_sl.start) + grad = -np.asarray(self.storage_jacobian[blk_sl, :].sum(axis=0)).ravel() + nz = np.flatnonzero(grad) + j_base.rows[row0], j_base.data[row0] = nz.tolist(), grad[nz].tolist() + k_base.rows[row0], k_base.data[row0] = [], [] + rhs[row0] = 0.0j + elif np.any(freqs == 0.0): + raise CapabilityError( + "0 Hz mobile ions require positive diffusivity across domain" + ) + j_csc = j_base.tocsc() + k_csc = k_base.tocsc() + + solutions_by_idx = list( + solve_frequency_systems( + j_csc, k_csc, rhs, freqs, options=controls, fixed_coordinates=known + ) + ) + + points: list[DynamicDefectACSweepPoint] = [] + admittances = np.empty(freqs.size, dtype=np.complex128) + impedances = np.empty(freqs.size, dtype=np.complex128) + spreads = np.empty(freqs.size, dtype=np.float64) + + for f_idx, sol in enumerate(solutions_by_idx): + pt = self._observe_point( + sol, + voltage=voltage, + freeze_ions=freeze_ions, + freeze_bulk_traps=freeze_bulk_traps, + freeze_interface_traps=freeze_interface_traps, + ) + points.append(pt) + admittances[f_idx] = pt.admittance_density_S_m2 + impedances[f_idx] = pt.impedance_area_ohm_m2 + spreads[f_idx] = pt.maxwell_spread_A_m2_V + + for arr in (admittances, impedances, spreads): + arr.setflags(write=False) + freqs_out = np.array(freqs, dtype=np.float64, copy=True) + freqs_out.setflags(write=False) + active_sp, frozen_sp = self.species_partition( + freeze_ions=freeze_ions, + freeze_bulk_traps=freeze_bulk_traps, + freeze_interface_traps=freeze_interface_traps, + ) + return DynamicDefectACSweepResult( + frequencies_Hz=freqs_out, + voltage_phasor_V=voltage, + admittance_density_S_m2=admittances, + impedance_area_ohm_m2=impedances, + maxwell_spread_A_m2_V=spreads, + points=tuple(points), + active_species=active_sp, + frozen_species=frozen_sp, + operating_voltage_V=self.operating_state.voltage_V, + generation_scale=self.generation_scale, + working_state_digest=self.working_state_digest, + ) + + def _observe_point( + self, + sol: FrequencySolution, + *, + voltage: complex, + freeze_ions: bool, + freeze_bulk_traps: bool, + freeze_interface_traps: bool, + ) -> DynamicDefectACSweepPoint: + dev = self.device + comp = dev.electronic_component + N = dev.node_count + vt = dev.thermal_voltage_V + u0 = self.operating_state.u + x = sol.solution + omega = 2.0 * math.pi * sol.frequency_Hz + + state_eval = self.problem.binding.assembler.state(u0, self.problem.inputs) + assert state_eval is not None + + phi_x = x[:N] + zn_x = x[N : 2 * N] + zp_x = x[2 * N : 3 * N] + + n0 = self.operating_state.electronic_state.electron_density_m3 + p0 = self.operating_state.electronic_state.hole_density_m3 + dn = n0 * (phi_x / vt + zn_x) + dp = -p0 * (phi_x / vt + zp_x) + + # 1. Dynamic bulk trap perturbations: + if dev.dynamic_bulk_traps is not None: + trap_ev = cast(DynamicBulkTrapEvaluation, state_eval.field("dynamic_bulk_traps")) + u_bt_x = x[dev.bulk_trap_slice] + df_bt = ( + np.zeros(dev.dynamic_bulk_traps.size, dtype=np.complex128) + if freeze_bulk_traps + else (trap_ev.occupancy * trap_ev.one_minus_occupancy) * u_bt_x + ) + drho_bt_local = trap_ev.d_charge_df_C_m3 * df_bt + drho_bt: ComplexVector = np.zeros(N, dtype=np.complex128) + np.add.at(drho_bt, dev.dynamic_bulk_traps.device_node_indices, drho_bt_local) + d_cap_n_local = ( + trap_ev.d_electron_capture_dn_s1 * dn[dev.dynamic_bulk_traps.device_node_indices] + + trap_ev.d_electron_capture_df_m3_s * df_bt + ) + d_cap_p_local = ( + trap_ev.d_hole_capture_dp_s1 * dp[dev.dynamic_bulk_traps.device_node_indices] + + trap_ev.d_hole_capture_df_m3_s * df_bt + ) + d_cap_n: ComplexVector = np.zeros(N, dtype=np.complex128) + d_cap_p: ComplexVector = np.zeros(N, dtype=np.complex128) + np.add.at(d_cap_n, dev.dynamic_bulk_traps.device_node_indices, d_cap_n_local) + np.add.at(d_cap_p, dev.dynamic_bulk_traps.device_node_indices, d_cap_p_local) + else: + df_bt = np.empty(0, dtype=np.complex128) + drho_bt = np.zeros(N, dtype=np.complex128) + d_cap_n = np.zeros(N, dtype=np.complex128) + d_cap_p = np.zeros(N, dtype=np.complex128) + + # 2. Stationary defect perturbations: + if dev.stationary_defects is not None: + stat_ev = cast(StationaryDefectEvaluation1D, state_eval.field("stationary_defects")) + drho_stat = ( + stat_ev.d_charge_dphi_fixed_qf_C_m3_V * phi_x + + (stat_ev.d_charge_dn_C * n0) * zn_x + - (stat_ev.d_charge_dp_C * p0) * zp_x + ) + d_rec_stat = stat_ev.d_recombination_dn_s1 * dn + stat_ev.d_recombination_dp_s1 * dp + else: + drho_stat = np.zeros(N, dtype=np.complex128) + d_rec_stat = np.zeros(N, dtype=np.complex128) + + # 3. Dynamic interface trap perturbations: + if dev.dynamic_interface_traps: + df_it: ComplexVector = np.zeros(len(dev.dynamic_interface_traps), dtype=np.complex128) + dsigma_it: ComplexVector = np.zeros(len(dev.dynamic_interface_traps), dtype=np.complex128) + for idx, (itrap, sl) in enumerate( + zip(dev.dynamic_interface_traps, dev.interface_trap_slices) + ): + if not freeze_interface_traps: + res = state_eval.field(f"dyn_iface:{itrap.interface_index}") + f_occ = float(res.occupancy) + df_it[idx] = f_occ * float(res.one_minus_occupancy) * x[sl.start] + if itrap.has_sheet_charge: + dsigma_it[idx] = float(res.d_sheet_charge_df_C_m2) * df_it[idx] + else: + df_it = np.empty(0, dtype=np.complex128) + dsigma_it = np.empty(0, dtype=np.complex128) + + # 4. Electronic face particle flux perturbations (grouping exact SG differences): + fluxes = self.problem.binding.electronic.transport.fluxes(state_eval) + transport = None if comp.field_transport is None else comp.field_transport.evaluate(u0[:N]) + fn_pert: list[ComplexVector] = [] + for offset, dens, flx, sign in ( + (N, n0, fluxes.electron, 1.0), + (2 * N, p0, fluxes.hole, -1.0), + ): + drive = sign * np.diff(u0[offset : offset + N]) + l_phi, _ = quasi_fermi_potential_tangents(flx, drive, sign, vt) + if transport is not None: + diff = ( + transport.electron_diffusivity_m2_s + if offset == N + else transport.hole_diffusivity_m2_s + ) + d_diff = ( + transport.electron_d_diffusivity_d_field + if offset == N + else transport.hole_d_diffusivity_d_field + ) + l_phi = l_phi + (flx.flux / diff) * d_diff / np.diff(comp.nodes_m) + l_z = sign * flx.left_density_derivative * dens[:-1] + z_blk = x[offset : offset + N] + pert = ( + l_phi * (phi_x[:-1] - phi_x[1:]) + + l_z * (z_blk[:-1] - z_blk[1:]) + + sign * flx.flux * (z_blk[1:] + phi_x[1:] / vt) + ) + fn_pert.append(pert) + dfn, dfp = fn_pert[0], fn_pert[1] + + # Override thermionic / two-sided interface faces with their exact analytical tangents: + if comp.interface_model is not None: + if comp.interface_model.topology == "deduplicated": + for tf in comp.interface_model.thermionic_faces: + f = tf.face + dfn[f] = ( + state_eval.field("iface:e_left_phi")[f] * phi_x[f] + + state_eval.field("iface:e_right_phi")[f] * phi_x[f + 1] + + state_eval.field("iface:e_left_zn")[f] * zn_x[f] + + state_eval.field("iface:e_right_zn")[f] * zn_x[f + 1] + ) + dfp[f] = ( + state_eval.field("iface:h_left_phi")[f] * phi_x[f] + + state_eval.field("iface:h_right_phi")[f] * phi_x[f + 1] + + state_eval.field("iface:h_left_zp")[f] * zp_x[f] + + state_eval.field("iface:h_right_zp")[f] * zp_x[f + 1] + ) + elif comp.interface_model.topology == "two_sided_trace": + dyn_idx_map = { + it.interface_index: (pos, it) + for pos, it in enumerate(dev.dynamic_interface_traps) + } + for tspec in comp.interface_model.two_sided: + k = tspec.interface_index + f = tspec.face + ln, rn = tspec.left_node, tspec.right_node + if k in dyn_idx_map: + pos, itrap = dyn_idx_map[k] + res = state_eval.field(f"dyn_iface:{k}") + jb = res.bulk_flux_jacobian_bulk + dbf = res.bulk_flux_derivative_occupancy + gl_e = (jb[0, 0] + (jb[0, 2] - jb[0, 3]) / vt) * phi_x[ln] + jb[0, 2] * zn_x[ln] - jb[0, 3] * zp_x[ln] + gr_e = (jb[0, 1] + (jb[0, 4] - jb[0, 5]) / vt) * phi_x[rn] + jb[0, 4] * zn_x[rn] - jb[0, 5] * zp_x[rn] + gl_h = (jb[1, 0] + (jb[1, 2] - jb[1, 3]) / vt) * phi_x[ln] + jb[1, 2] * zn_x[ln] - jb[1, 3] * zp_x[ln] + gr_h = (jb[1, 1] + (jb[1, 4] - jb[1, 5]) / vt) * phi_x[rn] + jb[1, 4] * zn_x[rn] - jb[1, 5] * zp_x[rn] + dfn[f] = gl_e + gr_e + float(dbf[0]) * df_it[pos] + dfp[f] = gl_h + gr_h + float(dbf[1]) * df_it[pos] + else: + # Reconstruct left-side bulk flux perturbation from bulk interface tangents: + bulk = TwoSidedBulkState( + phi_left_V=float(u0[ln]), + phi_right_V=float(u0[rn]), + n_left_m3=float(n0[ln]), + p_left_m3=float(p0[ln]), + n_right_m3=float(n0[rn]), + p_right_m3=float(p0[rn]), + electron_electrochemical_step=float(u0[N + rn] - u0[N + ln]), + hole_electrochemical_step=float(-(u0[2 * N + rn] - u0[2 * N + ln])), + ) + if tspec.charge is not None: + qres = solve_charged_two_sided_interface_qss( + tspec.trace_electrostatics, tspec.physics, bulk, tspec.charge + ) + jb = qres.bulk_flux_jacobian_bulk + else: + ures = solve_two_sided_interface_qss( + tspec.trace_electrostatics, tspec.physics, bulk + ) + jb = ures.bulk_flux_jacobian_bulk + dfn[f] = ( + (jb[0, 0] + (jb[0, 2] - jb[0, 3]) / vt) * phi_x[ln] + + (jb[0, 1] + (jb[0, 4] - jb[0, 5]) / vt) * phi_x[rn] + + jb[0, 2] * zn_x[ln] + + jb[0, 4] * zn_x[rn] + - jb[0, 3] * zp_x[ln] + - jb[0, 5] * zp_x[rn] + ) + dfp[f] = ( + (jb[1, 0] + (jb[1, 2] - jb[1, 3]) / vt) * phi_x[ln] + + (jb[1, 1] + (jb[1, 4] - jb[1, 5]) / vt) * phi_x[rn] + + jb[1, 2] * zn_x[ln] + + jb[1, 4] * zn_x[rn] + - jb[1, 3] * zp_x[ln] + - jb[1, 5] * zp_x[rn] + ) + + # Terminal electronic conduction currents: + rate = self.problem.binding.electronic.recombination.rate(n0, p0, derivatives=True) + assert rate.d_rate_dn is not None and rate.d_rate_dp is not None + d_rec_base = rate.d_rate_dn * dn + rate.d_rate_dp * dp + d_src_n = -(d_rec_base + d_rec_stat + d_cap_n) + d_src_p = -(d_rec_base + d_rec_stat + d_cap_p) + w = comp.geometry.cell_measures_m + + terminals: list[complex] = [] + for side, node, face, orient in (("left", 0, 0, -1.0), ("right", N - 1, -1, 1.0)): + j_term = 0.0j + for carrier, d_dens, d_flux, d_src, q_sign in ( + ("n", dn, dfn, d_src_n, -Q), + ("p", dp, dfp, d_src_p, Q), + ): + ch = comp.channel(carrier, side) + if ch.kind == "fixed_reservoir": + exch = d_flux[face] + orient * w[node] * (d_src[node] - 1j * omega * d_dens[node]) + else: + slope = boundary_particle_flux(ch, ch.reservoir_density_m3).density_derivative + exch = slope * d_dens[node] + j_term += q_sign * exch + terminals.append(j_term) + + j_elec: ComplexVector = np.r_[terminals[0], -Q * dfn + Q * dfp, terminals[1]] + + # 5. Mobile-ion density, inventory, charge, and conduction current perturbations: + j_ion: ComplexVector = np.zeros(N + 1, dtype=np.complex128) + drho_ion: ComplexVector = np.zeros(N, dtype=np.complex128) + ion_dens_map: dict[str, ComplexVector] = {} + ion_inv_map: dict[str, complex] = {} + ion_inv_rel_map: dict[str, float] = {} + + if dev.ionic_component is not None: + ion_dev = dev.ionic_component + ion_st = self.operating_state.ionic_state + assert ion_st is not None + mass = ion_dev.ion_coordinate_jacobian_m3( + u0[: ion_dev.state_size], voltage_V=self.operating_state.voltage_V + ) + coords = np.stack([x[sl] for sl in ion_dev.ion_species_slices], axis=1) + dens_perts = np.sum(mass * coords[:, None, :], axis=2).T + pops = ( + (ion_st.positive_ion_density_m3,) + if ion_dev.ion_species_count == 1 + else (ion_st.positive_ion_density_m3, ion_st.negative_ion_density_m3) + ) + w_ratio = ion_dev.ion_geometry.cell_measures_m / w[ion_dev.ion_node_indices] + for s_idx, sp in enumerate(ion_dev.ion_species_names): + sign = 1.0 if s_idx == 0 else -1.0 + d_ion = ( + np.zeros(ion_dev.ion_node_count, dtype=np.complex128) + if freeze_ions + else dens_perts[s_idx] + ) + ion_dens_map[sp] = d_ion + weighted = ion_dev.ion_geometry.cell_measures_m * d_ion + inv_c = complex( + math.fsum(weighted.real.tolist()), math.fsum(weighted.imag.tolist()) + ) + target_inv = math.fsum( + ( + ion_dev.ion_geometry.cell_measures_m + * getattr(ion_dev, sp + "_ion_reference_m3") + ).tolist() + ) + ion_inv_map[sp] = inv_c + ion_inv_rel_map[sp] = abs(inv_c) / (target_inv * abs(voltage)) + drho_ion[ion_dev.ion_node_indices] += sign * Q * w_ratio * d_ion + + if not freeze_ions: + tan = ion_face_flux_jacobian( + ion_st.electronic_state.potential_V[ion_dev.ion_node_indices], + pops[s_idx], + np.diff(ion_dev.ion_geometry.nodes_m), + getattr(ion_dev, sp + "_ion_diffusivity_faces_m2_s"), + vt, + getattr(ion_dev, sp + "_ion_site_limit_m3")[:-1], + steric_diffusion_only=ion_dev.steric_model == DIFFUSION_ONLY_STERIC_V1, + P_lim_node=getattr(ion_dev, sp + "_ion_site_limit_m3"), + P_other_node=( + pops[1 - s_idx] + if ion_dev.ion_site_contract == "shared_finite_sites" + else None + ), + drift_sign=sign, + ) + other = ( + dens_perts[1 - s_idx] + if ion_dev.ion_species_count == 2 + else np.zeros_like(d_ion) + ) + j_int = ( + tan.potential_left_derivative * phi_x[ion_dev.ion_node_indices[:-1]] + + tan.potential_right_derivative * phi_x[ion_dev.ion_node_indices[1:]] + + tan.density_left_derivative * d_ion[:-1] + + tan.density_right_derivative * d_ion[1:] + + tan.partner_left_derivative * other[:-1] + + tan.partner_right_derivative * other[1:] + ) + j_ion[ion_dev.ion_node_indices[:-1] + 1] += sign * Q * j_int + + # 6. Displacement current across all N+1 faces (accounting for two-sided D_left): + cell_charge = w * (Q * (dp - dn) + drho_ion + drho_stat + drho_bt) + d_series_orig = -comp.poisson.face_capacitance_F_m2 * np.diff(phi_x) + d_interior = np.array(d_series_orig, dtype=np.complex128, copy=True) + + if comp.interface_model is not None and comp.interface_model.topology == "two_sided_trace": + dyn_idx_map = { + it.interface_index: (pos, it) + for pos, it in enumerate(dev.dynamic_interface_traps) + } + for tspec in comp.interface_model.two_sided: + k = tspec.interface_index + f = tspec.face + ln, rn = tspec.left_node, tspec.right_node + if k in dyn_idx_map: + pos, itrap = dyn_idx_map[k] + if itrap.has_sheet_charge: + dsig = dsigma_it[pos] + cell_charge[ln] += itrap.weight_left * dsig + cell_charge[rn] += itrap.weight_right * dsig + d_interior[f] -= itrap.weight_left * dsig + elif tspec.charge is not None: + bulk = TwoSidedBulkState( + phi_left_V=float(u0[ln]), + phi_right_V=float(u0[rn]), + n_left_m3=float(n0[ln]), + p_left_m3=float(p0[ln]), + n_right_m3=float(n0[rn]), + p_right_m3=float(p0[rn]), + electron_electrochemical_step=float(u0[N + rn] - u0[N + ln]), + hole_electrochemical_step=float(-(u0[2 * N + rn] - u0[2 * N + ln])), + ) + qres = solve_charged_two_sided_interface_qss( + tspec.trace_electrostatics, tspec.physics, bulk, tspec.charge + ) + js = qres.sheet_charge_jacobian_bulk + dsig = ( + (js[0] + (js[2] - js[3]) / vt) * phi_x[ln] + + (js[1] + (js[4] - js[5]) / vt) * phi_x[rn] + + js[2] * zn_x[ln] + + js[4] * zn_x[rn] + - js[3] * zp_x[ln] + - js[5] * zp_x[rn] + ) + cell_charge[ln] += tspec.weight_left * dsig + cell_charge[rn] += tspec.weight_right * dsig + d_interior[f] -= tspec.weight_left * dsig + + d_left_contact = d_series_orig[0] - cell_charge[0] + d_right_contact = d_series_orig[-1] + cell_charge[-1] + d_all: ComplexVector = np.r_[d_left_contact, d_interior, d_right_contact] + j_disp: ComplexVector = 1j * omega * d_all + + j_total: ComplexVector = j_elec + j_ion + j_disp + pos_electrode = 0 if dev.voltage_polarity > 0.0 else -1 + j_in = dev.voltage_polarity * j_total[pos_electrode] + y_val = complex(j_in / voltage) + z_val = complex(1.0 / y_val) if y_val != 0.0 else complex(math.nan, math.nan) + spread = float(np.max(np.abs((j_total - j_total[0]) / voltage))) + + return DynamicDefectACSweepPoint( + frequency_Hz=sol.frequency_Hz, + linear_solution=sol, + admittance_density_S_m2=y_val, + impedance_area_ohm_m2=z_val, + electronic_conduction_current_A_m2=j_elec, + ionic_conduction_current_A_m2=j_ion, + displacement_current_A_m2=j_disp, + total_current_A_m2=j_total, + maxwell_spread_A_m2_V=spread, + potential_perturbation_V=phi_x, + electron_density_perturbation_m3=dn, + hole_density_perturbation_m3=dp, + bulk_trap_occupancy_perturbation_per_V=df_bt / voltage, + bulk_trap_charge_perturbation_C_m3_per_V=drho_bt / voltage, + interface_trap_occupancy_perturbation_per_V=df_it / voltage, + interface_sheet_charge_perturbation_C_m2_per_V=dsigma_it / voltage, + ion_density_perturbation_m3=ion_dens_map, + ion_inventory_perturbation_m2=ion_inv_map, + ion_inventory_relative_per_V=ion_inv_rel_map, + ) diff --git a/src/solarlab/equations/dynamic_defect_1d.py b/src/solarlab/equations/dynamic_defect_1d.py new file mode 100644 index 00000000..932d8ffd --- /dev/null +++ b/src/solarlab/equations/dynamic_defect_1d.py @@ -0,0 +1,955 @@ +"""Compiled 1D state, layout metadata, and constitutive bindings for dynamic defects. + +Supports: +- Stationary QSS bulk defects (charged/distributed/spatial monovalent, multivalent, + and frozen metastable configurations); +- Dynamic bulk trap occupancy modes (interior active nodes, logit-increment DOFs); +- Dynamic two-sided heterointerface trap occupancy DOFs with equilibrium-referenced + or off sheet-charge closure; +- Coupled mobile ions + dynamic bulk/interface defects in one unified state vector. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +import json +import math +from typing import Any, Callable, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import frozen_array +from solarlab.contracts.arrays import integer_indices +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.device.defects import MetastablePreparationInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CompiledDevice1D, State1D +from solarlab.equations.ionic_1d import CompiledIonicDevice1D, IonicState1D +from solarlab.mesh.geometry import ControlVolumeGeometry1D, TWO_SIDED_TRACE_V1 +from solarlab.physics.defects import ( + DynamicBulkTrapLayout, + DynamicInterfaceTrapSpec, + FrozenMetastableRegion, + MetastableDefectSpec, + MonovalentDefectRegion, + MultivalentDefectRegion, + bulk_trap_charge_density, + evaluate_frozen_metastable_region, + evaluate_monovalent_region_closure, + evaluate_multivalent_region_closure, + logit_occupancy_secant, + occupancy_from_logit_increment, + one_minus_occupancy_from_logit_increment, + stable_expit, +) +from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger +from solarlab.physics.electrostatics.interface_traces import TraceElectrostatics +from solarlab.physics.interface_transport import TwoSidedInterfacePhysics +from solarlab.physics.ions import ( + DIFFUSION_ONLY_STERIC_V1, + WHOLE_FLUX_STERIC_V1, + shared_site_densities, + shifted_logistic_density, + single_site_density, +) +from solarlab.physics.ions.shared_site import ( + shared_site_coordinate_hessian_m3, + shared_site_coordinate_jacobian_m3, +) + +Vector: TypeAlias = NDArray[np.float64] + +__all__ = [ + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "DynamicDefectState1D", + "DynamicInterfaceTrapBinding1D", + "StationaryDefectEvaluation1D", + "StationaryDefectModel1D", + "TwoSidedIonicComponent1D", +] + + +@dataclass(frozen=True, slots=True) +class StationaryDefectEvaluation1D: + """Grid-summed stationary defect space charge, recombination, and exact partials.""" + + charge_density_C_m3: Vector + d_charge_dn_C: Vector + d_charge_dp_C: Vector + d_charge_dphi_fixed_qf_C_m3_V: Vector + recombination_rate_m3_s: Vector + d_recombination_dn_s1: Vector + d_recombination_dp_s1: Vector + + +@dataclass(frozen=True, slots=True) +class StationaryDefectModel1D: + """Stationary QSS bulk defect model (monovalent, multivalent, frozen metastable).""" + + node_count: int + identity_sha256: str + monovalent_regions: tuple[MonovalentDefectRegion, ...] = () + multivalent_regions: tuple[MultivalentDefectRegion, ...] = () + metastable_regions: tuple[FrozenMetastableRegion, ...] = () + + def __post_init__(self) -> None: + if self.node_count < 2: + raise ValueError("StationaryDefectModel1D requires node_count >= 2") + if not self.identity_sha256: + raise ValueError("StationaryDefectModel1D requires identity_sha256") + if not ( + self.monovalent_regions + or self.multivalent_regions + or self.metastable_regions + ): + raise ValueError("StationaryDefectModel1D requires at least one region") + + def evaluate( + self, + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + ) -> StationaryDefectEvaluation1D: + """Evaluate net stationary defect space charge and recombination on all nodes.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + if n.shape != (self.node_count,) or p.shape != (self.node_count,): + raise ValueError("carrier vectors must match StationaryDefectModel1D.node_count") + + rho: Vector = np.zeros(self.node_count, dtype=np.float64) + drho_dn: Vector = np.zeros(self.node_count, dtype=np.float64) + drho_dp: Vector = np.zeros(self.node_count, dtype=np.float64) + drho_dphi: Vector = np.zeros(self.node_count, dtype=np.float64) + rec: Vector = np.zeros(self.node_count, dtype=np.float64) + drec_dn: Vector = np.zeros(self.node_count, dtype=np.float64) + drec_dp: Vector = np.zeros(self.node_count, dtype=np.float64) + + for mono in self.monovalent_regions: + ev_m = evaluate_monovalent_region_closure(mono, n, p) + mask = mono.active_nodes + rho[mask] += ev_m.total_charge_density_C_m3 + drho_dn[mask] += ev_m.total_charge_derivative_n_C + drho_dp[mask] += ev_m.total_charge_derivative_p_C + drho_dphi[mask] += ev_m.total_charge_derivative_fixed_qf_C_m3_V + rec[mask] += ev_m.total_recombination_rate_m3_s + drec_dn[mask] += ev_m.total_recombination_derivative_n_s1 + drec_dp[mask] += ev_m.total_recombination_derivative_p_s1 + + for mv in self.multivalent_regions: + mask = mv.active_nodes + for ev_v in evaluate_multivalent_region_closure(mv, n, p): + rho[mask] += ev_v.charge_density_C_m3 + drho_dn[mask] += ev_v.charge_derivative_n_C + drho_dp[mask] += ev_v.charge_derivative_p_C + drho_dphi[mask] += ev_v.charge_derivative_fixed_qf_C_m3_V + rec[mask] += ev_v.total_recombination_rate_m3_s + drec_dn[mask] += ev_v.total_recombination_derivative_n_s1 + drec_dp[mask] += ev_v.total_recombination_derivative_p_s1 + + for meta in self.metastable_regions: + ev_f = evaluate_frozen_metastable_region(meta, n, p) + rho += ev_f.total_charge_density_C_m3 + drho_dn += ev_f.total_charge_derivative_n_C + drho_dp += ev_f.total_charge_derivative_p_C + drho_dphi += ev_f.total_charge_derivative_fixed_qf_C_m3_V + rec += ev_f.total_recombination_rate_m3_s + drec_dn += ev_f.total_recombination_derivative_n_s1 + drec_dp += ev_f.total_recombination_derivative_p_s1 + + for arr in (rho, drho_dn, drho_dp, drho_dphi, rec, drec_dn, drec_dp): + arr.setflags(write=False) + + return StationaryDefectEvaluation1D( + charge_density_C_m3=rho, + d_charge_dn_C=drho_dn, + d_charge_dp_C=drho_dp, + d_charge_dphi_fixed_qf_C_m3_V=drho_dphi, + recombination_rate_m3_s=rec, + d_recombination_dn_s1=drec_dn, + d_recombination_dp_s1=drec_dp, + ) + + +@dataclass(frozen=True, slots=True) +class DynamicInterfaceTrapBinding1D: + """Two-sided heterointerface with an explicit dynamic trap occupancy DOF.""" + + interface_index: int + interface_id: str + face: int + left_node: int + right_node: int + trace_electrostatics: TraceElectrostatics + physics: TwoSidedInterfacePhysics + trap_spec: DynamicInterfaceTrapSpec + reference_logit: float + weight_left: float = 0.0 + weight_right: float = 0.0 + + def __post_init__(self) -> None: + if self.right_node != self.left_node + 1 or self.face != self.left_node: + raise ValueError("dynamic two-sided interface requires adjacent left/right nodes") + if not math.isfinite(self.reference_logit): + raise ValueError("reference_logit must be finite") + if self.trap_spec.sheet_density_m2 <= 0.0 or ( + self.physics.surface_recombination_velocity_n_m_s <= 0.0 + and self.physics.surface_recombination_velocity_p_m_s <= 0.0 + ): + raise ValueError("dynamic interface trap requires positive sheet density and capture") + + @property + def has_sheet_charge(self) -> bool: + return bool(self.trap_spec.equilibrium_referenced_charge) + + @property + def trap_density_m2(self) -> float: + return float(self.trap_spec.sheet_density_m2) + + @property + def node_set(self) -> str: + return f"iface_trap:{self.interface_index}" + + @property + def block(self) -> str: + return f"iface_trap:{self.interface_index}" + + @property + def left_port(self) -> str: + return f"iface_left:{self.interface_index}" + + def occupancy_from_increment(self, increment: float) -> float: + inc = float(increment) + if not math.isfinite(inc): + raise ValueError("interface trap logit increment must be finite") + return float(stable_expit(self.reference_logit + inc)) + + def one_minus_occupancy_from_increment(self, increment: float) -> float: + inc = float(increment) + if not math.isfinite(inc): + raise ValueError("interface trap logit increment must be finite") + return float(stable_expit(-(self.reference_logit + inc))) + + def occupancy_minus_equilibrium_from_increment(self, increment: float) -> float: + inc = float(increment) + if not math.isfinite(inc): + raise ValueError("interface trap logit increment must be finite") + return float( + logit_occupancy_secant( + np.array([self.reference_logit + inc]), + np.array([self.reference_logit]), + )[0] + ) + + def sheet_charge_C_m2(self, occupancy: float) -> float: + if not self.has_sheet_charge: + return 0.0 + return -Q * self.trap_density_m2 * ( + float(occupancy) - self.trap_spec.equilibrium_occupancy + ) + + def sheet_charge_from_increment_C_m2(self, increment: float) -> float: + if not self.has_sheet_charge: + return 0.0 + return -Q * self.trap_density_m2 * self.occupancy_minus_equilibrium_from_increment( + increment + ) + + +@dataclass(frozen=True) +class DynamicDefectState1D: + """Physical trial/accepted state bound to CompiledDynamicDefectDevice1D.""" + + u: Vector + electronic_state: State1D + device_sha256: str + voltage_V: float + ionic_state: IonicState1D | None = None + bulk_trap_occupancy: Vector = field(default_factory=lambda: np.empty(0)) + interface_trap_occupancy: Vector = field(default_factory=lambda: np.empty(0)) + interface_sheet_charges_C_m2: Vector = field(default_factory=lambda: np.empty(0)) + + def __post_init__(self) -> None: + object.__setattr__(self, "u", frozen_array(self.u)) + object.__setattr__(self, "bulk_trap_occupancy", frozen_array(self.bulk_trap_occupancy)) + object.__setattr__( + self, "interface_trap_occupancy", frozen_array(self.interface_trap_occupancy) + ) + object.__setattr__( + self, + "interface_sheet_charges_C_m2", + frozen_array(self.interface_sheet_charges_C_m2), + ) + if not self.device_sha256 or not math.isfinite(self.voltage_V): + raise ValueError("DynamicDefectState1D requires device_sha256 and finite voltage_V") + + +@dataclass(frozen=True) +class TwoSidedIonicComponent1D: + """Blocking single-layer finite-site ion domain on a TWO_SIDED_TRACE_V1 grid.""" + + device_id: str + sha256: str + original_prepared_sha256: str + electronic_component: CompiledDevice1D + ion_geometry: ControlVolumeGeometry1D + domain_layer_id: str + positive_ion_reference_m3: Vector + positive_ion_site_limit_m3: Vector + positive_ion_logit_reference: Vector + positive_ion_diffusivity_faces_m2_s: Vector + steric_model: str + binding_manifest_json: str + capabilities: tuple[str, ...] = ( + "two_sided_trace_electronic_component", + "two_sided_ionic_1d_residual", + "finite_sites", + "blocking_ion_contacts", + "physical_ion_storage", + ) + ion_node_indices: NDArray[np.intp] = field(default_factory=lambda: np.empty(0, dtype=np.intp)) + negative_ion_reference_m3: Vector = field(default_factory=lambda: np.empty(0)) + negative_ion_site_limit_m3: Vector = field(default_factory=lambda: np.empty(0)) + negative_ion_logit_reference: Vector = field(default_factory=lambda: np.empty(0)) + negative_ion_diffusivity_faces_m2_s: Vector = field(default_factory=lambda: np.empty(0)) + ion_site_contract: str = "independent_finite_sites" + + def __post_init__(self) -> None: + count = self.ion_node_count + if self.ion_site_contract not in {"independent_finite_sites", "shared_finite_sites"}: + raise ValueError("unsupported ionic site contract") + indices = integer_indices(self.ion_node_indices) + if ( + indices.shape != (count,) + or count < 3 + or np.any(np.diff(indices) != 1) + or indices[0] < 0 + or indices[-1] >= self.node_count + ): + raise ValueError("two-sided ion-node map must be ordered, contiguous, >=3 nodes, inside grid") + object.__setattr__(self, "ion_node_indices", np.frombuffer(indices.tobytes(), dtype=np.intp)) + layer_ids = [layer.name for layer in self.electronic_component.parameters.layers] + if layer_ids.count(self.domain_layer_id) != 1: + raise ValueError("two-sided ionic binding: domain layer is absent from electronic component") + layer_index = layer_ids.index(self.domain_layer_id) + planes = self.electronic_component.geometry.interfaces + left = 0 if layer_index == 0 else planes[layer_index - 1].right_node + right = self.node_count - 1 if layer_index == len(layer_ids) - 1 else planes[layer_index].left_node + if not np.array_equal(indices, np.arange(left, right + 1)): + raise ValueError("two-sided ionic binding: node map must cover the layer's two-sided trace nodes") + if self.electronic_component.geometry.name != TWO_SIDED_TRACE_V1 or self.ion_geometry.name != TWO_SIDED_TRACE_V1: + raise ValueError("TwoSidedIonicComponent1D requires TWO_SIDED_TRACE_V1 electronic and ion geometry") + if not np.array_equal(self.ion_geometry.nodes_m, self.nodes_m[indices]): + raise ValueError("ion and electronic nodes must coincide") + if not np.array_equal( + self.ion_geometry.cell_measures_m, + self.electronic_component.geometry.cell_measures_m[indices], + ): + raise ValueError("two-sided ion cell measures must match electronic cell measures") + for name in ("positive_ion_reference_m3", "positive_ion_site_limit_m3", "positive_ion_logit_reference"): + object.__setattr__(self, name, frozen_array(getattr(self, name))) + if getattr(self, name).shape != (count,): + raise ValueError(f"{name} must match the declared ion nodes") + object.__setattr__( + self, "positive_ion_diffusivity_faces_m2_s", frozen_array(self.positive_ion_diffusivity_faces_m2_s) + ) + if self.positive_ion_diffusivity_faces_m2_s.shape != (count - 1,) or np.any( + self.positive_ion_diffusivity_faces_m2_s < 0.0 + ): + raise ValueError("ionic diffusivity must be non-negative on every domain face") + for name in ( + "negative_ion_reference_m3", + "negative_ion_site_limit_m3", + "negative_ion_logit_reference", + "negative_ion_diffusivity_faces_m2_s", + ): + object.__setattr__(self, name, frozen_array(getattr(self, name))) + neg_count = count if self.negative_ion_reference_m3.size else 0 + if ( + any( + getattr(self, name).shape != (neg_count,) + for name in ( + "negative_ion_reference_m3", + "negative_ion_site_limit_m3", + "negative_ion_logit_reference", + ) + ) + or self.negative_ion_diffusivity_faces_m2_s.shape != (count - 1 if neg_count else 0,) + ): + raise ValueError("negative-ion arrays must all match the complete domain or all be absent") + if np.any(self.negative_ion_diffusivity_faces_m2_s < 0.0): + raise ValueError("negative-ion diffusivity must be non-negative on every domain face") + if self.ion_site_contract == "shared_finite_sites" and not neg_count: + raise ValueError("shared sites require both complete populations") + if np.any(self.positive_ion_reference_m3 <= 0.0) or np.any( + self.positive_ion_reference_m3 >= self.positive_ion_site_limit_m3 + ): + raise ValueError("finite-site reference must lie strictly between zero and capacity") + if self.steric_model not in {WHOLE_FLUX_STERIC_V1, DIFFUSION_ONLY_STERIC_V1}: + raise ValueError("unsupported ionic constitutive law") + if not self.sha256 or not self.original_prepared_sha256 or not self.domain_layer_id: + raise ValueError("two-sided ionic component needs complete identities") + + @property + def identity(self) -> str: + return self.sha256 + + @property + def node_count(self) -> int: + return self.electronic_component.node_count + + @property + def ion_node_count(self) -> int: + return self.ion_geometry.node_count + + @property + def state_size(self) -> int: + return 3 * self.node_count + self.ion_species_count * self.ion_node_count + + @property + def ion_species_names(self) -> tuple[str, ...]: + return ("positive", "negative") if self.negative_ion_reference_m3.size else ("positive",) + + @property + def ion_species_count(self) -> int: + return len(self.ion_species_names) + + @property + def ion_species_slices(self) -> tuple[slice, ...]: + start, m_nodes = 3 * self.node_count, self.ion_node_count + return tuple( + slice(start + index * m_nodes, start + (index + 1) * m_nodes) + for index in range(self.ion_species_count) + ) + + @property + def nodes_m(self) -> Vector: + return self.electronic_component.nodes_m + + @property + def domain_bounds_m(self) -> tuple[float, float]: + return float(self.ion_geometry.nodes_m[0]), float(self.ion_geometry.nodes_m[-1]) + + @property + def reference_inventory_m2(self) -> float: + return math.fsum((self.ion_geometry.cell_measures_m * self.positive_ion_reference_m3).tolist()) + + @property + def negative_reference_inventory_m2(self) -> float: + if self.ion_species_count == 1: + return 0.0 + return math.fsum((self.ion_geometry.cell_measures_m * self.negative_ion_reference_m3).tolist()) + + @property + def ion_charge_weight_ratio(self) -> Vector: + return frozen_array( + self.ion_geometry.cell_measures_m + / self.electronic_component.geometry.cell_measures_m[self.ion_node_indices] + ) + + def project_ion_density(self, density: ArrayLike) -> Vector: + values = np.asarray(density, dtype=float) + if values.shape != (self.ion_node_count,) or not np.all(np.isfinite(values)): + raise ValueError("ion density projection requires finite domain-local values") + result = np.zeros(self.node_count) + result[self.ion_node_indices] = self.ion_charge_weight_ratio * values + return result + + @property + def binding_manifest(self) -> dict[str, object]: + loaded = json.loads(self.binding_manifest_json) + assert isinstance(loaded, dict) + return loaded + + def fields(self, y: ArrayLike, *, voltage_V: float = 0.0) -> tuple[Vector, Vector, Vector, Vector]: + if self.ion_species_count != 1: + raise ValueError("dual-ion fields require fields_by_species") + phi, n, p, populations = self.fields_by_species(y, voltage_V=voltage_V) + return phi, n, p, populations[0] + + def fields_by_species( + self, y: ArrayLike, *, voltage_V: float = 0.0 + ) -> tuple[Vector, Vector, Vector, tuple[Vector, ...]]: + values = np.asarray(y, dtype=float) + count = self.node_count + if values.shape != (self.state_size,) or not np.all(np.isfinite(values)): + raise ValueError("ionic coordinates must be finite with shape (3*N + species_count*M,)") + phi, n, p = self.electronic_component.fields(values[: 3 * count], voltage_V=voltage_V) + populations: list[Vector] = [] + if self.ion_site_contract == "shared_finite_sites": + positive, negative = self.ion_species_slices + populations.extend( + shared_site_densities( + self.positive_ion_site_limit_m3, + self.positive_ion_logit_reference, + self.negative_ion_logit_reference, + values[positive], + values[negative], + ) + ) + if np.any(populations[0] + populations[1] >= self.positive_ion_site_limit_m3): + raise ValueError("shared-site trial summed occupancy exceeded site capacity") + for species, block in zip(self.ion_species_names, self.ion_species_slices): + if self.ion_site_contract == "shared_finite_sites": + break + reference = getattr(self, species + "_ion_reference_m3") + capacity = getattr(self, species + "_ion_site_limit_m3") + logit = getattr(self, species + "_ion_logit_reference") + if self.ion_species_count == 1: + density = single_site_density(reference, capacity, logit, values[block]) + else: + density = shifted_logistic_density(reference, capacity, logit, values[block], label=species) + if np.any(density >= capacity): + raise ValueError(f"{species}-ion finite-site density saturated") + populations.append(density) + if any(not np.all(np.isfinite(value)) or np.any(value <= 0.0) for value in (n, p, *populations)): + raise ValueError("ionic/electronic trial density is outside the finite positive domain") + return phi, n, p, tuple(populations) + + def ion_coordinate_jacobian_m3(self, y: ArrayLike, *, voltage_V: float = 0.0) -> Vector: + populations = self.fields_by_species(y, voltage_V=voltage_V)[3] + if self.ion_site_contract == "shared_finite_sites": + return shared_site_coordinate_jacobian_m3( + populations[0], populations[1], self.positive_ion_site_limit_m3 + ) + result = np.zeros((self.ion_node_count, self.ion_species_count, self.ion_species_count)) + for index, (species, density) in enumerate(zip(self.ion_species_names, populations)): + result[:, index, index] = density * ( + 1.0 - density / getattr(self, species + "_ion_site_limit_m3") + ) + return result + + def ion_coordinate_hessian_m3(self, y: ArrayLike, *, voltage_V: float = 0.0) -> Vector: + populations = self.fields_by_species(y, voltage_V=voltage_V)[3] + if self.ion_site_contract == "shared_finite_sites": + return shared_site_coordinate_hessian_m3( + populations[0], populations[1], self.positive_ion_site_limit_m3 + ) + result = np.zeros( + (self.ion_node_count, self.ion_species_count, self.ion_species_count, self.ion_species_count) + ) + for index, (species, density) in enumerate(zip(self.ion_species_names, populations)): + capacity = getattr(self, species + "_ion_site_limit_m3") + result[:, index, index, index] = ( + density * (1.0 - density / capacity) * (1.0 - 2.0 * density / capacity) + ) + return result + + def state(self, y: ArrayLike, *, voltage_V: float = 0.0) -> IonicState1D: + values = np.asarray(y, dtype=float) + _, _, _, populations = self.fields_by_species(values, voltage_V=voltage_V) + component = self.electronic_component.state(values[: 3 * self.node_count], voltage_V=voltage_V) + inventory = math.fsum((self.ion_geometry.cell_measures_m * populations[0]).tolist()) + negative = populations[1] if self.ion_species_count == 2 else np.empty(0) + neg_inv = ( + math.fsum((self.ion_geometry.cell_measures_m * negative).tolist()) + if negative.size + else 0.0 + ) + return IonicState1D(values, component, populations[0], self.identity, inventory, negative, neg_inv) + + def initial_state(self, *, voltage_V: float = 0.0) -> IonicState1D: + left, right = self.electronic_component.contact_potentials(voltage_V) + position = (self.nodes_m - self.nodes_m[0]) / self.electronic_component.geometry.extent_m + phi = left + (right - left) * position + return self.state( + np.r_[phi, np.zeros(2 * self.node_count + self.ion_species_count * self.ion_node_count)], + voltage_V=voltage_V, + ) + + def charge_ledger( + self, n: Vector, p: Vector, density: Vector, negative_density: Vector | None = None + ) -> ChargeLedger: + component = self.electronic_component.charge_ledger(n, p) + ion = ChargeEntry( + "positive_ion", + "ion_charge_projection", + 1, + self.project_ion_density(density), + self.project_ion_density(self.positive_ion_reference_m3), + ) + ledger = ChargeLedger( + self.node_count, + component.interface_count, + component.entries[:2] + (ion,) + component.entries[2:], + ) + if self.ion_species_count == 2: + if negative_density is None: + raise ValueError("dual-ion charge requires the declared negative population") + negative = ChargeEntry( + "negative_ion", + "ion_charge_projection", + -1, + self.project_ion_density(negative_density), + self.project_ion_density(self.negative_ion_reference_m3), + group="negative_ion_space_charge", + ) + return ledger.with_entry(negative) + if negative_density is not None: + raise ValueError("negative charge is not assembled for this positive-only device") + return ledger + + +@dataclass(frozen=True) +class CompiledDynamicDefectDevice1D: + """Unified compiled 1D device supporting stationary, dynamic, and ionic-defect models.""" + + device_id: str + sha256: str + original_prepared_sha256: str + electronic_component: CompiledDevice1D + ionic_component: CompiledIonicDevice1D | TwoSidedIonicComponent1D | None = None + stationary_defects: StationaryDefectModel1D | None = None + dynamic_bulk_traps: DynamicBulkTrapLayout | None = None + bulk_trap_reference_logit: Vector = field(default_factory=lambda: np.empty(0)) + dynamic_interface_traps: tuple[DynamicInterfaceTrapBinding1D, ...] = () + binding_manifest_json: str = "{}" + capabilities: tuple[str, ...] = () + dark_equilibrium_seed: Vector = field(default_factory=lambda: np.empty(0), repr=False, compare=False) + + def __post_init__(self) -> None: + object.__setattr__( + self, "bulk_trap_reference_logit", frozen_array(self.bulk_trap_reference_logit) + ) + object.__setattr__( + self, "dark_equilibrium_seed", frozen_array(self.dark_equilibrium_seed) + ) + if self.dark_equilibrium_seed.size not in {0, self.state_size}: + raise ValueError("dark_equilibrium_seed must be empty or match state_size") + if self.ionic_component is not None: + if ( + self.ionic_component.electronic_component.identity + != self.electronic_component.identity + ): + raise ValueError( + "ionic_component must share the exact electronic_component" + ) + if self.dynamic_bulk_traps is not None: + if self.dynamic_bulk_traps.node_count != self.electronic_component.node_count: + raise ValueError("dynamic_bulk_traps.node_count must match electronic_component") + if self.bulk_trap_reference_logit.shape != (self.dynamic_bulk_traps.size,): + raise ValueError("bulk_trap_reference_logit must match dynamic_bulk_traps.size") + elif self.bulk_trap_reference_logit.size != 0: + raise ValueError("absent dynamic_bulk_traps requires empty bulk_trap_reference_logit") + if self.stationary_defects is not None: + if self.stationary_defects.node_count != self.electronic_component.node_count: + raise ValueError("stationary_defects.node_count must match electronic_component") + seen_ifaces = set() + for itrap in self.dynamic_interface_traps: + if itrap.interface_index in seen_ifaces: + raise ValueError("duplicate dynamic interface trap binding") + seen_ifaces.add(itrap.interface_index) + if not 0 < itrap.left_node < itrap.right_node < self.node_count - 1: + raise ValueError("dynamic interface trap nodes must be interior") + + @property + def identity(self) -> str: + return self.sha256 + + @property + def node_count(self) -> int: + return self.electronic_component.node_count + + @property + def nodes_m(self) -> Vector: + return self.electronic_component.nodes_m + + @property + def thermal_voltage_V(self) -> float: + return self.electronic_component.thermal_voltage_V + + @property + def voltage_polarity(self) -> float: + return self.electronic_component.voltage_polarity + + @property + def has_ions(self) -> bool: + return self.ionic_component is not None + + @property + def has_dynamic_bulk_traps(self) -> bool: + return self.dynamic_bulk_traps is not None + + @property + def has_dynamic_interface_traps(self) -> bool: + return len(self.dynamic_interface_traps) > 0 + + @property + def has_stationary_defects(self) -> bool: + return self.stationary_defects is not None + + @property + def electronic_slice(self) -> slice: + return slice(0, 3 * self.node_count) + + @property + def ion_dof_count(self) -> int: + if self.ionic_component is None: + return 0 + return self.ionic_component.state_size - 3 * self.node_count + + @property + def ion_slice(self) -> slice: + start = 3 * self.node_count + return slice(start, start + self.ion_dof_count) + + @property + def bulk_trap_dof_count(self) -> int: + if self.dynamic_bulk_traps is None: + return 0 + return self.dynamic_bulk_traps.size + + @property + def bulk_trap_slice(self) -> slice: + start = 3 * self.node_count + self.ion_dof_count + return slice(start, start + self.bulk_trap_dof_count) + + @property + def bulk_trap_mode_slices(self) -> tuple[slice, ...]: + if self.dynamic_bulk_traps is None: + return () + base = 3 * self.node_count + self.ion_dof_count + return tuple( + slice(base + m.flat_slice.start, base + m.flat_slice.stop) + for m in self.dynamic_bulk_traps.modes + ) + + @property + def interface_trap_dof_count(self) -> int: + return 2 * len(self.dynamic_interface_traps) + + @property + def interface_trap_slice(self) -> slice: + start = 3 * self.node_count + self.ion_dof_count + self.bulk_trap_dof_count + return slice(start, start + self.interface_trap_dof_count) + + @property + def interface_trap_slices(self) -> tuple[slice, ...]: + base = 3 * self.node_count + self.ion_dof_count + self.bulk_trap_dof_count + return tuple( + slice(base + 2 * i, base + 2 * (i + 1)) + for i in range(len(self.dynamic_interface_traps)) + ) + + @property + def state_size(self) -> int: + return ( + 3 * self.node_count + + self.ion_dof_count + + self.bulk_trap_dof_count + + self.interface_trap_dof_count + ) + + @property + def binding_manifest(self) -> dict[str, Any]: + loaded = json.loads(self.binding_manifest_json) + assert isinstance(loaded, dict) + return loaded + + def rebase_coordinates( + self, u: ArrayLike, old_voltage_V: float, new_voltage_V: float + ) -> Vector: + values = np.array(u, dtype=np.float64, copy=True) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + values[self.electronic_slice] = self.electronic_component.rebase_coordinates( + values[self.electronic_slice], old_voltage_V, new_voltage_V + ) + return values + + def bulk_trap_occupancies(self, u: ArrayLike) -> Vector: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + if self.dynamic_bulk_traps is None: + return np.empty(0, dtype=np.float64) + return occupancy_from_logit_increment( + self.bulk_trap_reference_logit, + values[self.bulk_trap_slice], + self.dynamic_bulk_traps, + ) + + def bulk_trap_one_minus_occupancies(self, u: ArrayLike) -> Vector: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + if self.dynamic_bulk_traps is None: + return np.empty(0, dtype=np.float64) + return one_minus_occupancy_from_logit_increment( + self.bulk_trap_reference_logit, + values[self.bulk_trap_slice], + self.dynamic_bulk_traps, + ) + + def interface_trap_occupancies(self, u: ArrayLike) -> Vector: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + if not self.dynamic_interface_traps: + return np.empty(0, dtype=np.float64) + occ = np.array( + [ + itrap.occupancy_from_increment(float(values[sl.start])) + for itrap, sl in zip(self.dynamic_interface_traps, self.interface_trap_slices) + ], + dtype=np.float64, + ) + occ.setflags(write=False) + return occ + + def interface_trap_one_minus_occupancies(self, u: ArrayLike) -> Vector: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + if not self.dynamic_interface_traps: + return np.empty(0, dtype=np.float64) + omf = np.array( + [ + itrap.one_minus_occupancy_from_increment(float(values[sl.start])) + for itrap, sl in zip(self.dynamic_interface_traps, self.interface_trap_slices) + ], + dtype=np.float64, + ) + omf.setflags(write=False) + return omf + + def interface_sheet_charges_C_m2(self, u: ArrayLike, *, voltage_V: float = 0.0) -> Vector: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,): + raise ValueError("coordinate vector shape does not match state_size") + sheets = np.array( + self.electronic_component.interface_sheet_charges_C_m2( + values[self.electronic_slice], voltage_V=voltage_V + ), + dtype=np.float64, + copy=True, + ) + if self.dynamic_interface_traps: + for itrap, sl in zip(self.dynamic_interface_traps, self.interface_trap_slices): + sheets[itrap.interface_index] = itrap.sheet_charge_from_increment_C_m2( + float(values[sl.start]) + ) + sheets.setflags(write=False) + return sheets + + def space_charge_density_C_m3( + self, n: Vector, p: Vector, u: ArrayLike + ) -> Vector: + """Total volumetric space charge density [C m^-3] on all device nodes.""" + values = np.asarray(u, dtype=np.float64) + if self.ionic_component is not None: + ion_u = values[: self.ionic_component.state_size] + _, _, _, pops = self.ionic_component.fields_by_species(ion_u, voltage_V=0.0) + base_ledger: ChargeLedger = self.ionic_component.charge_ledger( + n, p, pops[0], pops[1] if len(pops) == 2 else None + ) + rho = np.array(base_ledger.space_charge_C_m3(), dtype=np.float64, copy=True) + else: + rho = np.array( + self.electronic_component.charge_ledger(n, p).space_charge_C_m3(), + dtype=np.float64, + copy=True, + ) + if self.stationary_defects is not None: + rho += self.stationary_defects.evaluate(n, p).charge_density_C_m3 + if self.dynamic_bulk_traps is not None: + occ = self.bulk_trap_occupancies(values) + omf = self.bulk_trap_one_minus_occupancies(values) + rho += bulk_trap_charge_density( + occ, self.dynamic_bulk_traps, one_minus_occupancy=omf + ) + rho.setflags(write=False) + return rho + + def state(self, u: ArrayLike, *, voltage_V: float = 0.0) -> DynamicDefectState1D: + values = np.asarray(u, dtype=np.float64) + if values.shape != (self.state_size,) or not np.all(np.isfinite(values)): + raise ValueError("state coordinates must be finite and match state_size") + elec_state = self.electronic_component.state( + values[self.electronic_slice], voltage_V=voltage_V + ) + ion_state: IonicState1D | None = None + if self.ionic_component is not None: + ion_state = self.ionic_component.state( + values[: self.ionic_component.state_size], voltage_V=voltage_V + ) + bulk_occ = self.bulk_trap_occupancies(values) + iface_occ = self.interface_trap_occupancies(values) + sheets = self.interface_sheet_charges_C_m2(values, voltage_V=voltage_V) + return DynamicDefectState1D( + u=values, + electronic_state=elec_state, + device_sha256=self.sha256, + voltage_V=float(voltage_V), + ionic_state=ion_state, + bulk_trap_occupancy=bulk_occ, + interface_trap_occupancy=iface_occ, + interface_sheet_charges_C_m2=sheets, + ) + + def initial_equilibrium_seed(self, *, voltage_V: float = 0.0) -> Vector: + """Construct zero-excess dark/reference coordinate seed at ``voltage_V``.""" + N = self.node_count + if self.dark_equilibrium_seed.size == self.state_size: + seed = np.array(self.dark_equilibrium_seed, dtype=np.float64, copy=True) + if voltage_V != 0.0: + seed = self.rebase_coordinates(seed, 0.0, voltage_V) + phi_l, phi_r = self.electronic_component.contact_potentials(voltage_V) + dv = (phi_r - phi_l) - (seed[N - 1] - seed[0]) + nodes = self.nodes_m + seed[:N] += dv * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + return seed + seed = np.zeros(self.state_size, dtype=np.float64) + phi_l, phi_r = self.electronic_component.contact_potentials(voltage_V) + nodes = self.nodes_m + seed[:N] = phi_l + (phi_r - phi_l) * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + if voltage_V != 0.0: + seed = self.rebase_coordinates(seed, 0.0, voltage_V) + seed[:N] = phi_l + (phi_r - phi_l) * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + return seed + + +@dataclass(frozen=True) +class CompiledMetastableDevice1D: + """Compiled metastable bulk-defect model supporting preparation, frozen J-V, and transients.""" + + device_id: str + sha256: str + prepared: PreparedDevice + metastable_layer_id: str + metastable_layer_index: int + metastable_specs: tuple[MetastableDefectSpec, ...] + preparation: MetastablePreparationInput | None + intervals_per_layer: int | tuple[int, ...] + base_electronic_device: CompiledDevice1D + active_nodes: NDArray[np.bool_] + band_gap_eV: Vector + conduction_dos_m3: Vector + valence_dos_m3: Vector + temperature_K: float + freeze_builder: Callable[ + [Mapping[str, ArrayLike] | Sequence[ArrayLike], float | None], + CompiledDynamicDefectDevice1D, + ] = field(repr=False, compare=False) + + @property + def identity(self) -> str: + return self.sha256 + + @property + def active_node_count(self) -> int: + return int(np.count_nonzero(self.active_nodes)) + + @property + def node_count(self) -> int: + return self.base_electronic_device.node_count + + def compile_frozen_device( + self, + donor_fractions: Mapping[str, ArrayLike] | Sequence[ArrayLike], + *, + temperature_K: float | None = None, + ) -> CompiledDynamicDefectDevice1D: + """Compile a stationary frozen-configuration device at ``donor_fractions``.""" + return self.freeze_builder(donor_fractions, temperature_K) diff --git a/src/solarlab/experiments/capacitance_frequency.py b/src/solarlab/experiments/capacitance_frequency.py new file mode 100644 index 00000000..f4a7162d --- /dev/null +++ b/src/solarlab/experiments/capacitance_frequency.py @@ -0,0 +1,379 @@ +"""Defect- and ion-aware capacitance-frequency (C-f) spectroscopy. + +Extracts parallel/series capacitance, conductance, loss tangent, scaled +conductance ``G_p / omega``, and the Walter trap-DOS derivative +``-omega * dC_p / domega`` from unified ``DynamicDefectSmallSignal1D`` sweeps or +admittance arrays while preserving sign-faithful susceptance masking and dark +equilibrium passivity checks. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import frozen_array +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + DynamicDefectACSweepResult, + DynamicDefectSmallSignal1D, + DynamicDefectSteadyOptions, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dynamic_defect_1d import CompiledDynamicDefectDevice1D +from solarlab.physics.defects import DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER +from solarlab.solvers.linear.frequency_domain import FrequencyOptions + +Vector: TypeAlias = NDArray[np.float64] +ComplexVector: TypeAlias = NDArray[np.complex128] +BoolVector: TypeAlias = NDArray[np.bool_] + +__all__ = [ + "DefectCFError", + "DefectCFOptions", + "DefectCFResult", + "capacitance_frequency_from_admittance", + "capacitance_frequency_from_sweep", + "run_defect_capacitance_frequency", +] + + +class DefectCFError(RuntimeError): + """Raised when strict capacitance-frequency extraction or passivity fails.""" + + +@dataclass(frozen=True, slots=True) +class DefectCFOptions: + """Extraction, masking, and passivity controls for C-f spectroscopy.""" + + strict_capacitive: bool = False + minimum_phase_angle_rad: float = 0.0 + passivity_tolerance_S_m2: float = 1.0e-12 + require_dark_passivity: bool = True + voltage_phasor_V: complex = 1.0 + steady_options: DynamicDefectSteadyOptions | None = None + linear_options: FrequencyOptions | None = None + + def __post_init__(self) -> None: + if not math.isfinite(self.minimum_phase_angle_rad) or not ( + 0.0 <= self.minimum_phase_angle_rad < 0.5 * math.pi + ): + raise ValueError("minimum_phase_angle_rad must lie in [0, pi/2)") + if not math.isfinite(self.passivity_tolerance_S_m2) or self.passivity_tolerance_S_m2 < 0.0: + raise ValueError("passivity_tolerance_S_m2 must be finite and non-negative") + if not np.isfinite(self.voltage_phasor_V) or self.voltage_phasor_V == 0.0: + raise ValueError("voltage_phasor_V must be finite and nonzero") + + +@dataclass(frozen=True) +class DefectCFResult: + """Capacitance-frequency observables, Walter derivative, and masking ledger.""" + + frequencies_Hz: Vector + angular_frequencies_rad_s: Vector + admittance_density_S_m2: ComplexVector + impedance_area_ohm_m2: ComplexVector + parallel_capacitance_F_m2: Vector + parallel_conductance_S_m2: Vector + series_capacitance_F_m2: Vector + loss_tangent: Vector + scaled_conductance_F_m2: Vector + walter_derivative_F_m2: Vector + phase_angle_rad: Vector + capacitance_accepted: BoolVector + mask_reasons: tuple[str | None, ...] + operating_voltage_V: float + generation_scale: float + active_species: tuple[str, ...] + frozen_species: tuple[str, ...] + working_state_digest: str + dark_equilibrium_passive: bool | None + peak_walter_frequency_Hz: float | None + peak_walter_value_F_m2: float | None + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + for attr in ("frequencies_Hz", "angular_frequencies_rad_s"): + object.__setattr__(self, attr, frozen_array(getattr(self, attr))) + for attr in ("admittance_density_S_m2", "impedance_area_ohm_m2"): + c_arr = np.asarray(getattr(self, attr), dtype=np.complex128) + object.__setattr__( + self, + attr, + np.frombuffer(c_arr.tobytes(), dtype=np.complex128).reshape(c_arr.shape), + ) + for attr in ( + "parallel_capacitance_F_m2", + "parallel_conductance_S_m2", + "series_capacitance_F_m2", + "loss_tangent", + "scaled_conductance_F_m2", + "walter_derivative_F_m2", + "phase_angle_rad", + ): + f_arr = np.asarray(getattr(self, attr), dtype=np.float64) + object.__setattr__( + self, + attr, + np.frombuffer(f_arr.tobytes(), dtype=np.float64).reshape(f_arr.shape), + ) + acc = np.array(self.capacitance_accepted, dtype=bool, copy=True) + acc.setflags(write=False) + object.__setattr__(self, "capacitance_accepted", acc) + + +def capacitance_frequency_from_admittance( + frequencies_Hz: ArrayLike, + admittance_density_S_m2: ArrayLike, + *, + operating_voltage_V: float = 0.0, + generation_scale: float = 0.0, + active_species: Sequence[str] = (), + frozen_species: Sequence[str] = (), + working_state_digest: str = "", + options: DefectCFOptions | None = None, +) -> DefectCFResult: + """Compute C-f observables and Walter derivative from ``(f, Y(f))`` arrays.""" + controls = DefectCFOptions() if options is None else options + freqs = np.asarray(frequencies_Hz, dtype=np.float64) + y_arr = np.asarray(admittance_density_S_m2, dtype=np.complex128) + if freqs.ndim != 1 or freqs.size == 0 or not np.all(np.isfinite(freqs)) or np.any(freqs < 0.0): + raise ValueError("frequencies_Hz must be a non-empty 1D array of finite non-negative values") + if y_arr.shape != freqs.shape: + raise ValueError("admittance_density_S_m2 must match frequencies_Hz shape") + if not math.isfinite(operating_voltage_V) or not math.isfinite(generation_scale) or generation_scale < 0.0: + raise ValueError("operating_voltage_V must be finite and generation_scale >= 0") + + count = freqs.size + omega = 2.0 * math.pi * freqs + z_arr: ComplexVector = np.full(count, np.nan + 1j * np.nan, dtype=np.complex128) + cp: Vector = np.full(count, np.nan, dtype=np.float64) + gp: Vector = np.full(count, np.nan, dtype=np.float64) + cs: Vector = np.full(count, np.nan, dtype=np.float64) + tan_d: Vector = np.full(count, np.nan, dtype=np.float64) + g_over_w: Vector = np.full(count, np.nan, dtype=np.float64) + phase: Vector = np.full(count, np.nan, dtype=np.float64) + accepted: BoolVector = np.zeros(count, dtype=bool) + reasons: list[str | None] = [None] * count + + for idx in range(count): + f_val = float(freqs[idx]) + w_val = float(omega[idx]) + y_val = complex(y_arr[idx]) + g_val = float(y_val.real) + b_val = float(y_val.imag) + if not (math.isfinite(g_val) and math.isfinite(b_val)): + if controls.strict_capacitive: + raise DefectCFError(f"non-finite admittance at f={f_val:.4g} Hz") + reasons[idx] = "nonfinite_admittance" + continue + + gp[idx] = g_val + phase[idx] = math.atan2(b_val, g_val) + if y_val != 0.0j: + z_arr[idx] = 1.0 / y_val + + if f_val <= 0.0: + if controls.strict_capacitive: + raise DefectCFError("capacitance extraction requires strictly positive frequency (f > 0)") + reasons[idx] = "zero_frequency" + continue + + g_over_w[idx] = g_val / w_val + if b_val < 0.0: + if controls.strict_capacitive: + raise DefectCFError( + f"inductive susceptance Im(Y)={b_val:.3e} S/m^2 at f={f_val:.4g} Hz" + ) + reasons[idx] = "inductive_susceptance" + continue + if b_val == 0.0: + if controls.strict_capacitive: + raise DefectCFError(f"zero susceptance Im(Y)=0 at f={f_val:.4g} Hz") + reasons[idx] = "zero_susceptance" + continue + + if controls.minimum_phase_angle_rad > 0.0 and math.atan2(b_val, abs(g_val)) < controls.minimum_phase_angle_rad: + if controls.strict_capacitive: + raise DefectCFError( + f"unresolved capacitive phase at f={f_val:.4g} Hz" + ) + tan_d[idx] = g_val / b_val + reasons[idx] = "unresolved_phase" + continue + + cp[idx] = b_val / w_val + cs[idx] = (g_val * g_val + b_val * b_val) / (w_val * b_val) + tan_d[idx] = g_val / b_val + accepted[idx] = True + reasons[idx] = None + + walter: Vector = np.full(count, np.nan, dtype=np.float64) + acc_indices = np.flatnonzero(accepted) + peak_f: float | None = None + peak_w: float | None = None + if acc_indices.size >= 2: + w_acc = omega[acc_indices] + c_acc = cp[acc_indices] + if np.all(np.diff(w_acc) > 0.0): + ln_w = np.log(w_acc) + dcp_dlnw = np.gradient(c_acc, ln_w) + w_vals = -dcp_dlnw + walter[acc_indices] = w_vals + best_local = int(np.argmax(w_vals)) + peak_f = float(freqs[acc_indices[best_local]]) + peak_w = float(w_vals[best_local]) + + dark_passive: bool | None = None + if generation_scale == 0.0 and abs(operating_voltage_V) <= 1.0e-12: + finite_g = gp[np.isfinite(gp)] + dark_passive = bool(np.all(finite_g >= -controls.passivity_tolerance_S_m2)) + if controls.require_dark_passivity and not dark_passive: + raise DefectCFError( + f"dark 0 V passivity violated: min Re(Y)={float(np.min(finite_g)):.3e} S/m^2" + ) + + return DefectCFResult( + frequencies_Hz=freqs, + angular_frequencies_rad_s=omega, + admittance_density_S_m2=y_arr, + impedance_area_ohm_m2=z_arr, + parallel_capacitance_F_m2=cp, + parallel_conductance_S_m2=gp, + series_capacitance_F_m2=cs, + loss_tangent=tan_d, + scaled_conductance_F_m2=g_over_w, + walter_derivative_F_m2=walter, + phase_angle_rad=phase, + capacitance_accepted=accepted, + mask_reasons=tuple(reasons), + operating_voltage_V=float(operating_voltage_V), + generation_scale=float(generation_scale), + active_species=tuple(active_species), + frozen_species=tuple(frozen_species), + working_state_digest=str(working_state_digest), + dark_equilibrium_passive=dark_passive, + peak_walter_frequency_Hz=peak_f, + peak_walter_value_F_m2=peak_w, + ) + + +def capacitance_frequency_from_sweep( + sweep: DynamicDefectACSweepResult, + *, + options: DefectCFOptions | None = None, +) -> DefectCFResult: + """Extract C-f observables from an existing ``DynamicDefectACSweepResult``.""" + return capacitance_frequency_from_admittance( + sweep.frequencies_Hz, + sweep.admittance_density_S_m2, + operating_voltage_V=sweep.operating_voltage_V, + generation_scale=sweep.generation_scale, + active_species=sweep.active_species, + frozen_species=sweep.frozen_species, + working_state_digest=sweep.working_state_digest, + options=options, + ) + + +def _layer_param_float(layer: object, key: str) -> float: + params = dict(getattr(layer, "parameters", ())) + val = params.get(key) + return float(val) if isinstance(val, (int, float)) and not isinstance(val, bool) else 0.0 + + +def _infer_active_ion_layer(prepared: PreparedDevice) -> str | None: + elec_layers = [ly for ly in prepared.layers if ly.role != "substrate"] + ion_layers = [ + ly.id + for ly in elec_layers + if ( + _layer_param_float(ly, "D_ion") > 0.0 + and _layer_param_float(ly, "P0") > 0.0 + ) + or ( + _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ) + ] + return ion_layers[0] if len(ion_layers) == 1 else None + + +def run_defect_capacitance_frequency( + device_or_prepared: CompiledDynamicDefectDevice1D | PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + intervals_per_layer: int | Sequence[int] = 24, + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + dynamic_bulk_defects: bool | None = None, + dynamic_interface_defects: bool | None = None, + ion_domain_layer: str | None = None, + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking"), + freeze_ions: bool = False, + freeze_bulk_traps: bool = False, + freeze_interface_traps: bool = False, + options: DefectCFOptions | None = None, +) -> DefectCFResult: + """Solve coupled DC + small-signal AC and extract C-f observables.""" + controls = DefectCFOptions() if options is None else options + if isinstance(device_or_prepared, CompiledDynamicDefectDevice1D): + compiled = device_or_prepared + elif isinstance(device_or_prepared, PreparedDevice): + has_bulk = any( + ly.role != "substrate" + and (bool(ly.defects) or ly.bulk_trap_distribution_json is not None) + and ly.defect_schema_version != "solarlab-explicit-bulk-defects-v4" + for ly in device_or_prepared.layers + ) + has_iface = any( + iface.electrical and iface.to_mapping().get("defect") is not None + for iface in device_or_prepared.interfaces + ) + inferred_ion = ( + ion_domain_layer + if ion_domain_layer is not None + else _infer_active_ion_layer(device_or_prepared) + ) + compiled = compile_dynamic_defect_device_1d( + device_or_prepared, + intervals_per_layer=intervals_per_layer, + energy_quadrature_order=energy_quadrature_order, + dynamic_bulk_defects=has_bulk if dynamic_bulk_defects is None else dynamic_bulk_defects, + dynamic_interface_defects=( + has_iface if dynamic_interface_defects is None else dynamic_interface_defects + ), + ion_domain_layer=inferred_ion, + ion_domain_endpoints=ion_domain_endpoints, + ) + else: + raise TypeError("device_or_prepared must be CompiledDynamicDefectDevice1D or PreparedDevice") + + steady = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=controls.steady_options, + ) + ss = DynamicDefectSmallSignal1D( + compiled, + steady.state, + generation_scale=generation_scale, + ) + sweep = ss.solve_sweep( + frequencies_Hz, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=freeze_ions, + freeze_bulk_traps=freeze_bulk_traps, + freeze_interface_traps=freeze_interface_traps, + ) + return capacitance_frequency_from_sweep(sweep, options=controls) diff --git a/src/solarlab/experiments/defect_ion_impedance.py b/src/solarlab/experiments/defect_ion_impedance.py new file mode 100644 index 00000000..a2643b76 --- /dev/null +++ b/src/solarlab/experiments/defect_ion_impedance.py @@ -0,0 +1,297 @@ +"""Joint dynamic-defect and mobile-ion small-signal impedance. + +Linearizes coupled electronic, mobile-ion, bulk-trap, and two-sided +interface-trap balances around a single certified nonlinear DC working state. +Deliberately evaluates four diagnostic species-freezing modes (``coupled``, +``frozen_ions``, ``frozen_traps``, and ``frozen_ions_and_traps``) from the +exact same ``working_state_digest`` rather than summing independent spectra. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Literal, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import frozen_array +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + DynamicDefectACSweepResult, + DynamicDefectSmallSignal1D, + DynamicDefectSteadyOptions, + DynamicDefectSteadyResult, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dynamic_defect_1d import CompiledDynamicDefectDevice1D +from solarlab.experiments.dynamic_defect_impedance import classify_dynamic_defect_capability +from solarlab.physics.defects import ( + DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + validate_defect_energy_quadrature_order, +) +from solarlab.solvers.linear.frequency_domain import FrequencyOptions + +Vector: TypeAlias = NDArray[np.float64] +ComplexVector: TypeAlias = NDArray[np.complex128] + +DefectIonCapability = Literal[ + "bulk_defect_plus_ions", + "interface_defect_plus_ions", + "bulk_interface_defect_plus_ions", +] + +__all__ = [ + "DefectIonCapability", + "DefectIonImpedanceCapabilityError", + "DefectIonImpedanceError", + "DefectIonImpedanceOptions", + "DefectIonImpedanceResult", + "solve_defect_ion_impedance", +] + + +class DefectIonImpedanceError(RuntimeError): + """Raised when combined defect/ion impedance validation or execution fails.""" + + +class DefectIonImpedanceCapabilityError(DefectIonImpedanceError, CapabilityError): + """Raised when a device stack lacks joint dynamic-defect + mobile-ion support.""" + + +@dataclass(frozen=True, slots=True) +class DefectIonImpedanceOptions: + """Execution controls for coupled dynamic-defect + mobile-ion impedance.""" + + intervals_per_layer: int | tuple[int, ...] = 24 + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER + voltage_phasor_V: complex = 1.0 + ion_domain_layer: str | None = None + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + steady_options: DynamicDefectSteadyOptions | None = None + linear_options: FrequencyOptions | None = None + + def __post_init__(self) -> None: + validate_defect_energy_quadrature_order(self.energy_quadrature_order) + if isinstance(self.intervals_per_layer, int): + if isinstance(self.intervals_per_layer, bool) or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be >= 2") + else: + tup = tuple(int(v) for v in self.intervals_per_layer) + if not tup or any(v < 2 for v in tup): + raise ValueError("intervals_per_layer entries must be >= 2") + object.__setattr__(self, "intervals_per_layer", tup) + if not np.isfinite(self.voltage_phasor_V) or self.voltage_phasor_V == 0.0: + raise ValueError("voltage_phasor_V must be finite and nonzero") + + +@dataclass(frozen=True) +class DefectIonImpedanceResult: + """Coupled and species-frozen small-signal spectra about one DC working state.""" + + capability: DefectIonCapability + device: CompiledDynamicDefectDevice1D + steady: DynamicDefectSteadyResult + working_state_digest: str + frequencies_Hz: Vector + coupled: DynamicDefectACSweepResult + frozen_ions: DynamicDefectACSweepResult + frozen_traps: DynamicDefectACSweepResult + frozen_ions_and_traps: DynamicDefectACSweepResult + qss_zero_hz_admittance_S_m2: complex + low_frequency_qss_relative_error: float + high_frequency_frozen_relative_error: float + maximum_maxwell_spread_A_m2_V: float + maximum_ion_inventory_relative_per_V: float + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + object.__setattr__(self, "frequencies_Hz", frozen_array(self.frequencies_Hz)) + + +def _layer_param_float(layer: object, key: str) -> float: + params = dict(getattr(layer, "parameters", ())) + val = params.get(key) + return float(val) if isinstance(val, (int, float)) and not isinstance(val, bool) else 0.0 + + +def _infer_single_ion_layer(prepared: PreparedDevice) -> str: + layers = [ + ly.id + for ly in prepared.layers + if ly.role != "substrate" + and ( + (_layer_param_float(ly, "D_ion") > 0.0 and _layer_param_float(ly, "P0") > 0.0) + or ( + _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ) + ) + ] + if len(layers) != 1: + raise DefectIonImpedanceCapabilityError( + "combined defect/ion impedance requires exactly one active mobile-ion layer" + ) + return layers[0] + + +def solve_defect_ion_impedance( + prepared: PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: DefectIonImpedanceOptions | None = None, +) -> DefectIonImpedanceResult: + """Solve coupled and frozen-species impedance sweeps about one DC working state.""" + controls = DefectIonImpedanceOptions() if options is None else options + freqs = np.asarray(frequencies_Hz, dtype=np.float64) + if ( + freqs.ndim != 1 + or freqs.size < 1 + or not np.all(np.isfinite(freqs)) + or np.any(freqs < 0.0) + ): + raise ValueError("frequencies_Hz must be a non-empty 1D array of finite non-negative values") + if freqs.size > 1 and np.any(np.diff(freqs) <= 0.0): + raise ValueError("frequencies_Hz must be strictly increasing") + if not math.isfinite(voltage_V) or not math.isfinite(generation_scale) or generation_scale < 0.0: + raise ValueError("voltage_V must be finite and generation_scale >= 0") + + try: + raw_cap = classify_dynamic_defect_capability(prepared) + except CapabilityError as error: + raise DefectIonImpedanceCapabilityError(str(error)) from error + + if raw_cap not in { + "bulk_defect_plus_ions", + "interface_defect_plus_ions", + "bulk_interface_defect_plus_ions", + }: + raise DefectIonImpedanceCapabilityError( + f"combined defect/ion impedance requires active mobile ions plus dynamic defects, got {raw_cap!r}" + ) + capability: DefectIonCapability = raw_cap # type: ignore[assignment] + + ion_layer = ( + controls.ion_domain_layer + if controls.ion_domain_layer is not None + else _infer_single_ion_layer(prepared) + ) + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=("bulk" in capability), + dynamic_interface_defects=("interface" in capability), + energy_quadrature_order=controls.energy_quadrature_order, + ion_domain_layer=ion_layer, + ion_domain_endpoints=controls.ion_domain_endpoints, + ) + except CapabilityError as error: + raise DefectIonImpedanceCapabilityError(str(error)) from error + + steady = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=controls.steady_options, + ) + ss = DynamicDefectSmallSignal1D( + compiled, + steady.state, + generation_scale=generation_scale, + ) + + coupled = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=False, + freeze_bulk_traps=False, + freeze_interface_traps=False, + ) + frozen_ions = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=True, + freeze_bulk_traps=False, + freeze_interface_traps=False, + ) + frozen_traps = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=False, + freeze_bulk_traps=True, + freeze_interface_traps=True, + ) + frozen_both = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=True, + freeze_bulk_traps=True, + freeze_interface_traps=True, + ) + zero_hz = ss.solve_sweep( + np.array([0.0]), + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + ) + + digest = ss.working_state_digest + if not ( + coupled.working_state_digest + == frozen_ions.working_state_digest + == frozen_traps.working_state_digest + == frozen_both.working_state_digest + == digest + ): + raise DefectIonImpedanceError("working_state_digest drifted across frozen-species modes") + + y0 = complex(zero_hz.admittance_density_S_m2[0]) + y_hf = complex(frozen_both.admittance_density_S_m2[-1]) + low_err = float( + abs(complex(coupled.admittance_density_S_m2[0]) - y0) + / max(abs(complex(coupled.admittance_density_S_m2[0])), abs(y0), 1.0e-30) + ) + high_err = float( + abs(complex(coupled.admittance_density_S_m2[-1]) - y_hf) + / max(abs(complex(coupled.admittance_density_S_m2[-1])), abs(y_hf), 1.0e-30) + ) + + max_spread = float( + max( + np.max(coupled.maxwell_spread_A_m2_V), + np.max(frozen_ions.maxwell_spread_A_m2_V), + np.max(frozen_traps.maxwell_spread_A_m2_V), + np.max(frozen_both.maxwell_spread_A_m2_V), + ) + ) + max_inv = 0.0 + for pt in (*zero_hz.points, *coupled.points, *frozen_traps.points): + if pt.ion_inventory_relative_per_V: + max_inv = max(max_inv, max(pt.ion_inventory_relative_per_V.values())) + + return DefectIonImpedanceResult( + capability=capability, + device=compiled, + steady=steady, + working_state_digest=digest, + frequencies_Hz=coupled.frequencies_Hz, + coupled=coupled, + frozen_ions=frozen_ions, + frozen_traps=frozen_traps, + frozen_ions_and_traps=frozen_both, + qss_zero_hz_admittance_S_m2=y0, + low_frequency_qss_relative_error=low_err, + high_frequency_frozen_relative_error=high_err, + maximum_maxwell_spread_A_m2_V=max_spread, + maximum_ion_inventory_relative_per_V=max_inv, + ) diff --git a/src/solarlab/experiments/dynamic_defect_impedance.py b/src/solarlab/experiments/dynamic_defect_impedance.py new file mode 100644 index 00000000..bc0e436e --- /dev/null +++ b/src/solarlab/experiments/dynamic_defect_impedance.py @@ -0,0 +1,567 @@ +"""Dynamic explicit-defect small-signal impedance on unified 1D assembly. + +Migrates bulk dynamic-defect impedance, interface dynamic-defect impedance, and +the protocol-bound dynamic-defect capability classifier onto +``CompiledDynamicDefectDevice1D`` + ``DynamicDefectSmallSignal1D``, computing +low-frequency QSS (`0 Hz`) and high-frequency frozen-trap reference limits from +the exact same nonlinear DC working state. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from hashlib import sha256 +import json +import math +from typing import Any, Literal, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import frozen_array +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + DynamicDefectACSweepResult, + DynamicDefectSmallSignal1D, + DynamicDefectSteadyOptions, + DynamicDefectSteadyResult, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dynamic_defect_1d import CompiledDynamicDefectDevice1D +from solarlab.physics.defects import ( + DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + evaluate_dynamic_bulk_traps, + validate_defect_energy_quadrature_order, +) +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + solve_fixed_occupancy_two_sided_interface, +) +from solarlab.solvers.linear.frequency_domain import FrequencyOptions + +Vector: TypeAlias = NDArray[np.float64] +ComplexVector: TypeAlias = NDArray[np.complex128] + +DynamicDefectCapability = Literal[ + "bulk_dynamic_defect", + "interface_dynamic_defect", + "bulk_defect_plus_ions", + "interface_defect_plus_ions", + "bulk_interface_defect_plus_ions", +] + +DYNAMIC_DEFECT_IMPEDANCE_SCHEMA = "solarlab.dynamic-defect-impedance.v1" + +__all__ = [ + "DYNAMIC_DEFECT_IMPEDANCE_SCHEMA", + "DynamicDefectCapability", + "DynamicDefectImpedanceCapabilityError", + "DynamicDefectImpedanceError", + "DynamicDefectImpedanceOptions", + "DynamicDefectImpedanceProtocol", + "DynamicDefectImpedanceResult", + "build_dynamic_defect_impedance_protocol", + "classify_dynamic_defect_capability", + "solve_bulk_defect_impedance", + "solve_dynamic_defect_impedance", + "solve_interface_defect_impedance", +] + + +class DynamicDefectImpedanceError(RuntimeError): + """Raised when dynamic-defect impedance validation or execution fails.""" + + +class DynamicDefectImpedanceCapabilityError(DynamicDefectImpedanceError, CapabilityError): + """Raised when a device stack falls outside qualified dynamic-defect capabilities.""" + + +def _relative_admittance_error(left: complex, right: complex) -> float: + scale = max(abs(left), abs(right), 1.0e-30) + return float(abs(left - right) / scale) + + +def _validate_positive_increasing_frequencies(frequencies_Hz: ArrayLike) -> Vector: + freqs = np.asarray(frequencies_Hz, dtype=np.float64) + if ( + freqs.ndim != 1 + or freqs.size < 3 + or not np.all(np.isfinite(freqs)) + or np.any(freqs <= 0.0) + or np.any(np.diff(freqs) <= 0.0) + ): + raise ValueError( + "frequencies_Hz must contain at least three finite, positive, strictly increasing values" + ) + return freqs + + +def _layer_param_float(layer: object, key: str) -> float: + params = dict(getattr(layer, "parameters", ())) + val = params.get(key) + return float(val) if isinstance(val, (int, float)) and not isinstance(val, bool) else 0.0 + + +def _active_ion_layers(prepared: PreparedDevice) -> list[str]: + layers: list[str] = [] + for layer in prepared.layers: + if layer.role == "substrate": + continue + p0 = _layer_param_float(layer, "P0") + d_pos = _layer_param_float(layer, "D_ion") + p0_neg = _layer_param_float(layer, "P0_neg") + d_neg = _layer_param_float(layer, "D_ion_neg") + if (d_pos > 0.0 and p0 > 0.0) or (d_neg > 0.0 and p0_neg > 0.0): + layers.append(layer.id) + return layers + + +def classify_dynamic_defect_capability( + prepared: PreparedDevice, +) -> DynamicDefectCapability: + """Classify ``prepared`` into a supported dynamic-defect impedance capability.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("classify_dynamic_defect_capability requires PreparedDevice") + + elec_layers = [ly for ly in prepared.layers if ly.role != "substrate"] + if not elec_layers: + raise DynamicDefectImpedanceCapabilityError( + "dynamic-defect impedance requires at least one electrical layer" + ) + + has_bulk = False + for layer in elec_layers: + if layer.metastable_document is not None: + raise DynamicDefectImpedanceCapabilityError( + f"layers.{layer.id}: metastable bulk defects are not dynamic-trap impedance species" + ) + if layer.defect_schema_version == "solarlab-explicit-bulk-defects-v4": + raise DynamicDefectImpedanceCapabilityError( + f"layers.{layer.id}: multivalent bulk defects do not expose dynamic single-level impedance modes" + ) + if layer.defects or layer.bulk_trap_distribution_json is not None: + has_bulk = True + + has_interface = False + for iface in prepared.interfaces: + if not iface.electrical: + continue + entry = iface.to_mapping() + defect = entry.get("defect") + if defect is None: + continue + has_interface = True + cal = float(defect["calibration_factor"]) + state_cal = float(defect["iface_state_calibration_factor"]) + if cal != 1.0 or state_cal != 1.0: + raise DynamicDefectImpedanceCapabilityError( + f"interfaces.{entry['id']}: empirical calibration factors are refused" + ) + raw_vn = entry.get("v_n") + raw_vp = entry.get("v_p") + micro_pair = tuple(float(v) for v in entry["microscopic_capture_velocities_m_s"]) + if raw_vn is not None and raw_vp is not None and not ( + math.isclose(float(raw_vn), micro_pair[0], rel_tol=1.0e-12, abs_tol=0.0) + and math.isclose(float(raw_vp), micro_pair[1], rel_tol=1.0e-12, abs_tol=0.0) + ): + raise DynamicDefectImpedanceCapabilityError( + f"interfaces.{entry['id']}: compatibility SRV disagrees with microscopic capture" + ) + + ion_layers = _active_ion_layers(prepared) + if len(ion_layers) > 1: + raise DynamicDefectImpedanceCapabilityError( + "dynamic-defect impedance currently supports at most one active mobile-ion layer" + ) + has_ions = len(ion_layers) == 1 + + if not has_bulk and not has_interface: + raise DynamicDefectImpedanceCapabilityError( + "dynamic-defect impedance requires an explicit bulk or microscopic interface defect population" + ) + + if has_ions: + if has_bulk and has_interface: + return "bulk_interface_defect_plus_ions" + if has_bulk: + return "bulk_defect_plus_ions" + return "interface_defect_plus_ions" + + if has_bulk and has_interface: + raise DynamicDefectImpedanceCapabilityError( + "bulk + interface dynamic defects without active mobile ions do not have a jointly certified production operator" + ) + return "bulk_dynamic_defect" if has_bulk else "interface_dynamic_defect" + + +@dataclass(frozen=True, slots=True) +class DynamicDefectImpedanceOptions: + """Execution controls for dynamic-defect small-signal impedance.""" + + intervals_per_layer: int | tuple[int, ...] = 24 + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER + voltage_phasor_V: complex = 1.0 + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + verify_zero_hz_fd: bool = False + fd_voltage_step_V: float = 1.0e-5 + steady_options: DynamicDefectSteadyOptions | None = None + linear_options: FrequencyOptions | None = None + + def __post_init__(self) -> None: + validate_defect_energy_quadrature_order(self.energy_quadrature_order) + if isinstance(self.intervals_per_layer, int): + if isinstance(self.intervals_per_layer, bool) or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be >= 2") + else: + tup = tuple(int(v) for v in self.intervals_per_layer) + if not tup or any(v < 2 for v in tup): + raise ValueError("intervals_per_layer entries must be >= 2") + object.__setattr__(self, "intervals_per_layer", tup) + if not np.isfinite(self.voltage_phasor_V) or self.voltage_phasor_V == 0.0: + raise ValueError("voltage_phasor_V must be finite and nonzero") + if not math.isfinite(self.fd_voltage_step_V) or self.fd_voltage_step_V <= 0.0: + raise ValueError("fd_voltage_step_V must be finite and positive") + + +@dataclass(frozen=True, slots=True) +class DynamicDefectImpedanceProtocol: + """Immutable protocol digest for a dynamic-defect impedance calculation.""" + + schema_version: str + capability: DynamicDefectCapability + voltage_V: float + generation_scale: float + frequencies_Hz: tuple[float, ...] + intervals_per_layer: int | tuple[int, ...] + actual_grid_nodes: int + energy_quadrature_order: int + prepared_sha256: str + compiled_device_sha256: str + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "capability": self.capability, + "voltage_V": self.voltage_V, + "generation_scale": self.generation_scale, + "frequencies_Hz": list(self.frequencies_Hz), + "intervals_per_layer": ( + list(self.intervals_per_layer) + if isinstance(self.intervals_per_layer, tuple) + else self.intervals_per_layer + ), + "actual_grid_nodes": self.actual_grid_nodes, + "energy_quadrature_order": self.energy_quadrature_order, + "prepared_sha256": self.prepared_sha256, + "compiled_device_sha256": self.compiled_device_sha256, + } + + @property + def protocol_sha256(self) -> str: + text = json.dumps( + self.to_dict(), sort_keys=True, separators=(",", ":"), allow_nan=False + ) + return sha256(text.encode("ascii")).hexdigest() + + +@dataclass(frozen=True) +class DynamicDefectImpedanceResult: + """Result of dynamic-defect small-signal impedance analysis.""" + + capability: DynamicDefectCapability + protocol: DynamicDefectImpedanceProtocol + device: CompiledDynamicDefectDevice1D + steady: DynamicDefectSteadyResult + ac_sweep: DynamicDefectACSweepResult + frozen_reference_sweep: DynamicDefectACSweepResult + frequencies_Hz: Vector + admittance_density_S_m2: ComplexVector + impedance_area_ohm_m2: ComplexVector + qss_reference_admittance_S_m2: complex + frozen_high_frequency_admittance_S_m2: complex + low_frequency_qss_relative_error: float + high_frequency_frozen_relative_error: float + trap_relaxation_frequencies_Hz: Vector + frequency_window_brackets_traps: bool + maximum_maxwell_spread_A_m2_V: float + maximum_ion_inventory_relative_per_V: float + dc_differential_conductance_S_m2: float | None = None + zero_hz_fd_relative_error: float | None = None + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + for attr in ("frequencies_Hz", "trap_relaxation_frequencies_Hz"): + object.__setattr__(self, attr, frozen_array(getattr(self, attr))) + for attr in ("admittance_density_S_m2", "impedance_area_ohm_m2"): + c_arr = np.asarray(getattr(self, attr), dtype=np.complex128) + object.__setattr__( + self, + attr, + np.frombuffer(c_arr.tobytes(), dtype=np.complex128).reshape(c_arr.shape), + ) + + +def _trap_relaxation_frequencies_Hz( + device: CompiledDynamicDefectDevice1D, + steady: DynamicDefectSteadyResult, +) -> Vector: + rates: list[float] = [] + elec = steady.state.electronic_state + n = elec.electron_density_m3 + p = elec.hole_density_m3 + phi = elec.potential_V + N = device.node_count + zn = elec.u[N : 2 * N] + zp = elec.u[2 * N : 3 * N] + + if device.dynamic_bulk_traps is not None: + ev = evaluate_dynamic_bulk_traps( + n, p, steady.state.bulk_trap_occupancy, device.dynamic_bulk_traps + ) + # Relaxation rate k_relax = -d(C_n - C_p) / (N_t df) [s^-1]: + k_bt = -ev.d_trap_storage_rate_df_m3_s / device.dynamic_bulk_traps.population_density_m3 + rates.extend(float(val) for val in k_bt if val > 0.0) + + for idx, itrap in enumerate(device.dynamic_interface_traps): + ln, rn = itrap.left_node, itrap.right_node + eq_charge = EquilibriumReferencedSheetCharge( + equilibrium_occupancy=itrap.trap_spec.equilibrium_occupancy, + trap_density_m2=itrap.trap_density_m2 if itrap.has_sheet_charge else 0.0, + ) + res = solve_fixed_occupancy_two_sided_interface( + itrap.trace_electrostatics, + itrap.physics, + TwoSidedBulkState( + phi_left_V=float(phi[ln]), + phi_right_V=float(phi[rn]), + n_left_m3=float(n[ln]), + p_left_m3=float(p[ln]), + n_right_m3=float(n[rn]), + p_right_m3=float(p[rn]), + electron_electrochemical_step=float(zn[rn] - zn[ln]), + hole_electrochemical_step=float(-(zp[rn] - zp[ln])), + ), + eq_charge, + occupancy=float(steady.state.interface_trap_occupancy[idx]), + ) + if res.relaxation_rate_s1 > 0.0: + rates.append(float(res.relaxation_rate_s1)) + + if not rates: + return np.empty(0, dtype=np.float64) + return np.asarray(sorted(r / (2.0 * math.pi) for r in rates), dtype=np.float64) + + +def build_dynamic_defect_impedance_protocol( + prepared: PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: DynamicDefectImpedanceOptions | None = None, +) -> tuple[DynamicDefectImpedanceProtocol, CompiledDynamicDefectDevice1D]: + """Classify capability, compile unified device, and return bound protocol.""" + controls = DynamicDefectImpedanceOptions() if options is None else options + freqs = _validate_positive_increasing_frequencies(frequencies_Hz) + if not math.isfinite(voltage_V) or not math.isfinite(generation_scale) or generation_scale < 0.0: + raise ValueError("voltage_V must be finite and generation_scale >= 0") + + capability = classify_dynamic_defect_capability(prepared) + ion_layers = _active_ion_layers(prepared) + ion_layer = ion_layers[0] if ion_layers else None + + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=("bulk" in capability), + dynamic_interface_defects=("interface" in capability), + energy_quadrature_order=controls.energy_quadrature_order, + ion_domain_layer=ion_layer, + ion_domain_endpoints=controls.ion_domain_endpoints, + ) + except CapabilityError as error: + raise DynamicDefectImpedanceCapabilityError(str(error)) from error + + protocol = DynamicDefectImpedanceProtocol( + schema_version=DYNAMIC_DEFECT_IMPEDANCE_SCHEMA, + capability=capability, + voltage_V=float(voltage_V), + generation_scale=float(generation_scale), + frequencies_Hz=tuple(float(f) for f in freqs), + intervals_per_layer=controls.intervals_per_layer, + actual_grid_nodes=compiled.node_count, + energy_quadrature_order=controls.energy_quadrature_order, + prepared_sha256=prepared.content_sha256, + compiled_device_sha256=compiled.identity, + ) + return protocol, compiled + + +def solve_dynamic_defect_impedance( + prepared: PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: DynamicDefectImpedanceOptions | None = None, +) -> DynamicDefectImpedanceResult: + """Solve dynamic-defect small-signal impedance across ``frequencies_Hz``.""" + controls = DynamicDefectImpedanceOptions() if options is None else options + freqs = _validate_positive_increasing_frequencies(frequencies_Hz) + protocol, compiled = build_dynamic_defect_impedance_protocol( + prepared, + freqs, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=controls, + ) + + steady = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=controls.steady_options, + ) + ss = DynamicDefectSmallSignal1D( + compiled, + steady.state, + generation_scale=generation_scale, + ) + + ac_sweep = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + ) + qss_zero = ss.solve_sweep( + np.array([0.0]), + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + ) + frozen_sweep = ss.solve_sweep( + freqs, + voltage_phasor_V=controls.voltage_phasor_V, + options=controls.linear_options, + freeze_ions=compiled.has_ions, + freeze_bulk_traps=compiled.has_dynamic_bulk_traps, + freeze_interface_traps=compiled.has_dynamic_interface_traps, + ) + + y_qss = complex(qss_zero.admittance_density_S_m2[0]) + y_hf_frozen = complex(frozen_sweep.admittance_density_S_m2[-1]) + low_rel = _relative_admittance_error(complex(ac_sweep.admittance_density_S_m2[0]), y_qss) + high_rel = _relative_admittance_error( + complex(ac_sweep.admittance_density_S_m2[-1]), y_hf_frozen + ) + + f_traps = _trap_relaxation_frequencies_Hz(compiled, steady) + brackets = bool( + f_traps.size > 0 + and float(freqs[0]) <= float(f_traps[0]) + and float(freqs[-1]) >= float(f_traps[-1]) + ) + + max_inv = 0.0 + if compiled.has_ions: + for pt in (*qss_zero.points, *ac_sweep.points): + if pt.ion_inventory_relative_per_V: + max_inv = max(max_inv, max(pt.ion_inventory_relative_per_V.values())) + + dc_g: float | None = None + fd_rel: float | None = None + if controls.verify_zero_hz_fd: + dv = controls.fd_voltage_step_V + u_plus = compiled.rebase_coordinates(steady.state.u, voltage_V, voltage_V + dv) + u_minus = compiled.rebase_coordinates(steady.state.u, voltage_V, voltage_V - dv) + st_plus = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=voltage_V + dv, + generation_scale=generation_scale, + initial_u=u_plus, + options=controls.steady_options, + ) + st_minus = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=voltage_V - dv, + generation_scale=generation_scale, + initial_u=u_minus, + options=controls.steady_options, + ) + dc_g = float( + (st_plus.terminal_current_density_A_m2 - st_minus.terminal_current_density_A_m2) + / (2.0 * dv) + ) + fd_rel = _relative_admittance_error(y_qss, complex(dc_g, 0.0)) + + return DynamicDefectImpedanceResult( + capability=protocol.capability, + protocol=protocol, + device=compiled, + steady=steady, + ac_sweep=ac_sweep, + frozen_reference_sweep=frozen_sweep, + frequencies_Hz=ac_sweep.frequencies_Hz, + admittance_density_S_m2=ac_sweep.admittance_density_S_m2, + impedance_area_ohm_m2=ac_sweep.impedance_area_ohm_m2, + qss_reference_admittance_S_m2=y_qss, + frozen_high_frequency_admittance_S_m2=y_hf_frozen, + low_frequency_qss_relative_error=low_rel, + high_frequency_frozen_relative_error=high_rel, + trap_relaxation_frequencies_Hz=f_traps, + frequency_window_brackets_traps=brackets, + maximum_maxwell_spread_A_m2_V=float(np.max(ac_sweep.maxwell_spread_A_m2_V)), + maximum_ion_inventory_relative_per_V=max_inv, + dc_differential_conductance_S_m2=dc_g, + zero_hz_fd_relative_error=fd_rel, + ) + + +def solve_bulk_defect_impedance( + prepared: PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: DynamicDefectImpedanceOptions | None = None, +) -> DynamicDefectImpedanceResult: + """Solve ion-free bulk dynamic-defect impedance (requires ``bulk_dynamic_defect``).""" + cap = classify_dynamic_defect_capability(prepared) + if cap != "bulk_dynamic_defect": + raise DynamicDefectImpedanceCapabilityError( + f"solve_bulk_defect_impedance requires 'bulk_dynamic_defect', got {cap!r}" + ) + return solve_dynamic_defect_impedance( + prepared, + frequencies_Hz, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=options, + ) + + +def solve_interface_defect_impedance( + prepared: PreparedDevice, + frequencies_Hz: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + options: DynamicDefectImpedanceOptions | None = None, +) -> DynamicDefectImpedanceResult: + """Solve ion-free two-sided interface dynamic-defect impedance.""" + cap = classify_dynamic_defect_capability(prepared) + if cap != "interface_dynamic_defect": + raise DynamicDefectImpedanceCapabilityError( + f"solve_interface_defect_impedance requires 'interface_dynamic_defect', got {cap!r}" + ) + return solve_dynamic_defect_impedance( + prepared, + frequencies_Hz, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=options, + ) diff --git a/src/solarlab/experiments/dynamic_defect_transient.py b/src/solarlab/experiments/dynamic_defect_transient.py new file mode 100644 index 00000000..9fb4ae99 --- /dev/null +++ b/src/solarlab/experiments/dynamic_defect_transient.py @@ -0,0 +1,871 @@ +"""Unified storage-form BDF1/BDF2 transient drivers for dynamic bulk/interface defects and ions. + +Decomposes the legacy combinatorial transient runners (`bulk_defect_transient`, +`interface_defect_transient`, `bulk_defect_ion_transient`, +`interface_defect_ion_transient`, and the narrow-gate production +`dynamic_defect_transient`) onto one unified ``DynamicDefectStorage1D`` + +``BDFStep`` + ``dynamic_defect_step_accounting`` integration engine while +preserving every explicit capability gate. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math +from typing import Any, Literal, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.sparse import csc_matrix, diags +from scipy.sparse.linalg import splu + +from solarlab.contracts import frozen_array +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + AssembledDynamicDefect1DProblem, + DynamicDefectSteadyOptions, + DynamicDefectStorage1D, + dynamic_defect_step_accounting, + dynamic_defect_system_1d, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dynamic_defect_1d import CompiledDynamicDefectDevice1D +from solarlab.solvers.time.bdf import BDFStep, HistoryPoint + +Vector: TypeAlias = NDArray[np.float64] + +VoltageInterpolation = Literal["right_continuous_step_and_hold", "piecewise_linear"] +DynamicDefectTransientCapability = Literal[ + "bulk_defect_transient", + "interface_defect_transient", + "bulk_defect_ion_transient", + "interface_defect_ion_transient", + "interface_defect_plus_positive_ions", +] + +__all__ = [ + "DynamicDefectTransientCapability", + "DynamicDefectTransientCapabilityError", + "DynamicDefectTransientError", + "DynamicDefectTransientOptions", + "DynamicDefectTransientResult", + "VoltageInterpolation", + "classify_dynamic_defect_transient_capability", + "solve_bulk_defect_ion_transient", + "solve_bulk_defect_transient", + "solve_dynamic_defect_transient", + "solve_interface_defect_ion_transient", + "solve_interface_defect_transient", +] + + +class DynamicDefectTransientError(RuntimeError): + """Raised when dynamic-defect transient integration or validation fails.""" + + +class DynamicDefectTransientCapabilityError(DynamicDefectTransientError, CapabilityError): + """Raised when a device or protocol violates a transient capability gate.""" + + +@dataclass(frozen=True, slots=True) +class DynamicDefectTransientOptions: + """Discretization and nonlinear solver controls for dynamic-defect transients.""" + + intervals_per_layer: int | tuple[int, ...] = 24 + substeps_per_interval: int = 1 + bdf_order: int = 1 + voltage_interpolation: VoltageInterpolation = "right_continuous_step_and_hold" + ion_domain_endpoints: tuple[str, str] = ("blocking", "blocking") + newton_tolerance: float = 1.0e-10 + max_newton_iterations: int = 50 + max_step_halvings: int = 8 + steady_options: DynamicDefectSteadyOptions | None = None + + def __post_init__(self) -> None: + if isinstance(self.intervals_per_layer, int): + if isinstance(self.intervals_per_layer, bool) or self.intervals_per_layer < 2: + raise ValueError("intervals_per_layer must be >= 2") + else: + tup = tuple(int(v) for v in self.intervals_per_layer) + if not tup or any(v < 2 for v in tup): + raise ValueError("intervals_per_layer entries must be >= 2") + object.__setattr__(self, "intervals_per_layer", tup) + if isinstance(self.substeps_per_interval, bool) or self.substeps_per_interval < 1: + raise ValueError("substeps_per_interval must be >= 1") + if self.bdf_order not in {1, 2}: + raise ValueError("bdf_order must be 1 or 2") + if self.voltage_interpolation not in { + "right_continuous_step_and_hold", + "piecewise_linear", + }: + raise ValueError(f"unsupported voltage_interpolation {self.voltage_interpolation!r}") + if not math.isfinite(self.newton_tolerance) or self.newton_tolerance <= 0.0: + raise ValueError("newton_tolerance must be finite and positive") + if self.max_newton_iterations < 5 or self.max_step_halvings < 0: + raise ValueError("invalid max_newton_iterations or max_step_halvings") + + +@dataclass(frozen=True) +class DynamicDefectTransientResult: + """Conservative all-face current, carrier, ion, and trap transient trajectory.""" + + capability: DynamicDefectTransientCapability + device: CompiledDynamicDefectDevice1D + grid_m: Vector + times_s: Vector + voltage_V: Vector + generation_scale: Vector + terminal_current_density_A_m2: Vector + conduction_current_faces_A_m2: Vector + ionic_current_faces_A_m2: Vector + displacement_current_faces_A_m2: Vector + total_current_faces_A_m2: Vector + maxwell_spread_A_m2: Vector + potential_V: Vector + electron_density_m3: Vector + hole_density_m3: Vector + bulk_trap_occupancy: Vector + interface_trap_occupancy: Vector + interface_sheet_charges_C_m2: Vector + positive_ion_density_m3: Vector + positive_ion_centroid_m: Vector + maximum_ion_inventory_relative_drift: float + maximum_maxwell_spread_A_m2: float + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + for attr in ( + "grid_m", + "times_s", + "voltage_V", + "generation_scale", + "terminal_current_density_A_m2", + "conduction_current_faces_A_m2", + "ionic_current_faces_A_m2", + "displacement_current_faces_A_m2", + "total_current_faces_A_m2", + "maxwell_spread_A_m2", + "potential_V", + "electron_density_m3", + "hole_density_m3", + "bulk_trap_occupancy", + "interface_trap_occupancy", + "interface_sheet_charges_C_m2", + "positive_ion_density_m3", + "positive_ion_centroid_m", + ): + object.__setattr__(self, attr, frozen_array(getattr(self, attr))) + + +def _validate_traces( + times_s: ArrayLike, + voltage_V: ArrayLike, + generation_scale: float | ArrayLike, +) -> tuple[Vector, Vector, Vector]: + t_arr = np.asarray(times_s, dtype=np.float64) + v_arr = np.asarray(voltage_V, dtype=np.float64) + if t_arr.ndim != 1 or t_arr.size < 2 or not np.all(np.isfinite(t_arr)): + raise ValueError("times_s must be a 1D array with at least two finite values") + if t_arr[0] != 0.0: + raise ValueError("transient times_s must start at t = 0.0") + if np.any(np.diff(t_arr) <= 0.0): + raise ValueError("times_s must be strictly increasing") + if v_arr.shape != t_arr.shape or not np.all(np.isfinite(v_arr)): + raise ValueError("voltage_V must be finite and aligned with times_s") + if np.ndim(generation_scale) == 0: + g_val = float(generation_scale) + if not math.isfinite(g_val) or g_val < 0.0: + raise ValueError("generation_scale must be finite and non-negative") + g_arr = np.full(t_arr.size, g_val, dtype=np.float64) + else: + g_arr = np.asarray(generation_scale, dtype=np.float64) + if g_arr.shape != t_arr.shape or not np.all(np.isfinite(g_arr)) or np.any(g_arr < 0.0): + raise ValueError("generation_scale trace must be finite, non-negative, and aligned") + return t_arr, v_arr, g_arr + + +def _require_uncalibrated_interface_defects(prepared: PreparedDevice) -> int: + count = 0 + for iface in prepared.interfaces: + if not iface.electrical: + continue + entry = iface.to_mapping() + defect = entry.get("defect") + if defect is None: + continue + count += 1 + if float(defect["calibration_factor"]) != 1.0 or float( + defect["iface_state_calibration_factor"] + ) != 1.0: + raise DynamicDefectTransientCapabilityError( + f"interfaces.{entry['id']}: empirical calibration factors are refused" + ) + raw_vn = entry.get("v_n") + raw_vp = entry.get("v_p") + micro_pair = tuple(float(v) for v in entry["microscopic_capture_velocities_m_s"]) + if raw_vn is not None and raw_vp is not None and not ( + math.isclose(float(raw_vn), micro_pair[0], rel_tol=1.0e-12, abs_tol=0.0) + and math.isclose(float(raw_vp), micro_pair[1], rel_tol=1.0e-12, abs_tol=0.0) + ): + raise DynamicDefectTransientCapabilityError( + f"interfaces.{entry['id']}: compatibility SRV disagrees with microscopic capture" + ) + return count + + +def _layer_param_float(layer: object, key: str) -> float: + params = dict(getattr(layer, "parameters", ())) + val = params.get(key) + return float(val) if isinstance(val, (int, float)) and not isinstance(val, bool) else 0.0 + + +def classify_dynamic_defect_transient_capability( + prepared: PreparedDevice, +) -> Literal["interface_defect_plus_positive_ions"]: + """Enforce the exact narrow v1 production dynamic-defect transient gate.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("classify_dynamic_defect_transient_capability requires PreparedDevice") + elec_layers = [ly for ly in prepared.layers if ly.role != "substrate"] + if len(elec_layers) != 2: + raise DynamicDefectTransientCapabilityError( + "v1 production transient requires exactly two electrical layers" + ) + for ly in elec_layers: + if ( + ly.defects + or ly.bulk_trap_distribution_json is not None + or ly.metastable_document is not None + ): + raise DynamicDefectTransientCapabilityError( + "v1 production transient excludes simultaneous bulk explicit defects" + ) + + iface_count = _require_uncalibrated_interface_defects(prepared) + if iface_count != 1: + raise DynamicDefectTransientCapabilityError( + "v1 production transient requires exactly one microscopic interface defect" + ) + + settings = prepared.to_mapping()["settings"] + if str(settings.get("interface_charge_closure", "off")) != "equilibrium_referenced": + raise DynamicDefectTransientCapabilityError( + "v1 production transient requires equilibrium-referenced interface charge" + ) + if not bool(settings.get("interface_charge_rebaseline_acknowledged", False)): + raise DynamicDefectTransientCapabilityError( + "v1 production transient requires interface charge rebaseline acknowledgement" + ) + + pos_layers = [ + idx + for idx, ly in enumerate(elec_layers) + if _layer_param_float(ly, "D_ion") > 0.0 + and _layer_param_float(ly, "P0") > 0.0 + ] + neg_layers = [ + idx + for idx, ly in enumerate(elec_layers) + if _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ] + if len(pos_layers) != 1: + raise DynamicDefectTransientCapabilityError( + "v1 production transient requires exactly one active positive-ion layer" + ) + if str(elec_layers[pos_layers[0]].role).lower() != "absorber": + raise DynamicDefectTransientCapabilityError( + "the active positive-ion layer must have role='absorber'" + ) + if neg_layers: + raise DynamicDefectTransientCapabilityError( + "v1 production transient excludes active negative ions" + ) + return "interface_defect_plus_positive_ions" + + +def _solve_bdf_step_newton( + step: BDFStep, + u_init: Vector, + *, + tolerance: float, + max_iterations: int, +) -> tuple[Vector, bool]: + u = np.array(u_init, dtype=np.float64, copy=True) + adapter = step.endpoint + assert isinstance(adapter, DynamicDefectStorage1D) + N = adapter.device.node_count + phi_l, phi_r = adapter.device.electronic_component.contact_potentials(adapter.voltage_V) + u[0] = phi_l + u[N - 1] = phi_r + + for iteration in range(max_iterations + 1): + try: + f = np.asarray(step.residual(u), dtype=np.float64) + jac = csc_matrix(step.jacobian(u)) + except (FloatingPointError, ValueError): + return u, False + if not np.all(np.isfinite(f)): + return u, False + row_max = np.asarray(np.abs(jac).max(axis=1).todense()).ravel() + row_scale = np.where(row_max > 0.0, 1.0 / row_max, 1.0) + fs = row_scale * f + if float(np.max(np.abs(fs))) <= tolerance: + return u, True + if iteration == max_iterations: + break + j_row = diags(row_scale) @ jac + col_max = np.asarray(np.abs(j_row).max(axis=0).todense()).ravel() + col_scale = np.where(col_max > 0.0, 1.0 / col_max, 1.0) + try: + du = -col_scale * splu((j_row @ diags(col_scale)).tocsc()).solve(fs) + except RuntimeError: + return u, False + if not np.all(np.isfinite(du)): + return u, False + max_dphi = float(np.max(np.abs(du[:N]))) + max_dlog = float(np.max(np.abs(du[N:]))) if du.size > N else 0.0 + clip = 1.0 + if max_dphi > 0.5: + clip = min(clip, 0.5 / max_dphi) + if max_dlog > 8.0: + clip = min(clip, 8.0 / max_dlog) + merit = float(np.linalg.norm(fs)) + alpha = clip + accepted = False + for _ in range(24): + u_try = u + alpha * du + try: + f_try = np.asarray(step.residual(u_try), dtype=np.float64) + except (FloatingPointError, ValueError): + alpha *= 0.5 + continue + if np.all(np.isfinite(f_try)): + m_try = float(np.linalg.norm(row_scale * f_try)) + if m_try <= (1.0 - 1.0e-4 * alpha) * merit or m_try <= tolerance: + u = u_try + accepted = True + break + alpha *= 0.5 + if not accepted: + return u, False + return u, False + + +def _advance_substep_recursive( + device: CompiledDynamicDefectDevice1D, + sys_binding: Any, + history: Sequence[HistoryPoint], + t_start: float, + t_end: float, + v_target: float, + g_target: float, + order: int, + options: DynamicDefectTransientOptions, + halvings_left: int, +) -> tuple[HistoryPoint, BDFStep]: + prob = AssembledDynamicDefect1DProblem(device, v_target, g_target, None, sys_binding) + adapter = DynamicDefectStorage1D(prob) + prev = history[0] + assert isinstance(prev.problem, DynamicDefectStorage1D) + u_guess = device.rebase_coordinates(prev.u, prev.problem.voltage_V, v_target) + + eff_order = 2 if (order == 2 and len(history) >= 2) else 1 + hist_slice = (history[0], history[1]) if eff_order == 2 else (history[0],) + step = BDFStep(adapter, hist_slice, t_end, eff_order) + u_sol, ok = _solve_bdf_step_newton( + step, + u_guess, + tolerance=options.newton_tolerance, + max_iterations=options.max_newton_iterations, + ) + if not ok and abs(v_target - prev.problem.voltage_V) > 1.0e-9: + u_cap = u_guess.copy() + N = device.node_count + vt = device.thermal_voltage_V + phi_l, phi_r = device.electronic_component.contact_potentials(v_target) + dv = (phi_r - phi_l) - (u_cap[N - 1] - u_cap[0]) + nodes = device.nodes_m + dphi_vec = dv * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + u_cap[:N] += dphi_vec + u_cap[N : 2 * N] -= dphi_vec / vt + u_cap[2 * N : 3 * N] += dphi_vec / vt + u_sol, ok = _solve_bdf_step_newton( + step, + u_cap, + tolerance=options.newton_tolerance, + max_iterations=options.max_newton_iterations, + ) + if ok: + hp = HistoryPoint(t_end, u_sol, adapter.storage(u_sol), adapter) + return hp, step + + if halvings_left <= 0: + raise DynamicDefectTransientError( + f"BDF transient failed to converge on [{t_start:.4e}, {t_end:.4e}] s at V={v_target:.4f} V" + ) + t_mid = 0.5 * (t_start + t_end) + v_mid = ( + 0.5 * (prev.problem.voltage_V + v_target) + if options.voltage_interpolation == "piecewise_linear" + else v_target + ) + g_mid = ( + 0.5 * (prev.problem.generation_scale + g_target) + if options.voltage_interpolation == "piecewise_linear" + else g_target + ) + hp_mid, _ = _advance_substep_recursive( + device, + sys_binding, + history, + t_start, + t_mid, + v_mid, + g_mid, + 1, + options, + halvings_left - 1, + ) + return _advance_substep_recursive( + device, + sys_binding, + (hp_mid, *history), + t_mid, + t_end, + v_target, + g_target, + order, + options, + halvings_left - 1, + ) + + +def _run_unified_transient( + capability: DynamicDefectTransientCapability, + compiled: CompiledDynamicDefectDevice1D, + times: Vector, + voltages: Vector, + generations: Vector, + options: DynamicDefectTransientOptions, +) -> DynamicDefectTransientResult: + steady0 = solve_dynamic_defect_steady_1d( + compiled, + voltage_V=float(voltages[0]), + generation_scale=float(generations[0]), + options=options.steady_options, + ) + sys_tr = dynamic_defect_system_1d(compiled, inventory_row_node=None) + prob0 = AssembledDynamicDefect1DProblem( + compiled, float(voltages[0]), float(generations[0]), None, sys_tr + ) + adapter0 = DynamicDefectStorage1D(prob0) + + T = times.size + N = compiled.node_count + bt_size = compiled.bulk_trap_dof_count + it_size = len(compiled.dynamic_interface_traps) + if_count = len(compiled.electronic_component.geometry.interfaces) + has_pos_ions = compiled.ionic_component is not None + + j_term = np.zeros(T, dtype=np.float64) + j_cond = np.zeros((T, N + 1), dtype=np.float64) + j_ion = np.zeros((T, N + 1), dtype=np.float64) + j_disp = np.zeros((T, N + 1), dtype=np.float64) + j_tot = np.zeros((T, N + 1), dtype=np.float64) + spreads = np.zeros(T, dtype=np.float64) + + pot = np.zeros((T, N), dtype=np.float64) + n_arr = np.zeros((T, N), dtype=np.float64) + p_arr = np.zeros((T, N), dtype=np.float64) + bt_occ = np.zeros((T, bt_size), dtype=np.float64) + it_occ = np.zeros((T, it_size), dtype=np.float64) + sheets = np.zeros((T, if_count), dtype=np.float64) + pos_ion = np.zeros((T, N if has_pos_ions else 0), dtype=np.float64) + pos_centroid: Vector = np.zeros(T if has_pos_ions else 0, dtype=np.float64) + + def record_state(k: int, u_vec: Vector, v_val: float) -> float: + st = compiled.state(u_vec, voltage_V=v_val) + pot[k] = st.electronic_state.potential_V + n_arr[k] = st.electronic_state.electron_density_m3 + p_arr[k] = st.electronic_state.hole_density_m3 + if bt_size: + bt_occ[k] = st.bulk_trap_occupancy + if it_size: + it_occ[k] = st.interface_trap_occupancy + if if_count: + sheets[k] = st.interface_sheet_charges_C_m2 + inv_drift = 0.0 + if compiled.ionic_component is not None and st.ionic_state is not None: + ion_c = compiled.ionic_component + pos_ion[k] = ion_c.project_ion_density(st.ionic_state.positive_ion_density_m3) + w_ion = ion_c.ion_geometry.cell_measures_m + x_ion = ion_c.ion_geometry.nodes_m + dens_pos = st.ionic_state.positive_ion_density_m3 + inv_pos = float(np.sum(w_ion * dens_pos)) + pos_centroid[k] = float(np.sum(w_ion * x_ion * dens_pos) / inv_pos) + ref_pos = ion_c.reference_inventory_m2 + inv_drift = abs(inv_pos - ref_pos) / ref_pos + if ion_c.ion_species_count == 2: + dens_neg = st.ionic_state.negative_ion_density_m3 + inv_neg = float(np.sum(w_ion * dens_neg)) + ref_neg = ion_c.negative_reference_inventory_m2 + inv_drift = max(inv_drift, abs(inv_neg - ref_neg) / ref_neg) + return inv_drift + + max_inv_drift = record_state(0, steady0.state.u, float(voltages[0])) + j_term[0] = steady0.terminal_current_density_A_m2 + j_cond[0] = steady0.all_face_current_density_A_m2 + j_tot[0] = steady0.all_face_current_density_A_m2 + spreads[0] = steady0.maxwell_spread_A_m2 + + history: tuple[HistoryPoint, ...] = ( + HistoryPoint(0.0, steady0.state.u, adapter0.storage(steady0.state.u), adapter0), + ) + + n_sub = options.substeps_per_interval + for k in range(1, T): + t0 = float(times[k - 1]) + t1 = float(times[k]) + v0 = float(voltages[k - 1]) + v1 = float(voltages[k]) + g0 = float(generations[k - 1]) + g1 = float(generations[k]) + abrupt = options.voltage_interpolation == "right_continuous_step_and_hold" and ( + v1 != v0 or g1 != g0 + ) + + last_step: BDFStep | None = None + for s_idx in range(1, n_sub + 1): + ta = t0 + (t1 - t0) * ((s_idx - 1) / n_sub) + tb = t0 + (t1 - t0) * (s_idx / n_sub) + if options.voltage_interpolation == "piecewise_linear": + v_sub = v0 + (v1 - v0) * (s_idx / n_sub) + g_sub = g0 + (g1 - g0) * (s_idx / n_sub) + else: + v_sub = v1 + g_sub = g1 + + req_order = 1 if (abrupt and s_idx == 1) else options.bdf_order + hp_new, last_step = _advance_substep_recursive( + compiled, + sys_tr, + history, + ta, + tb, + v_sub, + g_sub, + req_order, + options, + options.max_step_halvings, + ) + history = (hp_new, history[0]) + + assert last_step is not None + u_now = history[0].u + acc = dynamic_defect_step_accounting(last_step, u_now) + j_cond[k] = acc["conduction_current_density_A_m2"] + j_ion[k] = acc["ionic_current_density_A_m2"] + j_disp[k] = acc["displacement_current_density_A_m2"] + j_tot[k] = acc["total_current_density_A_m2"] + j_term[k] = acc["terminal_current_density_A_m2"] + spreads[k] = acc["maxwell_spread_A_m2"] + max_inv_drift = max(max_inv_drift, record_state(k, u_now, v1)) + + return DynamicDefectTransientResult( + capability=capability, + device=compiled, + grid_m=compiled.nodes_m, + times_s=times, + voltage_V=voltages, + generation_scale=generations, + terminal_current_density_A_m2=j_term, + conduction_current_faces_A_m2=j_cond, + ionic_current_faces_A_m2=j_ion, + displacement_current_faces_A_m2=j_disp, + total_current_faces_A_m2=j_tot, + maxwell_spread_A_m2=spreads, + potential_V=pot, + electron_density_m3=n_arr, + hole_density_m3=p_arr, + bulk_trap_occupancy=bt_occ, + interface_trap_occupancy=it_occ, + interface_sheet_charges_C_m2=sheets, + positive_ion_density_m3=pos_ion, + positive_ion_centroid_m=pos_centroid, + maximum_ion_inventory_relative_drift=max_inv_drift, + maximum_maxwell_spread_A_m2=float(np.max(spreads)), + ) + + +def solve_dynamic_defect_transient( + prepared: PreparedDevice, + times_s: ArrayLike, + voltage_V: ArrayLike, + *, + illuminated: bool = False, + options: DynamicDefectTransientOptions | None = None, +) -> DynamicDefectTransientResult: + """Solve the narrow v1 production dark interface-defect + positive-ion transient.""" + controls = DynamicDefectTransientOptions() if options is None else options + if not isinstance(illuminated, (bool, np.bool_)): + raise TypeError("illuminated must be boolean") + if bool(illuminated): + raise DynamicDefectTransientCapabilityError( + "the v1 production dynamic-defect transient capability is dark-only" + ) + if controls.voltage_interpolation != "right_continuous_step_and_hold": + raise DynamicDefectTransientCapabilityError( + "v1 production dynamic-defect transient requires right_continuous_step_and_hold" + ) + capability = classify_dynamic_defect_transient_capability(prepared) + times, voltages, generations = _validate_traces(times_s, voltage_V, 0.0) + + elec_layers = [ly for ly in prepared.layers if ly.role != "substrate"] + ion_layer = next( + ly.id + for ly in elec_layers + if _layer_param_float(ly, "D_ion") > 0.0 + and _layer_param_float(ly, "P0") > 0.0 + ) + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=False, + dynamic_interface_defects=True, + ion_domain_layer=ion_layer, + ion_domain_endpoints=controls.ion_domain_endpoints, + ) + except CapabilityError as error: + raise DynamicDefectTransientCapabilityError(str(error)) from error + + return _run_unified_transient(capability, compiled, times, voltages, generations, controls) + + +def solve_bulk_defect_transient( + prepared: PreparedDevice, + times_s: ArrayLike, + voltage_V: ArrayLike, + *, + generation_scale: float | ArrayLike = 0.0, + options: DynamicDefectTransientOptions | None = None, +) -> DynamicDefectTransientResult: + """Solve charged single-level non-spatial ion-free bulk-defect transient (D6-E1).""" + controls = DynamicDefectTransientOptions() if options is None else options + times, voltages, generations = _validate_traces(times_s, voltage_V, generation_scale) + + elec_layers = [ly for ly in prepared.layers if ly.role != "substrate"] + if _require_uncalibrated_interface_defects(prepared) > 0: + raise DynamicDefectTransientCapabilityError( + "solve_bulk_defect_transient excludes interface defects" + ) + has_bulk = False + for ly in elec_layers: + if ( + _layer_param_float(ly, "D_ion") > 0.0 + and _layer_param_float(ly, "P0") > 0.0 + ) or ( + _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ): + raise DynamicDefectTransientCapabilityError( + "solve_bulk_defect_transient excludes active mobile ions" + ) + if ly.bulk_trap_distribution_json is not None or ly.metastable_document is not None: + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}: solve_bulk_defect_transient supports only explicit single-level bulk defects" + ) + if ly.defect_schema_version == "solarlab-explicit-bulk-defects-v4": + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}: multivalent bulk defects are refused in D6-E1 bulk transient" + ) + for raw_bd in ly.defects: + bd = raw_bd.to_mapping() + has_bulk = True + if str(bd.get("charge_transition")) == "neutral": + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}.{bd['id']}: charge-coupled bulk transient rejects neutral transitions" + ) + dist = bd.get("distribution", {}) + if str(dist.get("kind", "single_level")) != "single_level": + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}.{bd['id']}: D6-E1 bulk transient requires single_level distribution" + ) + sp = bd.get("spatial_profile") + if sp is not None and str(sp.get("kind", "uniform")) != "uniform": + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}.{bd['id']}: D6-E1 bulk transient rejects non-uniform spatial_profile" + ) + if not has_bulk: + raise DynamicDefectTransientCapabilityError( + "solve_bulk_defect_transient requires at least one explicit charged bulk defect" + ) + + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=True, + dynamic_interface_defects=False, + ) + except CapabilityError as error: + raise DynamicDefectTransientCapabilityError(str(error)) from error + + return _run_unified_transient( + "bulk_defect_transient", compiled, times, voltages, generations, controls + ) + + +def solve_interface_defect_transient( + prepared: PreparedDevice, + times_s: ArrayLike, + voltage_V: ArrayLike, + *, + generation_scale: float | ArrayLike = 0.0, + options: DynamicDefectTransientOptions | None = None, +) -> DynamicDefectTransientResult: + """Solve ion-free two-sided dynamic interface-defect transient (D6-E2).""" + controls = DynamicDefectTransientOptions() if options is None else options + times, voltages, generations = _validate_traces(times_s, voltage_V, generation_scale) + + for ly in prepared.layers: + if ly.role == "substrate": + continue + if ly.defects or ly.bulk_trap_distribution_json is not None or ly.metastable_document is not None: + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_transient excludes bulk explicit defects" + ) + if ( + _layer_param_float(ly, "D_ion") > 0.0 + and _layer_param_float(ly, "P0") > 0.0 + ) or ( + _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ): + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_transient excludes active mobile ions" + ) + if _require_uncalibrated_interface_defects(prepared) < 1: + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_transient requires at least one microscopic interface defect" + ) + settings = prepared.to_mapping()["settings"] + if str(settings.get("interface_charge_closure", "off")) != "equilibrium_referenced": + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_transient requires equilibrium_referenced interface charge" + ) + + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=False, + dynamic_interface_defects=True, + ) + except CapabilityError as error: + raise DynamicDefectTransientCapabilityError(str(error)) from error + + return _run_unified_transient( + "interface_defect_transient", compiled, times, voltages, generations, controls + ) + + +def _single_ion_layer(prepared: PreparedDevice) -> str: + layers = [ + ly.id + for ly in prepared.layers + if ly.role != "substrate" + and ( + (_layer_param_float(ly, "D_ion") > 0.0 and _layer_param_float(ly, "P0") > 0.0) + or ( + _layer_param_float(ly, "D_ion_neg") > 0.0 + and _layer_param_float(ly, "P0_neg") > 0.0 + ) + ) + ] + if len(layers) != 1: + raise DynamicDefectTransientCapabilityError( + "coupled defect-ion transient requires exactly one active mobile-ion layer" + ) + return layers[0] + + +def solve_bulk_defect_ion_transient( + prepared: PreparedDevice, + times_s: ArrayLike, + voltage_V: ArrayLike, + *, + generation_scale: float | ArrayLike = 0.0, + options: DynamicDefectTransientOptions | None = None, +) -> DynamicDefectTransientResult: + """Solve coupled dynamic bulk-defect + mobile-ion transient (D6-E3a).""" + controls = DynamicDefectTransientOptions() if options is None else options + times, voltages, generations = _validate_traces(times_s, voltage_V, generation_scale) + if _require_uncalibrated_interface_defects(prepared) > 0: + raise DynamicDefectTransientCapabilityError( + "solve_bulk_defect_ion_transient excludes interface defects" + ) + ion_layer = _single_ion_layer(prepared) + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=True, + dynamic_interface_defects=False, + ion_domain_layer=ion_layer, + ion_domain_endpoints=controls.ion_domain_endpoints, + ) + except CapabilityError as error: + raise DynamicDefectTransientCapabilityError(str(error)) from error + if not compiled.has_dynamic_bulk_traps: + raise DynamicDefectTransientCapabilityError( + "solve_bulk_defect_ion_transient requires explicit bulk defects" + ) + + return _run_unified_transient( + "bulk_defect_ion_transient", compiled, times, voltages, generations, controls + ) + + +def solve_interface_defect_ion_transient( + prepared: PreparedDevice, + times_s: ArrayLike, + voltage_V: ArrayLike, + *, + generation_scale: float | ArrayLike = 0.0, + options: DynamicDefectTransientOptions | None = None, +) -> DynamicDefectTransientResult: + """Solve coupled dynamic interface-defect + mobile-ion transient (D6-E3b).""" + controls = DynamicDefectTransientOptions() if options is None else options + times, voltages, generations = _validate_traces(times_s, voltage_V, generation_scale) + for ly in prepared.layers: + if ly.role != "substrate" and ( + ly.defects or ly.bulk_trap_distribution_json is not None or ly.metastable_document is not None + ): + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_ion_transient excludes bulk explicit defects" + ) + if _require_uncalibrated_interface_defects(prepared) < 1: + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_ion_transient requires at least one microscopic interface defect" + ) + ion_layer = _single_ion_layer(prepared) + try: + compiled = compile_dynamic_defect_device_1d( + prepared, + intervals_per_layer=controls.intervals_per_layer, + dynamic_bulk_defects=False, + dynamic_interface_defects=True, + ion_domain_layer=ion_layer, + ion_domain_endpoints=controls.ion_domain_endpoints, + ) + except CapabilityError as error: + raise DynamicDefectTransientCapabilityError(str(error)) from error + + return _run_unified_transient( + "interface_defect_ion_transient", compiled, times, voltages, generations, controls + ) diff --git a/src/solarlab/experiments/metastable_transient.py b/src/solarlab/experiments/metastable_transient.py new file mode 100644 index 00000000..1ce70b7b --- /dev/null +++ b/src/solarlab/experiments/metastable_transient.py @@ -0,0 +1,749 @@ +"""Metastable configuration preparation, frozen measurement, and operator-split transients. + +Implements the explicit two-stage SCAPS-like metastable defect workflow on +``CompiledMetastableDevice1D`` + ``solve_dynamic_defect_steady_1d``: + +1. ``prepare_metastable_state``: clamped outer fixed-point ``y = Y(n(y), p(y))`` + at the declared preparation working point, followed by a mandatory unclamped + refinement step so a clamped iterate can never masquerade as converged. +2. ``solve_frozen_metastable_steady`` / ``solve_frozen_metastable_jv``: bias + measurement at ``measurement_temperature_K`` with frozen configuration + fractions ``y`` strictly preserved. +3. ``solve_metastable_transient``: sequential operator-split integration + advancing ``y(t)`` analytically via ``advance_metastable_configuration``, + gating both exact two-charge configuration transfer bookkeeping and + halved-``dt`` operator-splitting error. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from hashlib import sha256 +import json +import math +from typing import TypeAlias + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import frozen_array +from solarlab.device.compile_dynamic_defect_1d import compile_metastable_device_1d +from solarlab.device.defects import MetastablePreparationInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + DynamicDefectSteadyOptions, + DynamicDefectSteadyResult, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dc_1d import CapabilityError +from solarlab.equations.dynamic_defect_1d import ( + CompiledDynamicDefectDevice1D, + CompiledMetastableDevice1D, +) +from solarlab.physics.defects import ( + MultivalentSpeciesSpec, + advance_metastable_configuration, + configuration_charge_transfer_C_m3, + configuration_from_logit, + configuration_logit, + evaluate_metastable_configuration_closure, + evaluate_multivalent_defect_closure, +) + +Vector: TypeAlias = NDArray[np.float64] + +METASTABLE_TRANSIENT_SCHEME = "solarlab.metastable-operator-split-transient.v1" + +__all__ = [ + "METASTABLE_TRANSIENT_SCHEME", + "FrozenMetastableJVPoint", + "FrozenMetastableJVResult", + "MetastableCapabilityError", + "MetastablePreparationError", + "MetastableTransientCertificate", + "MetastableTransientError", + "MetastableTransientResult", + "PreparedMetastableState", + "prepare_metastable_state", + "solve_frozen_metastable_jv", + "solve_frozen_metastable_steady", + "solve_metastable_transient", +] + + +class MetastablePreparationError(RuntimeError): + """Raised when metastable configuration preparation or frozen provenance fails.""" + + +class MetastableTransientError(RuntimeError): + """Raised when operator-split metastable transient integration fails.""" + + +class MetastableCapabilityError(MetastableTransientError, CapabilityError): + """Raised when a device violates metastable preparation/transient capabilities.""" + + +def _array_digest(label: str, *arrays: ArrayLike) -> str: + h = sha256(label.encode("ascii")) + for arr in arrays: + contig = np.ascontiguousarray(np.asarray(arr, dtype=" None: + frozen_fracs = tuple(frozen_array(f) for f in self.donor_fractions) + object.__setattr__(self, "donor_fractions", frozen_fracs) + object.__setattr__(self, "grid_m", frozen_array(self.grid_m)) + act = np.array(self.active_nodes, dtype=bool, copy=True) + act.setflags(write=False) + object.__setattr__(self, "active_nodes", act) + + @property + def donor_fraction(self) -> Vector: + if len(self.donor_fractions) != 1: + raise ValueError("donor_fraction convenience property requires a single metastable species") + return self.donor_fractions[0] + + +@dataclass(frozen=True) +class FrozenMetastableJVPoint: + """One bias point on a frozen metastable J-V sweep.""" + + voltage_V: float + current_density_A_m2: float + steady: DynamicDefectSteadyResult + + +@dataclass(frozen=True) +class FrozenMetastableJVResult: + """J-V sweep measured against a strictly frozen metastable configuration.""" + + voltages_V: Vector + current_densities_A_m2: Vector + points: tuple[FrozenMetastableJVPoint, ...] + donor_fractions: tuple[Vector, ...] + measurement_temperature_K: float + generation_scale: float + preparation_state_sha256: str + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + object.__setattr__(self, "voltages_V", frozen_array(self.voltages_V)) + object.__setattr__( + self, "current_densities_A_m2", frozen_array(self.current_densities_A_m2) + ) + object.__setattr__( + self, "donor_fractions", tuple(frozen_array(f) for f in self.donor_fractions) + ) + + +@dataclass(frozen=True, slots=True) +class MetastableTransientCertificate: + """Numerical splitting and charge-transfer audit for one metastable transient.""" + + scheme: str + passed: bool + reasons: tuple[str, ...] + step_count: int + minimum_fraction: float + maximum_fraction: float + maximum_state_residual: float + maximum_charge_transfer_relative_error: float + maximum_refinement_fraction_change: float + maximum_step_over_relaxation_time: float + minimum_relaxation_time_s: float + + +@dataclass(frozen=True) +class MetastableTransientResult: + """Operator-split dynamic metastable configuration trajectory.""" + + times_s: Vector + donor_fractions: tuple[Vector, ...] + stationary_fractions: tuple[Vector, ...] + relaxation_times_s: tuple[Vector, ...] + configuration_charge_transfer_C_m2: Vector + terminal_current_density_A_m2: Vector + states: tuple[DynamicDefectSteadyResult, ...] + certificate: MetastableTransientCertificate + preparation_protocol_sha256: str + preparation_state_sha256: str + scientific_qualification: bool = False + physical_certificate_status: str = "not_evaluated" + + def __post_init__(self) -> None: + object.__setattr__(self, "times_s", frozen_array(self.times_s)) + object.__setattr__( + self, "donor_fractions", tuple(frozen_array(f) for f in self.donor_fractions) + ) + object.__setattr__( + self, + "stationary_fractions", + tuple(frozen_array(f) for f in self.stationary_fractions), + ) + object.__setattr__( + self, "relaxation_times_s", tuple(frozen_array(f) for f in self.relaxation_times_s) + ) + object.__setattr__( + self, + "configuration_charge_transfer_C_m2", + frozen_array(self.configuration_charge_transfer_C_m2), + ) + object.__setattr__( + self, + "terminal_current_density_A_m2", + frozen_array(self.terminal_current_density_A_m2), + ) + + @property + def donor_fraction(self) -> Vector: + if len(self.donor_fractions) != 1: + raise ValueError("donor_fraction convenience property requires a single metastable species") + return self.donor_fractions[0] + + +def prepare_metastable_state( + device_or_prepared: CompiledMetastableDevice1D | PreparedDevice, + *, + preparation: MetastablePreparationInput | None = None, + intervals_per_layer: int | Sequence[int] = 24, + steady_options: DynamicDefectSteadyOptions | None = None, +) -> PreparedMetastableState: + """Solve clamped outer fixed point + mandatory unclamped refinement for ``y``.""" + if isinstance(device_or_prepared, CompiledMetastableDevice1D): + meta_dev = device_or_prepared + elif isinstance(device_or_prepared, PreparedDevice): + try: + meta_dev = compile_metastable_device_1d( + device_or_prepared, intervals_per_layer=intervals_per_layer + ) + except CapabilityError as error: + raise MetastableCapabilityError(str(error)) from error + else: + raise TypeError( + "device_or_prepared must be CompiledMetastableDevice1D or PreparedDevice" + ) + + proto = preparation if preparation is not None else meta_dev.preparation + if proto is None: + raise MetastablePreparationError( + "metastable preparation requires a MetastablePreparationInput protocol" + ) + + if hasattr(proto, "model_dump"): + proto_dict = proto.model_dump() + elif hasattr(proto, "to_mapping"): + proto_dict = proto.to_mapping() + elif isinstance(proto, Mapping): + proto_dict = dict(proto) + else: + raise TypeError("unsupported metastable preparation protocol type") + numerics = proto_dict["numerics"] + prep_v = float(proto_dict["preparation_voltage_V"]) + prep_t = float(proto_dict["preparation_temperature_K"]) + prep_suns = float(proto_dict["preparation_illumination_suns"]) + meas_t = float(proto_dict["measurement_temperature_K"]) + freeze_flag = bool(proto_dict["freeze_configuration_during_measurement"]) + + init_guess = float(numerics["initial_donor_fraction_guess"]) + if not 0.0 < init_guess < 1.0: + raise MetastablePreparationError( + "initial_donor_fraction_guess must lie strictly inside (0, 1)" + ) + clamp = float(numerics["clamping_factor"]) + tol = float(numerics["relative_tolerance"]) + max_iters = int(numerics["max_iterations"]) + + m_active = meta_dev.active_node_count + mask = meta_dev.active_nodes + specs = meta_dev.metastable_specs + + fractions: list[Vector] = [np.full(m_active, init_guess, dtype=np.float64) for _ in specs] + + def evaluate_outer( + current_fracs: Sequence[Vector], + ) -> tuple[DynamicDefectSteadyResult, list[Vector]]: + frozen_dev = meta_dev.compile_frozen_device(current_fracs, temperature_K=prep_t) + assert frozen_dev.stationary_defects is not None + prep_reg = frozen_dev.stationary_defects.metastable_regions[0] + eg_prep = float(prep_reg.band_gap_eV[0]) + nc_prep = float(prep_reg.effective_conduction_dos_m3[0]) + nv_prep = float(prep_reg.effective_valence_dos_m3[0]) + try: + steady = solve_dynamic_defect_steady_1d( + frozen_dev, + voltage_V=prep_v, + generation_scale=prep_suns, + options=steady_options, + ) + except RuntimeError as error: + raise MetastablePreparationError( + f"metastable preparation electronic solve failed: {error}" + ) from error + n_act = steady.state.electronic_state.electron_density_m3[mask] + p_act = steady.state.electronic_state.hole_density_m3[mask] + targets: list[Vector] = [] + for sp in specs: + cl = evaluate_metastable_configuration_closure( + n_act, + p_act, + sp, + band_gap_eV=eg_prep, + effective_conduction_dos_m3=nc_prep, + effective_valence_dos_m3=nv_prep, + temperature_K=prep_t, + ) + targets.append(np.array(cl.donor_fraction, dtype=np.float64, copy=True)) + return steady, targets + + clamped_iters = 0 + rel_change = math.inf + steady_curr: DynamicDefectSteadyResult | None = None + + for outer_iter in range(1, max_iters + 1): + steady_curr, targets = evaluate_outer(fractions) + rel_change = max( + float(np.max(np.abs(tgt - cur))) / max(float(np.max(np.abs(cur))), 1.0e-12) + for cur, tgt in zip(fractions, targets) + ) + if clamp < 1.0: + clamped_iters += 1 + fractions = [cur + clamp * (tgt - cur) for cur, tgt in zip(fractions, targets)] + if any(not np.all(np.isfinite(f)) for f in fractions): + raise MetastablePreparationError( + "metastable preparation produced non-finite donor fraction" + ) + if rel_change <= tol: + break + else: + raise MetastablePreparationError( + f"metastable preparation did not converge within {max_iters} iterations " + f"(last change {rel_change:.4e} > {tol:.4e})" + ) + + # Mandatory unclamped refinement step: + _, unclamped_targets = evaluate_outer(fractions) + unclamped_change = max( + float(np.max(np.abs(tgt - cur))) / max(float(np.max(np.abs(cur))), 1.0e-12) + for cur, tgt in zip(fractions, unclamped_targets) + ) + fractions = unclamped_targets + if unclamped_change > tol: + raise MetastablePreparationError( + f"final unclamped metastable refinement exceeded tolerance: " + f"{unclamped_change:.4e} > {tol:.4e}" + ) + + final_steady, _ = evaluate_outer(fractions) + meas_dev = meta_dev.compile_frozen_device(fractions, temperature_K=meas_t) + + proto_sha = sha256( + json.dumps(proto_dict, sort_keys=True, separators=(",", ":")).encode("ascii") + ).hexdigest() + state_sha = _array_digest( + "solarlab-metastable-prepared-state-v1", + meta_dev.base_electronic_device.nodes_m, + *fractions, + final_steady.state.u, + np.array([prep_v, prep_t, prep_suns, meas_t]), + ) + return PreparedMetastableState( + compiled_metastable=meta_dev, + frozen_measurement_device=meas_dev, + donor_fractions=tuple(fractions), + active_nodes=mask, + grid_m=meta_dev.base_electronic_device.nodes_m, + preparation_steady=final_steady, + outer_iterations=outer_iter, + clamped_iterations=clamped_iters, + final_relative_change=rel_change, + unclamped_refinement_change=unclamped_change, + preparation_voltage_V=prep_v, + preparation_temperature_K=prep_t, + preparation_illumination_suns=prep_suns, + measurement_temperature_K=meas_t, + freeze_configuration_during_measurement=freeze_flag, + protocol_sha256=proto_sha, + state_sha256=state_sha, + ) + + +def solve_frozen_metastable_steady( + prepared_state: PreparedMetastableState, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + steady_options: DynamicDefectSteadyOptions | None = None, +) -> DynamicDefectSteadyResult: + """Solve one steady working point against a strictly frozen configuration.""" + if not isinstance(prepared_state, PreparedMetastableState): + raise TypeError("prepared_state must be PreparedMetastableState") + if not prepared_state.freeze_configuration_during_measurement: + raise MetastablePreparationError( + "measurement requires freeze_configuration_during_measurement=True" + ) + try: + return solve_dynamic_defect_steady_1d( + prepared_state.frozen_measurement_device, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=steady_options, + ) + except RuntimeError as error: + raise MetastablePreparationError( + f"frozen metastable steady solve failed: {error}" + ) from error + + +def solve_frozen_metastable_jv( + prepared_state: PreparedMetastableState, + voltages_V: ArrayLike, + *, + generation_scale: float = 0.0, + steady_options: DynamicDefectSteadyOptions | None = None, +) -> FrozenMetastableJVResult: + """Sweep J-V at ``measurement_temperature_K`` without updating ``donor_fractions``.""" + if not isinstance(prepared_state, PreparedMetastableState): + raise TypeError("prepared_state must be PreparedMetastableState") + if not prepared_state.freeze_configuration_during_measurement: + raise MetastablePreparationError( + "J-V measurement requires freeze_configuration_during_measurement=True" + ) + v_arr = np.asarray(voltages_V, dtype=np.float64) + if v_arr.ndim != 1 or v_arr.size < 1 or not np.all(np.isfinite(v_arr)): + raise ValueError("voltages_V must be a non-empty 1D array of finite biases") + + f_dev = prepared_state.frozen_measurement_device + points: list[FrozenMetastableJVPoint] = [] + j_arr = np.empty(v_arr.size, dtype=np.float64) + prev_u: Vector | None = None + prev_v = 0.0 + + for idx, v_val in enumerate(v_arr): + vf = float(v_val) + seed_u: Vector | None = None + if prev_u is not None and abs(vf - prev_v) <= 0.15: + seed_u = f_dev.rebase_coordinates(prev_u, prev_v, vf) + N = f_dev.node_count + phi_l, phi_r = f_dev.electronic_component.contact_potentials(vf) + dv = (phi_r - phi_l) - (seed_u[N - 1] - seed_u[0]) + nodes = f_dev.nodes_m + seed_u[:N] += dv * (nodes - nodes[0]) / (nodes[-1] - nodes[0]) + try: + st = solve_dynamic_defect_steady_1d( + f_dev, + voltage_V=vf, + generation_scale=generation_scale, + initial_u=seed_u, + options=steady_options, + ) + except RuntimeError: + st = solve_dynamic_defect_steady_1d( + f_dev, + voltage_V=vf, + generation_scale=generation_scale, + options=steady_options, + ) + points.append( + FrozenMetastableJVPoint( + voltage_V=vf, + current_density_A_m2=st.terminal_current_density_A_m2, + steady=st, + ) + ) + j_arr[idx] = st.terminal_current_density_A_m2 + prev_u = st.state.u + prev_v = vf + + return FrozenMetastableJVResult( + voltages_V=v_arr, + current_densities_A_m2=j_arr, + points=tuple(points), + donor_fractions=prepared_state.donor_fractions, + measurement_temperature_K=prepared_state.measurement_temperature_K, + generation_scale=float(generation_scale), + preparation_state_sha256=prepared_state.state_sha256, + ) + + +def _run_operator_split_trace( + prepared_state: PreparedMetastableState, + times: Vector, + *, + voltage_V: float, + generation_scale: float, + keep_states: bool, + steady_options: DynamicDefectSteadyOptions | None, +) -> tuple[ + tuple[Vector, ...], + tuple[Vector, ...], + tuple[Vector, ...], + list[float], + list[DynamicDefectSteadyResult], + list[float], + Vector, + Vector, +]: + meta_dev = prepared_state.compiled_metastable + specs = meta_dev.metastable_specs + mask = prepared_state.active_nodes + grid = prepared_state.grid_m + meas_t = prepared_state.measurement_temperature_K + assert prepared_state.frozen_measurement_device.stationary_defects is not None + meas_reg = prepared_state.frozen_measurement_device.stationary_defects.metastable_regions[0] + eg = float(meas_reg.band_gap_eV[0]) + nc = float(meas_reg.effective_conduction_dos_m3[0]) + nv = float(meas_reg.effective_valence_dos_m3[0]) + + # Round-trip through logit to reject boundary-saturated prepared fractions: + curr_fracs = [ + configuration_from_logit(configuration_logit(np.asarray(f, dtype=np.float64))) + for f in prepared_state.donor_fractions + ] + + T = times.size + m_act = meta_dev.active_node_count + frac_hist = [np.zeros((T, m_act), dtype=np.float64) for _ in specs] + stat_hist = [np.zeros((T - 1, m_act), dtype=np.float64) for _ in specs] + tau_hist = [np.zeros((T - 1, m_act), dtype=np.float64) for _ in specs] + for s_idx, cf in enumerate(curr_fracs): + frac_hist[s_idx][0] = cf + + charge_errors: list[float] = [] + states: list[DynamicDefectSteadyResult] = [] + step_ratios: list[float] = [] + areal_transfers = np.zeros(T - 1, dtype=np.float64) + j_trace = np.zeros(T, dtype=np.float64) + + for k in range(T): + dev_k = meta_dev.compile_frozen_device(curr_fracs, temperature_K=meas_t) + try: + steady_k = solve_dynamic_defect_steady_1d( + dev_k, + voltage_V=voltage_V, + generation_scale=generation_scale, + options=steady_options, + ) + except RuntimeError as error: + raise MetastableTransientError( + f"metastable transient step {k} failed electronic solve: {error}" + ) from error + + j_trace[k] = steady_k.terminal_current_density_A_m2 + if keep_states: + states.append(steady_k) + if k == T - 1: + break + + dt = float(times[k + 1] - times[k]) + n_full = steady_k.state.electronic_state.electron_density_m3 + p_full = steady_k.state.electronic_state.hole_density_m3 + n_act = n_full[mask] + p_act = p_full[mask] + + next_fracs: list[Vector] = [] + pred_delta_rho: Vector = np.zeros(m_act, dtype=np.float64) + for s_idx, (sp, cf) in enumerate(zip(specs, curr_fracs)): + cl = evaluate_metastable_configuration_closure( + n_act, + p_act, + sp, + band_gap_eV=eg, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=meas_t, + ) + adv = advance_metastable_configuration(cf, cl, dt) + donor_cl = evaluate_multivalent_defect_closure( + n_act, + p_act, + MultivalentSpeciesSpec(f"{sp.identifier}:donor", 1.0, sp.donor_configuration), + band_gap_eV=eg, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=meas_t, + ) + acc_cl = evaluate_multivalent_defect_closure( + n_act, + p_act, + MultivalentSpeciesSpec( + f"{sp.identifier}:acceptor", 1.0, sp.acceptor_configuration + ), + band_gap_eV=eg, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=meas_t, + ) + next_fracs.append(np.array(adv.next_donor_fraction, dtype=np.float64, copy=True)) + frac_hist[s_idx][k + 1] = adv.next_donor_fraction + stat_hist[s_idx][k] = adv.stationary_donor_fraction + tau_hist[s_idx][k] = 1.0 / adv.total_conversion_rate_s1 + pred_delta_rho += configuration_charge_transfer_C_m3( + sp.total_density_m3, + donor_cl.mean_charge_e, + acc_cl.mean_charge_e, + adv.delta_donor_fraction, + ) + step_ratios.append(float(np.max(dt * adv.total_conversion_rate_s1))) + + assert dev_k.stationary_defects is not None + dev_next = meta_dev.compile_frozen_device(next_fracs, temperature_K=meas_t) + assert dev_next.stationary_defects is not None + rho_before = dev_k.stationary_defects.evaluate(n_full, p_full).charge_density_C_m3[mask] + rho_after = dev_next.stationary_defects.evaluate(n_full, p_full).charge_density_C_m3[mask] + measured_delta = rho_after - rho_before + scale = max(float(np.max(np.abs(rho_before))), np.finfo(float).tiny) + charge_errors.append(float(np.max(np.abs(measured_delta - pred_delta_rho)) / scale)) + + areal_vec = np.zeros(grid.size, dtype=np.float64) + areal_vec[mask] = pred_delta_rho + areal_transfers[k] = float(np.trapezoid(areal_vec, grid)) + curr_fracs = next_fracs + + return ( + tuple(frac_hist), + tuple(stat_hist), + tuple(tau_hist), + charge_errors, + states, + step_ratios, + areal_transfers, + j_trace, + ) + + +def solve_metastable_transient( + prepared_state: PreparedMetastableState, + times_s: ArrayLike, + *, + voltage_V: float = 0.0, + generation_scale: float = 0.0, + maximum_charge_transfer_relative_error: float = 1.0e-10, + maximum_refinement_fraction_change: float = 5.0e-3, + require_certificate: bool = True, + steady_options: DynamicDefectSteadyOptions | None = None, +) -> MetastableTransientResult: + """Integrate dynamic metastable configuration evolution via operator splitting + dt/2 audit.""" + if not isinstance(prepared_state, PreparedMetastableState): + raise TypeError("prepared_state must be PreparedMetastableState") + times = np.asarray(times_s, dtype=np.float64) + if ( + times.ndim != 1 + or times.size < 2 + or not np.all(np.isfinite(times)) + or times[0] != 0.0 + or np.any(np.diff(times) <= 0.0) + ): + raise ValueError("times_s must start at 0.0 and strictly increase") + if not math.isfinite(voltage_V) or not math.isfinite(generation_scale) or generation_scale < 0.0: + raise ValueError("voltage_V must be finite and generation_scale >= 0") + if maximum_charge_transfer_relative_error <= 0.0 or maximum_refinement_fraction_change <= 0.0: + raise ValueError("certificate tolerances must be positive") + + ( + fracs, + stats, + taus, + charge_errs, + states, + ratios, + areal_transfers, + j_trace, + ) = _run_operator_split_trace( + prepared_state, + times, + voltage_V=voltage_V, + generation_scale=generation_scale, + keep_states=True, + steady_options=steady_options, + ) + + refined_times = np.unique(np.concatenate([times, 0.5 * (times[:-1] + times[1:])])) + refined_fracs, *_ = _run_operator_split_trace( + prepared_state, + refined_times, + voltage_V=voltage_V, + generation_scale=generation_scale, + keep_states=False, + steady_options=steady_options, + ) + sampled = np.searchsorted(refined_times, times) + refinement_change = max( + float(np.max(np.abs(rf[sampled] - cf))) + for rf, cf in zip(refined_fracs, fracs) + ) + + min_frac = min(float(np.min(cf)) for cf in fracs) + max_frac = max(float(np.max(cf)) for cf in fracs) + max_q_err = max(charge_errs) if charge_errs else 0.0 + max_res = max(st.residual_inf_norm for st in states) + min_tau = min(float(np.min(tv)) for tv in taus) if taus else math.inf + + reasons: list[str] = [] + if min_frac <= 0.0 or max_frac >= 1.0: + reasons.append("configuration_fraction_left_open_interval") + if max_q_err > maximum_charge_transfer_relative_error: + reasons.append("configuration_charge_transfer_mismatch") + if refinement_change > maximum_refinement_fraction_change: + reasons.append("operator_splitting_not_resolved") + if not all(st.converged for st in states): + reasons.append("unconverged_carrier_state") + + cert = MetastableTransientCertificate( + scheme=METASTABLE_TRANSIENT_SCHEME, + passed=not reasons, + reasons=tuple(reasons), + step_count=int(times.size), + minimum_fraction=min_frac, + maximum_fraction=max_frac, + maximum_state_residual=max_res, + maximum_charge_transfer_relative_error=max_q_err, + maximum_refinement_fraction_change=refinement_change, + maximum_step_over_relaxation_time=max(ratios) if ratios else 0.0, + minimum_relaxation_time_s=min_tau, + ) + if require_certificate and not cert.passed: + raise MetastableTransientError( + "metastable transient failed numerical audit: " + ", ".join(cert.reasons) + ) + + return MetastableTransientResult( + times_s=times, + donor_fractions=fracs, + stationary_fractions=stats, + relaxation_times_s=taus, + configuration_charge_transfer_C_m2=areal_transfers, + terminal_current_density_A_m2=j_trace, + states=tuple(states), + certificate=cert, + preparation_protocol_sha256=prepared_state.protocol_sha256, + preparation_state_sha256=prepared_state.state_sha256, + ) diff --git a/src/solarlab/physics/defects/__init__.py b/src/solarlab/physics/defects/__init__.py new file mode 100644 index 00000000..5f3354bd --- /dev/null +++ b/src/solarlab/physics/defects/__init__.py @@ -0,0 +1,173 @@ +"""Defect constitutive laws: distributions, monovalent/dynamic, multivalent, metastable.""" + +from solarlab.physics.defects.distributions import ( + DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + DENSITY_INTEGRATED, + DENSITY_PEAK, + DIST_CONDUCTION_BAND_TAIL, + DIST_GAUSSIAN, + DIST_SINGLE_LEVEL, + DIST_UNIFORM, + DIST_VALENCE_BAND_TAIL, + DefectDistributionSpec, + DefectEnergyQuadrature, + MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER, + MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER, + SUPPORTED_DISTRIBUTIONS, + SpatialDensityProfileSpec, + SpatialProfileKnot, + WIDTH_GAUSSIAN_SIGMA, + WIDTH_NOT_APPLICABLE, + WIDTH_SCAPS_CHARACTERISTIC, + WIDTH_UNIFORM_FULL, + build_defect_energy_quadrature, + density_weighted_mean_occupancy, + distribution_shape_integral_eV, + evaluate_spatial_density_profile, + integrated_density_from_peak_density, + peak_density_from_integrated_density, + validate_defect_energy_quadrature_order, +) +from solarlab.physics.defects.dynamic_single_level import ( + DynamicBulkTrapEvaluation, + DynamicBulkTrapLayout, + DynamicBulkTrapMode, + DynamicInterfaceTrapEvaluation, + DynamicInterfaceTrapSpec, + MonovalentDefectClosureResult, + MonovalentDefectNeutralityState, + MonovalentDefectRegion, + MonovalentSpeciesSpec, + SUPPORTED_MONOVALENT_TRANSITIONS, + TRANSITION_ACCEPTOR, + TRANSITION_DONOR, + TRANSITION_NEUTRAL, + bulk_trap_charge_density, + compile_dynamic_bulk_trap_layout, + evaluate_dynamic_bulk_traps, + evaluate_dynamic_bulk_traps_about_qss, + evaluate_dynamic_interface_trap, + evaluate_monovalent_defect_closure, + evaluate_monovalent_region_closure, + logit_occupancy_secant, + occupancy_from_logit_increment, + occupancy_logit, + one_minus_occupancy_from_logit_increment, + quasi_steady_bulk_trap_logit, + quasi_steady_bulk_trap_occupancy, + solve_monovalent_defect_charge_neutrality, + stable_expit, +) +from solarlab.physics.defects.metastable import ( + DOUBLE_ELECTRON_CAPTURE, + DOUBLE_HOLE_CAPTURE, + ELECTRON_CAPTURE_PLUS_HOLE_EMISSION, + FrozenMetastableEvaluation, + FrozenMetastableRegion, + HOLE_CAPTURE_PLUS_ELECTRON_EMISSION, + MetastableConfigurationClosureResult, + MetastableConversionKineticsSpec, + MetastableDefectSpec, + MetastableDynamicStep, + advance_metastable_configuration, + configuration_charge_transfer_C_m3, + configuration_from_logit, + configuration_logit, + evaluate_frozen_metastable_region, + evaluate_metastable_configuration_closure, + solve_frozen_metastable_charge_neutrality, +) +from solarlab.physics.defects.multivalent import ( + MultivalentConfigurationSpec, + MultivalentDefectClosureResult, + MultivalentDefectNeutralityState, + MultivalentDefectRegion, + MultivalentSpeciesSpec, + MultivalentTransitionKineticsSpec, + evaluate_multivalent_defect_closure, + evaluate_multivalent_region_closure, + solve_multivalent_defect_charge_neutrality, +) + +__all__ = [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "SUPPORTED_DISTRIBUTIONS", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "advance_metastable_configuration", + "build_defect_energy_quadrature", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "peak_density_from_integrated_density", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_frozen_metastable_charge_neutrality", + "solve_monovalent_defect_charge_neutrality", + "solve_multivalent_defect_charge_neutrality", + "stable_expit", + "validate_defect_energy_quadrature_order", +] diff --git a/src/solarlab/physics/defects/distributions.py b/src/solarlab/physics/defects/distributions.py new file mode 100644 index 00000000..1d589786 --- /dev/null +++ b/src/solarlab/physics/defects/distributions.py @@ -0,0 +1,531 @@ +"""Energy-distributed and spatially graded bulk defect quadrature and profiles. + +All canonical defect energies use ``center_eV_above_vb`` (electron energy above +the local valence-band edge ``E_v``, bounded by ``[0, E_g]``). Quadrature rules +preserve exact zero-th moment ``sum(density_weights_m3) == total_density_m3`` +via inverse-CDF Gauss-Legendre nodes on bounded support. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math + +import numpy as np +from numpy.polynomial.legendre import leggauss +from numpy.typing import ArrayLike, NDArray +from scipy.special import ndtr, ndtri + +DIST_SINGLE_LEVEL = "single_level" +DIST_UNIFORM = "uniform" +DIST_GAUSSIAN = "gaussian" +DIST_CONDUCTION_BAND_TAIL = "conduction_band_tail" +DIST_VALENCE_BAND_TAIL = "valence_band_tail" +SUPPORTED_DISTRIBUTIONS = frozenset( + { + DIST_SINGLE_LEVEL, + DIST_UNIFORM, + DIST_GAUSSIAN, + DIST_CONDUCTION_BAND_TAIL, + DIST_VALENCE_BAND_TAIL, + } +) + +WIDTH_NOT_APPLICABLE = "not_applicable" +WIDTH_UNIFORM_FULL = "uniform_full_width" +WIDTH_GAUSSIAN_SIGMA = "gaussian_standard_deviation" +WIDTH_SCAPS_CHARACTERISTIC = "scaps_characteristic_energy" + +DENSITY_INTEGRATED = "integrated_total" +DENSITY_PEAK = "peak_density" + +DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER = 64 +MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER = 8 +MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER = 512 + +__all__ = [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "SUPPORTED_DISTRIBUTIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "build_defect_energy_quadrature", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "peak_density_from_integrated_density", + "validate_defect_energy_quadrature_order", +] + + +def _ro_float(values: ArrayLike) -> NDArray[np.float64]: + arr = np.array(values, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _finite(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be a finite real number") + number = float(value) + if not math.isfinite(number): + raise ValueError(f"{name} must be finite") + return number + + +def _finite_nonnegative(value: float, name: str) -> float: + number = _finite(value, name) + if number < 0.0: + raise ValueError(f"{name} must be non-negative") + return number + + +def _finite_positive(value: float, name: str) -> float: + number = _finite(value, name) + if number <= 0.0: + raise ValueError(f"{name} must be positive") + return number + + +def validate_defect_energy_quadrature_order(order: int) -> int: + """Validate energy quadrature order for continuous defect distributions.""" + if isinstance(order, bool) or not isinstance(order, int): + raise ValueError("defect energy quadrature order must be an integer") + if not ( + MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER + <= order + <= MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER + ): + raise ValueError( + f"defect energy quadrature order must lie in " + f"[{MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER}, " + f"{MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER}]" + ) + return order + + +def distribution_shape_integral_eV( + kind: str, + width_eV: float, + *, + width_convention: str = WIDTH_NOT_APPLICABLE, + support_width_multiplier: float | None = None, +) -> float: + """Exact integral [eV] of the unit-peak continuous distribution shape.""" + w = _finite_positive(width_eV, "width_eV") + if kind == DIST_UNIFORM: + if width_convention not in (WIDTH_UNIFORM_FULL, WIDTH_NOT_APPLICABLE): + raise ValueError(f"unsupported uniform width_convention: {width_convention}") + return w + if support_width_multiplier is None: + raise ValueError(f"{kind} requires support_width_multiplier") + m = _finite_positive(support_width_multiplier, "support_width_multiplier") + if kind == DIST_GAUSSIAN: + if width_convention == WIDTH_GAUSSIAN_SIGMA: + return w * math.sqrt(2.0 * math.pi) * math.erf(m / (2.0 * math.sqrt(2.0))) + if width_convention == WIDTH_SCAPS_CHARACTERISTIC: + return w * math.sqrt(math.pi) * math.erf(0.5 * m) + raise ValueError(f"unsupported gaussian width_convention: {width_convention}") + if kind in (DIST_CONDUCTION_BAND_TAIL, DIST_VALENCE_BAND_TAIL): + return w * (-math.expm1(-m)) + raise ValueError(f"continuous shape integral not defined for kind={kind!r}") + + +def integrated_density_from_peak_density( + peak_density_m3_eV: float, shape_integral_eV: float +) -> float: + """Convert peak density [m^-3 eV^-1] to integrated density [m^-3].""" + peak = _finite_nonnegative(peak_density_m3_eV, "peak_density_m3_eV") + shape = _finite_positive(shape_integral_eV, "shape_integral_eV") + result = peak * shape + if not math.isfinite(result): + raise ValueError("integrated defect density overflowed") + return result + + +def peak_density_from_integrated_density( + total_density_m3: float, shape_integral_eV: float +) -> float: + """Convert integrated density [m^-3] to peak density [m^-3 eV^-1].""" + total = _finite_nonnegative(total_density_m3, "total_density_m3") + shape = _finite_positive(shape_integral_eV, "shape_integral_eV") + result = total / shape + if not math.isfinite(result): + raise ValueError("peak defect density overflowed") + return result + + +@dataclass(frozen=True, slots=True) +class DefectDistributionSpec: + """Canonical energy distribution specification above the valence band.""" + + kind: str + center_eV_above_vb: float + total_density_m3: float + width_eV: float = 0.0 + width_convention: str = WIDTH_NOT_APPLICABLE + support_width_multiplier: float | None = None + peak_density_m3_eV: float | None = None + + def __post_init__(self) -> None: + if self.kind not in SUPPORTED_DISTRIBUTIONS: + raise ValueError(f"unsupported defect distribution kind: {self.kind!r}") + center = _finite(self.center_eV_above_vb, "center_eV_above_vb") + total = _finite_nonnegative(self.total_density_m3, "total_density_m3") + object.__setattr__(self, "center_eV_above_vb", center) + object.__setattr__(self, "total_density_m3", total) + if self.kind == DIST_SINGLE_LEVEL: + if self.width_eV != 0.0: + raise ValueError("single_level requires width_eV == 0") + if self.support_width_multiplier is not None: + raise ValueError("single_level forbids support_width_multiplier") + if self.peak_density_m3_eV is not None: + raise ValueError("single_level forbids peak_density_m3_eV") + return + width = _finite_positive(self.width_eV, "width_eV") + object.__setattr__(self, "width_eV", width) + if self.kind == DIST_UNIFORM: + conv = ( + WIDTH_UNIFORM_FULL + if self.width_convention == WIDTH_NOT_APPLICABLE + else self.width_convention + ) + if conv != WIDTH_UNIFORM_FULL: + raise ValueError(f"uniform requires {WIDTH_UNIFORM_FULL!r}") + object.__setattr__(self, "width_convention", conv) + mult = ( + 1.0 + if self.support_width_multiplier is None + else _finite_positive( + self.support_width_multiplier, "support_width_multiplier" + ) + ) + if mult != 1.0: + raise ValueError("uniform support_width_multiplier must equal 1.0") + object.__setattr__(self, "support_width_multiplier", 1.0) + elif self.kind == DIST_GAUSSIAN: + conv = ( + WIDTH_GAUSSIAN_SIGMA + if self.width_convention == WIDTH_NOT_APPLICABLE + else self.width_convention + ) + if conv not in (WIDTH_GAUSSIAN_SIGMA, WIDTH_SCAPS_CHARACTERISTIC): + raise ValueError(f"unsupported gaussian width_convention: {conv!r}") + object.__setattr__(self, "width_convention", conv) + if self.support_width_multiplier is None: + if self.peak_density_m3_eV is not None: + raise ValueError( + "gaussian peak_density_m3_eV requires explicit support_width_multiplier" + ) + object.__setattr__(self, "peak_density_m3_eV", None) + return + mult = _finite_positive( + self.support_width_multiplier, "support_width_multiplier" + ) + object.__setattr__(self, "support_width_multiplier", mult) + else: + if self.support_width_multiplier is None: + raise ValueError(f"{self.kind} requires support_width_multiplier") + mult = _finite_positive( + self.support_width_multiplier, "support_width_multiplier" + ) + conv = ( + WIDTH_SCAPS_CHARACTERISTIC + if self.width_convention == WIDTH_NOT_APPLICABLE + else self.width_convention + ) + if conv != WIDTH_SCAPS_CHARACTERISTIC: + raise ValueError( + f"{self.kind} requires width_convention={WIDTH_SCAPS_CHARACTERISTIC!r}" + ) + object.__setattr__(self, "width_convention", conv) + object.__setattr__(self, "support_width_multiplier", mult) + + shape = distribution_shape_integral_eV( + self.kind, + self.width_eV, + width_convention=self.width_convention, + support_width_multiplier=self.support_width_multiplier, + ) + expected_peak = peak_density_from_integrated_density(total, shape) + if self.peak_density_m3_eV is None: + object.__setattr__(self, "peak_density_m3_eV", expected_peak) + else: + supplied_peak = _finite_nonnegative( + self.peak_density_m3_eV, "peak_density_m3_eV" + ) + if not math.isclose( + supplied_peak, expected_peak, rel_tol=1e-12, abs_tol=0.0 + ): + raise ValueError( + "peak_density_m3_eV disagrees with total_density_m3 / shape_integral_eV" + ) + object.__setattr__(self, "peak_density_m3_eV", supplied_peak) + + @property + def support_bounds_eV_above_vb(self) -> tuple[float, float]: + c = self.center_eV_above_vb + if self.kind == DIST_SINGLE_LEVEL: + return (c, c) + w = self.width_eV + if self.kind == DIST_UNIFORM: + return (c - 0.5 * w, c + 0.5 * w) + if self.support_width_multiplier is None: + raise ValueError( + "unbounded gaussian requires band_gap_eV to resolve truncated support" + ) + m = self.support_width_multiplier + if self.kind == DIST_GAUSSIAN: + half = 0.5 * m * w + return (c - half, c + half) + if self.kind == DIST_CONDUCTION_BAND_TAIL: + return (c - m * w, c) + return (c, c + m * w) + + +@dataclass(frozen=True, slots=True) +class DefectEnergyQuadrature: + """Normalized discrete energy quadrature for a defect distribution.""" + + distribution_kind: str + quadrature_rule: str + order: int + support_lower_eV_above_vb: float + support_upper_eV_above_vb: float + energies_eV_above_vb: NDArray[np.float64] + density_weights_m3: NDArray[np.float64] + normalized_weights: NDArray[np.float64] + total_density_m3: float + peak_density_m3_eV: float | None + shape_integral_eV: float | None + + def __post_init__(self) -> None: + object.__setattr__( + self, "energies_eV_above_vb", _ro_float(self.energies_eV_above_vb) + ) + object.__setattr__( + self, "density_weights_m3", _ro_float(self.density_weights_m3) + ) + object.__setattr__( + self, "normalized_weights", _ro_float(self.normalized_weights) + ) + if ( + self.energies_eV_above_vb.shape != (self.order,) + or self.density_weights_m3.shape != (self.order,) + or self.normalized_weights.shape != (self.order,) + ): + raise ValueError("quadrature arrays must match declared order") + if self.order > 1 and np.any(np.diff(self.energies_eV_above_vb) <= 0.0): + raise ValueError("quadrature energies must be strictly increasing") + if np.any(self.normalized_weights <= 0.0) or not math.isclose( + float(np.sum(self.normalized_weights)), 1.0, rel_tol=0.0, abs_tol=1e-14 + ): + raise ValueError("normalized quadrature weights must be positive and sum to 1") + + +def build_defect_energy_quadrature( + spec: DefectDistributionSpec, + *, + order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + band_gap_eV: float | None = None, +) -> DefectEnergyQuadrature: + """Build exact-zeroth-moment energy quadrature on ``[0, band_gap_eV]``.""" + if spec.kind == DIST_GAUSSIAN and spec.support_width_multiplier is None: + if band_gap_eV is None: + raise ValueError( + "band-gap-truncated gaussian distribution requires band_gap_eV" + ) + gap = _finite_positive(band_gap_eV, "band_gap_eV") + if not 0.0 <= spec.center_eV_above_vb <= gap: + raise ValueError("gaussian center_eV_above_vb lies outside [0, band_gap_eV]") + lo, hi = 0.0, gap + else: + lo, hi = spec.support_bounds_eV_above_vb + if band_gap_eV is not None: + gap = _finite_positive(band_gap_eV, "band_gap_eV") + tol = 16.0 * math.ulp(max(gap, abs(lo), abs(hi), 1.0)) + if lo < -tol or hi > gap + tol: + raise ValueError( + f"defect distribution support [{lo}, {hi}] lies outside [0, {gap}] eV" + ) + if spec.kind == DIST_SINGLE_LEVEL: + return DefectEnergyQuadrature( + distribution_kind=DIST_SINGLE_LEVEL, + quadrature_rule="dirac_delta", + order=1, + support_lower_eV_above_vb=lo, + support_upper_eV_above_vb=hi, + energies_eV_above_vb=np.array([spec.center_eV_above_vb], dtype=np.float64), + density_weights_m3=np.array([spec.total_density_m3], dtype=np.float64), + normalized_weights=np.array([1.0], dtype=np.float64), + total_density_m3=spec.total_density_m3, + peak_density_m3_eV=None, + shape_integral_eV=None, + ) + + n = validate_defect_energy_quadrature_order(order) + xi, omega = leggauss(n) + weights = 0.5 * omega + weights = weights / float(np.sum(weights)) + c = spec.center_eV_above_vb + w = spec.width_eV + + if spec.kind == DIST_GAUSSIAN and spec.support_width_multiplier is None: + sigma = ( + w + if spec.width_convention == WIDTH_GAUSSIAN_SIGMA + else w / math.sqrt(2.0) + ) + u_lo = float(ndtr(-c / sigma)) + u_hi = float(ndtr((hi - c) / sigma)) + mass = u_hi - u_lo + if not math.isfinite(mass) or mass <= np.finfo(float).eps: + raise ValueError("gaussian defect distribution has no resolvable mass inside the gap") + u = u_lo + 0.5 * (xi + 1.0) * mass + energies = c + sigma * np.asarray(ndtri(u), dtype=np.float64) + shape: float | None = sigma * math.sqrt(2.0 * math.pi) * mass + rule = "gauss_legendre_truncated_normal_cdf" + else: + assert spec.support_width_multiplier is not None + m = spec.support_width_multiplier + shape = distribution_shape_integral_eV( + spec.kind, + w, + width_convention=spec.width_convention, + support_width_multiplier=m, + ) + if spec.kind == DIST_UNIFORM: + energies = c + 0.5 * w * xi + rule = "gauss_legendre_energy" + elif spec.kind == DIST_GAUSSIAN: + sigma = ( + w + if spec.width_convention == WIDTH_GAUSSIAN_SIGMA + else w / math.sqrt(2.0) + ) + z_bound = 0.5 * m * w / sigma + u_lo = float(ndtr(-z_bound)) + u_hi = float(ndtr(z_bound)) + if not (0.0 <= u_lo < u_hi <= 1.0): + raise ValueError("truncated Gaussian CDF bounds collapsed in float64") + u = 0.5 * (u_lo + u_hi) + 0.5 * (u_hi - u_lo) * xi + energies = c + sigma * np.asarray(ndtri(u), dtype=np.float64) + rule = "gauss_legendre_truncated_normal_cdf" + elif spec.kind == DIST_CONDUCTION_BAND_TAIL: + trunc = -math.expm1(-m) + # Map xi in [-1, 1] -> u in [1, 0] so energies increase strictly from c - m*w to c. + u_desc = 0.5 * (1.0 - xi) + energies = c + w * np.log1p(-u_desc * trunc) + rule = "gauss_legendre_truncated_exponential_cdf" + else: + trunc = -math.expm1(-m) + u_asc = 0.5 * (1.0 + xi) + energies = c - w * np.log1p(-u_asc * trunc) + rule = "gauss_legendre_truncated_exponential_cdf" + + density_weights = spec.total_density_m3 * weights + # Enforce exact floating-point sum on positive total_density_m3 if within 4 ULP. + if spec.total_density_m3 > 0.0: + scale = spec.total_density_m3 / float(np.sum(density_weights)) + density_weights = density_weights * scale + + return DefectEnergyQuadrature( + distribution_kind=spec.kind, + quadrature_rule=rule, + order=n, + support_lower_eV_above_vb=lo, + support_upper_eV_above_vb=hi, + energies_eV_above_vb=energies, + density_weights_m3=density_weights, + normalized_weights=weights, + total_density_m3=spec.total_density_m3, + peak_density_m3_eV=spec.peak_density_m3_eV, + shape_integral_eV=shape, + ) + + +def density_weighted_mean_occupancy( + quadrature: DefectEnergyQuadrature, + node_occupancy: ArrayLike, +) -> NDArray[np.float64]: + """Mean occupancy ``sum_k w_k f_k`` across quadrature modes (axis 0).""" + occ = np.asarray(node_occupancy, dtype=np.float64) + if occ.shape[0] != quadrature.order: + raise ValueError( + f"node_occupancy axis 0 ({occ.shape[0]}) != quadrature order ({quadrature.order})" + ) + return np.tensordot(quadrature.normalized_weights, occ, axes=(0, 0)) + + +@dataclass(frozen=True, slots=True) +class SpatialProfileKnot: + """Normalized ``[0, 1]`` knot for piecewise-linear spatial defect profiles.""" + + position_fraction: float + density_multiplier: float + + def __post_init__(self) -> None: + pos = _finite(self.position_fraction, "position_fraction") + if not 0.0 <= pos <= 1.0: + raise ValueError("position_fraction must lie in [0, 1]") + mult = _finite_nonnegative(self.density_multiplier, "density_multiplier") + object.__setattr__(self, "position_fraction", pos) + object.__setattr__(self, "density_multiplier", mult) + + +@dataclass(frozen=True, slots=True) +class SpatialDensityProfileSpec: + """Layer-average-preserving piecewise-linear defect spatial profile.""" + + knots: tuple[SpatialProfileKnot, ...] + + def __post_init__(self) -> None: + items = tuple(self.knots) + if len(items) < 2: + raise ValueError("spatial density profile requires at least 2 knots") + if items[0].position_fraction != 0.0 or items[-1].position_fraction != 1.0: + raise ValueError("spatial density profile knots must span [0, 1]") + segments: list[float] = [] + for left, right in zip(items, items[1:]): + dx = right.position_fraction - left.position_fraction + if dx <= 0.0: + raise ValueError("spatial density profile knots must strictly increase") + segments.append( + 0.5 * (left.density_multiplier + right.density_multiplier) * dx + ) + integral = math.fsum(segments) + if not math.isclose(integral, 1.0, rel_tol=0.0, abs_tol=1e-12): + raise ValueError( + f"spatial density profile must have unit layer average (got {integral})" + ) + object.__setattr__(self, "knots", items) + + +def evaluate_spatial_density_profile( + profile: SpatialDensityProfileSpec, + normalized_positions: ArrayLike, +) -> NDArray[np.float64]: + """Evaluate spatial density multipliers on normalized layer positions in ``[0, 1]``.""" + pos = np.asarray(normalized_positions, dtype=np.float64) + if np.any(~np.isfinite(pos)) or np.any(pos < 0.0) or np.any(pos > 1.0): + raise ValueError("normalized_positions must be finite and lie in [0, 1]") + xp = np.array([k.position_fraction for k in profile.knots], dtype=np.float64) + fp = np.array([k.density_multiplier for k in profile.knots], dtype=np.float64) + result = np.asarray(np.interp(pos, xp, fp), dtype=np.float64) + result.setflags(write=False) + return result diff --git a/src/solarlab/physics/defects/dynamic_single_level.py b/src/solarlab/physics/defects/dynamic_single_level.py new file mode 100644 index 00000000..4d0938d2 --- /dev/null +++ b/src/solarlab/physics/defects/dynamic_single_level.py @@ -0,0 +1,1357 @@ +"""Monovalent single-level, energy-distributed, and dynamic trap constitutive laws. + +Covers: +1. Quasi-steady (QSS) monovalent defect closure (neutral, acceptor, donor; + single-level, continuous energy quadrature, and spatial density profiles) + with exact analytical derivatives with respect to ``(n, p)`` and fixed + quasi-Fermi potential ``phi``. +2. Equilibrium charge-neutrality solver including monovalent/distributed traps. +3. Dynamic bulk trap occupancy layout, unbounded logit coordinates, + cancellation-free logistic secants, and non-equilibrium capture/emission + + trap storage + electrostatic charge with exact analytical derivatives. +4. Dynamic two-sided heterointerface trap kinetics, storage, and equilibrium- + referenced sheet charge ``Delta_sigma = -q * N_it * (f - f_eq)`` with exact + analytical derivatives. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.physics.defects.distributions import ( + DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + DIST_SINGLE_LEVEL, + DefectDistributionSpec, + DefectEnergyQuadrature, + SpatialDensityProfileSpec, + build_defect_energy_quadrature, + evaluate_spatial_density_profile, + validate_defect_energy_quadrature_order, +) +from solarlab.physics.statistics import ( + CHARGE_NEUTRALITY_RELATIVE_TOLERANCE, + thermal_voltage, +) + +TRANSITION_NEUTRAL = "neutral" +TRANSITION_ACCEPTOR = "acceptor" +TRANSITION_DONOR = "donor" +SUPPORTED_MONOVALENT_TRANSITIONS = frozenset( + {TRANSITION_NEUTRAL, TRANSITION_ACCEPTOR, TRANSITION_DONOR} +) + +__all__ = [ + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_monovalent_defect_charge_neutrality", + "stable_expit", +] + + +def _ro_float(values: ArrayLike) -> NDArray[np.float64]: + arr = np.array(values, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_int(values: ArrayLike) -> NDArray[np.int64]: + arr = np.array(values, dtype=np.int64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(values: ArrayLike) -> NDArray[np.bool_]: + arr = np.array(values, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +def _canonical_sha256(payload: object) -> str: + raw = json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + return hashlib.sha256(raw.encode("ascii")).hexdigest() + + +def _finite_positive(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and positive") + number = float(value) + if not math.isfinite(number) or number <= 0.0: + raise ValueError(f"{name} must be finite and positive") + return number + + +def _finite_nonnegative(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and non-negative") + number = float(value) + if not math.isfinite(number) or number < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + return number + + +def stable_expit(logit: ArrayLike) -> NDArray[np.float64]: + """Overflow-safe logistic function ``1 / (1 + exp(-x))``.""" + x = np.asarray(logit, dtype=np.float64) + out = np.empty_like(x) + pos = x >= 0.0 + out[pos] = 1.0 / (1.0 + np.exp(-x[pos])) + exp_x = np.exp(x[~pos]) + out[~pos] = exp_x / (1.0 + exp_x) + return out + + +def logit_occupancy_secant( + new_logit: ArrayLike, old_logit: ArrayLike +) -> NDArray[np.float64]: + """Cancellation-free ``expit(new_logit) - expit(old_logit)``.""" + ln = np.asarray(new_logit, dtype=np.float64) + lo = np.asarray(old_logit, dtype=np.float64) + if ln.shape != lo.shape: + raise ValueError("new_logit and old_logit must have identical shape") + d = ln - lo + out = np.empty_like(d) + nonneg = d >= 0.0 + if np.any(nonneg): + f_new = stable_expit(ln[nonneg]) + one_minus_old = stable_expit(-lo[nonneg]) + out[nonneg] = f_new * one_minus_old * (-np.expm1(-d[nonneg])) + neg = ~nonneg + if np.any(neg): + one_minus_new = stable_expit(-ln[neg]) + f_old = stable_expit(lo[neg]) + out[neg] = one_minus_new * f_old * np.expm1(d[neg]) + return out + + +@dataclass(frozen=True, slots=True) +class MonovalentSpeciesSpec: + """Canonical monovalent defect species (single-level or continuous distribution).""" + + identifier: str + charge_transition: str + distribution: DefectDistributionSpec + sigma_n_m2: float + sigma_p_m2: float + thermal_velocity_n_m_s: float + thermal_velocity_p_m_s: float + degeneracy: float = 1.0 + spatial_profile: SpatialDensityProfileSpec | None = None + + def __post_init__(self) -> None: + ident = str(self.identifier).strip() + if not ident: + raise ValueError("MonovalentSpeciesSpec requires a non-empty identifier") + if self.charge_transition not in SUPPORTED_MONOVALENT_TRANSITIONS: + raise ValueError( + f"unsupported monovalent charge_transition: {self.charge_transition!r}" + ) + sn = _finite_nonnegative(self.sigma_n_m2, "sigma_n_m2") + sp = _finite_nonnegative(self.sigma_p_m2, "sigma_p_m2") + vn = _finite_positive(self.thermal_velocity_n_m_s, "thermal_velocity_n_m_s") + vp = _finite_positive(self.thermal_velocity_p_m_s, "thermal_velocity_p_m_s") + deg = _finite_positive(self.degeneracy, "degeneracy") + if deg != 1.0: + raise ValueError( + "monovalent DEF-2 species require unit degeneracy (degeneracy == 1.0); " + "use MultivalentSpeciesSpec for explicit state degeneracies" + ) + if sn == 0.0 and sp == 0.0: + raise ValueError( + f"monovalent defect {ident!r} has zero electron and hole capture cross sections" + ) + object.__setattr__(self, "identifier", ident) + object.__setattr__(self, "sigma_n_m2", sn) + object.__setattr__(self, "sigma_p_m2", sp) + object.__setattr__(self, "thermal_velocity_n_m_s", vn) + object.__setattr__(self, "thermal_velocity_p_m_s", vp) + object.__setattr__(self, "degeneracy", deg) + + @property + def capture_n_m3_s(self) -> float: + return self.sigma_n_m2 * self.thermal_velocity_n_m_s + + @property + def capture_p_m3_s(self) -> float: + return self.sigma_p_m2 * self.thermal_velocity_p_m_s + + +@dataclass(frozen=True, slots=True) +class MonovalentDefectClosureResult: + """Exact QSS occupancy, SRH rate, space charge, and analytical tangents.""" + + species_identifiers: tuple[str, ...] + charge_transitions: tuple[str, ...] + occupancy: NDArray[np.float64] + occupancy_derivative_n_m3: NDArray[np.float64] + occupancy_derivative_p_m3: NDArray[np.float64] + occupied_density_m3: NDArray[np.float64] + charge_density_C_m3: NDArray[np.float64] + charge_derivative_n_C: NDArray[np.float64] + charge_derivative_p_C: NDArray[np.float64] + charge_derivative_fixed_qf_C_m3_V: NDArray[np.float64] + recombination_rate_m3_s: NDArray[np.float64] + recombination_derivative_n_s1: NDArray[np.float64] + recombination_derivative_p_s1: NDArray[np.float64] + recombination_derivative_fixed_qf_m3_s_V: NDArray[np.float64] + total_charge_density_C_m3: NDArray[np.float64] + total_charge_derivative_n_C: NDArray[np.float64] + total_charge_derivative_p_C: NDArray[np.float64] + total_charge_derivative_fixed_qf_C_m3_V: NDArray[np.float64] + total_recombination_rate_m3_s: NDArray[np.float64] + total_recombination_derivative_n_s1: NDArray[np.float64] + total_recombination_derivative_p_s1: NDArray[np.float64] + total_recombination_derivative_fixed_qf_m3_s_V: NDArray[np.float64] + kinetic_denominator_s1: NDArray[np.float64] + + def __post_init__(self) -> None: + for name in ( + "occupancy", + "occupancy_derivative_n_m3", + "occupancy_derivative_p_m3", + "occupied_density_m3", + "charge_density_C_m3", + "charge_derivative_n_C", + "charge_derivative_p_C", + "charge_derivative_fixed_qf_C_m3_V", + "recombination_rate_m3_s", + "recombination_derivative_n_s1", + "recombination_derivative_p_s1", + "recombination_derivative_fixed_qf_m3_s_V", + "total_charge_density_C_m3", + "total_charge_derivative_n_C", + "total_charge_derivative_p_C", + "total_charge_derivative_fixed_qf_C_m3_V", + "total_recombination_rate_m3_s", + "total_recombination_derivative_n_s1", + "total_recombination_derivative_p_s1", + "total_recombination_derivative_fixed_qf_m3_s_V", + "kinetic_denominator_s1", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + +def evaluate_monovalent_defect_closure( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + species: Sequence[MonovalentSpeciesSpec], + *, + band_gap_eV: ArrayLike, + effective_conduction_dos_m3: ArrayLike, + effective_valence_dos_m3: ArrayLike, + temperature_K: float, + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + normalized_layer_positions: ArrayLike | None = None, +) -> MonovalentDefectClosureResult: + """Evaluate QSS monovalent/distributed/spatial defect closure and exact tangents.""" + if not species: + raise ValueError("species sequence must not be empty") + n, p = np.broadcast_arrays( + np.asarray(electron_density_m3, dtype=np.float64), + np.asarray(hole_density_m3, dtype=np.float64), + ) + if np.any(~np.isfinite(n)) or np.any(~np.isfinite(p)) or np.any(n < 0.0) or np.any(p < 0.0): + raise ValueError("carrier densities must be finite and non-negative") + gap = np.broadcast_to(np.asarray(band_gap_eV, dtype=np.float64), n.shape) + nc = np.broadcast_to( + np.asarray(effective_conduction_dos_m3, dtype=np.float64), n.shape + ) + nv = np.broadcast_to( + np.asarray(effective_valence_dos_m3, dtype=np.float64), n.shape + ) + if np.any(gap <= 0.0) or np.any(nc <= 0.0) or np.any(nv <= 0.0): + raise ValueError("band_gap_eV, Nc, and Nv must be positive") + vt = thermal_voltage(_finite_positive(temperature_K, "temperature_K")) + order = validate_defect_energy_quadrature_order(energy_quadrature_order) + + min_gap = float(np.min(gap)) + s_count = len(species) + out_shape = (s_count, *n.shape) + occ_arr = np.zeros(out_shape, dtype=np.float64) + docc_dn_arr = np.zeros(out_shape, dtype=np.float64) + docc_dp_arr = np.zeros(out_shape, dtype=np.float64) + occ_dens_arr = np.zeros(out_shape, dtype=np.float64) + rho_arr = np.zeros(out_shape, dtype=np.float64) + drho_dn_arr = np.zeros(out_shape, dtype=np.float64) + drho_dp_arr = np.zeros(out_shape, dtype=np.float64) + drho_dphi_arr = np.zeros(out_shape, dtype=np.float64) + rate_arr = np.zeros(out_shape, dtype=np.float64) + drate_dn_arr = np.zeros(out_shape, dtype=np.float64) + drate_dp_arr = np.zeros(out_shape, dtype=np.float64) + drate_dphi_arr = np.zeros(out_shape, dtype=np.float64) + denom_min_arr = np.zeros(out_shape, dtype=np.float64) + + ni_sq = nc * nv * np.exp(-gap / vt) + excess = n * p - ni_sq + + for idx, item in enumerate(species): + quad = build_defect_energy_quadrature( + item.distribution, order=order, band_gap_eV=min_gap + ) + if item.spatial_profile is not None: + if normalized_layer_positions is None: + raise ValueError( + f"species {item.identifier!r} has a spatial_profile, so " + "normalized_layer_positions must be provided" + ) + mult = np.broadcast_to( + evaluate_spatial_density_profile( + item.spatial_profile, normalized_layer_positions + ), + n.shape, + ) + else: + mult = np.ones(n.shape, dtype=np.float64) + + cn = item.capture_n_m3_s + cp = item.capture_p_m3_s + # Broadcast over quadrature axis 0 and spatial axes 1.. + energies = quad.energies_eV_above_vb.reshape((quad.order,) + (1,) * n.ndim) + weights_norm = quad.normalized_weights.reshape((quad.order,) + (1,) * n.ndim) + dens_k = quad.density_weights_m3.reshape((quad.order,) + (1,) * n.ndim) * mult[None, ...] + + n_e = n[None, ...] + p_e = p[None, ...] + nc_e = nc[None, ...] + nv_e = nv[None, ...] + gap_e = gap[None, ...] + excess_e = excess[None, ...] + + n1 = nc_e * np.exp(-(gap_e - energies) / vt) + p1 = nv_e * np.exp(-energies / vt) + filled = cn * n_e + cp * p1 + empty = cn * n1 + cp * p_e + denom = filled + empty + if np.any(~np.isfinite(denom)) or np.any(denom <= 0.0): + raise FloatingPointError( + f"non-positive or non-finite kinetic denominator for {item.identifier!r}" + ) + f_k = filled / denom + one_minus_f_k = empty / denom + df_dn_k = cn * one_minus_f_k / denom + df_dp_k = -cp * f_k / denom + + pref = dens_k * cn * cp + r_k = pref * excess_e / denom + dr_dn_k = pref * (p_e * denom - excess_e * cn) / (denom * denom) + dr_dp_k = pref * (n_e * denom - excess_e * cp) / (denom * denom) + + occ_arr[idx] = np.sum(weights_norm * f_k, axis=0) + docc_dn_arr[idx] = np.sum(weights_norm * df_dn_k, axis=0) + docc_dp_arr[idx] = np.sum(weights_norm * df_dp_k, axis=0) + occ_dens_arr[idx] = np.sum(dens_k * f_k, axis=0) + rate_arr[idx] = np.sum(r_k, axis=0) + drate_dn_arr[idx] = np.sum(dr_dn_k, axis=0) + drate_dp_arr[idx] = np.sum(dr_dp_k, axis=0) + drate_dphi_arr[idx] = ( + drate_dn_arr[idx] * (n / vt) - drate_dp_arr[idx] * (p / vt) + ) + denom_min_arr[idx] = np.min(denom, axis=0) + + if item.charge_transition == TRANSITION_ACCEPTOR: + rho_arr[idx] = -Q * occ_dens_arr[idx] + drho_dn_arr[idx] = -Q * np.sum(dens_k * df_dn_k, axis=0) + drho_dp_arr[idx] = -Q * np.sum(dens_k * df_dp_k, axis=0) + drho_dphi_arr[idx] = ( + drho_dn_arr[idx] * (n / vt) - drho_dp_arr[idx] * (p / vt) + ) + elif item.charge_transition == TRANSITION_DONOR: + rho_arr[idx] = Q * np.sum(dens_k * one_minus_f_k, axis=0) + drho_dn_arr[idx] = -Q * np.sum(dens_k * df_dn_k, axis=0) + drho_dp_arr[idx] = -Q * np.sum(dens_k * df_dp_k, axis=0) + drho_dphi_arr[idx] = ( + drho_dn_arr[idx] * (n / vt) - drho_dp_arr[idx] * (p / vt) + ) + + return MonovalentDefectClosureResult( + species_identifiers=tuple(item.identifier for item in species), + charge_transitions=tuple(item.charge_transition for item in species), + occupancy=occ_arr, + occupancy_derivative_n_m3=docc_dn_arr, + occupancy_derivative_p_m3=docc_dp_arr, + occupied_density_m3=occ_dens_arr, + charge_density_C_m3=rho_arr, + charge_derivative_n_C=drho_dn_arr, + charge_derivative_p_C=drho_dp_arr, + charge_derivative_fixed_qf_C_m3_V=drho_dphi_arr, + recombination_rate_m3_s=rate_arr, + recombination_derivative_n_s1=drate_dn_arr, + recombination_derivative_p_s1=drate_dp_arr, + recombination_derivative_fixed_qf_m3_s_V=drate_dphi_arr, + total_charge_density_C_m3=np.sum(rho_arr, axis=0), + total_charge_derivative_n_C=np.sum(drho_dn_arr, axis=0), + total_charge_derivative_p_C=np.sum(drho_dp_arr, axis=0), + total_charge_derivative_fixed_qf_C_m3_V=np.sum(drho_dphi_arr, axis=0), + total_recombination_rate_m3_s=np.sum(rate_arr, axis=0), + total_recombination_derivative_n_s1=np.sum(drate_dn_arr, axis=0), + total_recombination_derivative_p_s1=np.sum(drate_dp_arr, axis=0), + total_recombination_derivative_fixed_qf_m3_s_V=np.sum(drate_dphi_arr, axis=0), + kinetic_denominator_s1=denom_min_arr, + ) + + +@dataclass(frozen=True, slots=True) +class MonovalentDefectRegion: + """Compiled monovalent/distributed/spatial defect inventory on a disjoint region.""" + + identifier: str + document_sha256: str + active_nodes: NDArray[np.bool_] + band_gap_eV: NDArray[np.float64] + effective_conduction_dos_m3: NDArray[np.float64] + effective_valence_dos_m3: NDArray[np.float64] + temperature_K: float + species: tuple[MonovalentSpeciesSpec, ...] + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER + normalized_layer_positions: NDArray[np.float64] | None = None + quadratures: tuple[DefectEnergyQuadrature, ...] = field(init=False, repr=False) + + def __post_init__(self) -> None: + ident = str(self.identifier).strip() + if not ident: + raise ValueError("region identifier must be non-empty") + mask = _ro_bool(self.active_nodes) + if mask.ndim != 1 or not np.any(mask): + raise ValueError("active_nodes must be a non-empty 1D boolean mask") + active_count = int(np.sum(mask)) + gap = _ro_float(np.broadcast_to(self.band_gap_eV, (active_count,))) + nc = _ro_float( + np.broadcast_to(self.effective_conduction_dos_m3, (active_count,)) + ) + nv = _ro_float( + np.broadcast_to(self.effective_valence_dos_m3, (active_count,)) + ) + temp = _finite_positive(self.temperature_K, "temperature_K") + order = validate_defect_energy_quadrature_order(self.energy_quadrature_order) + sp = tuple(self.species) + if not sp: + raise ValueError("MonovalentDefectRegion requires at least one species") + min_gap = float(np.min(gap)) + quads = tuple( + build_defect_energy_quadrature( + item.distribution, order=order, band_gap_eV=min_gap + ) + for item in sp + ) + pos: NDArray[np.float64] | None = None + if self.normalized_layer_positions is not None: + pos = _ro_float(self.normalized_layer_positions) + if pos.shape != (active_count,): + raise ValueError( + "normalized_layer_positions must match active node count" + ) + elif any(item.spatial_profile is not None for item in sp): + raise ValueError("spatial defect profile requires normalized_layer_positions") + + object.__setattr__(self, "identifier", ident) + object.__setattr__(self, "active_nodes", mask) + object.__setattr__(self, "band_gap_eV", gap) + object.__setattr__(self, "effective_conduction_dos_m3", nc) + object.__setattr__(self, "effective_valence_dos_m3", nv) + object.__setattr__(self, "temperature_K", temp) + object.__setattr__(self, "species", sp) + object.__setattr__(self, "energy_quadrature_order", order) + object.__setattr__(self, "normalized_layer_positions", pos) + object.__setattr__(self, "quadratures", quads) + + @property + def has_distributed_species(self) -> bool: + return any(item.distribution.kind != DIST_SINGLE_LEVEL for item in self.species) + + @property + def has_spatial_profiles(self) -> bool: + return any(item.spatial_profile is not None for item in self.species) + + +def evaluate_monovalent_region_closure( + region: MonovalentDefectRegion, + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, +) -> MonovalentDefectClosureResult: + """Evaluate a compiled ``MonovalentDefectRegion`` on full-grid carrier vectors.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + if n.shape != region.active_nodes.shape or p.shape != region.active_nodes.shape: + raise ValueError("carrier vectors must match region.active_nodes shape") + return evaluate_monovalent_defect_closure( + n[region.active_nodes], + p[region.active_nodes], + region.species, + band_gap_eV=region.band_gap_eV, + effective_conduction_dos_m3=region.effective_conduction_dos_m3, + effective_valence_dos_m3=region.effective_valence_dos_m3, + temperature_K=region.temperature_K, + energy_quadrature_order=region.energy_quadrature_order, + normalized_layer_positions=region.normalized_layer_positions, + ) + + +@dataclass(frozen=True, slots=True) +class MonovalentDefectNeutralityState: + """Equilibrium contact/bulk charge-neutrality state with monovalent/distributed traps.""" + + temperature_K: float + thermal_voltage_V: float + band_gap_eV: float + effective_conduction_dos_m3: float + effective_valence_dos_m3: float + donor_density_m3: float + acceptor_density_m3: float + reduced_electron_fermi_level: float + reduced_hole_fermi_level: float + electron_density_m3: float + hole_density_m3: float + trap_charge_density_C_m3: float + normalized_charge_residual: float + work_function_eV: float | None = None + + +def solve_monovalent_defect_charge_neutrality( + *, + temperature_K: float, + band_gap_eV: float, + effective_conduction_dos_m3: float, + effective_valence_dos_m3: float, + donor_density_m3: float, + acceptor_density_m3: float, + species: Sequence[MonovalentSpeciesSpec], + electron_affinity_eV: float | None = None, + energy_quadrature_order: int = DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER, + normalized_layer_position: float = 0.0, +) -> MonovalentDefectNeutralityState: + """Solve MB equilibrium neutrality ``p - n + N_D - N_A + rho_trap/q == 0``. + + In thermal equilibrium ``n*p == n_i^2``, so every monovalent trap energy + node satisfies exact Fermi-Dirac occupancy ``f(E) = 1 / (1 + exp((E - E_F)/kT))``, + making total charge strictly decreasing in ``eta_n = (E_F - E_c) / V_T``. + """ + temp = _finite_positive(temperature_K, "temperature_K") + gap = _finite_positive(band_gap_eV, "band_gap_eV") + nc = _finite_positive(effective_conduction_dos_m3, "effective_conduction_dos_m3") + nv = _finite_positive(effective_valence_dos_m3, "effective_valence_dos_m3") + nd = _finite_nonnegative(donor_density_m3, "donor_density_m3") + na = _finite_nonnegative(acceptor_density_m3, "acceptor_density_m3") + vt = thermal_voltage(temp) + pos_arr = np.array([normalized_layer_position], dtype=np.float64) + + def eval_eta(eta_n: float) -> tuple[float, float, float, float, float]: + eta_p = -gap / vt - eta_n + n_val = nc * math.exp(eta_n) + p_val = nv * math.exp(eta_p) + if species: + closure = evaluate_monovalent_defect_closure( + np.array([n_val]), + np.array([p_val]), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + energy_quadrature_order=energy_quadrature_order, + normalized_layer_positions=pos_arr, + ) + rho_trap = float(closure.total_charge_density_C_m3[0]) + else: + rho_trap = 0.0 + trap_num = rho_trap / Q + net = (p_val + nd + max(trap_num, 0.0)) - (n_val + na + max(-trap_num, 0.0)) + scale = max(p_val + n_val + nd + na + abs(trap_num), 1.0) + return net, scale, n_val, p_val, rho_trap + + eta_mid = -0.5 * gap / vt + 0.5 * math.log(nv / nc) + lo = eta_mid - 1.0 + hi = eta_mid + 1.0 + f_lo, _, _, _, _ = eval_eta(lo) + f_hi, _, _, _, _ = eval_eta(hi) + step = 2.0 + for _ in range(60): + if f_lo >= 0.0 and f_hi <= 0.0: + break + if f_lo < 0.0: + lo -= step + f_lo, _, _, _, _ = eval_eta(lo) + if f_hi > 0.0: + hi += step + f_hi, _, _, _, _ = eval_eta(hi) + step = min(step * 1.5, 40.0) + else: + raise RuntimeError("failed to bracket defect-charged equilibrium Fermi level") + + mid = 0.5 * (lo + hi) + for _ in range(120): + mid = 0.5 * (lo + hi) + val, scale, _, _, _ = eval_eta(mid) + if abs(val) / scale <= CHARGE_NEUTRALITY_RELATIVE_TOLERANCE or hi - lo <= 1e-15 * max( + 1.0, abs(lo), abs(hi) + ): + break + if val > 0.0: + lo = mid + else: + hi = mid + + val, scale, n_eq, p_eq, rho_eq = eval_eta(mid) + norm_res = abs(val) / scale + if norm_res > 10.0 * CHARGE_NEUTRALITY_RELATIVE_TOLERANCE: + raise RuntimeError( + f"monovalent defect neutrality residual {norm_res:.3e} exceeded tolerance" + ) + wf: float | None = None + if electron_affinity_eV is not None: + chi = _finite_positive(electron_affinity_eV, "electron_affinity_eV") + wf = chi - vt * mid + return MonovalentDefectNeutralityState( + temperature_K=temp, + thermal_voltage_V=vt, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=nd, + acceptor_density_m3=na, + reduced_electron_fermi_level=mid, + reduced_hole_fermi_level=-gap / vt - mid, + electron_density_m3=n_eq, + hole_density_m3=p_eq, + trap_charge_density_C_m3=rho_eq, + normalized_charge_residual=norm_res, + work_function_eV=wf, + ) + + +@dataclass(frozen=True, slots=True) +class DynamicBulkTrapMode: + """One spatially contiguous dynamic trap mode (one region/species/energy node).""" + + mode_id: str + region_identifier: str + source_identifier: str + energy_index: int + charge_transition: str + device_node_indices: NDArray[np.int64] + population_density_m3: NDArray[np.float64] + capture_n_m3_s: float + capture_p_m3_s: float + n1_m3: NDArray[np.float64] + p1_m3: NDArray[np.float64] + intrinsic_product_m6: NDArray[np.float64] + flat_slice: slice + + def __post_init__(self) -> None: + object.__setattr__( + self, "device_node_indices", _ro_int(self.device_node_indices) + ) + for name in ( + "population_density_m3", + "n1_m3", + "p1_m3", + "intrinsic_product_m6", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + @property + def size(self) -> int: + return int(self.device_node_indices.size) + + +@dataclass(frozen=True, slots=True) +class DynamicBulkTrapLayout: + """Canonical ordering of dynamic bulk trap states across regions and energy nodes.""" + + model_identity_sha256: str + node_count: int + modes: tuple[DynamicBulkTrapMode, ...] + device_node_indices: NDArray[np.int64] + region_identifiers: tuple[str, ...] + source_identifiers: tuple[str, ...] + energy_node_identifiers: tuple[str, ...] + charge_transitions: tuple[str, ...] + population_density_m3: NDArray[np.float64] + capture_n_m3_s: NDArray[np.float64] + capture_p_m3_s: NDArray[np.float64] + n1_m3: NDArray[np.float64] + p1_m3: NDArray[np.float64] + intrinsic_product_m6: NDArray[np.float64] + + def __post_init__(self) -> None: + object.__setattr__( + self, "device_node_indices", _ro_int(self.device_node_indices) + ) + for name in ( + "population_density_m3", + "capture_n_m3_s", + "capture_p_m3_s", + "n1_m3", + "p1_m3", + "intrinsic_product_m6", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + @property + def size(self) -> int: + return int(self.device_node_indices.size) + + @property + def identity_sha256(self) -> str: + return _canonical_sha256( + { + "model_identity_sha256": self.model_identity_sha256, + "node_count": self.node_count, + "device_node_indices": self.device_node_indices.tolist(), + "energy_node_identifiers": list(self.energy_node_identifiers), + "charge_transitions": list(self.charge_transitions), + "population_density_m3": self.population_density_m3.tolist(), + "capture_n_m3_s": self.capture_n_m3_s.tolist(), + "capture_p_m3_s": self.capture_p_m3_s.tolist(), + "n1_m3": self.n1_m3.tolist(), + "p1_m3": self.p1_m3.tolist(), + } + ) + + +def compile_dynamic_bulk_trap_layout( + regions: Sequence[MonovalentDefectRegion], + *, + node_count: int, + dynamic_node_mask: ArrayLike | None = None, +) -> DynamicBulkTrapLayout: + """Compile disjoint ``MonovalentDefectRegion`` objects into a dynamic trap layout. + + By default, contact boundary nodes ``0`` and ``node_count - 1`` are excluded + from dynamic trap DOFs because fixed-reservoir/Robin contact equations own + the boundary carrier balances; interior nodes ``1..node_count-2`` carry + explicit dynamic trap storage DOFs. + """ + if node_count < 3: + raise ValueError("dynamic bulk trap layout requires node_count >= 3") + if dynamic_node_mask is None: + dyn_mask: NDArray[np.bool_] = np.ones(node_count, dtype=bool) + dyn_mask[0] = False + dyn_mask[-1] = False + else: + dyn_mask = np.asarray(dynamic_node_mask, dtype=bool) + if dyn_mask.shape != (node_count,): + raise ValueError("dynamic_node_mask must match node_count") + + modes: list[DynamicBulkTrapMode] = [] + dev_nodes_all: list[int] = [] + reg_ids_all: list[str] = [] + src_ids_all: list[str] = [] + e_ids_all: list[str] = [] + trans_all: list[str] = [] + pop_all: list[float] = [] + cn_all: list[float] = [] + cp_all: list[float] = [] + n1_all: list[float] = [] + p1_all: list[float] = [] + nisq_all: list[float] = [] + + offset = 0 + region_digests: list[tuple[str, str]] = [] + for region in regions: + if region.active_nodes.size != node_count: + raise ValueError("region.active_nodes must match node_count") + region_digests.append((region.identifier, region.document_sha256)) + vt = thermal_voltage(region.temperature_K) + active_full_indices = np.flatnonzero(region.active_nodes) + selected_local = np.flatnonzero(dyn_mask[active_full_indices]) + if selected_local.size == 0: + continue + sel_nodes = active_full_indices[selected_local] + local_gap = region.band_gap_eV[selected_local] + local_nc = region.effective_conduction_dos_m3[selected_local] + local_nv = region.effective_valence_dos_m3[selected_local] + local_nisq = local_nc * local_nv * np.exp(-local_gap / vt) + + for sp_idx, (sp, quad) in enumerate(zip(region.species, region.quadratures)): + if sp.spatial_profile is not None: + assert region.normalized_layer_positions is not None + mult = evaluate_spatial_density_profile( + sp.spatial_profile, + region.normalized_layer_positions[selected_local], + ) + else: + mult = np.ones(selected_local.size, dtype=np.float64) + cn = sp.capture_n_m3_s + cp = sp.capture_p_m3_s + + for e_idx in range(quad.order): + dens_base = float(quad.density_weights_m3[e_idx]) + pop_vec = dens_base * mult + if np.all(pop_vec <= 0.0): + continue + if np.any(pop_vec <= 0.0): + raise ValueError( + f"dynamic trap mode {region.identifier}/{sp.identifier}[{e_idx}] " + "has zero density on a subset of active nodes" + ) + energy = float(quad.energies_eV_above_vb[e_idx]) + n1_vec = local_nc * np.exp(-(local_gap - energy) / vt) + p1_vec = local_nv * np.exp(-energy / vt) + mode_id = ( + f"{region.identifier}:{sp.identifier}" + if quad.order == 1 + else f"{region.identifier}:{sp.identifier}:e{e_idx:03d}" + ) + sl = slice(offset, offset + sel_nodes.size) + offset += sel_nodes.size + modes.append( + DynamicBulkTrapMode( + mode_id=mode_id, + region_identifier=region.identifier, + source_identifier=sp.identifier, + energy_index=e_idx, + charge_transition=sp.charge_transition, + device_node_indices=sel_nodes, + population_density_m3=pop_vec, + capture_n_m3_s=cn, + capture_p_m3_s=cp, + n1_m3=n1_vec, + p1_m3=p1_vec, + intrinsic_product_m6=local_nisq, + flat_slice=sl, + ) + ) + for k in range(sel_nodes.size): + dev_nodes_all.append(int(sel_nodes[k])) + reg_ids_all.append(region.identifier) + src_ids_all.append(sp.identifier) + e_ids_all.append(f"{mode_id}@{int(sel_nodes[k])}") + trans_all.append(sp.charge_transition) + pop_all.append(float(pop_vec[k])) + cn_all.append(cn) + cp_all.append(cp) + n1_all.append(float(n1_vec[k])) + p1_all.append(float(p1_vec[k])) + nisq_all.append(float(local_nisq[k])) + + if not modes: + raise ValueError("compile_dynamic_bulk_trap_layout found zero active trap modes") + + model_sha = _canonical_sha256({"regions": region_digests, "node_count": node_count}) + return DynamicBulkTrapLayout( + model_identity_sha256=model_sha, + node_count=node_count, + modes=tuple(modes), + device_node_indices=np.asarray(dev_nodes_all, dtype=np.int64), + region_identifiers=tuple(reg_ids_all), + source_identifiers=tuple(src_ids_all), + energy_node_identifiers=tuple(e_ids_all), + charge_transitions=tuple(trans_all), + population_density_m3=np.asarray(pop_all, dtype=np.float64), + capture_n_m3_s=np.asarray(cn_all, dtype=np.float64), + capture_p_m3_s=np.asarray(cp_all, dtype=np.float64), + n1_m3=np.asarray(n1_all, dtype=np.float64), + p1_m3=np.asarray(p1_all, dtype=np.float64), + intrinsic_product_m6=np.asarray(nisq_all, dtype=np.float64), + ) + + +def quasi_steady_bulk_trap_occupancy( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + layout: DynamicBulkTrapLayout, +) -> NDArray[np.float64]: + """Exact local QSS occupancy ``f_0 in (0, 1)`` in flat layout order.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + if n.shape != (layout.node_count,) or p.shape != (layout.node_count,): + raise ValueError("carrier densities must match layout.node_count") + idx = layout.device_node_indices + filled = layout.capture_n_m3_s * n[idx] + layout.capture_p_m3_s * layout.p1_m3 + empty = layout.capture_n_m3_s * layout.n1_m3 + layout.capture_p_m3_s * p[idx] + denom = filled + empty + if np.any(~np.isfinite(denom)) or np.any(denom <= 0.0): + raise ValueError("dynamic bulk trap kinetic denominator must be positive") + f = filled / denom + if np.any((f <= 0.0) | (f >= 1.0)): + raise ValueError("QSS trap occupancy saturated outside (0, 1)") + return _ro_float(f) + + +def quasi_steady_bulk_trap_logit( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + layout: DynamicBulkTrapLayout, +) -> NDArray[np.float64]: + """Cancellation-free QSS trap logit ``log(filled) - log(empty)`` in flat order.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + if n.shape != (layout.node_count,) or p.shape != (layout.node_count,): + raise ValueError("carrier densities must match layout.node_count") + idx = layout.device_node_indices + filled = layout.capture_n_m3_s * n[idx] + layout.capture_p_m3_s * layout.p1_m3 + empty = layout.capture_n_m3_s * layout.n1_m3 + layout.capture_p_m3_s * p[idx] + if np.any(~np.isfinite(filled)) or np.any(~np.isfinite(empty)) or np.any(filled <= 0.0) or np.any(empty <= 0.0): + raise ValueError("dynamic bulk trap capture/emission rates must be finite and positive") + return _ro_float(np.log(filled) - np.log(empty)) + + +def occupancy_logit( + occupancy: ArrayLike, layout: DynamicBulkTrapLayout | None = None +) -> NDArray[np.float64]: + """Map physical occupancy ``f in (0, 1)`` to unbounded logit ``log(f/(1-f))``.""" + f = np.asarray(occupancy, dtype=np.float64) + if layout is not None and f.shape != (layout.size,): + raise ValueError("occupancy shape does not match layout.size") + if np.any(~np.isfinite(f)) or np.any((f <= 0.0) | (f >= 1.0)): + raise ValueError("logit occupancy must be finite and strictly inside (0, 1)") + return _ro_float(np.log(f) - np.log1p(-f)) + + +def occupancy_from_logit_increment( + reference_logit: ArrayLike, + increment: ArrayLike, + layout: DynamicBulkTrapLayout | None = None, +) -> NDArray[np.float64]: + """Map ``reference_logit + increment`` back to physical occupancy ``f in (0, 1)``.""" + ref = np.asarray(reference_logit, dtype=np.float64) + inc = np.asarray(increment, dtype=np.float64) + if ref.shape != inc.shape: + raise ValueError("reference_logit and increment must have matching shapes") + if layout is not None and ref.shape != (layout.size,): + raise ValueError("logit shape does not match layout.size") + if np.any(~np.isfinite(ref)) or np.any(~np.isfinite(inc)): + raise ValueError("logit values must be finite") + f = stable_expit(ref + inc) + return _ro_float(f) + + +def one_minus_occupancy_from_logit_increment( + reference_logit: ArrayLike, + increment: ArrayLike, + layout: DynamicBulkTrapLayout | None = None, +) -> NDArray[np.float64]: + """Cancellation-free ``1 - f = expit(-(reference_logit + increment))``.""" + ref = np.asarray(reference_logit, dtype=np.float64) + inc = np.asarray(increment, dtype=np.float64) + if ref.shape != inc.shape: + raise ValueError("reference_logit and increment must have matching shapes") + if layout is not None and ref.shape != (layout.size,): + raise ValueError("logit shape does not match layout.size") + if np.any(~np.isfinite(ref)) or np.any(~np.isfinite(inc)): + raise ValueError("logit values must be finite") + omf = stable_expit(-(ref + inc)) + return _ro_float(omf) + + +def bulk_trap_charge_density( + occupancy: ArrayLike, + layout: DynamicBulkTrapLayout, + *, + one_minus_occupancy: ArrayLike | None = None, +) -> NDArray[np.float64]: + """Aggregate dynamic bulk-trap space charge [C m^-3] onto the device grid.""" + f = np.asarray(occupancy, dtype=np.float64) + if f.shape != (layout.size,): + raise ValueError("occupancy must match layout.size") + omf = ( + 1.0 - f + if one_minus_occupancy is None + else np.asarray(one_minus_occupancy, dtype=np.float64) + ) + trans = np.asarray(layout.charge_transitions) + local_rho: NDArray[np.float64] = np.zeros(layout.size, dtype=np.float64) + acc = trans == TRANSITION_ACCEPTOR + don = trans == TRANSITION_DONOR + local_rho[acc] = -Q * layout.population_density_m3[acc] * f[acc] + local_rho[don] = Q * layout.population_density_m3[don] * omf[don] + total: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + np.add.at(total, layout.device_node_indices, local_rho) + return _ro_float(total) + + +@dataclass(frozen=True, slots=True) +class DynamicBulkTrapEvaluation: + """Non-equilibrium dynamic bulk-trap rates, storage, charge, and exact tangents.""" + + occupancy: NDArray[np.float64] + one_minus_occupancy: NDArray[np.float64] + relaxation_rate_s1: NDArray[np.float64] + occupied_storage_m3: NDArray[np.float64] + trap_storage_rate_m3_s: NDArray[np.float64] + electron_capture_rate_m3_s: NDArray[np.float64] + hole_capture_rate_m3_s: NDArray[np.float64] + charge_density_C_m3: NDArray[np.float64] + # Exact analytical partial derivatives per flat trap state: + d_electron_capture_dn_s1: NDArray[np.float64] + d_electron_capture_df_m3_s: NDArray[np.float64] + d_hole_capture_dp_s1: NDArray[np.float64] + d_hole_capture_df_m3_s: NDArray[np.float64] + d_trap_storage_rate_dn_s1: NDArray[np.float64] + d_trap_storage_rate_dp_s1: NDArray[np.float64] + d_trap_storage_rate_df_m3_s: NDArray[np.float64] + d_charge_df_C_m3: NDArray[np.float64] + # Grid-summed totals (shape == (node_count,)): + total_electron_capture_rate_m3_s: NDArray[np.float64] + total_hole_capture_rate_m3_s: NDArray[np.float64] + total_trap_storage_rate_m3_s: NDArray[np.float64] + total_charge_density_C_m3: NDArray[np.float64] + + +def evaluate_dynamic_bulk_traps( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + occupancy: ArrayLike, + layout: DynamicBulkTrapLayout, + *, + one_minus_occupancy: ArrayLike | None = None, +) -> DynamicBulkTrapEvaluation: + """Evaluate dynamic bulk trap kinetics, storage, charge, and exact derivatives.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + f = np.asarray(occupancy, dtype=np.float64) + if n.shape != (layout.node_count,) or p.shape != (layout.node_count,): + raise ValueError("carrier vectors must match layout.node_count") + if f.shape != (layout.size,) or np.any(~np.isfinite(f)) or np.any((f < 0.0) | (f > 1.0)): + raise ValueError("occupancy must be finite in [0, 1] and match layout.size") + omf = ( + 1.0 - f + if one_minus_occupancy is None + else np.asarray(one_minus_occupancy, dtype=np.float64) + ) + + idx = layout.device_node_indices + nt = layout.population_density_m3 + cn = layout.capture_n_m3_s + cp = layout.capture_p_m3_s + n_loc = n[idx] + p_loc = p[idx] + + filled = cn * n_loc + cp * layout.p1_m3 + empty = cn * layout.n1_m3 + cp * p_loc + relax = filled + empty + offset = (f * empty - omf * filled) / relax + + qss_per_trap = cn * cp * (n_loc * p_loc - layout.intrinsic_product_m6) / relax + cap_n = nt * (qss_per_trap - cn * (n_loc + layout.n1_m3) * offset) + cap_p = nt * (qss_per_trap + cp * (p_loc + layout.p1_m3) * offset) + storage_rate = -nt * relax * offset + storage = nt * f + + trans = np.asarray(layout.charge_transitions) + acc = trans == TRANSITION_ACCEPTOR + don = trans == TRANSITION_DONOR + rho: NDArray[np.float64] = np.zeros(layout.size, dtype=np.float64) + d_rho_df: NDArray[np.float64] = np.zeros(layout.size, dtype=np.float64) + rho[acc] = -Q * storage[acc] + rho[don] = Q * nt[don] * omf[don] + d_rho_df[acc | don] = -Q * nt[acc | don] + + d_cap_n_dn = nt * cn * omf + d_cap_n_df = -nt * cn * (n_loc + layout.n1_m3) + d_cap_p_dp = nt * cp * f + d_cap_p_df = nt * cp * (p_loc + layout.p1_m3) + d_sr_dn = d_cap_n_dn + d_sr_dp = -d_cap_p_dp + d_sr_df = -nt * relax + + tot_cn: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_cp: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_sr: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_rho: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + np.add.at(tot_cn, idx, cap_n) + np.add.at(tot_cp, idx, cap_p) + np.add.at(tot_sr, idx, storage_rate) + np.add.at(tot_rho, idx, rho) + + return DynamicBulkTrapEvaluation( + occupancy=_ro_float(f), + one_minus_occupancy=_ro_float(omf), + relaxation_rate_s1=_ro_float(relax), + occupied_storage_m3=_ro_float(storage), + trap_storage_rate_m3_s=_ro_float(storage_rate), + electron_capture_rate_m3_s=_ro_float(cap_n), + hole_capture_rate_m3_s=_ro_float(cap_p), + charge_density_C_m3=_ro_float(rho), + d_electron_capture_dn_s1=_ro_float(d_cap_n_dn), + d_electron_capture_df_m3_s=_ro_float(d_cap_n_df), + d_hole_capture_dp_s1=_ro_float(d_cap_p_dp), + d_hole_capture_df_m3_s=_ro_float(d_cap_p_df), + d_trap_storage_rate_dn_s1=_ro_float(d_sr_dn), + d_trap_storage_rate_dp_s1=_ro_float(d_sr_dp), + d_trap_storage_rate_df_m3_s=_ro_float(d_sr_df), + d_charge_df_C_m3=_ro_float(d_rho_df), + total_electron_capture_rate_m3_s=_ro_float(tot_cn), + total_hole_capture_rate_m3_s=_ro_float(tot_cp), + total_trap_storage_rate_m3_s=_ro_float(tot_sr), + total_charge_density_C_m3=_ro_float(tot_rho), + ) + + +def evaluate_dynamic_bulk_traps_about_qss( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + occupancy: ArrayLike, + layout: DynamicBulkTrapLayout, + *, + reference_electron_density_m3: ArrayLike, + reference_hole_density_m3: ArrayLike, + reference_occupancy: ArrayLike, + occupancy_increment: ArrayLike | None = None, + one_minus_occupancy: ArrayLike | None = None, +) -> DynamicBulkTrapEvaluation: + """Exact bilinear increment evaluation about a certified QSS reference state.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + n0 = np.asarray(reference_electron_density_m3, dtype=np.float64) + p0 = np.asarray(reference_hole_density_m3, dtype=np.float64) + f = np.asarray(occupancy, dtype=np.float64) + f0 = np.asarray(reference_occupancy, dtype=np.float64) + df = f - f0 if occupancy_increment is None else np.asarray(occupancy_increment, dtype=np.float64) + omf = ( + 1.0 - f + if one_minus_occupancy is None + else np.asarray(one_minus_occupancy, dtype=np.float64) + ) + + idx = layout.device_node_indices + nt = layout.population_density_m3 + cn = layout.capture_n_m3_s + cp = layout.capture_p_m3_s + n_loc, p_loc = n[idx], p[idx] + n0_loc, p0_loc = n0[idx], p0[idx] + dn = n_loc - n0_loc + dp = p_loc - p0_loc + + relax = cn * (n_loc + layout.n1_m3) + cp * (p_loc + layout.p1_m3) + relax0 = cn * (n0_loc + layout.n1_m3) + cp * (p0_loc + layout.p1_m3) + qss0 = cn * cp * (n0_loc * p0_loc - layout.intrinsic_product_m6) / relax0 + + cap_n = nt * (qss0 + cn * (1.0 - f0) * dn - cn * (n_loc + layout.n1_m3) * df) + cap_p = nt * (qss0 + cp * f0 * dp + cp * (p_loc + layout.p1_m3) * df) + storage_rate = nt * (cn * (1.0 - f0) * dn - cp * f0 * dp - relax * df) + storage = nt * f + + trans = np.asarray(layout.charge_transitions) + acc = trans == TRANSITION_ACCEPTOR + don = trans == TRANSITION_DONOR + rho: NDArray[np.float64] = np.zeros(layout.size, dtype=np.float64) + d_rho_df: NDArray[np.float64] = np.zeros(layout.size, dtype=np.float64) + rho[acc] = -Q * storage[acc] + rho[don] = Q * nt[don] * omf[don] + d_rho_df[acc | don] = -Q * nt[acc | don] + + d_cap_n_dn = nt * cn * omf + d_cap_n_df = -nt * cn * (n_loc + layout.n1_m3) + d_cap_p_dp = nt * cp * f + d_cap_p_df = nt * cp * (p_loc + layout.p1_m3) + d_sr_dn = d_cap_n_dn + d_sr_dp = -d_cap_p_dp + d_sr_df = -nt * relax + + tot_cn: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_cp: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_sr: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + tot_rho: NDArray[np.float64] = np.zeros(layout.node_count, dtype=np.float64) + np.add.at(tot_cn, idx, cap_n) + np.add.at(tot_cp, idx, cap_p) + np.add.at(tot_sr, idx, storage_rate) + np.add.at(tot_rho, idx, rho) + + return DynamicBulkTrapEvaluation( + occupancy=_ro_float(f), + one_minus_occupancy=_ro_float(omf), + relaxation_rate_s1=_ro_float(relax), + occupied_storage_m3=_ro_float(storage), + trap_storage_rate_m3_s=_ro_float(storage_rate), + electron_capture_rate_m3_s=_ro_float(cap_n), + hole_capture_rate_m3_s=_ro_float(cap_p), + charge_density_C_m3=_ro_float(rho), + d_electron_capture_dn_s1=_ro_float(d_cap_n_dn), + d_electron_capture_df_m3_s=_ro_float(d_cap_n_df), + d_hole_capture_dp_s1=_ro_float(d_cap_p_dp), + d_hole_capture_df_m3_s=_ro_float(d_cap_p_df), + d_trap_storage_rate_dn_s1=_ro_float(d_sr_dn), + d_trap_storage_rate_dp_s1=_ro_float(d_sr_dp), + d_trap_storage_rate_df_m3_s=_ro_float(d_sr_df), + d_charge_df_C_m3=_ro_float(d_rho_df), + total_electron_capture_rate_m3_s=_ro_float(tot_cn), + total_hole_capture_rate_m3_s=_ro_float(tot_cp), + total_trap_storage_rate_m3_s=_ro_float(tot_sr), + total_charge_density_C_m3=_ro_float(tot_rho), + ) + + +@dataclass(frozen=True, slots=True) +class DynamicInterfaceTrapSpec: + """Microscopic two-sided heterointerface trap parameters.""" + + interface_id: str + left_node: int + right_node: int + charge_type: str + sheet_density_m2: float + v_n_m_s: float + v_p_m_s: float + n1_left_m3: float + p1_left_m3: float + n1_right_m3: float + p1_right_m3: float + equilibrium_occupancy: float + equilibrium_referenced_charge: bool = True + + def __post_init__(self) -> None: + if self.right_node != self.left_node + 1 or self.left_node < 0: + raise ValueError("DynamicInterfaceTrapSpec requires adjacent left/right nodes") + if self.charge_type not in SUPPORTED_MONOVALENT_TRANSITIONS: + raise ValueError(f"unsupported interface charge_type: {self.charge_type!r}") + nt = _finite_positive(self.sheet_density_m2, "sheet_density_m2") + vn = _finite_nonnegative(self.v_n_m_s, "v_n_m_s") + vp = _finite_nonnegative(self.v_p_m_s, "v_p_m_s") + if vn == 0.0 and vp == 0.0: + raise ValueError("dynamic interface trap requires v_n > 0 or v_p > 0") + feq = float(self.equilibrium_occupancy) + if not math.isfinite(feq) or not 0.0 < feq < 1.0: + raise ValueError("equilibrium_occupancy must lie strictly inside (0, 1)") + object.__setattr__(self, "sheet_density_m2", nt) + object.__setattr__(self, "v_n_m_s", vn) + object.__setattr__(self, "v_p_m_s", vp) + + +@dataclass(frozen=True, slots=True) +class DynamicInterfaceTrapEvaluation: + """Two-sided interface trap capture, storage, sheet charge, and exact tangents.""" + + occupancy: float + one_minus_occupancy: float + qss_occupancy: float + relaxation_rate_s1: float + occupied_storage_m2: float + trap_storage_rate_m2_s: float + cap_n_left_m2_s: float + cap_n_right_m2_s: float + cap_p_left_m2_s: float + cap_p_right_m2_s: float + sheet_charge_C_m2: float + # Exact partial derivatives wrt (n_L, p_L, n_R, p_R, f): + d_cap_n_left_dn_L: float + d_cap_n_left_df: float + d_cap_n_right_dn_R: float + d_cap_n_right_df: float + d_cap_p_left_dp_L: float + d_cap_p_left_df: float + d_cap_p_right_dp_R: float + d_cap_p_right_df: float + d_storage_rate_dn_L: float + d_storage_rate_dp_L: float + d_storage_rate_dn_R: float + d_storage_rate_dp_R: float + d_storage_rate_df: float + d_sheet_charge_df: float + + +def evaluate_dynamic_interface_trap( + spec: DynamicInterfaceTrapSpec, + *, + n_left_m3: float, + p_left_m3: float, + n_right_m3: float, + p_right_m3: float, + occupancy: float, + one_minus_occupancy: float | None = None, + occupancy_minus_equilibrium: float | None = None, +) -> DynamicInterfaceTrapEvaluation: + """Evaluate two-sided interface trap kinetics, sheet charge, and tangents.""" + f = float(occupancy) + omf = 1.0 - f if one_minus_occupancy is None else float(one_minus_occupancy) + vn = spec.v_n_m_s + vp = spec.v_p_m_s + nt = spec.sheet_density_m2 + + filled = vn * (n_left_m3 + n_right_m3) + vp * (spec.p1_left_m3 + spec.p1_right_m3) + empty = vn * (spec.n1_left_m3 + spec.n1_right_m3) + vp * (p_left_m3 + p_right_m3) + denom = filled + empty + if not math.isfinite(denom) or denom <= 0.0: + raise FloatingPointError("dynamic interface trap kinetic denominator is invalid") + f_qss = filled / denom + relax = denom / nt + + cap_n_l = vn * (n_left_m3 * omf - spec.n1_left_m3 * f) + cap_n_r = vn * (n_right_m3 * omf - spec.n1_right_m3 * f) + cap_p_l = vp * (p_left_m3 * f - spec.p1_left_m3 * omf) + cap_p_r = vp * (p_right_m3 * f - spec.p1_right_m3 * omf) + # Exact sum (cap_n_l + cap_n_r) - (cap_p_l + cap_p_r) == filled - denom * f: + storage_rate = -denom * (f - f_qss) + + if spec.charge_type == TRANSITION_NEUTRAL: + sigma = 0.0 + d_sigma_df = 0.0 + elif spec.equilibrium_referenced_charge: + df_eq = ( + f - spec.equilibrium_occupancy + if occupancy_minus_equilibrium is None + else float(occupancy_minus_equilibrium) + ) + sigma = -Q * nt * df_eq + d_sigma_df = -Q * nt + elif spec.charge_type == TRANSITION_ACCEPTOR: + sigma = -Q * nt * f + d_sigma_df = -Q * nt + else: + sigma = Q * nt * omf + d_sigma_df = -Q * nt + + return DynamicInterfaceTrapEvaluation( + occupancy=f, + one_minus_occupancy=omf, + qss_occupancy=f_qss, + relaxation_rate_s1=relax, + occupied_storage_m2=nt * f, + trap_storage_rate_m2_s=storage_rate, + cap_n_left_m2_s=cap_n_l, + cap_n_right_m2_s=cap_n_r, + cap_p_left_m2_s=cap_p_l, + cap_p_right_m2_s=cap_p_r, + sheet_charge_C_m2=sigma, + d_cap_n_left_dn_L=vn * omf, + d_cap_n_left_df=-vn * (n_left_m3 + spec.n1_left_m3), + d_cap_n_right_dn_R=vn * omf, + d_cap_n_right_df=-vn * (n_right_m3 + spec.n1_right_m3), + d_cap_p_left_dp_L=vp * f, + d_cap_p_left_df=vp * (p_left_m3 + spec.p1_left_m3), + d_cap_p_right_dp_R=vp * f, + d_cap_p_right_df=vp * (p_right_m3 + spec.p1_right_m3), + d_storage_rate_dn_L=vn * omf, + d_storage_rate_dp_L=-vp * f, + d_storage_rate_dn_R=vn * omf, + d_storage_rate_dp_R=-vp * f, + d_storage_rate_df=-denom, + d_sheet_charge_df=d_sigma_df, + ) diff --git a/src/solarlab/physics/defects/metastable.py b/src/solarlab/physics/defects/metastable.py new file mode 100644 index 00000000..98f63280 --- /dev/null +++ b/src/solarlab/physics/defects/metastable.py @@ -0,0 +1,644 @@ +"""Metastable donor/acceptor configuration kinetics, frozen closure, and step advance. + +Implements the Lany-Zunger / Igalson two-configuration metastable defect model: +- Stationary infinite-time configuration closure ``y* = k_AD / (k_DA + k_AD)`` + with exact detailed-balance barrier verification and carrier derivatives; +- Frozen-configuration bulk evaluation weighting separate donor ``N_t * y`` and + acceptor ``N_t * (1 - y)`` multivalent closures; +- Exact piecewise-exponential step advance ``y(t + dt) = y* + (y(t) - y*) exp(-(k_DA + k_AD) dt)`` + and fixed-carrier configuration charge transfer ``Delta_rho_cfg = q * N_t * ( - ) * Delta_y``. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.physics.defects.dynamic_single_level import stable_expit +from solarlab.physics.defects.multivalent import ( + MultivalentConfigurationSpec, + MultivalentDefectNeutralityState, + MultivalentSpeciesSpec, + evaluate_multivalent_defect_closure, + solve_multivalent_defect_charge_neutrality, +) +from solarlab.physics.statistics import thermal_voltage + +DOUBLE_ELECTRON_CAPTURE = "double_electron_capture" +ELECTRON_CAPTURE_PLUS_HOLE_EMISSION = "electron_capture_plus_hole_emission" +DOUBLE_HOLE_CAPTURE = "double_hole_capture" +HOLE_CAPTURE_PLUS_ELECTRON_EMISSION = "hole_capture_plus_electron_emission" + +__all__ = [ + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "advance_metastable_configuration", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "solve_frozen_metastable_charge_neutrality", +] + + +def _ro_float(values: ArrayLike) -> NDArray[np.float64]: + arr = np.array(values, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(values: ArrayLike) -> NDArray[np.bool_]: + arr = np.array(values, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +def _finite_positive(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and positive") + number = float(value) + if not math.isfinite(number) or number <= 0.0: + raise ValueError(f"{name} must be finite and positive") + return number + + +def _finite_nonnegative(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and non-negative") + number = float(value) + if not math.isfinite(number) or number < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + return number + + +@dataclass(frozen=True, slots=True) +class MetastableConversionKineticsSpec: + """Thermally activated two-carrier conversion barriers and attempt frequency.""" + + transition_energy_eV_above_vb: float + electron_capture_activation_eV: float + electron_emission_activation_eV: float + hole_capture_activation_eV: float + hole_emission_activation_eV: float + electron_capture_path: str + hole_capture_path: str + capture_n_m3_s: float + capture_p_m3_s: float + phonon_frequency_Hz: float + + def __post_init__(self) -> None: + if self.electron_capture_path not in ( + DOUBLE_ELECTRON_CAPTURE, + ELECTRON_CAPTURE_PLUS_HOLE_EMISSION, + ): + raise ValueError( + f"unsupported electron_capture_path: {self.electron_capture_path!r}" + ) + if self.hole_capture_path not in ( + DOUBLE_HOLE_CAPTURE, + HOLE_CAPTURE_PLUS_ELECTRON_EMISSION, + ): + raise ValueError( + f"unsupported hole_capture_path: {self.hole_capture_path!r}" + ) + _finite_nonnegative( + self.transition_energy_eV_above_vb, "transition_energy_eV_above_vb" + ) + _finite_nonnegative( + self.electron_capture_activation_eV, "electron_capture_activation_eV" + ) + _finite_nonnegative( + self.electron_emission_activation_eV, "electron_emission_activation_eV" + ) + _finite_nonnegative( + self.hole_capture_activation_eV, "hole_capture_activation_eV" + ) + _finite_nonnegative( + self.hole_emission_activation_eV, "hole_emission_activation_eV" + ) + _finite_positive(self.capture_n_m3_s, "capture_n_m3_s") + _finite_positive(self.capture_p_m3_s, "capture_p_m3_s") + _finite_positive(self.phonon_frequency_Hz, "phonon_frequency_Hz") + + def validate_band_gap(self, band_gap_eV: float) -> None: + gap = _finite_positive(band_gap_eV, "band_gap_eV") + tr = self.transition_energy_eV_above_vb + if tr > gap: + raise ValueError("metastable transition energy lies outside [0, band_gap_eV]") + ec = self.electron_capture_activation_eV + hc = self.hole_capture_activation_eV + expected_ee = ( + ec + 2.0 * (gap - tr) + if self.electron_capture_path == DOUBLE_ELECTRON_CAPTURE + else ec + gap - 2.0 * tr + ) + expected_he = ( + hc + 2.0 * tr + if self.hole_capture_path == DOUBLE_HOLE_CAPTURE + else hc + 2.0 * tr - gap + ) + tol = 64.0 * math.ulp( + max( + gap, + tr, + abs(expected_ee), + abs(expected_he), + self.electron_emission_activation_eV, + self.hole_emission_activation_eV, + 1.0, + ) + ) + if ( + abs(self.electron_emission_activation_eV - expected_ee) > tol + or abs(self.hole_emission_activation_eV - expected_he) > tol + ): + raise ValueError("metastable activation barriers violate detailed balance") + + +@dataclass(frozen=True, slots=True) +class MetastableDefectSpec: + """Two-configuration metastable defect species (donor vs acceptor branches).""" + + identifier: str + total_density_m3: float + donor_configuration: MultivalentConfigurationSpec + acceptor_configuration: MultivalentConfigurationSpec + donor_conversion_state_index: int + acceptor_conversion_state_index: int + conversion_kinetics: MetastableConversionKineticsSpec + + def __post_init__(self) -> None: + ident = str(self.identifier).strip() + if not ident: + raise ValueError("MetastableDefectSpec requires a non-empty identifier") + nt = _finite_positive(self.total_density_m3, "total_density_m3") + di = int(self.donor_conversion_state_index) + ai = int(self.acceptor_conversion_state_index) + d_charges = self.donor_configuration.charge_states_e + a_charges = self.acceptor_configuration.charge_states_e + if not (0 <= di < len(d_charges) and 0 <= ai < len(a_charges)): + raise ValueError("conversion state indices out of configuration bounds") + if d_charges[di] - a_charges[ai] != 2: + raise ValueError("metastable conversion states must differ by +2e") + object.__setattr__(self, "identifier", ident) + object.__setattr__(self, "total_density_m3", nt) + + def validate_band_gap(self, band_gap_eV: float) -> None: + self.donor_configuration.validate_band_gap(band_gap_eV) + self.acceptor_configuration.validate_band_gap(band_gap_eV) + self.conversion_kinetics.validate_band_gap(band_gap_eV) + + +@dataclass(frozen=True, slots=True) +class MetastableConfigurationClosureResult: + """Stationary donor/acceptor configuration fractions, rates, and tangents.""" + + defect_identifier: str + total_density_m3: float + donor_to_acceptor_rate_s1: NDArray[np.float64] + acceptor_to_donor_rate_s1: NDArray[np.float64] + total_conversion_rate_s1: NDArray[np.float64] + donor_fraction: NDArray[np.float64] + acceptor_fraction: NDArray[np.float64] + donor_fraction_derivative_n_m3: NDArray[np.float64] + donor_fraction_derivative_p_m3: NDArray[np.float64] + donor_density_m3: NDArray[np.float64] + acceptor_density_m3: NDArray[np.float64] + maximum_stationary_residual_s1: float + maximum_rate_s1: float + + def __post_init__(self) -> None: + for name in ( + "donor_to_acceptor_rate_s1", + "acceptor_to_donor_rate_s1", + "total_conversion_rate_s1", + "donor_fraction", + "acceptor_fraction", + "donor_fraction_derivative_n_m3", + "donor_fraction_derivative_p_m3", + "donor_density_m3", + "acceptor_density_m3", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + +def evaluate_metastable_configuration_closure( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + spec: MetastableDefectSpec, + *, + band_gap_eV: ArrayLike, + effective_conduction_dos_m3: ArrayLike, + effective_valence_dos_m3: ArrayLike, + temperature_K: float, +) -> MetastableConfigurationClosureResult: + """Evaluate stationary ``y* = k_AD / (k_DA + k_AD)`` and exact carrier tangents.""" + n, p = np.broadcast_arrays( + np.asarray(electron_density_m3, dtype=np.float64), + np.asarray(hole_density_m3, dtype=np.float64), + ) + if np.any(~np.isfinite(n)) or np.any(~np.isfinite(p)) or np.any(n <= 0.0) or np.any(p <= 0.0): + raise ValueError("metastable closure requires finite positive carrier densities") + gap = np.broadcast_to(np.asarray(band_gap_eV, dtype=np.float64), n.shape) + nc = np.broadcast_to( + np.asarray(effective_conduction_dos_m3, dtype=np.float64), n.shape + ) + nv = np.broadcast_to( + np.asarray(effective_valence_dos_m3, dtype=np.float64), n.shape + ) + spec.validate_band_gap(float(np.min(gap))) + vt = thermal_voltage(_finite_positive(temperature_K, "temperature_K")) + kin = spec.conversion_kinetics + + red_n = n / nc + red_p = p / nv + e_act = ( + red_n * red_n + if kin.electron_capture_path == DOUBLE_ELECTRON_CAPTURE + else red_n / red_p + ) + h_act = ( + red_p * red_p + if kin.hole_capture_path == DOUBLE_HOLE_CAPTURE + else red_p / red_n + ) + + e_pref = kin.capture_n_m3_s * nc + h_pref = kin.capture_p_m3_s * nv + e_cap = e_pref * e_act * math.exp(-kin.electron_capture_activation_eV / vt) + e_em = e_pref * math.exp(-kin.electron_emission_activation_eV / vt) + h_cap = h_pref * h_act * math.exp(-kin.hole_capture_activation_eV / vt) + h_em = h_pref * math.exp(-kin.hole_emission_activation_eV / vt) + + k_da = e_cap + h_em + k_ad = h_cap + e_em + k_tot = k_da + k_ad + if np.any(~np.isfinite(k_tot)) or np.any(k_da <= 0.0) or np.any(k_ad <= 0.0): + raise FloatingPointError("metastable conversion rates must be finite and positive") + peak_rate = float(np.max(k_tot)) + if peak_rate > kin.phonon_frequency_Hz: + raise ValueError( + f"metastable conversion rate {peak_rate:.6g} Hz exceeds phonon attempt " + f"frequency {kin.phonon_frequency_Hz:.6g} Hz" + ) + + y_star = k_ad / k_tot + one_minus_y = k_da / k_tot + res = np.abs(k_ad * one_minus_y - k_da * y_star) + + if kin.electron_capture_path == DOUBLE_ELECTRON_CAPTURE: + de_dn = 2.0 * e_cap / n + de_dp = np.zeros_like(n) + else: + de_dn = e_cap / n + de_dp = -e_cap / p + if kin.hole_capture_path == DOUBLE_HOLE_CAPTURE: + dh_dp = 2.0 * h_cap / p + dh_dn = np.zeros_like(n) + else: + dh_dp = h_cap / p + dh_dn = -h_cap / n + + dy_dn = (dh_dn * k_tot - k_ad * (de_dn + dh_dn)) / (k_tot * k_tot) + dy_dp = (dh_dp * k_tot - k_ad * (de_dp + dh_dp)) / (k_tot * k_tot) + nt = spec.total_density_m3 + + return MetastableConfigurationClosureResult( + defect_identifier=spec.identifier, + total_density_m3=nt, + donor_to_acceptor_rate_s1=k_da, + acceptor_to_donor_rate_s1=k_ad, + total_conversion_rate_s1=k_tot, + donor_fraction=y_star, + acceptor_fraction=one_minus_y, + donor_fraction_derivative_n_m3=dy_dn, + donor_fraction_derivative_p_m3=dy_dp, + donor_density_m3=nt * y_star, + acceptor_density_m3=nt * one_minus_y, + maximum_stationary_residual_s1=float(np.max(res)), + maximum_rate_s1=peak_rate, + ) + + +def configuration_logit(donor_fraction: ArrayLike) -> NDArray[np.float64]: + """Unbounded logit coordinate ``log(y / (1 - y))`` without clipping.""" + y = np.asarray(donor_fraction, dtype=np.float64) + if np.any(~np.isfinite(y)) or np.any((y <= 0.0) | (y >= 1.0)): + raise ValueError("metastable donor_fraction must lie strictly inside (0, 1)") + return _ro_float(np.log(y) - np.log1p(-y)) + + +def configuration_from_logit(logit: ArrayLike) -> NDArray[np.float64]: + """Map logit coordinate back to ``y in (0, 1)`` without clipping.""" + x = np.asarray(logit, dtype=np.float64) + if np.any(~np.isfinite(x)): + raise ValueError("metastable logit must be finite") + y = stable_expit(x) + if np.any((y <= 0.0) | (y >= 1.0)): + raise ValueError("metastable logit saturated outside (0, 1)") + return _ro_float(y) + + +@dataclass(frozen=True, slots=True) +class FrozenMetastableRegion: + """Metastable bulk-defect region evaluated at a fixed donor fraction profile ``y``.""" + + identifier: str + document_sha256: str + active_nodes: NDArray[np.bool_] + band_gap_eV: NDArray[np.float64] + effective_conduction_dos_m3: NDArray[np.float64] + effective_valence_dos_m3: NDArray[np.float64] + temperature_K: float + species: tuple[MetastableDefectSpec, ...] + donor_fractions: NDArray[np.float64] # shape: (len(species), active_node_count) + frozen: bool = True + + def __post_init__(self) -> None: + mask = _ro_bool(self.active_nodes) + if mask.ndim != 1 or not np.any(mask): + raise ValueError("active_nodes must be a non-empty 1D boolean mask") + active_count = int(np.sum(mask)) + sp = tuple(self.species) + if not sp: + raise ValueError("FrozenMetastableRegion requires at least one species") + y = _ro_float(self.donor_fractions) + if y.shape != (len(sp), active_count) or np.any(~np.isfinite(y)) or np.any((y < 0.0) | (y > 1.0)): + raise ValueError( + "donor_fractions must have shape (len(species), active_count) in [0, 1]" + ) + gap = _ro_float(np.broadcast_to(self.band_gap_eV, (active_count,))) + nc = _ro_float( + np.broadcast_to(self.effective_conduction_dos_m3, (active_count,)) + ) + nv = _ro_float( + np.broadcast_to(self.effective_valence_dos_m3, (active_count,)) + ) + temp = _finite_positive(self.temperature_K, "temperature_K") + min_gap = float(np.min(gap)) + for item in sp: + item.validate_band_gap(min_gap) + object.__setattr__(self, "active_nodes", mask) + object.__setattr__(self, "band_gap_eV", gap) + object.__setattr__(self, "effective_conduction_dos_m3", nc) + object.__setattr__(self, "effective_valence_dos_m3", nv) + object.__setattr__(self, "temperature_K", temp) + object.__setattr__(self, "species", sp) + object.__setattr__(self, "donor_fractions", y) + + +@dataclass(frozen=True, slots=True) +class FrozenMetastableEvaluation: + """Grid-aligned charge, SRH recombination, and exact tangents at fixed ``y``.""" + + donor_mean_charge_e: NDArray[np.float64] # (len(species), active_count) + acceptor_mean_charge_e: NDArray[np.float64] # (len(species), active_count) + total_charge_density_C_m3: NDArray[np.float64] # (node_count,) + total_charge_derivative_n_C: NDArray[np.float64] + total_charge_derivative_p_C: NDArray[np.float64] + total_charge_derivative_fixed_qf_C_m3_V: NDArray[np.float64] + total_recombination_rate_m3_s: NDArray[np.float64] + total_recombination_derivative_n_s1: NDArray[np.float64] + total_recombination_derivative_p_s1: NDArray[np.float64] + + def __post_init__(self) -> None: + for name in ( + "donor_mean_charge_e", + "acceptor_mean_charge_e", + "total_charge_density_C_m3", + "total_charge_derivative_n_C", + "total_charge_derivative_p_C", + "total_charge_derivative_fixed_qf_C_m3_V", + "total_recombination_rate_m3_s", + "total_recombination_derivative_n_s1", + "total_recombination_derivative_p_s1", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + +def evaluate_frozen_metastable_region( + region: FrozenMetastableRegion, + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, +) -> FrozenMetastableEvaluation: + """Evaluate donor + acceptor multivalent branches weighted by frozen ``y``.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + node_count = region.active_nodes.size + if n.shape != (node_count,) or p.shape != (node_count,): + raise ValueError("carrier vectors must match region.active_nodes") + mask = region.active_nodes + n_loc = n[mask] + p_loc = p[mask] + active_count = n_loc.size + s_count = len(region.species) + + q_don = np.zeros((s_count, active_count), dtype=np.float64) + q_acc = np.zeros((s_count, active_count), dtype=np.float64) + tot_rho = np.zeros(node_count, dtype=np.float64) + tot_drho_dn = np.zeros(node_count, dtype=np.float64) + tot_drho_dp = np.zeros(node_count, dtype=np.float64) + tot_drho_dphi = np.zeros(node_count, dtype=np.float64) + tot_r = np.zeros(node_count, dtype=np.float64) + tot_dr_dn = np.zeros(node_count, dtype=np.float64) + tot_dr_dp = np.zeros(node_count, dtype=np.float64) + + for idx, sp in enumerate(region.species): + y = region.donor_fractions[idx] + one_minus_y = 1.0 - y + # Evaluate unit-density multivalent branches, then scale by N_t * y and N_t * (1 - y): + don_sp = MultivalentSpeciesSpec( + f"{sp.identifier}:donor", sp.total_density_m3, sp.donor_configuration + ) + acc_sp = MultivalentSpeciesSpec( + f"{sp.identifier}:acceptor", sp.total_density_m3, sp.acceptor_configuration + ) + d_res = evaluate_multivalent_defect_closure( + n_loc, + p_loc, + don_sp, + band_gap_eV=region.band_gap_eV, + effective_conduction_dos_m3=region.effective_conduction_dos_m3, + effective_valence_dos_m3=region.effective_valence_dos_m3, + temperature_K=region.temperature_K, + ) + a_res = evaluate_multivalent_defect_closure( + n_loc, + p_loc, + acc_sp, + band_gap_eV=region.band_gap_eV, + effective_conduction_dos_m3=region.effective_conduction_dos_m3, + effective_valence_dos_m3=region.effective_valence_dos_m3, + temperature_K=region.temperature_K, + ) + q_don[idx] = d_res.mean_charge_e + q_acc[idx] = a_res.mean_charge_e + + tot_rho[mask] += y * d_res.charge_density_C_m3 + one_minus_y * a_res.charge_density_C_m3 + tot_drho_dn[mask] += y * d_res.charge_derivative_n_C + one_minus_y * a_res.charge_derivative_n_C + tot_drho_dp[mask] += y * d_res.charge_derivative_p_C + one_minus_y * a_res.charge_derivative_p_C + tot_drho_dphi[mask] += ( + y * d_res.charge_derivative_fixed_qf_C_m3_V + + one_minus_y * a_res.charge_derivative_fixed_qf_C_m3_V + ) + tot_r[mask] += ( + y * d_res.total_recombination_rate_m3_s + + one_minus_y * a_res.total_recombination_rate_m3_s + ) + tot_dr_dn[mask] += ( + y * d_res.total_recombination_derivative_n_s1 + + one_minus_y * a_res.total_recombination_derivative_n_s1 + ) + tot_dr_dp[mask] += ( + y * d_res.total_recombination_derivative_p_s1 + + one_minus_y * a_res.total_recombination_derivative_p_s1 + ) + + return FrozenMetastableEvaluation( + donor_mean_charge_e=q_don, + acceptor_mean_charge_e=q_acc, + total_charge_density_C_m3=tot_rho, + total_charge_derivative_n_C=tot_drho_dn, + total_charge_derivative_p_C=tot_drho_dp, + total_charge_derivative_fixed_qf_C_m3_V=tot_drho_dphi, + total_recombination_rate_m3_s=tot_r, + total_recombination_derivative_n_s1=tot_dr_dn, + total_recombination_derivative_p_s1=tot_dr_dp, + ) + + +def solve_frozen_metastable_charge_neutrality( + *, + temperature_K: float, + band_gap_eV: float, + effective_conduction_dos_m3: float, + effective_valence_dos_m3: float, + donor_density_m3: float, + acceptor_density_m3: float, + species: Sequence[MetastableDefectSpec], + donor_fractions: Sequence[float], + electron_affinity_eV: float | None = None, +) -> MultivalentDefectNeutralityState: + """Solve equilibrium contact/bulk charge neutrality at frozen donor fractions.""" + if len(species) != len(donor_fractions): + raise ValueError("one donor_fraction is required per metastable species") + mv_species: list[MultivalentSpeciesSpec] = [] + for sp, y in zip(species, donor_fractions): + yf = float(y) + if not 0.0 <= yf <= 1.0: + raise ValueError("donor_fraction must lie in [0, 1]") + if yf > 0.0: + mv_species.append( + MultivalentSpeciesSpec( + f"{sp.identifier}:donor", + sp.total_density_m3 * yf, + sp.donor_configuration, + ) + ) + if 1.0 - yf > 0.0: + mv_species.append( + MultivalentSpeciesSpec( + f"{sp.identifier}:acceptor", + sp.total_density_m3 * (1.0 - yf), + sp.acceptor_configuration, + ) + ) + return solve_multivalent_defect_charge_neutrality( + temperature_K=temperature_K, + band_gap_eV=band_gap_eV, + effective_conduction_dos_m3=effective_conduction_dos_m3, + effective_valence_dos_m3=effective_valence_dos_m3, + donor_density_m3=donor_density_m3, + acceptor_density_m3=acceptor_density_m3, + species=mv_species, + electron_affinity_eV=electron_affinity_eV, + ) + + +def configuration_charge_transfer_C_m3( + total_density_m3: float, + donor_mean_charge_e: ArrayLike, + acceptor_mean_charge_e: ArrayLike, + delta_donor_fraction: ArrayLike, +) -> NDArray[np.float64]: + """Exact fixed-carrier space-charge transfer ``q N_t ( - ) Delta_y``.""" + nt = _finite_positive(total_density_m3, "total_density_m3") + qd = np.asarray(donor_mean_charge_e, dtype=np.float64) + qa = np.asarray(acceptor_mean_charge_e, dtype=np.float64) + dy = np.asarray(delta_donor_fraction, dtype=np.float64) + return _ro_float(Q * nt * (qd - qa) * dy) + + +@dataclass(frozen=True, slots=True) +class MetastableDynamicStep: + """Exact frozen-rate exponential advance of ``y(t)`` over one interval ``dt_s``.""" + + dt_s: float + previous_donor_fraction: NDArray[np.float64] + stationary_donor_fraction: NDArray[np.float64] + next_donor_fraction: NDArray[np.float64] + delta_donor_fraction: NDArray[np.float64] + next_logit: NDArray[np.float64] + total_conversion_rate_s1: NDArray[np.float64] + clipping_used: bool = False + + def __post_init__(self) -> None: + for name in ( + "previous_donor_fraction", + "stationary_donor_fraction", + "next_donor_fraction", + "delta_donor_fraction", + "next_logit", + "total_conversion_rate_s1", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + +def advance_metastable_configuration( + previous_donor_fraction: ArrayLike, + closure: MetastableConfigurationClosureResult, + dt_s: float, +) -> MetastableDynamicStep: + """Advance ``dy/dt = -k_DA y + k_AD (1 - y)`` analytically at frozen rates.""" + dt = _finite_positive(dt_s, "dt_s") + y_prev = np.asarray(previous_donor_fraction, dtype=np.float64) + y_star = closure.donor_fraction + if y_prev.shape != y_star.shape: + raise ValueError("previous_donor_fraction shape must match closure.donor_fraction") + if np.any((y_prev <= 0.0) | (y_prev >= 1.0)): + raise ValueError("previous_donor_fraction must lie strictly inside (0, 1)") + + k_tot = closure.total_conversion_rate_s1 + # Cancellation-safe increment: y_next - y_prev = (y_star - y_prev) * (-expm1(-k_tot * dt)) + decay_complement = -np.expm1(-k_tot * dt) + delta_y = (y_star - y_prev) * decay_complement + y_next = y_prev + delta_y + if np.any((y_next <= 0.0) | (y_next >= 1.0)): + raise ValueError( + "metastable configuration advance saturated outside (0, 1) without clipping" + ) + logit_next = configuration_logit(y_next) + return MetastableDynamicStep( + dt_s=dt, + previous_donor_fraction=y_prev, + stationary_donor_fraction=y_star, + next_donor_fraction=y_next, + delta_donor_fraction=delta_y, + next_logit=logit_next, + total_conversion_rate_s1=k_tot, + clipping_used=False, + ) diff --git a/src/solarlab/physics/defects/multivalent.py b/src/solarlab/physics/defects/multivalent.py new file mode 100644 index 00000000..4c1b130f --- /dev/null +++ b/src/solarlab/physics/defects/multivalent.py @@ -0,0 +1,540 @@ +"""Multivalent / amphoteric defect grand-partition closure and exact tangents. + +Implements the Decock-Khelifi-Burgelman coupled charge-state chain on 2..5 +descending integer charge states ``q_0 > q_1 > ... > q_{M-1}`` with explicit +state degeneracies ``g_s`` (`unity`, `scaps_binomial`, or `explicit`), log-space +partition normalization (preventing overflow/underflow without clipping), +cancellation-free ``(P_s + P_{s+1}) * c_n c_p (n p - n_i^2) / (a_s + b_s)`` +stationary SRH transition rates, and exact analytical tangents with respect to +``(n, p)`` and fixed-QF ``phi``. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.physics.statistics import ( + CHARGE_NEUTRALITY_RELATIVE_TOLERANCE, + thermal_voltage, +) + +__all__ = [ + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "solve_multivalent_defect_charge_neutrality", +] + + +def _ro_float(values: ArrayLike) -> NDArray[np.float64]: + arr = np.array(values, dtype=np.float64, copy=True) + arr.setflags(write=False) + return arr + + +def _ro_bool(values: ArrayLike) -> NDArray[np.bool_]: + arr = np.array(values, dtype=np.bool_, copy=True) + arr.setflags(write=False) + return arr + + +def _finite_positive(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and positive") + number = float(value) + if not math.isfinite(number) or number <= 0.0: + raise ValueError(f"{name} must be finite and positive") + return number + + +def _finite_nonnegative(value: float, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite and non-negative") + number = float(value) + if not math.isfinite(number) or number < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + return number + + +@dataclass(frozen=True, slots=True) +class MultivalentTransitionKineticsSpec: + """Capture kinetics for one adjacent charge-state transition ``q_s <-> q_{s+1}``.""" + + sigma_n_m2: float + sigma_p_m2: float + thermal_velocity_n_m_s: float + thermal_velocity_p_m_s: float + + def __post_init__(self) -> None: + sn = _finite_nonnegative(self.sigma_n_m2, "sigma_n_m2") + sp = _finite_nonnegative(self.sigma_p_m2, "sigma_p_m2") + vn = _finite_positive(self.thermal_velocity_n_m_s, "thermal_velocity_n_m_s") + vp = _finite_positive(self.thermal_velocity_p_m_s, "thermal_velocity_p_m_s") + if sn == 0.0 and sp == 0.0: + raise ValueError("multivalent transition requires at least one nonzero capture leg") + object.__setattr__(self, "sigma_n_m2", sn) + object.__setattr__(self, "sigma_p_m2", sp) + object.__setattr__(self, "thermal_velocity_n_m_s", vn) + object.__setattr__(self, "thermal_velocity_p_m_s", vp) + + @property + def capture_n_m3_s(self) -> float: + return self.sigma_n_m2 * self.thermal_velocity_n_m_s + + @property + def capture_p_m3_s(self) -> float: + return self.sigma_p_m2 * self.thermal_velocity_p_m_s + + +@dataclass(frozen=True, slots=True) +class MultivalentConfigurationSpec: + """Charge-state ladder, degeneracies, transition energies, and kinetics.""" + + family: str + charge_states_e: tuple[int, ...] + degeneracy_convention: str + state_degeneracies: tuple[float, ...] + transition_energies_eV_above_vb: tuple[float, ...] + transition_kinetics: tuple[MultivalentTransitionKineticsSpec, ...] + + def __post_init__(self) -> None: + charges = tuple(self.charge_states_e) + if not 2 <= len(charges) <= 5 or any( + isinstance(c, bool) or not isinstance(c, int) or not -3 <= c <= 3 + for c in charges + ): + raise ValueError("multivalent charge_states_e requires 2..5 integers in [-3, 3]") + if any(right_q != left_q - 1 for left_q, right_q in zip(charges, charges[1:])): + raise ValueError("multivalent charge_states_e must descend by 1") + degs = tuple(_finite_positive(g, "state_degeneracy") for g in self.state_degeneracies) + if len(degs) != len(charges): + raise ValueError("state_degeneracies length must match charge_states_e") + if self.degeneracy_convention == "unity" and any(g != 1.0 for g in degs): + raise ValueError("unity degeneracy_convention requires all degeneracies == 1") + if self.degeneracy_convention == "scaps_binomial" and degs != tuple( + float(math.comb(len(charges) - 1, i)) for i in range(len(charges)) + ): + raise ValueError("scaps_binomial requires binomial degeneracies") + energies = tuple( + float(e) for e in self.transition_energies_eV_above_vb + ) + if any(not math.isfinite(e) for e in energies) or len(energies) != len(charges) - 1: + raise ValueError("one finite transition energy is required per adjacent pair") + kins = tuple(self.transition_kinetics) + if len(kins) != len(charges) - 1: + raise ValueError("one kinetics specification is required per adjacent pair") + object.__setattr__(self, "charge_states_e", charges) + object.__setattr__(self, "state_degeneracies", degs) + object.__setattr__(self, "transition_energies_eV_above_vb", energies) + object.__setattr__(self, "transition_kinetics", kins) + + def validate_band_gap(self, band_gap_eV: float) -> None: + gap = _finite_positive(band_gap_eV, "band_gap_eV") + tol = 16.0 * math.ulp(max(gap, *(abs(e) for e in self.transition_energies_eV_above_vb), 1.0)) + if any(e < -tol or e > gap + tol for e in self.transition_energies_eV_above_vb): + raise ValueError("multivalent transition energy lies outside [0, band_gap_eV]") + + +@dataclass(frozen=True, slots=True) +class MultivalentSpeciesSpec: + """Named multivalent bulk defect species with total physical center density.""" + + identifier: str + total_density_m3: float + configuration: MultivalentConfigurationSpec + + def __post_init__(self) -> None: + ident = str(self.identifier).strip() + if not ident: + raise ValueError("MultivalentSpeciesSpec requires a non-empty identifier") + dens = _finite_nonnegative(self.total_density_m3, "total_density_m3") + object.__setattr__(self, "identifier", ident) + object.__setattr__(self, "total_density_m3", dens) + + +@dataclass(frozen=True, slots=True) +class MultivalentDefectClosureResult: + """Stationary state probabilities, charge, recombination, and exact tangents.""" + + species_identifier: str + total_density_m3: float + charge_states_e: tuple[int, ...] + state_degeneracies: tuple[float, ...] + state_probability: NDArray[np.float64] + state_probability_derivative_n_m3: NDArray[np.float64] + state_probability_derivative_p_m3: NDArray[np.float64] + transition_recombination_rate_m3_s: NDArray[np.float64] + transition_recombination_derivative_n_s1: NDArray[np.float64] + transition_recombination_derivative_p_s1: NDArray[np.float64] + mean_charge_e: NDArray[np.float64] + charge_density_C_m3: NDArray[np.float64] + charge_derivative_n_C: NDArray[np.float64] + charge_derivative_p_C: NDArray[np.float64] + charge_derivative_fixed_qf_C_m3_V: NDArray[np.float64] + total_recombination_rate_m3_s: NDArray[np.float64] + total_recombination_derivative_n_s1: NDArray[np.float64] + total_recombination_derivative_p_s1: NDArray[np.float64] + recombination_derivative_fixed_qf_m3_s_V: NDArray[np.float64] + maximum_probability_sum_error: float + maximum_master_residual_s1: float + + def __post_init__(self) -> None: + for name in ( + "state_probability", + "state_probability_derivative_n_m3", + "state_probability_derivative_p_m3", + "transition_recombination_rate_m3_s", + "transition_recombination_derivative_n_s1", + "transition_recombination_derivative_p_s1", + "mean_charge_e", + "charge_density_C_m3", + "charge_derivative_n_C", + "charge_derivative_p_C", + "charge_derivative_fixed_qf_C_m3_V", + "total_recombination_rate_m3_s", + "total_recombination_derivative_n_s1", + "total_recombination_derivative_p_s1", + "recombination_derivative_fixed_qf_m3_s_V", + ): + object.__setattr__(self, name, _ro_float(getattr(self, name))) + + +def evaluate_multivalent_defect_closure( + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, + species: MultivalentSpeciesSpec, + *, + band_gap_eV: ArrayLike, + effective_conduction_dos_m3: ArrayLike, + effective_valence_dos_m3: ArrayLike, + temperature_K: float, +) -> MultivalentDefectClosureResult: + """Solve coupled adjacent-state probabilities and exact derivatives without clipping.""" + n, p = np.broadcast_arrays( + np.asarray(electron_density_m3, dtype=np.float64), + np.asarray(hole_density_m3, dtype=np.float64), + ) + if np.any(~np.isfinite(n)) or np.any(~np.isfinite(p)) or np.any(n <= 0.0) or np.any(p <= 0.0): + raise ValueError("multivalent closure requires finite positive carrier densities") + gap = np.broadcast_to(np.asarray(band_gap_eV, dtype=np.float64), n.shape) + nc = np.broadcast_to( + np.asarray(effective_conduction_dos_m3, dtype=np.float64), n.shape + ) + nv = np.broadcast_to( + np.asarray(effective_valence_dos_m3, dtype=np.float64), n.shape + ) + if np.any(gap <= 0.0) or np.any(nc <= 0.0) or np.any(nv <= 0.0): + raise ValueError("band_gap_eV, Nc, and Nv must be positive") + vt = thermal_voltage(_finite_positive(temperature_K, "temperature_K")) + + cfg = species.configuration + cfg.validate_band_gap(float(np.min(gap))) + t_count = len(cfg.transition_energies_eV_above_vb) + s_count = t_count + 1 + t_exp = (t_count,) + (1,) * n.ndim + s_shape = (s_count, *n.shape) + + energies = np.asarray(cfg.transition_energies_eV_above_vb, dtype=np.float64).reshape(t_exp) + cn = np.asarray( + [k.capture_n_m3_s for k in cfg.transition_kinetics], dtype=np.float64 + ).reshape(t_exp) + cp = np.asarray( + [k.capture_p_m3_s for k in cfg.transition_kinetics], dtype=np.float64 + ).reshape(t_exp) + degs: NDArray[np.float64] = np.asarray(cfg.state_degeneracies, dtype=np.float64) + deg_ratio = (degs[1:] / degs[:-1]).reshape(t_exp) + + n_e = n[None, ...] + p_e = p[None, ...] + gap_e = gap[None, ...] + nc_e = nc[None, ...] + nv_e = nv[None, ...] + + n1 = nc_e * np.exp(-(gap_e - energies) / vt) + p1 = nv_e * np.exp(-energies / vt) + em_n = cn * n1 / deg_ratio + em_p = cp * p1 * deg_ratio + + forward = cn * n_e + em_p + backward = em_n + cp * p_e + if np.any(~np.isfinite(forward)) or np.any(~np.isfinite(backward)) or np.any(forward <= 0.0) or np.any(backward <= 0.0): + raise FloatingPointError("multivalent adjacent-state transition rates are invalid") + + log_ratio = np.log(forward) - np.log(backward) + log_w = np.zeros(s_shape, dtype=np.float64) + log_w[1:] = np.cumsum(log_ratio, axis=0) + log_w -= np.max(log_w, axis=0, keepdims=True) + w = np.exp(log_w) + prob = w / np.sum(w, axis=0, keepdims=True) + + dlog_dn = np.zeros(s_shape, dtype=np.float64) + dlog_dp = np.zeros(s_shape, dtype=np.float64) + dlog_dn[1:] = np.cumsum(cn / forward, axis=0) + dlog_dp[1:] = np.cumsum(-cp / backward, axis=0) + mean_dn = np.sum(prob * dlog_dn, axis=0, keepdims=True) + mean_dp = np.sum(prob * dlog_dp, axis=0, keepdims=True) + dprob_dn = prob * (dlog_dn - mean_dn) + dprob_dp = prob * (dlog_dp - mean_dp) + + # Master-equation stationary residual diagnostic: + master_res = np.zeros(s_shape, dtype=np.float64) + flux_diff = backward * prob[1:] - forward * prob[:-1] + master_res[:-1] += flux_diff + master_res[1:] -= flux_diff + max_master_res = float(np.max(np.abs(master_res))) + max_sum_err = float(np.max(np.abs(np.sum(prob, axis=0) - 1.0))) + + ni_sq = (nc * nv * np.exp(-gap / vt))[None, ...] + pair_prob = prob[:-1] + prob[1:] + dpair_dn = dprob_dn[:-1] + dprob_dn[1:] + dpair_dp = dprob_dp[:-1] + dprob_dp[1:] + + cap_prod = cn * cp + num = cap_prod * (n_e * p_e - ni_sq) + denom = forward + backward + frac = num / denom + dfrac_dn = (cap_prod * p_e * denom - num * cn) / (denom * denom) + dfrac_dp = (cap_prod * n_e * denom - num * cp) / (denom * denom) + + nt = species.total_density_m3 + tr_rate = nt * pair_prob * frac + dtr_dn = nt * (dpair_dn * frac + pair_prob * dfrac_dn) + dtr_dp = nt * (dpair_dp * frac + pair_prob * dfrac_dp) + + tot_rate = np.sum(tr_rate, axis=0) + dtot_dn = np.sum(dtr_dn, axis=0) + dtot_dp = np.sum(dtr_dp, axis=0) + dtot_dphi = (dtot_dn * n - dtot_dp * p) / vt + + charges_e = np.asarray(cfg.charge_states_e, dtype=np.float64).reshape( + (s_count,) + (1,) * n.ndim + ) + mean_q = np.sum(charges_e * prob, axis=0) + rho = Q * nt * mean_q + drho_dn = Q * nt * np.sum(charges_e * dprob_dn, axis=0) + drho_dp = Q * nt * np.sum(charges_e * dprob_dp, axis=0) + drho_dphi = (drho_dn * n - drho_dp * p) / vt + + return MultivalentDefectClosureResult( + species_identifier=species.identifier, + total_density_m3=nt, + charge_states_e=cfg.charge_states_e, + state_degeneracies=cfg.state_degeneracies, + state_probability=prob, + state_probability_derivative_n_m3=dprob_dn, + state_probability_derivative_p_m3=dprob_dp, + transition_recombination_rate_m3_s=tr_rate, + transition_recombination_derivative_n_s1=dtr_dn, + transition_recombination_derivative_p_s1=dtr_dp, + mean_charge_e=mean_q, + charge_density_C_m3=rho, + charge_derivative_n_C=drho_dn, + charge_derivative_p_C=drho_dp, + charge_derivative_fixed_qf_C_m3_V=drho_dphi, + total_recombination_rate_m3_s=tot_rate, + total_recombination_derivative_n_s1=dtot_dn, + total_recombination_derivative_p_s1=dtot_dp, + recombination_derivative_fixed_qf_m3_s_V=dtot_dphi, + maximum_probability_sum_error=max_sum_err, + maximum_master_residual_s1=max_master_res, + ) + + +@dataclass(frozen=True, slots=True) +class MultivalentDefectRegion: + """Compiled multivalent defect inventory on a disjoint region.""" + + identifier: str + document_sha256: str + active_nodes: NDArray[np.bool_] + band_gap_eV: NDArray[np.float64] + effective_conduction_dos_m3: NDArray[np.float64] + effective_valence_dos_m3: NDArray[np.float64] + temperature_K: float + species: tuple[MultivalentSpeciesSpec, ...] + + def __post_init__(self) -> None: + mask = _ro_bool(self.active_nodes) + if mask.ndim != 1 or not np.any(mask): + raise ValueError("active_nodes must be a non-empty 1D boolean mask") + active_count = int(np.sum(mask)) + gap = _ro_float(np.broadcast_to(self.band_gap_eV, (active_count,))) + nc = _ro_float( + np.broadcast_to(self.effective_conduction_dos_m3, (active_count,)) + ) + nv = _ro_float( + np.broadcast_to(self.effective_valence_dos_m3, (active_count,)) + ) + temp = _finite_positive(self.temperature_K, "temperature_K") + sp = tuple(self.species) + if not sp: + raise ValueError("MultivalentDefectRegion requires at least one species") + min_gap = float(np.min(gap)) + for item in sp: + item.configuration.validate_band_gap(min_gap) + object.__setattr__(self, "active_nodes", mask) + object.__setattr__(self, "band_gap_eV", gap) + object.__setattr__(self, "effective_conduction_dos_m3", nc) + object.__setattr__(self, "effective_valence_dos_m3", nv) + object.__setattr__(self, "temperature_K", temp) + object.__setattr__(self, "species", sp) + + +def evaluate_multivalent_region_closure( + region: MultivalentDefectRegion, + electron_density_m3: ArrayLike, + hole_density_m3: ArrayLike, +) -> tuple[MultivalentDefectClosureResult, ...]: + """Evaluate all multivalent species in ``region`` on full-grid carrier vectors.""" + n = np.asarray(electron_density_m3, dtype=np.float64) + p = np.asarray(hole_density_m3, dtype=np.float64) + n_loc = n[region.active_nodes] + p_loc = p[region.active_nodes] + return tuple( + evaluate_multivalent_defect_closure( + n_loc, + p_loc, + sp, + band_gap_eV=region.band_gap_eV, + effective_conduction_dos_m3=region.effective_conduction_dos_m3, + effective_valence_dos_m3=region.effective_valence_dos_m3, + temperature_K=region.temperature_K, + ) + for sp in region.species + ) + + +@dataclass(frozen=True, slots=True) +class MultivalentDefectNeutralityState: + """Equilibrium charge-neutrality state including multivalent defects.""" + + temperature_K: float + thermal_voltage_V: float + band_gap_eV: float + effective_conduction_dos_m3: float + effective_valence_dos_m3: float + donor_density_m3: float + acceptor_density_m3: float + reduced_electron_fermi_level: float + reduced_hole_fermi_level: float + electron_density_m3: float + hole_density_m3: float + defect_charge_density_C_m3: float + normalized_charge_residual: float + work_function_eV: float | None = None + + +def solve_multivalent_defect_charge_neutrality( + *, + temperature_K: float, + band_gap_eV: float, + effective_conduction_dos_m3: float, + effective_valence_dos_m3: float, + donor_density_m3: float, + acceptor_density_m3: float, + species: Sequence[MultivalentSpeciesSpec], + electron_affinity_eV: float | None = None, +) -> MultivalentDefectNeutralityState: + """Solve equilibrium charge neutrality ``p - n + N_D - N_A + rho_mv/q == 0``. + + Even under negative-U (inverted correlation energies), the grand-canonical + mean charge ``(E_F)`` satisfies ``d/d(eta_n) = -Var(q) <= 0``, so total + charge is strictly decreasing in ``eta_n`` and has a unique root. + """ + temp = _finite_positive(temperature_K, "temperature_K") + gap = _finite_positive(band_gap_eV, "band_gap_eV") + nc = _finite_positive(effective_conduction_dos_m3, "effective_conduction_dos_m3") + nv = _finite_positive(effective_valence_dos_m3, "effective_valence_dos_m3") + nd = _finite_nonnegative(donor_density_m3, "donor_density_m3") + na = _finite_nonnegative(acceptor_density_m3, "acceptor_density_m3") + vt = thermal_voltage(temp) + + def eval_eta(eta_n: float) -> tuple[float, float, float, float, float]: + eta_p = -gap / vt - eta_n + n_val = nc * math.exp(eta_n) + p_val = nv * math.exp(eta_p) + rho_mv = 0.0 + for sp in species: + res = evaluate_multivalent_defect_closure( + np.array([n_val]), + np.array([p_val]), + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + rho_mv += float(res.charge_density_C_m3[0]) + mv_num = rho_mv / Q + net = (p_val + nd + max(mv_num, 0.0)) - (n_val + na + max(-mv_num, 0.0)) + scale = max(p_val + n_val + nd + na + abs(mv_num), 1.0) + return net, scale, n_val, p_val, rho_mv + + eta_mid = -0.5 * gap / vt + 0.5 * math.log(nv / nc) + lo = eta_mid - 1.0 + hi = eta_mid + 1.0 + f_lo, _, _, _, _ = eval_eta(lo) + f_hi, _, _, _, _ = eval_eta(hi) + step = 2.0 + for _ in range(60): + if f_lo >= 0.0 and f_hi <= 0.0: + break + if f_lo < 0.0: + lo -= step + f_lo, _, _, _, _ = eval_eta(lo) + if f_hi > 0.0: + hi += step + f_hi, _, _, _, _ = eval_eta(hi) + step = min(step * 1.5, 40.0) + else: + raise RuntimeError("failed to bracket multivalent equilibrium Fermi level") + + mid = 0.5 * (lo + hi) + for _ in range(120): + mid = 0.5 * (lo + hi) + val, scale, _, _, _ = eval_eta(mid) + if abs(val) / scale <= CHARGE_NEUTRALITY_RELATIVE_TOLERANCE or hi - lo <= 1e-15 * max( + 1.0, abs(lo), abs(hi) + ): + break + if val > 0.0: + lo = mid + else: + hi = mid + + val, scale, n_eq, p_eq, rho_eq = eval_eta(mid) + norm_res = abs(val) / scale + if norm_res > 10.0 * CHARGE_NEUTRALITY_RELATIVE_TOLERANCE: + raise RuntimeError( + f"multivalent neutrality residual {norm_res:.3e} exceeded tolerance" + ) + wf: float | None = None + if electron_affinity_eV is not None: + wf = _finite_positive(electron_affinity_eV, "electron_affinity_eV") - vt * mid + return MultivalentDefectNeutralityState( + temperature_K=temp, + thermal_voltage_V=vt, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=nd, + acceptor_density_m3=na, + reduced_electron_fermi_level=mid, + reduced_hole_fermi_level=-gap / vt - mid, + electron_density_m3=n_eq, + hole_density_m3=p_eq, + defect_charge_density_C_m3=rho_eq, + normalized_charge_residual=norm_res, + work_function_eV=wf, + ) diff --git a/src/solarlab/physics/interface_transport/__init__.py b/src/solarlab/physics/interface_transport/__init__.py index 79366138..ba7a6207 100644 --- a/src/solarlab/physics/interface_transport/__init__.py +++ b/src/solarlab/physics/interface_transport/__init__.py @@ -23,11 +23,13 @@ from solarlab.physics.interface_transport.two_sided import ( ChargedTwoSidedInterfaceQSSResult, EquilibriumReferencedSheetCharge, + FixedOccupancyTwoSidedResult, TwoSidedBulkState, TwoSidedInterfacePhysics, TwoSidedInterfaceQSSResult, remove_shared_interface_nodes, solve_charged_two_sided_interface_qss, + solve_fixed_occupancy_two_sided_interface, solve_two_sided_interface_qss, ) @@ -36,6 +38,7 @@ "ChargedTwoSidedInterfaceQSSResult", "ELECTRON_MASS_KG", "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", "PLANCK_CONSTANT_J_S", "TE_BARRIER_THRESHOLD_EV", "ThermionicCapEvaluation", @@ -56,6 +59,7 @@ "richardson_from_dos", "scaps_thermionic_flux", "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", "solve_two_sided_interface_qss", "thermionic_emission_bound_m2_s", ] diff --git a/src/solarlab/physics/interface_transport/two_sided.py b/src/solarlab/physics/interface_transport/two_sided.py index d1304bef..6d5e6613 100644 --- a/src/solarlab/physics/interface_transport/two_sided.py +++ b/src/solarlab/physics/interface_transport/two_sided.py @@ -41,11 +41,13 @@ __all__ = [ "ChargedTwoSidedInterfaceQSSResult", "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", "TwoSidedBulkState", "TwoSidedInterfacePhysics", "TwoSidedInterfaceQSSResult", "remove_shared_interface_nodes", "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", "solve_two_sided_interface_qss", ] @@ -1253,3 +1255,452 @@ def scaled_jac(y_loc: RealArray) -> RealArray: evaluations=eval_count, converged=converged, ) + + +@dataclass(frozen=True) +class FixedOccupancyTwoSidedResult: + """Two-sided trace elimination at an explicit dynamic trap occupancy ``f``. + + Used by unified dynamic-interface assembly (`P04-10`) where ``f`` is a + storage-bearing state variable rather than locally eliminated by QSS. + Provides exact IFT sensitivities wrt both the 6 bulk coordinates + ``(phi_L, phi_R, log n_L, log p_L, log n_R, log p_R)`` AND ``occupancy``. + """ + + phi_trace_left_V: float + phi_trace_right_V: float + state_m3: RealArray + bulk_flux_m2_s: RealArray + cross_flux_m2_s: RealArray + capture_flux_m2_s: RealArray + occupancy: float + qss_occupancy: float + relaxation_rate_s1: float + trap_storage_rate_m2_s: float + incremental_sheet_charge_C_m2: float + d_sheet_charge_df_C_m2: float + bulk_flux_jacobian_bulk: RealArray # (4, 6) + bulk_flux_derivative_occupancy: RealArray # (4,) + trap_storage_rate_jacobian_bulk: RealArray # (6,) + trap_storage_rate_derivative_occupancy: float + normalized_residual: float + evaluations: int + converged: bool + one_minus_occupancy: float = 0.0 + + +def _fixed_occupancy_balance_terms( + u_delta: RealArray, + drop_left_V: float, + drop_right_V: float, + potential_jump_V: float, + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + occupancy: float, + one_minus_occupancy: float, +) -> tuple[ + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, + RealArray, +]: + state = _state_from_u_delta(u_delta, drop_left_V, drop_right_V, physics, bulk) + bulk_flux, d_bulk_u, d_bulk_trace_u, d_bulk_coords_u = _bulk_sg_flux_and_derivatives_u( + u_delta, state, drop_left_V, drop_right_V, geometry, physics, bulk + ) + vt_local = float(physics.thermal_voltage_V) + xi_l = float(drop_left_V) / vt_local + xi_r_from_bulk = -float(drop_right_V) / vt_local + base_log_to_dos = np.array( + [ + math.log(float(bulk.n_left_m3) / float(physics.N_C_left_m3)) + xi_l, + math.log(float(bulk.p_left_m3) / float(physics.N_V_left_m3)) - xi_l, + math.log(float(bulk.n_right_m3) / float(physics.N_C_right_m3)) + xi_r_from_bulk, + math.log(float(bulk.p_right_m3) / float(physics.N_V_right_m3)) - xi_r_from_bulk, + ], + dtype=np.float64, + ) + cross_eval = fermi_dirac_richardson_flux( + state, + phi_trace_left_V=0.0, + phi_trace_right_V=float(potential_jump_V), + conduction_band_step_eV=physics.conduction_band_step_eV, + hole_transport_step_eV=physics.hole_transport_step_eV, + N_C_left_m3=physics.N_C_left_m3, + N_C_right_m3=physics.N_C_right_m3, + N_V_left_m3=physics.N_V_left_m3, + N_V_right_m3=physics.N_V_right_m3, + richardson_n_A_m2_K2=physics.richardson_n_A_m2_K2, + richardson_p_A_m2_K2=physics.richardson_p_A_m2_K2, + temperature_K=physics.temperature_K, + thermal_voltage_V=physics.thermal_voltage_V, + transmission=physics.transmission, + base_log_to_dos=base_log_to_dos, + u_delta=u_delta, + electrochemical_steps=( + bulk.electron_electrochemical_step, + bulk.hole_electrochemical_step, + ), + ) + + vn = float(physics.surface_recombination_velocity_n_m_s) + vp = float(physics.surface_recombination_velocity_p_m_s) + f = float(occupancy) + omf = float(one_minus_occupancy) + n_l, p_l, n_r, p_r = (float(v) for v in state) + capture = np.array( + [ + vn * _product_difference(n_l, omf, physics.n1_left_m3, f), + vp * _product_difference(p_l, f, physics.p1_left_m3, omf), + vn * _product_difference(n_r, omf, physics.n1_right_m3, f), + vp * _product_difference(p_r, f, physics.p1_right_m3, omf), + ], + dtype=np.float64, + ) + d_cap_log = np.diag( + [ + vn * omf * n_l, + vp * f * p_l, + vn * omf * n_r, + vp * f * p_r, + ] + ) + d_cap_df = np.array( + [ + -vn * (n_l + physics.n1_left_m3), + vp * (p_l + physics.p1_left_m3), + -vn * (n_r + physics.n1_right_m3), + vp * (p_r + physics.p1_right_m3), + ], + dtype=np.float64, + ) + + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + cross = cross_eval.cross_flux_m2_s + residual = np.array( + [ + bulk_flux[_N_LEFT] - cross[0] - capture[_N_LEFT], + bulk_flux[_P_LEFT] - cross[1] - capture[_P_LEFT], + bulk_flux[_N_RIGHT] + cross[0] - capture[_N_RIGHT], + bulk_flux[_P_RIGHT] + cross[1] - capture[_P_RIGHT], + ], + dtype=np.float64, + ) + j_u = d_bulk_u - d_cap_log + j_u[_N_LEFT, :] -= cross_eval.d_cross_d_log_state_m2_s[0, :] + j_u[_P_LEFT, :] -= cross_eval.d_cross_d_log_state_m2_s[1, :] + j_u[_N_RIGHT, :] += cross_eval.d_cross_d_log_state_m2_s[0, :] + j_u[_P_RIGHT, :] += cross_eval.d_cross_d_log_state_m2_s[1, :] + + d_cross_trace_u = ( + cross_eval.d_cross_d_trace_potentials_m2_s_V + + cross_eval.d_cross_d_log_state_m2_s @ m_trace + ) + j_trace_u = d_bulk_trace_u - d_cap_log @ m_trace + j_trace_u[_N_LEFT, :] -= d_cross_trace_u[0, :] + j_trace_u[_P_LEFT, :] -= d_cross_trace_u[1, :] + j_trace_u[_N_RIGHT, :] += d_cross_trace_u[0, :] + j_trace_u[_P_RIGHT, :] += d_cross_trace_u[1, :] + + d_cross_bulk_u = cross_eval.d_cross_d_log_state_m2_s @ m_bulk + j_coords_u = d_bulk_coords_u - d_cap_log @ m_bulk + j_coords_u[_N_LEFT, :] -= d_cross_bulk_u[0, :] + j_coords_u[_P_LEFT, :] -= d_cross_bulk_u[1, :] + j_coords_u[_N_RIGHT, :] += d_cross_bulk_u[0, :] + j_coords_u[_P_RIGHT, :] += d_cross_bulk_u[1, :] + + return ( + state, + bulk_flux, + cross, + capture, + residual, + j_u, + j_trace_u, + j_coords_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + d_cap_df, + cross_eval.one_way_scale_m2_s, + ) + + +def solve_fixed_occupancy_two_sided_interface( + geometry: TraceElectrostatics, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, + charge: EquilibriumReferencedSheetCharge, + *, + occupancy: float, + one_minus_occupancy: float | None = None, + occupancy_minus_equilibrium: float | None = None, + initial_state_m3: ArrayLike | None = None, + residual_tolerance: float = 1.0e-9, + max_evaluations: int = 200, + fail_on_residual: bool = True, +) -> FixedOccupancyTwoSidedResult: + """Eliminate two-sided electrostatic + carrier traces at explicit occupancy ``f``.""" + _positive(residual_tolerance, "residual_tolerance") + f = float(occupancy) + if not math.isfinite(f) or not 0.0 <= f <= 1.0: + raise ValueError("occupancy must lie in [0, 1]") + omf = 1.0 - f if one_minus_occupancy is None else float(one_minus_occupancy) + nt = float(charge.trap_density_m2) + df_eq = ( + f - float(charge.equilibrium_occupancy) + if occupancy_minus_equilibrium is None + else float(occupancy_minus_equilibrium) + ) + delta_sigma = -Q * nt * df_eq + d_sigma_df = -Q * nt + + eff_geometry = TraceElectrostatics( + eps_r_left=geometry.eps_r_left, + eps_r_right=geometry.eps_r_right, + left_distance_m=geometry.left_distance_m, + right_distance_m=geometry.right_distance_m, + potential_jump_right_minus_left_V=geometry.potential_jump_right_minus_left_V, + fixed_sheet_charge_C_m2=float(geometry.fixed_sheet_charge_C_m2) + delta_sigma, + ) + phi_t_l, phi_t_r = solve_electrostatic_traces( + eff_geometry, bulk.phi_left_V, bulk.phi_right_V + ) + drop_l_0, drop_r_0, jump_0, _, _ = _electrostatic_seed_drops(eff_geometry, bulk) + zero_flux_seed = _zero_bulk_flux_seed(drop_l_0, drop_r_0, physics, bulk) + + if initial_state_m3 is None: + seed = zero_flux_seed + u_seed_raw: NDArray[np.float64] = np.zeros(_STATE_SIZE, dtype=np.float64) + else: + seed = np.asarray(initial_state_m3, dtype=np.float64) + if seed.shape != (_STATE_SIZE,) or not np.all(np.isfinite(seed)) or np.any(seed <= 0.0): + raise ValueError("initial_state_m3 must contain four positive finite densities") + u_seed_raw = _u_delta_from_log_state(np.log(seed), drop_l_0, drop_r_0, physics, bulk) + + density_ref = max( + float(np.max(seed)), + float(np.max(zero_flux_seed)), + physics.N_C_left_m3, + physics.N_C_right_m3, + physics.N_V_left_m3, + physics.N_V_right_m3, + physics.n1_left_m3, + physics.n1_right_m3, + physics.p1_left_m3, + physics.p1_right_m3, + 1.0, + ) + vt = float(physics.thermal_voltage_V) + xi_left = drop_l_0 / vt + xi_right = drop_r_0 / vt + base_log = np.array( + [ + math.log(float(bulk.n_left_m3)) + xi_left, + math.log(float(bulk.p_left_m3)) - xi_left, + math.log(float(bulk.n_right_m3)) - xi_right, + math.log(float(bulk.p_right_m3)) + xi_right, + ], + dtype=np.float64, + ) + log_lower = math.log(1.0e-100) + log_upper = math.log(density_ref) + math.log(1.0e12) + u_lower = np.maximum(log_lower - base_log, -490.0) + u_upper = np.minimum(log_upper - base_log, 490.0) + u_upper = np.maximum(u_upper, u_lower + 2.0) + u_seed = np.clip(u_seed_raw, u_lower + 0.5, u_upper - 0.5) + + seed_terms = _fixed_occupancy_balance_terms( + u_seed, drop_l_0, drop_r_0, jump_0, eff_geometry, physics, bulk, f, omf + ) + e_scale = max( + abs(float(seed_terms[1][_N_LEFT])), + abs(float(seed_terms[1][_N_RIGHT])), + abs(float(seed_terms[8][_N_LEFT, _N_LEFT])), + abs(float(seed_terms[8][_N_RIGHT, _N_RIGHT])), + abs(float(seed_terms[3][_N_LEFT])), + abs(float(seed_terms[3][_N_RIGHT])), + float(seed_terms[12][0]), + 1.0, + ) + h_scale = max( + abs(float(seed_terms[1][_P_LEFT])), + abs(float(seed_terms[1][_P_RIGHT])), + abs(float(seed_terms[8][_P_LEFT, _P_LEFT])), + abs(float(seed_terms[8][_P_RIGHT, _P_RIGHT])), + abs(float(seed_terms[3][_P_LEFT])), + abs(float(seed_terms[3][_P_RIGHT])), + float(seed_terms[12][1]), + 1.0, + ) + row_scale = np.array([e_scale, h_scale, e_scale, h_scale], dtype=np.float64) + + def scaled_res(u_vec: RealArray) -> RealArray: + return ( + _fixed_occupancy_balance_terms( + u_vec, drop_l_0, drop_r_0, jump_0, eff_geometry, physics, bulk, f, omf + )[4] + / row_scale + ) + + def scaled_jac(u_vec: RealArray) -> RealArray: + return ( + _fixed_occupancy_balance_terms( + u_vec, drop_l_0, drop_r_0, jump_0, eff_geometry, physics, bulk, f, omf + )[5] + / row_scale[:, np.newaxis] + ) + + sol = least_squares( + scaled_res, + u_seed, + jac=scaled_jac, + bounds=(u_lower, u_upper), + x_scale="jac", + ftol=3.0e-16, + xtol=3.0e-16, + gtol=3.0e-16, + max_nfev=int(max_evaluations), + ) + x_best = sol.x.copy() + eval_count = int(sol.nfev) + + best_terms = _fixed_occupancy_balance_terms( + x_best, drop_l_0, drop_r_0, jump_0, eff_geometry, physics, bulk, f, omf + ) + for _ in range(8): + p_row = np.maximum(np.max(np.abs(best_terms[5]), axis=1), float(np.finfo(np.float64).tiny)) + p_norm = float(np.max(np.abs(best_terms[4] / p_row))) + if p_norm <= 1.0e-16: + break + try: + delta = -_equilibrated_solve( + best_terms[5] / p_row[:, np.newaxis], + best_terms[4] / p_row, + ) + except np.linalg.LinAlgError: + break + if not np.all(np.isfinite(delta)): + break + cand = np.clip(x_best + delta, u_lower, u_upper) + cand_terms = _fixed_occupancy_balance_terms( + cand, drop_l_0, drop_r_0, jump_0, eff_geometry, physics, bulk, f, omf + ) + eval_count += 1 + cand_norm = float(np.max(np.abs(cand_terms[4] / p_row))) + if cand_norm < p_norm or float(np.max(np.abs(delta))) <= 1.0e-15: + x_best = cand + best_terms = cand_terms + if float(np.max(np.abs(delta))) <= 1.0e-15: + break + else: + break + + ( + state, + bulk_flux, + cross_flux, + capture_flux, + residual, + j_u, + j_trace_u, + j_coords_u, + d_bulk_u, + d_bulk_trace_u, + d_bulk_coords_u, + d_cap_df, + _, + ) = best_terms + best_norm = float(np.max(np.abs(residual / row_scale))) + + c_l = EPS_0 * float(geometry.eps_r_left) / float(geometry.left_distance_m) + c_r = EPS_0 * float(geometry.eps_r_right) / float(geometry.right_distance_m) + c_sum = c_l + c_r + w_l = c_l / c_sum + w_r = c_r / c_sum + + d_trace_d_bulk = np.array( + [[w_l, w_r, 0.0, 0.0, 0.0, 0.0], [w_l, w_r, 0.0, 0.0, 0.0, 0.0]], + dtype=np.float64, + ) + d_trace_df = np.array([d_sigma_df / c_sum, d_sigma_df / c_sum], dtype=np.float64) + + ift_row = np.maximum(np.max(np.abs(j_u), axis=1), float(np.finfo(np.float64).tiny)) + rhs_bulk = -(j_coords_u + j_trace_u @ d_trace_d_bulk) + rhs_f = -(j_trace_u @ d_trace_df - d_cap_df) + du_all = _equilibrated_solve( + j_u / ift_row[:, np.newaxis], + np.column_stack((rhs_bulk, rhs_f)) / ift_row[:, np.newaxis], + ) + du_d_bulk = du_all[:, :6] + du_df = du_all[:, 6] + + bulk_flux_jac = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk + bulk_flux_df = d_bulk_trace_u @ d_trace_df + d_bulk_u @ du_df + + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + d_log_state_d_bulk = m_bulk + m_trace @ d_trace_d_bulk + du_d_bulk + d_log_state_df = m_trace @ d_trace_df + du_df + + vn = float(physics.surface_recombination_velocity_n_m_s) + vp = float(physics.surface_recombination_velocity_p_m_s) + n_l, p_l, n_r, p_r = (float(v) for v in state) + filled = vn * (n_l + n_r) + vp * (physics.p1_left_m3 + physics.p1_right_m3) + empty = vn * (physics.n1_left_m3 + physics.n1_right_m3) + vp * (p_l + p_r) + denom = filled + empty + f_qss = filled / denom if denom > 0.0 else f + relax = denom / nt if nt > 0.0 else 0.0 + storage_rate = _product_difference(filled, omf, empty, f) + + d_sr_d_log = np.array( + [vn * omf * n_l, -vp * f * p_l, vn * omf * n_r, -vp * f * p_r], + dtype=np.float64, + ) + sr_jac_bulk = d_sr_d_log @ d_log_state_d_bulk + sr_df = float(-denom + d_sr_d_log @ d_log_state_df) + + converged = bool( + (sol.success or best_norm <= residual_tolerance) + and best_norm <= residual_tolerance + and np.all(np.isfinite(bulk_flux_jac)) + and np.all(np.isfinite(bulk_flux_df)) + and np.all(np.isfinite(sr_jac_bulk)) + and math.isfinite(sr_df) + ) + if fail_on_residual and not converged: + raise RuntimeError( + f"fixed-occupancy two-sided interface did not certify: residual={best_norm:.6g}" + ) + + return FixedOccupancyTwoSidedResult( + phi_trace_left_V=float(phi_t_l), + phi_trace_right_V=float(phi_t_r), + state_m3=state, + bulk_flux_m2_s=bulk_flux, + cross_flux_m2_s=cross_flux, + capture_flux_m2_s=capture_flux, + occupancy=f, + qss_occupancy=float(f_qss), + relaxation_rate_s1=float(relax), + trap_storage_rate_m2_s=float(storage_rate), + incremental_sheet_charge_C_m2=float(delta_sigma), + d_sheet_charge_df_C_m2=float(d_sigma_df), + bulk_flux_jacobian_bulk=bulk_flux_jac, + bulk_flux_derivative_occupancy=bulk_flux_df, + trap_storage_rate_jacobian_bulk=sr_jac_bulk, + trap_storage_rate_derivative_occupancy=sr_df, + normalized_residual=best_norm, + evaluations=eval_count, + converged=converged, + one_minus_occupancy=float(omf), + ) diff --git a/tests/integration/test_defect_ion_impedance_parity.py b/tests/integration/test_defect_ion_impedance_parity.py new file mode 100644 index 00000000..9fe29dda --- /dev/null +++ b/tests/integration/test_defect_ion_impedance_parity.py @@ -0,0 +1,435 @@ +"""Live numerical parity tests (T4) for coupled dynamic-defect + mobile-ion impedance (P05-03b). + +Verifies end-to-end 1D small-signal AC parity between ``solve_defect_ion_impedance`` / +``run_defect_capacitance_frequency`` and ``perovskite_sim.experiments.defect_ion_combined_impedance`` +across all three coupled defect-ion capabilities: +1. ``bulk_defect_plus_ions`` (including dual positive + negative mobile ions); +2. ``interface_defect_plus_ions`` (two-sided equilibrium-referenced interface defect + mobile ions); +3. ``bulk_interface_defect_plus_ions`` (simultaneous charged bulk defect + two-sided interface defect + ions). +""" + +from __future__ import annotations + +from collections.abc import Iterator +from dataclasses import replace +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from numpy.typing import NDArray +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.constants import K_B, Q +from perovskite_sim.experiments.defect_ion_combined_impedance import ( + run_defect_ion_combined_impedance, +) +from perovskite_sim.experiments.jv_sweep import build_electrical_grid +from perovskite_sim.experiments.quasi_fermi_steady_state import ( + build_two_sided_trace_grid, +) +from perovskite_sim.models.config_loader import load_device_from_yaml +from perovskite_sim.models.device import DeviceStack +from perovskite_sim.models.mode import SimulationMode + +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.capacitance_frequency import ( + capacitance_frequency_from_admittance, + run_defect_capacitance_frequency, +) +from solarlab.experiments.defect_ion_impedance import ( + DefectIonImpedanceOptions, + solve_defect_ion_impedance, +) +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument + +ROOT = Path(__file__).resolve().parents[2] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +@pytest.fixture(scope="module", autouse=True) +def _blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def legacy_catalog() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_DEFAULTS) + ) + + +def _thermodynamic_ni(nc_m3: float, nv_m3: float, eg_eV: float, temp_K: float = 300.0) -> float: + vt = K_B * temp_K / Q + return float(math.sqrt(nc_m3 * nv_m3) * math.exp(-eg_eV / (2.0 * vt))) + + +def _load_paired( + raw_doc: dict[str, Any], + catalog: DefaultCatalog, + tmp_path: Path, + name: str, +) -> tuple[PreparedDevice, DeviceStack]: + payload = json.dumps(raw_doc, allow_nan=False).encode() + yaml_file = tmp_path / f"{name}.yaml" + yaml_file.write_bytes(payload) + source = SourceDocument(str(yaml_file), payload) + dev_input = import_standard_device(source, id=name, defaults=catalog) + prepared = resolve_device(dev_input, catalog, ResourceLibrary(), sources=(source,)) + stack = load_device_from_yaml(str(yaml_file)) + if raw_doc.get("device", {}).get("interface_charge_closure") != "equilibrium_referenced": + stack = replace(stack, mode=SimulationMode(name="full", use_thermionic_emission=False)) + return prepared, stack + + +def _coupled_pin_yaml( + *, + with_bulk: bool, + with_iface: bool, + dual_ions: bool = False, +) -> dict[str, Any]: + if not with_iface: + ni_abs = _thermodynamic_ni(1.0e24, 8.0e23, 0.85) + abs_only: dict[str, Any] = { + "name": "absorber", + "role": "absorber", + "thickness": 3.0e-7, + "eps_r": 20.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 1.0e-14, + "P0": 1.0e22, + "P_lim": 2.0e24 if dual_ions else 1.0e24, + "D_ion_neg": 6.0e-15 if dual_ions else 0.0, + "P0_neg": 1.0e22 if dual_ions else 0.0, + "P_lim_neg": 2.0e24 if dual_ions else 1.0e24, + "ni": ni_abs, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_abs, + "p1": ni_abs, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": 4.00, + "Eg": 0.85, + "Nc300": 1.0e24, + "Nv300": 8.0e23, + "defect_schema_version": "solarlab-explicit-bulk-defects-v1", + "defect_model": "explicit_quasi_steady", + "bulk_defects": [ + { + "name": "BulkAcceptor", + "charge_transition": "acceptor", + "neutral_reference": "empty", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 2.0e21, + "center_eV_above_vb": 0.39, + }, + "kinetics": { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 8.0e-20, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 8.0e4, + }, + } + ], + } + return { + "schema_version": "standard-device-v1", + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "T": 300.0, + "Phi": 0.0, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"absorber": 1.0}, + "alphas": {"absorber": 5.5}, + }, + "layers": [abs_only], + } + + ni_layer = _thermodynamic_ni(1.0e25, 1.0e25, 1.05) + left_layer: dict[str, Any] = { + "name": "left", + "role": "absorber", + "thickness": 1.0e-7, + "eps_r": 16.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 1.0e-14, + "P0": 1.0e22, + "P_lim": 1.0e24, + "ni": ni_layer, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_layer, + "p1": ni_layer, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": 4.00, + "Eg": 1.05, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + } + if with_bulk: + left_layer.update( + { + "defect_schema_version": "solarlab-explicit-bulk-defects-v1", + "defect_model": "explicit_quasi_steady", + "bulk_defects": [ + { + "name": "BulkAcceptor", + "charge_transition": "acceptor", + "neutral_reference": "empty", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 1.0e21, + "center_eV_above_vb": 0.50, + }, + "kinetics": { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 8.0e-20, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 8.0e4, + }, + } + ], + } + ) + + return { + "schema_version": "standard-device-v1", + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + "interface_defects": [ + { + "sigma_n_cm2": 6.0e-17, + "sigma_p_cm2": 4.0e-17, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 7.0e10, + "E_t_eV_below_cb": 0.50, + } + ], + "T": 300.0, + "Phi": 0.0, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"left": 6.0, "right": 4.0}, + "alphas": {"left": 5.0, "right": 5.0}, + }, + "layers": [ + left_layer, + { + "name": "right", + "role": "ETL", + "thickness": 1.0e-7, + "eps_r": 16.0, + "mu_n": 1.0e-3, + "mu_p": 1.0e-3, + "D_ion": 0.0, + "P0": 0.0, + "P_lim": 1.0e24, + "ni": ni_layer, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_layer, + "p1": ni_layer, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": 4.08, + "Eg": 1.05, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + }, + ], + } + + +@pytest.mark.parametrize( + ("expected_cap", "with_bulk", "with_iface", "dual_ions"), + [ + ("bulk_defect_plus_ions", True, False, True), + ("interface_defect_plus_ions", False, True, False), + ("bulk_interface_defect_plus_ions", True, True, False), + ], +) +def test_live_defect_ion_combined_impedance_parity( + expected_cap: str, + with_bulk: bool, + with_iface: bool, + dual_ions: bool, + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 parity of coupled defect+ion impedance and C-f against perovskite_sim across all 3 capabilities.""" + doc = _coupled_pin_yaml(with_bulk=with_bulk, with_iface=with_iface, dual_ions=dual_ions) + prep, stack = _load_paired(doc, legacy_catalog, tmp_path, f"parity_{expected_cap}") + + freqs = np.array([1.0e-2, 1.0e-1, 10.0, 1.0e3, 1.0e7]) + v_dc = 0.0 if with_iface else 0.06 + intervals: tuple[int, ...] = (6, 4) if with_iface else (8,) + + res_new = solve_defect_ion_impedance( + prep, + freqs, + voltage_V=v_dc, + options=DefectIonImpedanceOptions(intervals_per_layer=intervals), + ) + assert res_new.capability == expected_cap + assert res_new.scientific_qualification is False + assert res_new.maximum_ion_inventory_relative_per_V <= 1.0e-12 + assert ( + res_new.working_state_digest + == res_new.coupled.working_state_digest + == res_new.frozen_ions.working_state_digest + == res_new.frozen_traps.working_state_digest + == res_new.frozen_ions_and_traps.working_state_digest + ) + + x_dedup = build_electrical_grid(stack, sum(intervals)) + x_grid = build_two_sided_trace_grid(x_dedup, stack) if with_iface else x_dedup + np.testing.assert_allclose(res_new.device.nodes_m, x_grid, rtol=0.0, atol=1.0e-15) + + res_old = run_defect_ion_combined_impedance( + x_grid, + stack, + freqs, + V_dc=v_dc, + refinement_factors=(1.0, 0.5, 0.25), + require_certificate=False, + ) + assert res_old.certificate.capability == expected_cap + + np.testing.assert_allclose( + res_new.coupled.admittance_density_S_m2, + res_old.admittance_S_m2, + rtol=1.0e-4, + atol=1.0e-8, + ) + np.testing.assert_allclose( + res_new.coupled.impedance_area_ohm_m2, + res_old.impedance_ohm_m2, + rtol=1.0e-4, + atol=1.0e-8, + ) + + cf_target = prep if not with_iface else res_new.device + cf_new = run_defect_capacitance_frequency( + cf_target, + freqs, + voltage_V=v_dc, + intervals_per_layer=intervals, + ) + cf_from_coupled = capacitance_frequency_from_admittance( + freqs, res_new.coupled.admittance_density_S_m2, operating_voltage_V=v_dc + ) + np.testing.assert_allclose( + cf_new.parallel_capacitance_F_m2, + cf_from_coupled.parallel_capacitance_F_m2, + rtol=1.0e-12, + atol=1.0e-15, + ) + cf_old = capacitance_frequency_from_admittance( + freqs, res_old.admittance_S_m2, operating_voltage_V=v_dc + ) + # Legacy perovskite_sim uses O(1e-7) forward finite differences on Y = G + j*w*C, + # inducing an O(1e-7 * |Y| / w) floor in Im(Y)/w when G >> w*C; at high frequency + # (w*C >= G) direct C_p relative parity is strictly < 1e-4: + np.testing.assert_allclose( + cf_new.parallel_capacitance_F_m2[-1], + cf_old.parallel_capacitance_F_m2[-1], + rtol=1.0e-4, + atol=1.0e-10, + ) + valid_cap = ~np.isnan(cf_old.parallel_capacitance_F_m2) + omega_valid = 2.0 * np.pi * freqs[valid_cap] + admittance_cap_tol = 1.0e-4 * np.abs(res_old.admittance_S_m2[valid_cap]) / omega_valid + assert np.all( + np.abs(cf_new.parallel_capacitance_F_m2[valid_cap] - cf_old.parallel_capacitance_F_m2[valid_cap]) + <= np.maximum(1.0e-4 * np.abs(cf_old.parallel_capacitance_F_m2[valid_cap]), admittance_cap_tol) + + 1.0e-10 + ) + + # Local coarse-grid trap occupancy perturbations match to ~2e-3..3e-3 on N=8..10 + # (legacy ion_migration.py uses dx[0] / 0.5*(dx_l+dx_r) boundary ion cells rather + # than exact half-cells, while terminal Y, Z, and C_p match within 1e-4 above): + if with_bulk: + occ_bt_new: NDArray[np.complex128] = np.asarray( + [pt.bulk_trap_occupancy_perturbation_per_V for pt in res_new.coupled.points], + dtype=np.complex128, + ) + assert res_old.bulk_trap_occupancy_response_per_V is not None + np.testing.assert_allclose( + occ_bt_new, + res_old.bulk_trap_occupancy_response_per_V, + rtol=4.0e-3, + atol=1.0e-6, + ) + + if with_iface: + occ_it_new: NDArray[np.complex128] = np.asarray( + [pt.interface_trap_occupancy_perturbation_per_V for pt in res_new.coupled.points], + dtype=np.complex128, + ) + assert res_old.interface_occupancy_response_per_V is not None + np.testing.assert_allclose( + occ_it_new, + res_old.interface_occupancy_response_per_V, + rtol=4.0e-3, + atol=3.0e-5, + ) + + # Electrostatic non-additivity across coupled frequency band: + y_coupled = res_new.coupled.admittance_density_S_m2 + y_superpos = ( + res_new.frozen_ions.admittance_density_S_m2 + + res_new.frozen_traps.admittance_density_S_m2 + - res_new.frozen_ions_and_traps.admittance_density_S_m2 + ) + assert float(np.max(np.abs(y_coupled - y_superpos) / np.abs(y_coupled))) > 1.0e-4 diff --git a/tests/integration/test_dynamic_defect_parity_1d.py b/tests/integration/test_dynamic_defect_parity_1d.py new file mode 100644 index 00000000..f8ae79d5 --- /dev/null +++ b/tests/integration/test_dynamic_defect_parity_1d.py @@ -0,0 +1,1026 @@ +"""Live numerical parity tests (T4) for dynamic, distributed, multivalent, and metastable 1D defects (P04-10, P05-03b, P05-04b). + +Verifies end-to-end 1D numerical parity against legacy ``perovskite_sim`` on identical grids across: +1. Bulk dynamic-defect impedance (single-level & v2 Gaussian continuous energy distribution) and C-f; +2. Two-sided dynamic interface-defect impedance with equilibrium-referenced sheet charge; +3. Narrow-gate v1 dynamic interface-defect + positive-ion transient and charged bulk-defect transient; +4. Stationary multivalent v4 (amphoteric + double-acceptor) illuminated J-V figures of merit; +5. Metastable two-configuration stationary preparation, frozen 1-sun J-V, and operator-split transient. +""" + +from __future__ import annotations + +from collections.abc import Iterator +import copy +from dataclasses import replace +from decimal import Decimal +import json +import math +from pathlib import Path +from typing import Any, TypeAlias + +import numpy as np +from numpy.typing import NDArray +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.constants import K_B, Q +from perovskite_sim.discretization.grid import Layer, multilayer_grid +from perovskite_sim.experiments.bulk_defect_transient import ( + BulkDefectTransientPolicy, + run_bulk_defect_device_transient, +) +from perovskite_sim.experiments.defect_aware_impedance import ( + run_bulk_defect_device_impedance, +) +from perovskite_sim.experiments.interface_defect_aware_impedance import ( + run_interface_defect_device_impedance, +) +from perovskite_sim.experiments.interface_defect_ion_transient import ( + InterfaceDefectIonTransientPolicy, + run_interface_defect_ion_device_transient, +) +from perovskite_sim.experiments.jv_sweep import build_electrical_grid, compute_metrics +from perovskite_sim.experiments.metastable_preparation import ( + prepare_metastable_configuration, + solve_frozen_metastable_jv_sweep, +) +from perovskite_sim.experiments.metastable_transient import ( + run_metastable_configuration_transient, +) +from perovskite_sim.experiments.quasi_fermi_steady_state import ( + build_two_sided_trace_grid, + solve_quasi_fermi_jv_sweep, +) +from perovskite_sim.models.config_loader import load_device_from_yaml +from perovskite_sim.models.defects import BulkDefectKinetics +from perovskite_sim.models.device import DeviceStack, LayerSpec +from perovskite_sim.models.mode import SimulationMode +from perovskite_sim.models.multivalent_defects import ( + MetastableConversionKinetics, + MetastableDefectDefinition, + MetastablePreparationNumerics, + MetastablePreparationProtocol, + MultivalentDefectConfiguration, + MultivalentEnergyLevels, +) +from perovskite_sim.models.parameters import MaterialParams +from perovskite_sim.physics.metastable_defect_closure import ( + evaluate_metastable_configuration_closure, +) + +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.config.yaml import load_yaml_mapping +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + solve_dynamic_defect_steady_1d, +) +from solarlab.experiments.capacitance_frequency import ( + capacitance_frequency_from_admittance, + run_defect_capacitance_frequency, +) +from solarlab.experiments.dynamic_defect_impedance import ( + DynamicDefectImpedanceOptions, + solve_bulk_defect_impedance, + solve_interface_defect_impedance, +) +from solarlab.experiments.dynamic_defect_transient import ( + DynamicDefectTransientOptions, + solve_bulk_defect_transient, + solve_dynamic_defect_transient, +) +from solarlab.experiments.metastable_transient import ( + prepare_metastable_state, + solve_frozen_metastable_jv, + solve_metastable_transient, +) +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument + +ROOT = Path(__file__).resolve().parents[2] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + +Vector: TypeAlias = NDArray[np.float64] + + +@pytest.fixture(scope="module", autouse=True) +def _blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def legacy_catalog() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_DEFAULTS) + ) + + +def _thermodynamic_ni(nc_m3: float, nv_m3: float, eg_eV: float, temp_K: float = 300.0) -> float: + vt = K_B * temp_K / Q + return float(math.sqrt(nc_m3 * nv_m3) * math.exp(-eg_eV / (2.0 * vt))) + + +def _clean_json(value: Any) -> Any: + if isinstance(value, Decimal): + return float(value) + if isinstance(value, dict): + return {str(k): _clean_json(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_clean_json(v) for v in value] + return value + + +def _load_paired_models( + raw_doc: dict[str, Any], + catalog: DefaultCatalog, + tmp_path: Path, + name: str, +) -> tuple[PreparedDevice, DeviceStack]: + payload = json.dumps(_clean_json(raw_doc), allow_nan=False).encode() + yaml_file = tmp_path / f"{name}.yaml" + yaml_file.write_bytes(payload) + source = SourceDocument(str(yaml_file), payload) + dev_input = import_standard_device(source, id=name, defaults=catalog) + prepared = resolve_device(dev_input, catalog, ResourceLibrary(), sources=(source,)) + stack = load_device_from_yaml(str(yaml_file)) + if raw_doc.get("device", {}).get("interface_charge_closure") != "equilibrium_referenced": + stack = replace(stack, mode=SimulationMode(name="full", use_thermionic_emission=False)) + return prepared, stack + + +def _three_layer_pin_yaml(*, phi_flux: float = 0.0) -> dict[str, Any]: + ni_htl = _thermodynamic_ni(2.0e24, 2.0e24, 1.50) + ni_abs = _thermodynamic_ni(1.0e24, 8.0e23, 1.20) + ni_etl = _thermodynamic_ni(2.0e24, 2.0e24, 1.50) + return { + "schema_version": "standard-device-v1", + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "T": 300.0, + "Phi": phi_flux, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"htl": 1.0, "absorber": 1.0, "etl": 1.0}, + "alphas": {"htl": 2.0, "absorber": 2.0, "etl": 2.0}, + }, + "layers": [ + { + "name": "htl", + "role": "HTL", + "thickness": 6.0e-8, + "eps_r": 12.0, + "mu_n": 1.0e-3, + "mu_p": 1.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_htl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_htl, + "p1": ni_htl, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 2.0e22, + "N_D": 0.0, + "chi": 3.85, + "Eg": 1.50, + "Nc300": 2.0e24, + "Nv300": 2.0e24, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 2.4e-7, + "eps_r": 20.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_abs, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_abs, + "p1": ni_abs, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 3.5e5, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.95, + "Eg": 1.20, + "Nc300": 1.0e24, + "Nv300": 8.0e23, + }, + { + "name": "etl", + "role": "ETL", + "thickness": 6.0e-8, + "eps_r": 12.0, + "mu_n": 1.0e-3, + "mu_p": 1.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_etl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_etl, + "p1": ni_etl, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 2.0e22, + "chi": 4.05, + "Eg": 1.50, + "Nc300": 2.0e24, + "Nv300": 2.0e24, + }, + ], + } + + +def test_live_bulk_and_interface_dynamic_defect_impedance_parity( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 parity on single-level & Gaussian bulk defect AC, C-f, and two-sided interface AC.""" + freqs = np.array([1.0e-3, 1.0, 1.0e3, 1.0e7]) + + # 1(a). Distributed v2 Gaussian charged bulk acceptor impedance + C-f parity: + doc_gauss = _three_layer_pin_yaml() + doc_gauss["layers"][1].update( + { + "defect_schema_version": "solarlab-explicit-bulk-defects-v2", + "defect_model": "explicit_quasi_steady", + "bulk_defects": [ + { + "name": "GaussianAcceptor", + "charge_transition": "acceptor", + "neutral_reference": "empty", + "degeneracy": 1.0, + "distribution": { + "kind": "gaussian", + "normalization": "integrated_total", + "total_density_m3": 3.0e21, + "center_eV_above_vb": 0.58, + "energy_reference": "above_valence_band", + "width_eV": 0.05, + "width_convention": "gaussian_standard_deviation", + "support_width_multiplier": 6.0, + }, + "kinetics": { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 8.0e-20, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 8.0e4, + }, + } + ], + } + ) + prep_g, stack_g = _load_paired_models(doc_gauss, legacy_catalog, tmp_path, "bulk_gauss_ac") + res_new_g = solve_bulk_defect_impedance( + prep_g, + freqs, + voltage_V=0.25, + options=DynamicDefectImpedanceOptions(intervals_per_layer=(3, 3, 3), energy_quadrature_order=8), + ) + x_g = build_electrical_grid(stack_g, 9) + np.testing.assert_allclose(res_new_g.device.nodes_m, x_g, rtol=0.0, atol=1.0e-15) + + res_old_g = run_bulk_defect_device_impedance( + x_g, + stack_g, + freqs, + V_dc=0.25, + defect_energy_quadrature_order=8, + refinement_factors=(1.0, 0.5), + require_certificate=False, + ) + np.testing.assert_allclose( + res_new_g.admittance_density_S_m2, res_old_g.admittance_S_m2, rtol=1.0e-4, atol=1.0e-8 + ) + np.testing.assert_allclose( + res_new_g.impedance_area_ohm_m2, res_old_g.impedance_ohm_m2, rtol=1.0e-4, atol=1.0e-8 + ) + cf_new = run_defect_capacitance_frequency( + prep_g, + freqs, + voltage_V=0.25, + intervals_per_layer=(3, 3, 3), + energy_quadrature_order=8, + ) + cf_old = capacitance_frequency_from_admittance(freqs, res_old_g.admittance_S_m2, operating_voltage_V=0.25) + np.testing.assert_allclose( + cf_new.parallel_capacitance_F_m2, cf_old.parallel_capacitance_F_m2, rtol=1.0e-4, atol=1.0e-10 + ) + + # 1(b). Two-sided dynamic interface defect impedance parity: + ni_if = _thermodynamic_ni(1.0e25, 1.0e25, 1.35) + doc_if: dict[str, Any] = { + "schema_version": "standard-device-v1", + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "interface_charge_closure": "equilibrium_referenced", + "interface_charge_rebaseline_acknowledged": True, + "interface_defects": [ + { + "sigma_n_cm2": 8.0e-17, + "sigma_p_cm2": 5.0e-17, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 8.0e10, + "E_t_eV_below_cb": 0.62, + }, + { + "sigma_n_cm2": 6.0e-17, + "sigma_p_cm2": 4.0e-17, + "v_th_cm_s": 1.0e7, + "N_t_cm2": 6.0e10, + "E_t_eV_below_cb": 0.65, + }, + ], + "T": 300.0, + "Phi": 0.0, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"htl": 1.0, "absorber": 1.0, "etl": 1.0}, + "alphas": {"htl": 2.0, "absorber": 2.0, "etl": 2.0}, + }, + "layers": [ + { + "name": lname, + "role": lrole, + "thickness": 1.0e-7, + "eps_r": 16.0, + "mu_n": 1.0e-3, + "mu_p": 1.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_if, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_if, + "p1": ni_if, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": lchi, + "Eg": 1.35, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + } + for lname, lrole, lchi in ( + ("htl", "HTL", 4.00), + ("absorber", "absorber", 4.05), + ("etl", "ETL", 4.10), + ) + ], + } + prep_if, stack_if = _load_paired_models(doc_if, legacy_catalog, tmp_path, "iface_dyn_ac") + res_new_if = solve_interface_defect_impedance( + prep_if, + freqs, + voltage_V=0.10, + options=DynamicDefectImpedanceOptions(intervals_per_layer=(3, 3, 3)), + ) + x_if = build_two_sided_trace_grid(build_electrical_grid(stack_if, 9), stack_if) + np.testing.assert_allclose(res_new_if.device.nodes_m, x_if, rtol=0.0, atol=1.0e-15) + + res_old_if = run_interface_defect_device_impedance( + x_if, + stack_if, + freqs, + V_dc=0.10, + refinement_factors=(1.0, 0.5), + require_certificate=False, + ) + np.testing.assert_allclose( + res_new_if.admittance_density_S_m2, res_old_if.admittance_S_m2, rtol=1.0e-4, atol=1.0e-8 + ) + np.testing.assert_allclose( + res_new_if.impedance_area_ohm_m2, res_old_if.impedance_ohm_m2, rtol=1.0e-4, atol=1.0e-8 + ) + occ_resp_new: NDArray[np.complex128] = np.asarray( + [pt.interface_trap_occupancy_perturbation_per_V for pt in res_new_if.ac_sweep.points], + dtype=np.complex128, + ) + np.testing.assert_allclose( + occ_resp_new, res_old_if.interface_occupancy_response_per_V, rtol=1.0e-4, atol=1.0e-7 + ) + + +def test_live_dynamic_defect_and_bulk_defect_transient_parity( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 parity on narrow-gate v1 interface-defect+ion transient and D6-E1 bulk-defect transient.""" + # 2(a). Narrow-gate v1 dark interface-defect + absorber positive-ion transient: + fixture_yaml = ( + ROOT / "perovskite-sim/tests/fixtures/configs/dynamic_interface_defect_ion_transient_absorber_only.yaml" + ) + raw_v1 = dict(load_yaml_mapping(fixture_yaml.read_bytes())) + raw_v1["device"] = { + **dict(raw_v1["device"]), + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + } + prep_v1, stack_v1 = _load_paired_models(raw_v1, legacy_catalog, tmp_path, "v1_dyn_tr") + times_v1 = np.array([0.0, 1.0e-7, 2.0e-6, 5.0e-5]) + volts_v1 = np.array([0.0, 0.08, 0.08, 0.0]) + + tr_new_v1 = solve_dynamic_defect_transient( + prep_v1, + times_v1, + volts_v1, + options=DynamicDefectTransientOptions( + intervals_per_layer=(4, 4), substeps_per_interval=4, bdf_order=1 + ), + ) + x_v1 = build_two_sided_trace_grid(build_electrical_grid(stack_v1, 8), stack_v1) + np.testing.assert_allclose(tr_new_v1.grid_m, x_v1, rtol=0.0, atol=1.0e-15) + + tr_old_v1 = run_interface_defect_ion_device_transient( + x_v1, + stack_v1, + times_v1, + volts_v1, + policy=InterfaceDefectIonTransientPolicy(refinement_substeps=(2, 4)), + require_certificate=False, + ) + np.testing.assert_allclose( + tr_new_v1.terminal_current_density_A_m2, + np.mean(tr_old_v1.interface_total_current_A_m2[:, 0, :], axis=-1), + rtol=5.0e-4, + atol=1.0e-5, + ) + np.testing.assert_allclose( + tr_new_v1.interface_sheet_charges_C_m2, + tr_old_v1.interface_sheet_charge_C_m2, + rtol=5.0e-4, + atol=1.0e-10, + ) + abs_nodes = tr_new_v1.device.ionic_component.ion_node_indices # type: ignore[union-attr] + np.testing.assert_allclose( + tr_new_v1.positive_ion_density_m3[:, abs_nodes], + tr_old_v1.positive_ion_density_m3[:, abs_nodes], + rtol=1.0e-4, + atol=1.0e14, + ) + + # 2(b). Charged single-level bulk-defect transient (D6-E1): + ni_bt = _thermodynamic_ni(1.0e24, 8.0e23, 0.80) + doc_bt: dict[str, Any] = { + "schema_version": "standard-device-v1", + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "T": 300.0, + "Phi": 0.0, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"absorber": 1.0}, + "alphas": {"absorber": 2.5}, + }, + "layers": [ + { + "name": "absorber", + "role": "absorber", + "thickness": 3.0e-7, + "eps_r": 20.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 0.0, + "P0": 0.0, + "P_lim": 1.0e30, + "ni": ni_bt, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_bt, + "p1": ni_bt, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": 4.0, + "Eg": 0.80, + "Nc300": 1.0e24, + "Nv300": 8.0e23, + "defect_schema_version": "solarlab-explicit-bulk-defects-v1", + "defect_model": "explicit_quasi_steady", + "bulk_defects": [ + { + "name": "SingleLevelAcceptor", + "charge_transition": "acceptor", + "neutral_reference": "empty", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 2.0e21, + "center_eV_above_vb": 0.39, + }, + "kinetics": { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 7.0e-20, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 8.0e4, + }, + } + ], + } + ], + } + prep_bt, stack_bt = _load_paired_models(doc_bt, legacy_catalog, tmp_path, "bulk_dyn_tr") + times_bt = np.array([0.0, 1.0e-8, 1.0e-6, 1.0e-4]) + volts_bt = np.array([0.0, 0.02, 0.02, 0.0]) + + tr_new_bt = solve_bulk_defect_transient( + prep_bt, + times_bt, + volts_bt, + options=DynamicDefectTransientOptions( + intervals_per_layer=(5,), substeps_per_interval=4, bdf_order=1 + ), + ) + x_bt = build_electrical_grid(stack_bt, 5) + tr_old_bt = run_bulk_defect_device_transient( + x_bt, + stack_bt, + times_bt, + volts_bt, + policy=BulkDefectTransientPolicy(refinement_substeps=(2, 4)), + require_certificate=False, + ) + np.testing.assert_allclose( + tr_new_bt.bulk_trap_occupancy, tr_old_bt.trap_occupancy, rtol=5.0e-4, atol=1.0e-6 + ) + np.testing.assert_allclose( + tr_new_bt.potential_V, tr_old_bt.electrostatic_potential_V, rtol=5.0e-4, atol=1.0e-5 + ) + j_old_bt = np.median(tr_old_bt.total_current_faces_A_m2, axis=1) + np.testing.assert_allclose( + tr_new_bt.terminal_current_density_A_m2, j_old_bt, rtol=5.0e-4, atol=1.0e-5 + ) + + +def test_live_multivalent_v4_illuminated_jv_parity( + legacy_catalog: DefaultCatalog, + tmp_path: Path, +) -> None: + """T4 parity on illuminated 1-sun J-V for multivalent v4 amphoteric + double-acceptor defects.""" + doc_mv = _three_layer_pin_yaml(phi_flux=2.5e21) + # Moderate absorption coefficient so Beer-Lambert midpoint vs exact CV quadrature matches < 5e-6 on N=14: + doc_mv["layers"][1]["alpha"] = 1.5e5 + doc_mv["electrical_grid"]["interval_weights"] = {"htl": 4.0, "absorber": 6.0, "etl": 4.0} + doc_mv["layers"][1].update( + { + "defect_schema_version": "solarlab-explicit-bulk-defects-v4", + "defect_model": "explicit_quasi_steady", + "bulk_defects": [ + { + "name": "AmphotericCenter", + "total_density_m3": 1.5e21, + "configuration": { + "family": "amphoteric", + "charge_states_e": [1, 0, -1], + "degeneracy_convention": "scaps_binomial", + "state_degeneracies": [1.0, 2.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.42, + "correlation_energies_eV": [0.28], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [ + { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + { + "sigma_n_m2": 1.0e-19, + "sigma_p_m2": 2.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + ], + }, + }, + { + "name": "DoubleAcceptor", + "total_density_m3": 1.0e21, + "configuration": { + "family": "double_acceptor", + "charge_states_e": [0, -1, -2], + "degeneracy_convention": "unity", + "state_degeneracies": [1.0, 1.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.48, + "correlation_energies_eV": [0.24], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [ + { + "sigma_n_m2": 1.5e-19, + "sigma_p_m2": 1.5e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + { + "sigma_n_m2": 8.0e-20, + "sigma_p_m2": 1.5e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + ], + }, + }, + ], + } + ) + prep_mv, stack_mv = _load_paired_models(doc_mv, legacy_catalog, tmp_path, "multivalent_jv") + dev_mv = compile_dynamic_defect_device_1d( + prep_mv, intervals_per_layer=(4, 6, 4), dynamic_bulk_defects=False + ) + x_mv = build_electrical_grid(stack_mv, 14) + np.testing.assert_allclose(dev_mv.nodes_m, x_mv, rtol=0.0, atol=1.0e-15) + + voltages = np.linspace(0.0, 0.85, 6) + sweep_old = solve_quasi_fermi_jv_sweep( + x_mv, + stack_mv, + voltages, + illumination_steps=(0.0, 1.0e-4, 1.0e-2, 1.0), + stop_after_voc=True, + minimum_voltage_step_V=0.01, + continuity_tolerance_A_m2=5.0e-3, + current_spread_tolerance_A_m2=5.0e-3, + ) + v_used = np.asarray(sweep_old.voltages_V, dtype=np.float64) + + j_solar_new = np.empty_like(v_used) + prev_u: Vector | None = None + prev_v = 0.0 + for idx, vf in enumerate(v_used): + seed = None if prev_u is None else dev_mv.rebase_coordinates(prev_u, prev_v, float(vf)) + st = solve_dynamic_defect_steady_1d( + dev_mv, + voltage_V=float(vf), + generation_scale=1.0, + initial_u=seed, + voltage_step_max_V=0.05, + ) + j_solar_new[idx] = -st.terminal_current_density_A_m2 + prev_u = st.state.u + prev_v = float(vf) + + m_new = compute_metrics(v_used, j_solar_new, P_in=1000.0) + m_old = sweep_old.metrics + assert abs(m_new.V_oc - m_old.V_oc) <= 1.0e-4 + assert abs(m_new.J_sc - m_old.J_sc) / abs(m_old.J_sc) <= 1.0e-4 + assert abs(m_new.FF - m_old.FF) / abs(m_old.FF) <= 1.0e-4 + assert abs(m_new.PCE - m_old.PCE) / abs(m_old.PCE) <= 1.0e-4 + np.testing.assert_allclose(j_solar_new, sweep_old.currents_A_m2, rtol=1.0e-4, atol=1.0e-4) + + +def test_live_metastable_preparation_frozen_jv_and_transient_parity( + legacy_catalog: DefaultCatalog, +) -> None: + """T4 parity on metastable preparation (330 K -> 300 K), frozen 1-sun J-V, and operator-split transient.""" + gap_eV = 0.80 + nc_m3 = 1.0e24 + nv_m3 = 8.0e23 + ni_val = _thermodynamic_ni(nc_m3, nv_m3, gap_eV, 300.0) + trans_eV = 0.35 + ec_act = 0.20 + hc_act = 0.25 + phi_flux = 2.0e21 + alpha_val = 1.0e5 + + kin_dict = { + "sigma_n_m2": 2.0e-19, + "sigma_p_m2": 7.0e-20, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 8.0e4, + } + prep_dict = { + "schema_version": "solarlab-metastable-preparation-v1", + "preparation_limit": "stationary_infinite_time", + "preparation_temperature_K": 300.0, + "preparation_voltage_V": 0.04, + "preparation_illumination_suns": 0.0, + "voltage_continuation_steps": 0, + "illumination_continuation_steps": 0, + "measurement_temperature_K": 300.0, + "configuration_freeze_stage": "after_stationary_preparation_before_measurement", + "freeze_configuration_during_measurement": True, + "measurement_protocol_sha256": "a" * 64, + "numerics": { + "initial_donor_fraction_guess": 0.5, + "max_iterations": 80, + "relative_tolerance": 1.0e-10, + "clamping_factor": 0.5, + "final_unclamped_refinement": True, + }, + } + canon_doc = { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": "meta_parity", + "settings": { + "T": 300.0, + "Phi": phi_flux, + "mode": "legacy", + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + }, + "layers": [ + { + "id": "meta_absorber", + "name": "meta_absorber", + "role": "absorber", + "thickness": 300.0e-9, + "parameters": { + "eps_r": 20.0, + "mu_n": 2.0e-3, + "mu_p": 2.0e-3, + "D_ion": 0.0, + "P_lim": 1.0e30, + "P0": 0.0, + "ni": ni_val, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_val, + "p1": ni_val, + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "alpha": alpha_val, + "N_A": 0.0, + "N_D": 0.0, + "chi": 4.0, + "Eg": gap_eV, + "Nc300": nc_m3, + "Nv300": nv_m3, + }, + "metastable_document": { + "schema_version": "solarlab-metastable-bulk-defects-v1", + "defect_model": "explicit_metastable_frozen", + "metastable_defects": [ + { + "id": "meta_center", + "name": "metastable_center", + "total_density_m3": 2.0e21, + "donor_configuration": { + "family": "double_donor", + "charge_states_e": [2, 1, 0], + "degeneracy_convention": "unity", + "state_degeneracies": [1.0, 1.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.30, + "correlation_energies_eV": [0.15], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [copy.deepcopy(kin_dict), copy.deepcopy(kin_dict)], + }, + "acceptor_configuration": { + "family": "double_acceptor", + "charge_states_e": [0, -1, -2], + "degeneracy_convention": "unity", + "state_degeneracies": [1.0, 1.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.30, + "correlation_energies_eV": [0.15], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [copy.deepcopy(kin_dict), copy.deepcopy(kin_dict)], + }, + "donor_conversion_state_index": 1, + "acceptor_conversion_state_index": 1, + "conversion_kinetics": { + "transition_energy_eV_above_vb": trans_eV, + "electron_capture_activation_eV": ec_act, + "electron_emission_activation_eV": ec_act + 2.0 * (gap_eV - trans_eV), + "hole_capture_activation_eV": hc_act, + "hole_emission_activation_eV": hc_act + 2.0 * trans_eV, + "electron_capture_path": "double_electron_capture", + "hole_capture_path": "double_hole_capture", + "capture_n_m3_s": 1.0e-15, + "capture_p_m3_s": 1.0e-15, + "phonon_frequency_Hz": 1.0e15, + }, + } + ], + }, + "metastable_preparation": prep_dict, + } + ], + } + + prepared_new = resolve_device( + DeviceInput.model_validate(canon_doc), legacy_catalog, ResourceLibrary() + ) + state_new = prepare_metastable_state(prepared_new, intervals_per_layer=4) + + # Identical legacy DeviceStack + MetastableDefectDefinition + MetastablePreparationProtocol: + grid_old = multilayer_grid([Layer(300.0e-9, 4)]) + np.testing.assert_allclose( + state_new.grid_m, grid_old, rtol=0.0, atol=1.0e-15 + ) + + leg_kin = BulkDefectKinetics(**kin_dict) + leg_def = MetastableDefectDefinition( + name="metastable_center", + total_density_m3=2.0e21, + donor_configuration=MultivalentDefectConfiguration( + family="double_donor", + charge_states_e=(2, 1, 0), + degeneracy_convention="unity", + state_degeneracies=(1.0, 1.0, 1.0), + energy_levels=MultivalentEnergyLevels( + first_transition_eV_above_vb=0.30, correlation_energies_eV=(0.15,) + ), + transition_kinetics=(leg_kin, leg_kin), + ), + acceptor_configuration=MultivalentDefectConfiguration( + family="double_acceptor", + charge_states_e=(0, -1, -2), + degeneracy_convention="unity", + state_degeneracies=(1.0, 1.0, 1.0), + energy_levels=MultivalentEnergyLevels( + first_transition_eV_above_vb=0.30, correlation_energies_eV=(0.15,) + ), + transition_kinetics=(leg_kin, leg_kin), + ), + donor_conversion_state_index=1, + acceptor_conversion_state_index=1, + conversion_kinetics=MetastableConversionKinetics( + transition_energy_eV_above_vb=trans_eV, + electron_capture_activation_eV=ec_act, + electron_emission_activation_eV=ec_act + 2.0 * (gap_eV - trans_eV), + hole_capture_activation_eV=hc_act, + hole_emission_activation_eV=hc_act + 2.0 * trans_eV, + electron_capture_path="double_electron_capture", + hole_capture_path="double_hole_capture", + capture_n_m3_s=1.0e-15, + capture_p_m3_s=1.0e-15, + phonon_frequency_Hz=1.0e15, + ), + ) + leg_proto = MetastablePreparationProtocol( + schema_version="solarlab-metastable-preparation-v1", + preparation_limit="stationary_infinite_time", + preparation_temperature_K=300.0, + preparation_voltage_V=0.04, + preparation_illumination_suns=0.0, + voltage_continuation_steps=0, + illumination_continuation_steps=0, + measurement_temperature_K=300.0, + configuration_freeze_stage="after_stationary_preparation_before_measurement", + freeze_configuration_during_measurement=True, + measurement_protocol_sha256="a" * 64, + numerics=MetastablePreparationNumerics( + initial_donor_fraction_guess=0.5, + max_iterations=80, + relative_tolerance=1.0e-10, + clamping_factor=0.5, + final_unclamped_refinement=True, + ), + ) + leg_stack = DeviceStack( + layers=( + LayerSpec( + "meta_absorber", + 300.0e-9, + MaterialParams( + eps_r=20.0, + mu_n=2.0e-3, + mu_p=2.0e-3, + D_ion=0.0, + P_lim=1.0e30, + P0=0.0, + ni=ni_val, + tau_n=1.0e-6, + tau_p=1.0e-6, + n1=ni_val, + p1=ni_val, + B_rad=0.0, + C_n=0.0, + C_p=0.0, + alpha=alpha_val, + N_A=0.0, + N_D=0.0, + chi=4.0, + Eg=gap_eV, + Nc300=nc_m3, + Nv300=nv_m3, + ), + "absorber", + ), + ), + V_bi=0.0, + Phi=phi_flux, + interfaces=(), + mode="legacy", + built_in_potential_mode="semiconductor_work_function", + ) + frozen_old = prepare_metastable_configuration( + grid_old, leg_stack, leg_def, leg_proto, layer_name="meta_absorber" + ) + np.testing.assert_allclose( + state_new.donor_fractions[0], frozen_old.donor_fraction, rtol=1.0e-7, atol=1.0e-9 + ) + + # Frozen 1-sun J-V parity: + v_jv = np.array([0.0, 0.01]) + jv_new = solve_frozen_metastable_jv(state_new, v_jv, generation_scale=1.0) + jv_old = solve_frozen_metastable_jv_sweep( + grid_old, + leg_stack, + frozen_old, + v_jv, + illumination_steps=(0.0, 1.0e-2, 1.0), + continuity_tolerance_A_m2=2.0e-4, + current_spread_tolerance_A_m2=2.0e-4, + ) + np.testing.assert_allclose( + -jv_new.current_densities_A_m2, jv_old.currents_A_m2, rtol=1.0e-4, atol=1.0e-5 + ) + + # Operator-split dark relaxation transient parity at T = 300 K, V = 0.0 V: + mask_old = frozen_old.active_nodes + closure_300 = evaluate_metastable_configuration_closure( + np.asarray(frozen_old.preparation_state.y[: grid_old.size], dtype=float)[mask_old], + np.asarray(frozen_old.preparation_state.y[grid_old.size : 2 * grid_old.size], dtype=float)[mask_old], + leg_def, + band_gap_eV=gap_eV, + effective_conduction_dos_m3=nc_m3, + effective_valence_dos_m3=nv_m3, + temperature_K=300.0, + ) + tau_min = float( + np.min(1.0 / (np.asarray(closure_300.donor_to_acceptor_rate_s1) + np.asarray(closure_300.acceptor_to_donor_rate_s1))) + ) + t_meta = np.arange(3, dtype=np.float64) * (0.05 * tau_min) + tr_new = solve_metastable_transient(state_new, t_meta, voltage_V=0.0, generation_scale=0.0) + tr_old = run_metastable_configuration_transient( + grid_old, leg_stack, frozen_old, t_meta, V_app=0.0, illuminated=False + ) + assert tr_new.certificate.passed is True + assert tr_old.certificate.certified is True + np.testing.assert_allclose(tr_new.donor_fractions[0], tr_old.donor_fraction, rtol=1.0e-6, atol=1.0e-8) + np.testing.assert_allclose( + tr_new.stationary_fractions[0], tr_old.stationary_fraction, rtol=1.0e-6, atol=1.0e-8 + ) + np.testing.assert_allclose( + tr_new.relaxation_times_s[0], tr_old.relaxation_time_s, rtol=1.0e-6, atol=1.0e-12 + ) + np.testing.assert_allclose( + tr_new.configuration_charge_transfer_C_m2, + tr_old.configuration_charge_transfer_C_m2, + rtol=1.0e-5, + atol=1.0e-12, + ) diff --git a/tests/unit/equations/test_defect_ion_coupled_ac.py b/tests/unit/equations/test_defect_ion_coupled_ac.py new file mode 100644 index 00000000..46d82004 --- /dev/null +++ b/tests/unit/equations/test_defect_ion_coupled_ac.py @@ -0,0 +1,516 @@ +"""Unified assembly, steady QSS identity, Jacobian/storage tangents, and coupled AC tests (T2, P04-10).""" + +from __future__ import annotations + +from collections.abc import Iterator +import copy +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import ( + AssembledDynamicDefect1DProblem, + DynamicDefectSmallSignal1D, + DynamicDefectStorage1D, + dynamic_defect_system_1d, + solve_dynamic_defect_steady_1d, +) +from solarlab.equations.dc_1d import CapabilityError +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument + +ROOT = Path(__file__).resolve().parents[3] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +@pytest.fixture(scope="module", autouse=True) +def _blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def defaults() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in LEGACY_DEFAULTS) + ) + + +def _mat(eg: float = 1.6, chi: float = 3.9, *, nd: float = 0.0, na: float = 0.0) -> dict[str, Any]: + vt = 1.380649e-23 * 300.0 / 1.602176634e-19 + nc = 2.0e24 + nv = 2.0e24 + ni = float(np.sqrt(nc * nv * np.exp(-eg / vt))) + return { + "Eg": eg, + "chi": chi, + "Nc300": nc, + "Nv300": nv, + "ni": ni, + "n1": ni, + "p1": ni, + "eps_r": 24.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-16, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 1.0e7, + "A_star_n": 1.2e5, + "A_star_p": 1.2e5, + "N_D": nd, + "N_A": na, + "P0": 0.0, + "P_lim": 1.0e27, + "D_ion": 0.0, + } + + +def _settings(**extra: Any) -> dict[str, Any]: + return { + "T": 300.0, + "Phi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + **extra, + } + + +def _bulk_defect_entry( + defect_id: str = "t1", + *, + density: float = 3.0e21, + kind: str = "single_level", +) -> dict[str, Any]: + dist: dict[str, Any] = { + "kind": kind, + "normalization": "integrated_total", + "total_density_m3": density, + } + if kind == "gaussian": + dist["energy_reference"] = "above_valence_band" + dist["width_eV"] = 0.05 + dist["width_convention"] = "gaussian_standard_deviation" + dist["support_width_multiplier"] = 6.0 + return { + "id": defect_id, + "name": defect_id, + "charge_transition": "acceptor", + "neutral_reference": "empty", + "degeneracy": 1.0, + "energy_level": {"reference": "above_valence_band", "value_eV": 0.72}, + "distribution": dist, + "kinetics": { + "sigma_n_m2": 1.5e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + } + + +def _iface_defect_entry( + defect_id: str = "id1", + *, + density_m2: float = 1.5e15, + calibration_factor: float = 1.0, +) -> dict[str, Any]: + return { + "id": defect_id, + "total_density_m2": density_m2, + "trap_depth_eV": 0.62, + "energy_reference": "below_conduction_band", + "calibration_factor": calibration_factor, + "iface_state_calibration_factor": 1.0, + "kinetics": { + "sigma_n_m2": 1.2e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + } + + +def _resolve(doc: dict[str, Any], defaults: DefaultCatalog) -> PreparedDevice: + return resolve_device(DeviceInput.model_validate(doc), defaults, ResourceLibrary()) + + +def _three_layer_doc( + *, + with_bulk: bool = True, + bulk_kind: str = "single_level", + with_iface: bool = True, + with_ions: bool = True, + bulk_density: float = 3.0e21, +) -> dict[str, Any]: + abs_layer: dict[str, Any] = { + "id": "abs", + "name": "Abs", + "role": "absorber", + "thickness": 320e-9, + "parameters": { + **_mat(1.6, 3.9), + **( + {"P0": 1.5e23, "P_lim": 1.0e25, "D_ion": 2.0e-15} + if with_ions + else {} + ), + }, + } + if with_bulk: + abs_layer["defect_model"] = "explicit_quasi_steady" + abs_layer["defect_schema_version"] = ( + "solarlab-explicit-bulk-defects-v1" + if bulk_kind == "single_level" + else "solarlab-explicit-bulk-defects-v2" + ) + abs_layer["bulk_defects"] = [ + _bulk_defect_entry("t1", density=bulk_density, kind=bulk_kind) + ] + + if0: dict[str, Any] = {"id": "if_htl_abs", "left": "htl", "right": "abs"} + if with_iface: + if0["defect"] = _iface_defect_entry("id1") + + return { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": f"pin_{with_bulk}_{bulk_kind}_{with_iface}_{with_ions}", + "layers": [ + {"id": "htl", "name": "HTL", "role": "htl", "thickness": 70e-9, "parameters": _mat(2.1, 3.5, na=2e22)}, + abs_layer, + {"id": "etl", "name": "ETL", "role": "etl", "thickness": 70e-9, "parameters": _mat(2.2, 3.95, nd=2e22)}, + ], + "interfaces": [ + if0, + {"id": "if_abs_etl", "left": "abs", "right": "etl"}, + ], + "settings": _settings( + interface_charge_closure="equilibrium_referenced" if with_iface else "off", + interface_charge_rebaseline_acknowledged=with_iface, + ), + } + + +def _assert_jacobian_and_storage_fd( + dev: Any, u0: np.ndarray, *, voltage_V: float = 0.35 +) -> None: + rng = np.random.default_rng(20261114) + # Perturb away from exact steady QSS root so dynamic trap storage rates are nonzero: + u_test = u0.copy() + N = dev.node_count + u_test[1 : N - 1] += 0.005 * rng.standard_normal(N - 2) + u_test[N + 1 : 2 * N - 1] += 0.02 * rng.standard_normal(N - 2) + u_test[2 * N + 1 : 3 * N - 1] += 0.02 * rng.standard_normal(N - 2) + if u_test.size > 3 * N: + u_test[3 * N :] += 0.15 * rng.standard_normal(u_test.size - 3 * N) + + prob = AssembledDynamicDefect1DProblem(dev, voltage_V=voltage_V, generation_scale=0.0) + j_ana = prob.jacobian(u_test).toarray() + eps = 1.0e-7 + eps = 1.0e-5 + j_fd = np.zeros_like(j_ana) + for col in range(u_test.size): + step = eps * max(1.0, abs(float(u_test[col]))) + u_p1 = u_test.copy() + u_p1[col] += step + u_m1 = u_test.copy() + u_m1[col] -= step + u_p2 = u_test.copy() + u_p2[col] += 2.0 * step + u_m2 = u_test.copy() + u_m2[col] -= 2.0 * step + j_fd[:, col] = ( + -prob.residual(u_p2) + + 8.0 * prob.residual(u_p1) + - 8.0 * prob.residual(u_m1) + + prob.residual(u_m2) + ) / (12.0 * step) + rel_j = float(np.linalg.norm(j_ana - j_fd) / np.linalg.norm(j_fd)) + assert rel_j <= 1.0e-10 + + sys_tr = dynamic_defect_system_1d(dev, inventory_row_node=None) + prob_tr = AssembledDynamicDefect1DProblem( + dev, voltage_V=voltage_V, generation_scale=0.0, system=sys_tr + ) + adapter = DynamicDefectStorage1D(prob_tr) + k_ana = adapter.storage_tangent(u_test).toarray() + k_fd = np.zeros_like(k_ana) + for col in range(u_test.size): + step = eps * max(1.0, abs(float(u_test[col]))) + u_p1 = u_test.copy() + u_p1[col] += step + u_m1 = u_test.copy() + u_m1[col] -= step + u_p2 = u_test.copy() + u_p2[col] += 2.0 * step + u_m2 = u_test.copy() + u_m2[col] -= 2.0 * step + k_fd[:, col] = ( + -adapter.storage(u_p2) + + 8.0 * adapter.storage(u_p1) + - 8.0 * adapter.storage(u_m1) + + adapter.storage(u_m2) + ) / (12.0 * step) + rel_k = float(np.linalg.norm(k_ana - k_fd) / np.linalg.norm(k_fd)) + assert rel_k <= 1.0e-10 + + +def test_assembled_jacobians_and_storage_tangents_across_all_topologies( + defaults: DefaultCatalog, +) -> None: + """Verify full FD residual & storage Jacobians across bulk, interface, and coupled ion topologies.""" + cases = [ + (True, "gaussian", False, False), + (False, "single_level", True, False), + (True, "single_level", False, True), + (False, "single_level", True, True), + (True, "single_level", True, True), + ] + for with_bulk, bulk_kind, with_iface, with_ions in cases: + prep = _resolve( + _three_layer_doc( + with_bulk=with_bulk, + bulk_kind=bulk_kind, + with_iface=with_iface, + with_ions=with_ions, + ), + defaults, + ) + dev = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=6, + dynamic_bulk_defects=with_bulk, + dynamic_interface_defects=with_iface, + energy_quadrature_order=8, + ion_domain_layer="abs" if with_ions else None, + ion_domain_endpoints=("blocking", "blocking") if with_ions else None, + ) + st = solve_dynamic_defect_steady_1d(dev, voltage_V=0.35, generation_scale=0.0) + assert st.converged + _assert_jacobian_and_storage_fd(dev, st.state.u, voltage_V=0.35) + + +def test_steady_qss_embedding_and_zero_density_limit(defaults: DefaultCatalog) -> None: + """Verify dynamic steady state matches stationary QSS and N_t -> 0 approaches baseline.""" + prep = _resolve( + _three_layer_doc(with_bulk=True, with_iface=True, with_ions=False), defaults + ) + dev_dyn = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=8, + dynamic_bulk_defects=True, + dynamic_interface_defects=True, + ) + dev_qss = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=8, + dynamic_bulk_defects=False, + dynamic_interface_defects=False, + ) + st_dyn = solve_dynamic_defect_steady_1d(dev_dyn, voltage_V=0.45, generation_scale=0.0) + st_qss = solve_dynamic_defect_steady_1d(dev_qss, voltage_V=0.45, generation_scale=0.0) + assert st_dyn.converged and st_qss.converged + assert st_dyn.terminal_current_density_A_m2 == pytest.approx( + st_qss.terminal_current_density_A_m2, rel=1e-11 + ) + np.testing.assert_allclose( + st_dyn.state.electronic_state.potential_V, + st_qss.state.electronic_state.potential_V, + rtol=1e-11, + atol=1e-12, + ) + + # Small-density limit N_t -> 0 reproduces lifetime-SRH-free electronic baseline + # (explicit_quasi_steady replaces absorber effective-lifetime tau_n/tau_p SRH): + doc_zero = _three_layer_doc( + with_bulk=True, with_iface=False, with_ions=False, bulk_density=1.0e3 + ) + doc_clean = _three_layer_doc(with_bulk=False, with_iface=False, with_ions=False) + doc_clean["layers"][1]["parameters"]["tau_n"] = 1.0e30 + doc_clean["layers"][1]["parameters"]["tau_p"] = 1.0e30 + prep_zero = _resolve(doc_zero, defaults) + prep_clean = _resolve(doc_clean, defaults) + dev_zero = compile_dynamic_defect_device_1d( + prep_zero, intervals_per_layer=8, dynamic_bulk_defects=False + ) + dev_clean = compile_dynamic_defect_device_1d( + prep_clean, intervals_per_layer=8, dynamic_bulk_defects=False + ) + st_zero = solve_dynamic_defect_steady_1d(dev_zero, voltage_V=0.85, generation_scale=0.0) + st_clean = solve_dynamic_defect_steady_1d(dev_clean, voltage_V=0.85, generation_scale=0.0) + assert st_zero.terminal_current_density_A_m2 == pytest.approx( + st_clean.terminal_current_density_A_m2, rel=1e-9 + ) + + +def test_small_signal_ac_limits_digest_invariance_and_non_additivity( + defaults: DefaultCatalog, +) -> None: + """Verify 0 Hz FD slope, low/high-f limits, ion conservation, and electrostatic non-additivity.""" + prep = _resolve( + _three_layer_doc(with_bulk=True, with_iface=True, with_ions=True), defaults + ) + dev = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=8, + dynamic_bulk_defects=True, + dynamic_interface_defects=True, + ion_domain_layer="abs", + ion_domain_endpoints=("blocking", "blocking"), + ) + v0 = 0.40 + st = solve_dynamic_defect_steady_1d(dev, voltage_V=v0, generation_scale=0.0) + ss = DynamicDefectSmallSignal1D(dev, st.state, generation_scale=0.0) + + freqs = np.array([0.0, 1.0e-7, 1.0, 1.0e3, 1.0e9]) + coupled = ss.solve_sweep(freqs) + f_ions = ss.solve_sweep(freqs, freeze_ions=True) + f_traps = ss.solve_sweep( + freqs, freeze_bulk_traps=True, freeze_interface_traps=True + ) + f_both = ss.solve_sweep( + freqs, + freeze_ions=True, + freeze_bulk_traps=True, + freeze_interface_traps=True, + ) + + assert ( + coupled.working_state_digest + == f_ions.working_state_digest + == f_traps.working_state_digest + == f_both.working_state_digest + ) + + # Low-frequency limit approaches 0 Hz QSS and central-FD dJ/dV: + y0 = complex(coupled.admittance_density_S_m2[0]) + y_lf = complex(coupled.admittance_density_S_m2[1]) + assert abs(y_lf - y0) / abs(y0) <= 1.0e-4 + + dv = 1.0e-5 + st_p = solve_dynamic_defect_steady_1d( + dev, + voltage_V=v0 + dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st.state.u, v0, v0 + dv), + ) + st_m = solve_dynamic_defect_steady_1d( + dev, + voltage_V=v0 - dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st.state.u, v0, v0 - dv), + ) + dj_dv = (st_p.terminal_current_density_A_m2 - st_m.terminal_current_density_A_m2) / (2.0 * dv) + assert y0.imag == pytest.approx(0.0, abs=1e-16) + assert y0.real == pytest.approx(dj_dv, rel=1e-5) + + # High-frequency limit approaches frozen-species admittance: + y_hf = complex(coupled.admittance_density_S_m2[-1]) + y_hf_frozen = complex(f_both.admittance_density_S_m2[-1]) + assert abs(y_hf - y_hf_frozen) / abs(y_hf_frozen) <= 1.0e-4 + + # Ion inventory conservation across all frequencies including 0 Hz: + for pt in coupled.points: + assert pt.ion_inventory_relative_per_V["positive"] <= 1.0e-12 + + # Coupled defect + ion admittance is NOT equal to naive linear superposition at 1 Hz: + idx_mid = 2 + y_coupled_mid = coupled.admittance_density_S_m2[idx_mid] + y_naive_sum = ( + f_ions.admittance_density_S_m2[idx_mid] + + f_traps.admittance_density_S_m2[idx_mid] + - f_both.admittance_density_S_m2[idx_mid] + ) + assert abs(y_coupled_mid - y_naive_sum) / abs(y_coupled_mid) > 1.0e-4 + + +def test_compile_capability_refusals(defaults: DefaultCatalog) -> None: + """Verify pre-solve CapabilityError refusals on unsupported dynamic combinations.""" + # 1. Calibrated interface defect refused: + bad_cal = _three_layer_doc(with_bulk=False, with_iface=True, with_ions=False) + bad_cal["interfaces"][0]["defect"] = _iface_defect_entry(calibration_factor=2.5) + prep_cal = _resolve(bad_cal, defaults) + with pytest.raises(CapabilityError, match="calibration"): + compile_dynamic_defect_device_1d(prep_cal, dynamic_interface_defects=True) + + # 2. Two-sided interior ion layer with < 3 trace nodes refused: + prep_ion = _resolve( + _three_layer_doc(with_bulk=False, with_iface=True, with_ions=True), defaults + ) + with pytest.raises(CapabilityError, match="at least 3 trace nodes"): + compile_dynamic_defect_device_1d( + prep_ion, + intervals_per_layer=3, + dynamic_interface_defects=True, + ion_domain_layer="abs", + ion_domain_endpoints=("blocking", "blocking"), + ) + + # 3. Multivalent v4 refused when dynamic_bulk_defects=True: + mv_doc = copy.deepcopy(_three_layer_doc(with_bulk=False, with_iface=False, with_ions=False)) + mv_doc["layers"][1].update( + { + "defect_model": "explicit_quasi_steady", + "defect_schema_version": "solarlab-explicit-bulk-defects-v4", + "bulk_defects": [ + { + "id": "amp1", + "name": "Amphoteric", + "total_density_m3": 5.0e21, + "configuration": { + "family": "amphoteric", + "charge_states_e": [1, 0, -1], + "degeneracy_convention": "scaps_binomial", + "state_degeneracies": [1.0, 2.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.55, + "correlation_energies_eV": [0.35], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [ + { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 1e5, + "thermal_velocity_p_m_s": 1e5, + }, + { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 1e5, + "thermal_velocity_p_m_s": 1e5, + }, + ], + }, + } + ], + } + ) + prep_mv = _resolve(mv_doc, defaults) + with pytest.raises(CapabilityError, match="multivalent"): + compile_dynamic_defect_device_1d(prep_mv, dynamic_bulk_defects=True) diff --git a/tests/unit/experiments/test_dynamic_defect_experiments.py b/tests/unit/experiments/test_dynamic_defect_experiments.py new file mode 100644 index 00000000..4937fdc3 --- /dev/null +++ b/tests/unit/experiments/test_dynamic_defect_experiments.py @@ -0,0 +1,662 @@ +"""Unit tests for dynamic-defect C-f, impedance, coupled defect-ion impedance, and transients (P05-03b, P05-04b).""" + +from __future__ import annotations + +from collections.abc import Iterator +import copy +import math +from pathlib import Path +from typing import Any, cast + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.defects import MetastablePreparationInput +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.capacitance_frequency import ( + DefectCFError, + DefectCFOptions, + capacitance_frequency_from_admittance, + run_defect_capacitance_frequency, +) +from solarlab.experiments.defect_ion_impedance import ( + DefectIonImpedanceCapabilityError, + DefectIonImpedanceOptions, + solve_defect_ion_impedance, +) +from solarlab.experiments.dynamic_defect_impedance import ( + DynamicDefectImpedanceCapabilityError, + DynamicDefectImpedanceOptions, + classify_dynamic_defect_capability, + solve_bulk_defect_impedance, + solve_interface_defect_impedance, +) +from solarlab.experiments.dynamic_defect_transient import ( + DynamicDefectTransientCapabilityError, + DynamicDefectTransientOptions, + classify_dynamic_defect_transient_capability, + solve_bulk_defect_ion_transient, + solve_bulk_defect_transient, + solve_dynamic_defect_transient, + solve_interface_defect_ion_transient, + solve_interface_defect_transient, +) +from solarlab.experiments.metastable_transient import ( + MetastablePreparationError, + prepare_metastable_state, + solve_frozen_metastable_jv, + solve_frozen_metastable_steady, + solve_metastable_transient, +) +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument + +ROOT = Path(__file__).resolve().parents[3] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +@pytest.fixture(scope="module", autouse=True) +def _blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def defaults() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in LEGACY_DEFAULTS) + ) + + +def _mat(eg: float = 1.6, chi: float = 3.9, *, nd: float = 0.0, na: float = 0.0) -> dict[str, Any]: + vt = 1.380649e-23 * 300.0 / 1.602176634e-19 + nc = 2.0e24 + nv = 2.0e24 + ni = float(np.sqrt(nc * nv * np.exp(-eg / vt))) + return { + "Eg": eg, + "chi": chi, + "Nc300": nc, + "Nv300": nv, + "ni": ni, + "n1": ni, + "p1": ni, + "eps_r": 24.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "B_rad": 1.0e-16, + "C_n": 0.0, + "C_p": 0.0, + "alpha": 1.0e7, + "A_star_n": 1.2e5, + "A_star_p": 1.2e5, + "N_D": nd, + "N_A": na, + "P0": 0.0, + "P_lim": 1.0e27, + "D_ion": 0.0, + } + + +def _settings(**extra: Any) -> dict[str, Any]: + return { + "T": 300.0, + "Phi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + **extra, + } + + +def _bulk_defect( + charge_transition: str = "acceptor", + kind: str = "single_level", +) -> dict[str, Any]: + dist: dict[str, Any] = { + "kind": kind, + "normalization": "integrated_total", + "total_density_m3": 2.0e21, + } + if kind == "gaussian": + dist["energy_reference"] = "above_valence_band" + dist["width_eV"] = 0.05 + dist["width_convention"] = "gaussian_standard_deviation" + dist["support_width_multiplier"] = 6.0 + neutral_ref = ( + "filled" + if charge_transition == "donor" + else ("all_occupancies" if charge_transition == "neutral" else "empty") + ) + return { + "id": "t1", + "name": "Trap1", + "charge_transition": charge_transition, + "neutral_reference": neutral_ref, + "degeneracy": 1.0, + "energy_level": {"reference": "above_valence_band", "value_eV": 0.72}, + "distribution": dist, + "kinetics": { + "sigma_n_m2": 1.5e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + } + + +def _iface_defect(calibration_factor: float = 1.0) -> dict[str, Any]: + return { + "id": "id1", + "total_density_m2": 1.2e15, + "trap_depth_eV": 0.60, + "energy_reference": "below_conduction_band", + "calibration_factor": calibration_factor, + "iface_state_calibration_factor": 1.0, + "kinetics": { + "sigma_n_m2": 1.2e-19, + "sigma_p_m2": 1.0e-19, + "thermal_velocity_n_m_s": 1.0e5, + "thermal_velocity_p_m_s": 1.0e5, + }, + } + + +def _resolve(doc: dict[str, Any], defaults: DefaultCatalog) -> PreparedDevice: + return resolve_device(DeviceInput.model_validate(doc), defaults, ResourceLibrary()) + + +def _pin_doc( + *, + with_bulk: bool = False, + bulk_transition: str = "acceptor", + bulk_kind: str = "single_level", + with_iface: bool = False, + with_ions: bool = False, +) -> dict[str, Any]: + abs_layer: dict[str, Any] = { + "id": "abs", + "name": "Abs", + "role": "absorber", + "thickness": 320e-9, + "parameters": { + **_mat(1.6, 3.9), + **( + {"P0": 1.5e23, "P_lim": 1.0e25, "D_ion": 2.0e-15} + if with_ions + else {} + ), + }, + } + if with_bulk: + abs_layer["defect_model"] = "explicit_quasi_steady" + abs_layer["defect_schema_version"] = ( + "solarlab-explicit-bulk-defects-v1" + if bulk_kind == "single_level" + else "solarlab-explicit-bulk-defects-v2" + ) + abs_layer["bulk_defects"] = [_bulk_defect(bulk_transition, bulk_kind)] + + if0: dict[str, Any] = {"id": "if_htl_abs", "left": "htl", "right": "abs"} + if with_iface: + if0["defect"] = _iface_defect() + + return { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": "exp_pin", + "layers": [ + {"id": "htl", "name": "HTL", "role": "htl", "thickness": 70e-9, "parameters": _mat(2.1, 3.5, na=2e22)}, + abs_layer, + {"id": "etl", "name": "ETL", "role": "etl", "thickness": 70e-9, "parameters": _mat(2.2, 3.95, nd=2e22)}, + ], + "interfaces": [ + if0, + {"id": "if_abs_etl", "left": "abs", "right": "etl"}, + ], + "settings": _settings( + interface_charge_closure="equilibrium_referenced" if with_iface else "off", + interface_charge_rebaseline_acknowledged=with_iface, + ), + } + + +def _two_layer_v1_transient_doc() -> dict[str, Any]: + return { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": "v1_prod_tr", + "layers": [ + { + "id": "abs", + "name": "Abs", + "role": "absorber", + "thickness": 300e-9, + "parameters": { + **_mat(1.6, 3.9, na=1e21), + "P0": 1.0e23, + "P_lim": 1.0e25, + "D_ion": 2.0e-15, + }, + }, + { + "id": "etl", + "name": "ETL", + "role": "etl", + "thickness": 80e-9, + "parameters": _mat(2.2, 3.95, nd=2e22), + }, + ], + "interfaces": [ + {"id": "if_abs_etl", "left": "abs", "right": "etl", "defect": _iface_defect()}, + ], + "settings": _settings( + interface_charge_closure="equilibrium_referenced", + interface_charge_rebaseline_acknowledged=True, + ), + } + + +def test_capacitance_frequency_debye_analytics_masking_and_passivity( + defaults: DefaultCatalog, +) -> None: + """Verify exact Debye C_p/C_s/Walter peak, susceptance masking, and dark passivity.""" + g0 = 0.02 + c_inf = 4.0e-4 + dc = 2.0e-4 + tau = 1.0e-3 + freqs = np.geomspace(1.0, 1.0e6, 241) + omega = 2.0 * np.pi * freqs + y_debye = g0 + 1j * omega * (c_inf + dc / (1.0 + 1j * omega * tau)) + + cf = capacitance_frequency_from_admittance(freqs, y_debye, operating_voltage_V=0.0) + assert cf.scientific_qualification is False + assert cf.physical_certificate_status == "not_evaluated" + assert cf.dark_equilibrium_passive is True + assert np.all(cf.capacitance_accepted) + + expected_cp = c_inf + dc / (1.0 + (omega * tau) ** 2) + expected_gp = g0 + (omega**2 * tau * dc) / (1.0 + (omega * tau) ** 2) + np.testing.assert_allclose(cf.parallel_capacitance_F_m2, expected_cp, rtol=1e-13) + np.testing.assert_allclose(cf.parallel_conductance_S_m2, expected_gp, rtol=1e-13) + np.testing.assert_allclose( + cf.loss_tangent, expected_gp / (omega * expected_cp), rtol=1e-13 + ) + + f_peak_exact = 1.0 / (2.0 * math.pi * tau) + assert cf.peak_walter_frequency_Hz is not None + assert cf.peak_walter_value_F_m2 is not None + assert abs(math.log10(cf.peak_walter_frequency_Hz / f_peak_exact)) < 0.03 + assert cf.peak_walter_value_F_m2 == pytest.approx(0.5 * dc, rel=5e-3) + + # Masking ledger (0 Hz, inductive Im(Y) < 0, zero Im(Y) == 0, unresolved phase): + f_mix = np.array([0.0, 10.0, 100.0, 1000.0, 10000.0]) + y_mix = np.array([1.0 + 0.0j, 1.0 - 0.5j, 1.0 + 0.0j, 100.0 + 0.01j, 0.1 + 1.0j]) + masked = capacitance_frequency_from_admittance( + f_mix, + y_mix, + operating_voltage_V=0.2, + options=DefectCFOptions(minimum_phase_angle_rad=0.05), + ) + assert masked.mask_reasons == ( + "zero_frequency", + "inductive_susceptance", + "zero_susceptance", + "unresolved_phase", + None, + ) + assert list(masked.capacitance_accepted) == [False, False, False, False, True] + + with pytest.raises(DefectCFError, match="inductive"): + capacitance_frequency_from_admittance( + np.array([10.0]), + np.array([1.0 - 0.2j]), + operating_voltage_V=0.2, + options=DefectCFOptions(strict_capacitive=True), + ) + + with pytest.raises(DefectCFError, match="passivity"): + capacitance_frequency_from_admittance( + np.array([10.0, 100.0]), + np.array([-1.0e-3 + 0.1j, 0.2 + 0.5j]), + operating_voltage_V=0.0, + generation_scale=0.0, + ) + + # End-to-end device C-f run: + prep = _resolve(_pin_doc(with_bulk=True), defaults) + dev_cf = run_defect_capacitance_frequency( + prep, np.array([1.0, 100.0, 1.0e5]), intervals_per_layer=6 + ) + assert dev_cf.dark_equilibrium_passive is True + assert np.all(dev_cf.capacitance_accepted) + + +def test_dynamic_defect_and_combined_ion_impedance_capabilities_and_execution( + defaults: DefaultCatalog, +) -> None: + """Verify all 5 capability classifications, refusals, FD 0 Hz check, and 4-mode AC.""" + assert ( + classify_dynamic_defect_capability(_resolve(_pin_doc(with_bulk=True), defaults)) + == "bulk_dynamic_defect" + ) + assert ( + classify_dynamic_defect_capability(_resolve(_pin_doc(with_iface=True), defaults)) + == "interface_dynamic_defect" + ) + assert ( + classify_dynamic_defect_capability( + _resolve(_pin_doc(with_bulk=True, with_ions=True), defaults) + ) + == "bulk_defect_plus_ions" + ) + assert ( + classify_dynamic_defect_capability( + _resolve(_pin_doc(with_iface=True, with_ions=True), defaults) + ) + == "interface_defect_plus_ions" + ) + assert ( + classify_dynamic_defect_capability( + _resolve(_pin_doc(with_bulk=True, with_iface=True, with_ions=True), defaults) + ) + == "bulk_interface_defect_plus_ions" + ) + + # Refusal: bulk + interface WITHOUT active mobile ions: + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="without active mobile ions"): + classify_dynamic_defect_capability( + _resolve(_pin_doc(with_bulk=True, with_iface=True, with_ions=False), defaults) + ) + + # Refusal: no defects: + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="requires an explicit"): + classify_dynamic_defect_capability(_resolve(_pin_doc(), defaults)) + + # Refusal: solve_defect_ion_impedance on ion-free device: + prep_bulk = _resolve(_pin_doc(with_bulk=True), defaults) + with pytest.raises(DefectIonImpedanceCapabilityError, match="active mobile ions"): + solve_defect_ion_impedance(prep_bulk, [1.0, 100.0, 1.0e4]) + + freqs = np.array([1.0e-6, 10.0, 1.0e4, 1.0e9]) + res_bulk = solve_bulk_defect_impedance( + prep_bulk, + freqs, + voltage_V=0.55, + options=DynamicDefectImpedanceOptions(intervals_per_layer=6, verify_zero_hz_fd=True), + ) + assert res_bulk.scientific_qualification is False + assert res_bulk.zero_hz_fd_relative_error is not None + assert res_bulk.zero_hz_fd_relative_error <= 1.0e-4 + assert res_bulk.low_frequency_qss_relative_error <= 1.0e-3 + assert res_bulk.high_frequency_frozen_relative_error <= 1.0e-3 + + prep_iface = _resolve(_pin_doc(with_iface=True), defaults) + res_iface = solve_interface_defect_impedance( + prep_iface, + freqs, + voltage_V=0.25, + options=DynamicDefectImpedanceOptions(intervals_per_layer=6), + ) + assert res_iface.capability == "interface_dynamic_defect" + + prep_joint = _resolve( + _pin_doc(with_bulk=True, with_iface=True, with_ions=True), defaults + ) + res_joint = solve_defect_ion_impedance( + prep_joint, + freqs, + voltage_V=0.25, + options=DefectIonImpedanceOptions(intervals_per_layer=6), + ) + assert res_joint.capability == "bulk_interface_defect_plus_ions" + assert res_joint.scientific_qualification is False + assert ( + res_joint.working_state_digest + == res_joint.coupled.working_state_digest + == res_joint.frozen_ions.working_state_digest + == res_joint.frozen_traps.working_state_digest + == res_joint.frozen_ions_and_traps.working_state_digest + ) + assert res_joint.maximum_ion_inventory_relative_per_V <= 1.0e-12 + + +def test_dynamic_defect_transients_and_narrow_gate_refusals( + defaults: DefaultCatalog, +) -> None: + """Verify narrow v1 production transient gates and all 5 transient drivers.""" + prep_v1 = _resolve(_two_layer_v1_transient_doc(), defaults) + assert ( + classify_dynamic_defect_transient_capability(prep_v1) + == "interface_defect_plus_positive_ions" + ) + + times = np.array([0.0, 1.0e-5, 5.0e-5, 2.0e-4]) + volts = np.array([0.0, 0.30, 0.30, 0.0]) + + # Narrow-gate refusals: + with pytest.raises(DynamicDefectTransientCapabilityError, match="dark-only"): + solve_dynamic_defect_transient(prep_v1, times, volts, illuminated=True) + + with pytest.raises( + DynamicDefectTransientCapabilityError, match="right_continuous_step_and_hold" + ): + solve_dynamic_defect_transient( + prep_v1, + times, + volts, + options=DynamicDefectTransientOptions(voltage_interpolation="piecewise_linear"), + ) + + with pytest.raises(DynamicDefectTransientCapabilityError, match="two electrical layers"): + classify_dynamic_defect_transient_capability( + _resolve(_pin_doc(with_iface=True, with_ions=True), defaults) + ) + + no_ack_doc = _two_layer_v1_transient_doc() + no_ack_doc["settings"]["interface_charge_rebaseline_acknowledged"] = False + with pytest.raises((ValueError, DynamicDefectTransientCapabilityError), match="acknowledgement"): + classify_dynamic_defect_transient_capability(_resolve(no_ack_doc, defaults)) + + # Execute narrow-gate v1 transient: + opts = DynamicDefectTransientOptions(intervals_per_layer=6, bdf_order=2) + tr_v1 = solve_dynamic_defect_transient(prep_v1, times, volts, options=opts) + assert tr_v1.scientific_qualification is False + assert tr_v1.maximum_ion_inventory_relative_drift <= 1.0e-12 + assert tr_v1.interface_trap_occupancy.shape == (4, 1) + + # D6-E1 bulk transient + neutral/Gaussian refusals: + with pytest.raises(DynamicDefectTransientCapabilityError, match="neutral"): + solve_bulk_defect_transient( + _resolve(_pin_doc(with_bulk=True, bulk_transition="neutral"), defaults), + times, + volts, + ) + with pytest.raises(DynamicDefectTransientCapabilityError, match="single_level"): + solve_bulk_defect_transient( + _resolve(_pin_doc(with_bulk=True, bulk_kind="gaussian"), defaults), + times, + volts, + ) + + tr_bulk = solve_bulk_defect_transient( + _resolve(_pin_doc(with_bulk=True), defaults), times, volts, options=opts + ) + assert tr_bulk.capability == "bulk_defect_transient" + + tr_iface = solve_interface_defect_transient( + _resolve(_pin_doc(with_iface=True), defaults), times, volts, options=opts + ) + assert tr_iface.capability == "interface_defect_transient" + + tr_bi = solve_bulk_defect_ion_transient( + _resolve(_pin_doc(with_bulk=True, with_ions=True), defaults), + times, + volts, + options=opts, + ) + assert tr_bi.capability == "bulk_defect_ion_transient" + assert tr_bi.maximum_ion_inventory_relative_drift <= 1.0e-12 + + tr_ii = solve_interface_defect_ion_transient( + _resolve(_pin_doc(with_iface=True, with_ions=True), defaults), + times, + volts, + options=opts, + ) + assert tr_ii.capability == "interface_defect_ion_transient" + assert tr_ii.maximum_ion_inventory_relative_drift <= 1.0e-12 + + +def test_metastable_preparation_frozen_jv_and_operator_split_transient( + defaults: DefaultCatalog, +) -> None: + """Verify mandatory unclamped preparation gate, frozen J-V invariance, and dt/2 audit.""" + prep_dict = { + "schema_version": "solarlab-metastable-preparation-v1", + "preparation_limit": "stationary_infinite_time", + "preparation_temperature_K": 320.0, + "preparation_voltage_V": 0.45, + "preparation_illumination_suns": 0.0, + "voltage_continuation_steps": 0, + "illumination_continuation_steps": 0, + "measurement_temperature_K": 290.0, + "configuration_freeze_stage": "after_stationary_preparation_before_measurement", + "freeze_configuration_during_measurement": True, + "measurement_protocol_sha256": "c" * 64, + "numerics": { + "initial_donor_fraction_guess": 0.50, + "max_iterations": 25, + "relative_tolerance": 1.0e-7, + "clamping_factor": 0.7, + "final_unclamped_refinement": True, + }, + } + meta_doc = { + "schema_version": "solarlab.device-preparation.v1", + "source_format": "canonical", + "id": "meta_exp", + "settings": _settings(Phi=2.5e21), + "layers": [ + { + "id": "abs", + "name": "Abs", + "role": "absorber", + "thickness": 280e-9, + "metastable_document": { + "schema_version": "solarlab-metastable-bulk-defects-v1", + "defect_model": "explicit_metastable_frozen", + "metastable_defects": [ + { + "id": "vse_vcu", + "name": "MetastableComplex", + "total_density_m3": 2.0e21, + "donor_configuration": { + "family": "single_donor", + "charge_states_e": [1, 0], + "degeneracy_convention": "unity", + "state_degeneracies": [1.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 1.35, + "correlation_energies_eV": [], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [ + { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-20, + "thermal_velocity_n_m_s": 1e5, + "thermal_velocity_p_m_s": 1e5, + } + ], + }, + "acceptor_configuration": { + "family": "single_acceptor", + "charge_states_e": [0, -1], + "degeneracy_convention": "unity", + "state_degeneracies": [1.0, 1.0], + "energy_levels": { + "first_transition_eV_above_vb": 0.30, + "correlation_energies_eV": [], + "energy_reference": "above_valence_band", + }, + "transition_kinetics": [ + { + "sigma_n_m2": 1e-20, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 1e5, + "thermal_velocity_p_m_s": 1e5, + } + ], + }, + "donor_conversion_state_index": 0, + "acceptor_conversion_state_index": 1, + "conversion_kinetics": { + "transition_energy_eV_above_vb": 0.22, + "electron_capture_activation_eV": 0.25, + "electron_emission_activation_eV": 0.25 + 2.0 * (1.6 - 0.22), + "hole_capture_activation_eV": 0.30, + "hole_emission_activation_eV": 0.30 + 2.0 * 0.22, + "electron_capture_path": "double_electron_capture", + "hole_capture_path": "double_hole_capture", + "capture_n_m3_s": 1e-16, + "capture_p_m3_s": 1e-16, + "phonon_frequency_Hz": 1e12, + }, + } + ], + }, + "metastable_preparation": prep_dict, + "parameters": _mat(1.6, 3.9, na=1e22), + } + ], + } + prepared = _resolve(meta_doc, defaults) + state = prepare_metastable_state(prepared, intervals_per_layer=8) + assert state.clamped_iterations >= 1 + assert state.unclamped_refinement_change <= 1.0e-7 + + # Under-iterated clamped protocol must fail rather than masquerade as converged: + bad_proto_dict = copy.deepcopy(prep_dict) + bad_numerics = cast(dict[str, Any], bad_proto_dict["numerics"]) + bad_numerics["max_iterations"] = 1 + bad_numerics["clamping_factor"] = 0.05 + bad_proto = MetastablePreparationInput.model_validate(bad_proto_dict) + with pytest.raises(MetastablePreparationError): + prepare_metastable_state(prepared, preparation=bad_proto, intervals_per_layer=8) + + y_before = state.donor_fractions[0].copy() + st0 = solve_frozen_metastable_steady(state, voltage_V=0.0) + assert st0.converged + jv = solve_frozen_metastable_jv(state, np.array([0.0, 0.15, 0.30])) + assert jv.current_densities_A_m2.shape == (3,) + np.testing.assert_array_equal(jv.donor_fractions[0], y_before) + + # Operator-split relaxation at V = 0.0 V, T = 290 K: + tr = solve_metastable_transient( + state, + np.linspace(0.0, 1.0e-3, 5), + voltage_V=0.0, + ) + assert tr.scientific_qualification is False + assert tr.certificate.passed is True + assert tr.certificate.maximum_charge_transfer_relative_error <= 1.0e-10 diff --git a/tests/unit/physics/test_dynamic_defects.py b/tests/unit/physics/test_dynamic_defects.py new file mode 100644 index 00000000..d8eb2b71 --- /dev/null +++ b/tests/unit/physics/test_dynamic_defects.py @@ -0,0 +1,990 @@ +"""Unit tests (T1) for dynamic, energy-distributed, multivalent, and metastable defect physics (P04-10).""" + +from __future__ import annotations + +from collections.abc import Iterator +import math + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.physics.defects import ( + DIST_CONDUCTION_BAND_TAIL, + DIST_GAUSSIAN, + DIST_SINGLE_LEVEL, + DIST_UNIFORM, + DIST_VALENCE_BAND_TAIL, + DOUBLE_ELECTRON_CAPTURE, + DOUBLE_HOLE_CAPTURE, + ELECTRON_CAPTURE_PLUS_HOLE_EMISSION, + HOLE_CAPTURE_PLUS_ELECTRON_EMISSION, + TRANSITION_ACCEPTOR, + TRANSITION_DONOR, + TRANSITION_NEUTRAL, + WIDTH_GAUSSIAN_SIGMA, + WIDTH_SCAPS_CHARACTERISTIC, + WIDTH_UNIFORM_FULL, + DefectDistributionSpec, + DynamicInterfaceTrapSpec, + FrozenMetastableRegion, + MetastableConversionKineticsSpec, + MetastableDefectSpec, + MonovalentDefectRegion, + MonovalentSpeciesSpec, + MultivalentConfigurationSpec, + MultivalentSpeciesSpec, + MultivalentTransitionKineticsSpec, + SpatialDensityProfileSpec, + SpatialProfileKnot, + advance_metastable_configuration, + build_defect_energy_quadrature, + compile_dynamic_bulk_trap_layout, + configuration_charge_transfer_C_m3, + configuration_from_logit, + configuration_logit, + density_weighted_mean_occupancy, + distribution_shape_integral_eV, + evaluate_dynamic_bulk_traps, + evaluate_dynamic_bulk_traps_about_qss, + evaluate_dynamic_interface_trap, + evaluate_frozen_metastable_region, + evaluate_metastable_configuration_closure, + evaluate_monovalent_defect_closure, + evaluate_monovalent_region_closure, + evaluate_multivalent_defect_closure, + evaluate_spatial_density_profile, + integrated_density_from_peak_density, + logit_occupancy_secant, + occupancy_from_logit_increment, + occupancy_logit, + peak_density_from_integrated_density, + quasi_steady_bulk_trap_occupancy, + solve_frozen_metastable_charge_neutrality, + solve_monovalent_defect_charge_neutrality, + solve_multivalent_defect_charge_neutrality, + stable_expit, + validate_defect_energy_quadrature_order, +) +from solarlab.physics.electrostatics.interface_traces import TraceElectrostatics +from solarlab.physics.interface_transport import ( + EquilibriumReferencedSheetCharge, + TwoSidedBulkState, + TwoSidedInterfacePhysics, + solve_charged_two_sided_interface_qss, + solve_fixed_occupancy_two_sided_interface, +) +from solarlab.physics.statistics import thermal_voltage + + +@pytest.fixture(scope="module", autouse=True) +def _blas1() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +def test_energy_distributions_quadrature_and_refinement_convergence() -> None: + """Verify exact zeroth moment, peak/integrated conversions, and quadrature convergence.""" + assert validate_defect_energy_quadrature_order(16) == 16 + with pytest.raises(ValueError): + validate_defect_energy_quadrature_order(2) + with pytest.raises(ValueError): + validate_defect_energy_quadrature_order(True) + + gap = 1.60 + nt = 2.5e22 + specs = [ + DefectDistributionSpec(DIST_SINGLE_LEVEL, center_eV_above_vb=0.75, total_density_m3=nt), + DefectDistributionSpec( + DIST_UNIFORM, + center_eV_above_vb=0.80, + total_density_m3=nt, + width_eV=0.20, + width_convention=WIDTH_UNIFORM_FULL, + ), + DefectDistributionSpec( + DIST_GAUSSIAN, + center_eV_above_vb=0.80, + total_density_m3=nt, + width_eV=0.06, + width_convention=WIDTH_GAUSSIAN_SIGMA, + support_width_multiplier=6.0, + ), + DefectDistributionSpec( + DIST_GAUSSIAN, + center_eV_above_vb=0.80, + total_density_m3=nt, + width_eV=0.08, + width_convention=WIDTH_SCAPS_CHARACTERISTIC, + support_width_multiplier=None, # Legacy band-gap-truncated [0, Eg] + ), + DefectDistributionSpec( + DIST_CONDUCTION_BAND_TAIL, + center_eV_above_vb=1.55, + total_density_m3=nt, + width_eV=0.04, + support_width_multiplier=6.0, + ), + DefectDistributionSpec( + DIST_VALENCE_BAND_TAIL, + center_eV_above_vb=0.05, + total_density_m3=nt, + width_eV=0.04, + support_width_multiplier=6.0, + ), + ] + for spec in specs: + quad = build_defect_energy_quadrature(spec, order=16, band_gap_eV=gap) + assert math.isclose(float(np.sum(quad.density_weights_m3)), nt, rel_tol=1e-14, abs_tol=0.0) + assert math.isclose(float(np.sum(quad.normalized_weights)), 1.0, rel_tol=0.0, abs_tol=1e-14) + assert np.all(quad.energies_eV_above_vb >= 0.0) + assert np.all(quad.energies_eV_above_vb <= gap) + mean_occ = density_weighted_mean_occupancy( + quad, np.full((quad.order, 3), 0.37, dtype=np.float64) + ) + np.testing.assert_allclose(mean_occ, 0.37, rtol=1e-14, atol=0.0) + + shape = distribution_shape_integral_eV( + DIST_GAUSSIAN, + 0.05, + width_convention=WIDTH_GAUSSIAN_SIGMA, + support_width_multiplier=6.0, + ) + peak = peak_density_from_integrated_density(nt, shape) + assert math.isclose(integrated_density_from_peak_density(peak, shape), nt, rel_tol=1e-15) + + # Independent quadrature-order convergence on smooth Gaussian trap closure: + gauss_spec = MonovalentSpeciesSpec( + "gauss_acc", + TRANSITION_ACCEPTOR, + specs[2], + sigma_n_m2=1.0e-19, + sigma_p_m2=2.0e-19, + thermal_velocity_n_m_s=1.0e5, + thermal_velocity_p_m_s=1.0e5, + ) + n = np.array([3.0e20, 8.0e19]) + p = np.array([1.2e20, 5.0e20]) + ref = evaluate_monovalent_defect_closure( + n, + p, + (gauss_spec,), + band_gap_eV=gap, + effective_conduction_dos_m3=1.0e25, + effective_valence_dos_m3=1.0e25, + temperature_K=300.0, + energy_quadrature_order=64, + ) + err_8 = float( + np.max( + np.abs( + evaluate_monovalent_defect_closure( + n, + p, + (gauss_spec,), + band_gap_eV=gap, + effective_conduction_dos_m3=1.0e25, + effective_valence_dos_m3=1.0e25, + temperature_K=300.0, + energy_quadrature_order=8, + ).total_recombination_rate_m3_s + - ref.total_recombination_rate_m3_s + ) + / ref.total_recombination_rate_m3_s + ) + ) + err_24 = float( + np.max( + np.abs( + evaluate_monovalent_defect_closure( + n, + p, + (gauss_spec,), + band_gap_eV=gap, + effective_conduction_dos_m3=1.0e25, + effective_valence_dos_m3=1.0e25, + temperature_K=300.0, + energy_quadrature_order=24, + ).total_recombination_rate_m3_s + - ref.total_recombination_rate_m3_s + ) + / ref.total_recombination_rate_m3_s + ) + ) + err_32 = float( + np.max( + np.abs( + evaluate_monovalent_defect_closure( + n, + p, + (gauss_spec,), + band_gap_eV=gap, + effective_conduction_dos_m3=1.0e25, + effective_valence_dos_m3=1.0e25, + temperature_K=300.0, + energy_quadrature_order=32, + ).total_recombination_rate_m3_s + - ref.total_recombination_rate_m3_s + ) + / ref.total_recombination_rate_m3_s + ) + ) + assert err_32 < err_24 < err_8 and err_32 < 1.0e-10 + + +def test_spatial_density_profile_conservation_and_validation() -> None: + profile = SpatialDensityProfileSpec( + ( + SpatialProfileKnot(0.0, 1.8), + SpatialProfileKnot(0.5, 1.0), + SpatialProfileKnot(1.0, 0.2), + ) + ) + pos = np.linspace(0.0, 1.0, 201) + vals = evaluate_spatial_density_profile(profile, pos) + assert math.isclose(float(np.trapezoid(vals, pos)), 1.0, rel_tol=0.0, abs_tol=1e-14) + assert vals[0] == pytest.approx(1.8) + assert vals[-1] == pytest.approx(0.2) + + with pytest.raises(ValueError, match="unit layer average"): + SpatialDensityProfileSpec((SpatialProfileKnot(0.0, 2.0), SpatialProfileKnot(1.0, 2.0))) + + +def test_monovalent_qss_and_dynamic_derivatives_and_secant_stability() -> None: + """Verify cancellation-free logit secants, zero-density identity, and FD derivatives.""" + base = np.array([-50.0, -10.0, 0.0, 10.0, 50.0]) + shifted = base + np.array([1.0e-12, 1.0e-13, 1.0e-13, 1.0e-13, 1.0e-12]) + delta_exact = shifted - base + sec = logit_occupancy_secant(shifted, base) + expected_slope = stable_expit(base) * stable_expit(-base) * delta_exact + np.testing.assert_allclose(sec, expected_slope, rtol=1e-11, atol=0.0) + + f_vals = np.array([1.0e-9, 0.25, 0.5, 0.999999]) + logits = occupancy_logit(f_vals) + f_back = occupancy_from_logit_increment(logits, np.zeros_like(logits)) + np.testing.assert_allclose(f_back, f_vals, rtol=1e-14) + + gap = 1.60 + nc, nv, temp = 1.2e25, 1.8e25, 300.0 + vt = thermal_voltage(temp) + ni_sq = nc * nv * math.exp(-gap / vt) + n_eq = math.sqrt(ni_sq) * 3.0 + p_eq = ni_sq / n_eq + + species = ( + MonovalentSpeciesSpec( + "acc", + TRANSITION_ACCEPTOR, + DefectDistributionSpec(DIST_SINGLE_LEVEL, 0.72, 2.0e22), + 1.5e-19, + 2.5e-19, + 1.0e5, + 1.1e5, + ), + MonovalentSpeciesSpec( + "don", + TRANSITION_DONOR, + DefectDistributionSpec( + DIST_UNIFORM, 0.90, 1.5e22, width_eV=0.16, width_convention=WIDTH_UNIFORM_FULL + ), + 2.0e-19, + 1.0e-19, + 1.0e5, + 1.0e5, + ), + MonovalentSpeciesSpec( + "neu", + TRANSITION_NEUTRAL, + DefectDistributionSpec(DIST_SINGLE_LEVEL, 0.80, 3.0e22), + 1.0e-19, + 1.0e-19, + 1.0e5, + 1.0e5, + ), + MonovalentSpeciesSpec( + "zero", + TRANSITION_ACCEPTOR, + DefectDistributionSpec(DIST_SINGLE_LEVEL, 0.65, 0.0), + 1.0e-19, + 1.0e-19, + 1.0e5, + 1.0e5, + ), + ) + + eq_res = evaluate_monovalent_defect_closure( + np.array([n_eq]), + np.array([p_eq]), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + assert float(np.max(np.abs(eq_res.total_recombination_rate_m3_s))) <= 1.0e-8 + assert eq_res.charge_density_C_m3[2, 0] == 0.0 # neutral + assert eq_res.charge_density_C_m3[3, 0] == 0.0 and eq_res.recombination_rate_m3_s[3, 0] == 0.0 + + # Non-equilibrium analytical derivatives vs central FD: + n0 = np.array([2.5e20, 7.0e19, 4.0e21]) + p0 = np.array([1.1e20, 9.0e20, 3.0e19]) + res = evaluate_monovalent_defect_closure( + n0, + p0, + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + eps = 1.0e-6 + hi_n = evaluate_monovalent_defect_closure( + n0 * (1.0 + eps), + p0, + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + lo_n = evaluate_monovalent_defect_closure( + n0 * (1.0 - eps), + p0, + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + hi_p = evaluate_monovalent_defect_closure( + n0, + p0 * (1.0 + eps), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + lo_p = evaluate_monovalent_defect_closure( + n0, + p0 * (1.0 - eps), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + np.testing.assert_allclose( + res.total_charge_derivative_n_C, + (hi_n.total_charge_density_C_m3 - lo_n.total_charge_density_C_m3) / (2.0 * eps * n0), + rtol=1e-8, + ) + np.testing.assert_allclose( + res.total_charge_derivative_p_C, + (hi_p.total_charge_density_C_m3 - lo_p.total_charge_density_C_m3) / (2.0 * eps * p0), + rtol=1e-8, + ) + rec_scale = float(np.max(np.abs(res.total_recombination_rate_m3_s))) + fd_rec_n = ( + hi_n.total_recombination_rate_m3_s - lo_n.total_recombination_rate_m3_s + ) / (2.0 * eps * n0) + fd_rec_p = ( + hi_p.total_recombination_rate_m3_s - lo_p.total_recombination_rate_m3_s + ) / (2.0 * eps * p0) + assert np.all( + np.abs(res.total_recombination_derivative_n_s1 - fd_rec_n) + <= 1.0e-8 * np.abs(res.total_recombination_derivative_n_s1) + + 1.0e-13 * rec_scale / (eps * n0) + ) + assert np.all( + np.abs(res.total_recombination_derivative_p_s1 - fd_rec_p) + <= 1.0e-8 * np.abs(res.total_recombination_derivative_p_s1) + + 1.0e-13 * rec_scale / (eps * p0) + ) + # Fixed quasi-Fermi potential shift dphi: dn/dphi = n/Vt, dp/dphi = -p/Vt + dphi = 1.0e-7 + hi_phi = evaluate_monovalent_defect_closure( + n0 * math.exp(dphi / vt), + p0 * math.exp(-dphi / vt), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + lo_phi = evaluate_monovalent_defect_closure( + n0 * math.exp(-dphi / vt), + p0 * math.exp(dphi / vt), + species, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + np.testing.assert_allclose( + res.total_charge_derivative_fixed_qf_C_m3_V, + (hi_phi.total_charge_density_C_m3 - lo_phi.total_charge_density_C_m3) / (2.0 * dphi), + rtol=1e-9, + ) + + # Dynamic bulk trap layout & derivatives vs FD: + mask = np.array([False, True, True, True, False]) + region = MonovalentDefectRegion( + identifier="abs", + document_sha256="a" * 64, + active_nodes=mask, + band_gap_eV=np.full(3, gap), + effective_conduction_dos_m3=np.full(3, nc), + effective_valence_dos_m3=np.full(3, nv), + temperature_K=temp, + species=species[:3], + energy_quadrature_order=8, + ) + reg_qss = evaluate_monovalent_region_closure( + region, np.r_[1e20, n0, 1e20], np.r_[1e20, p0, 1e20] + ) + np.testing.assert_allclose( + reg_qss.total_recombination_rate_m3_s, res.total_recombination_rate_m3_s, rtol=1e-12 + ) + + layout = compile_dynamic_bulk_trap_layout((region,), node_count=5) + n_grid = np.r_[1e20, n0, 1e20] + p_grid = np.r_[1e20, p0, 1e20] + f_qss = quasi_steady_bulk_trap_occupancy(n_grid, p_grid, layout) + qss_dyn = evaluate_dynamic_bulk_traps_about_qss( + n_grid, + p_grid, + f_qss, + layout, + reference_electron_density_m3=n_grid, + reference_hole_density_m3=p_grid, + reference_occupancy=f_qss, + occupancy_increment=np.zeros(layout.size), + ) + assert float(np.max(np.abs(qss_dyn.trap_storage_rate_m3_s))) == 0.0 + + f_test = np.clip(f_qss * 0.73 + 0.11, 1.0e-4, 1.0 - 1.0e-4) + dyn = evaluate_dynamic_bulk_traps(n_grid, p_grid, f_test, layout) + df = 1.0e-7 + dyn_hi_f = evaluate_dynamic_bulk_traps(n_grid, p_grid, f_test + df, layout) + dyn_lo_f = evaluate_dynamic_bulk_traps(n_grid, p_grid, f_test - df, layout) + np.testing.assert_allclose( + dyn.d_trap_storage_rate_df_m3_s, + (dyn_hi_f.trap_storage_rate_m3_s - dyn_lo_f.trap_storage_rate_m3_s) / (2.0 * df), + rtol=1e-9, + ) + np.testing.assert_allclose( + dyn.d_charge_df_C_m3, + (dyn_hi_f.charge_density_C_m3 - dyn_lo_f.charge_density_C_m3) / (2.0 * df), + rtol=1e-9, + atol=1e-20, + ) + + # Contact neutrality with monovalent traps: + neut = solve_monovalent_defect_charge_neutrality( + temperature_K=temp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=5.0e22, + acceptor_density_m3=0.0, + species=species[:2], + electron_affinity_eV=3.9, + ) + assert neut.normalized_charge_residual <= 1.0e-12 + assert neut.work_function_eV is not None + + # Dynamic interface trap derivatives vs FD: + ispec = DynamicInterfaceTrapSpec( + interface_id="htl_abs", + left_node=1, + right_node=2, + charge_type=TRANSITION_ACCEPTOR, + sheet_density_m2=2.0e15, + v_n_m_s=12.0, + v_p_m_s=8.0, + n1_left_m3=1.0e14, + p1_left_m3=2.0e14, + n1_right_m3=3.0e14, + p1_right_m3=4.0e14, + equilibrium_occupancy=0.42, + ) + iev = evaluate_dynamic_interface_trap( + ispec, + n_left_m3=2.0e19, + p_left_m3=5.0e20, + n_right_m3=8.0e19, + p_right_m3=3.0e19, + occupancy=0.61, + ) + iev_hi = evaluate_dynamic_interface_trap( + ispec, + n_left_m3=2.0e19, + p_left_m3=5.0e20, + n_right_m3=8.0e19, + p_right_m3=3.0e19, + occupancy=0.61 + df, + ) + iev_lo = evaluate_dynamic_interface_trap( + ispec, + n_left_m3=2.0e19, + p_left_m3=5.0e20, + n_right_m3=8.0e19, + p_right_m3=3.0e19, + occupancy=0.61 - df, + ) + assert iev.d_storage_rate_df == pytest.approx( + (iev_hi.trap_storage_rate_m2_s - iev_lo.trap_storage_rate_m2_s) / (2.0 * df), rel=1e-9 + ) + assert iev.d_sheet_charge_df == pytest.approx( + (iev_hi.sheet_charge_C_m2 - iev_lo.sheet_charge_C_m2) / (2.0 * df), rel=1e-9 + ) + + +def test_multivalent_simplex_detailed_balance_and_fd_derivatives() -> None: + """Verify simplex bounds across extreme Fermi shifts, detailed balance, and FD Jacobians.""" + kin1 = MultivalentTransitionKineticsSpec(1.0e-19, 2.0e-19, 1.0e5, 1.2e5) + kin2 = MultivalentTransitionKineticsSpec(3.0e-19, 1.5e-19, 1.0e5, 1.0e5) + cfg = MultivalentConfigurationSpec( + family="amphoteric", + charge_states_e=(1, 0, -1), + degeneracy_convention="scaps_binomial", + state_degeneracies=(1.0, 2.0, 1.0), + transition_energies_eV_above_vb=(0.55, 1.05), + transition_kinetics=(kin1, kin2), + ) + sp = MultivalentSpeciesSpec("amp_1", 4.0e22, cfg) + + gap, nc, nv, temp = 1.60, 1.0e25, 1.5e25, 300.0 + vt = thermal_voltage(temp) + ni_sq = nc * nv * math.exp(-gap / vt) + + # Extreme Fermi-level sweep [-25 V, +25 V] on exact n*p == ni^2 equilibrium manifold: + shifts = np.linspace(-25.0, 25.0, 21) + n_ext = nc * np.exp(shifts) + p_ext = nv * np.exp(-gap / vt - shifts) + ext_res = evaluate_multivalent_defect_closure( + n_ext, + p_ext, + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + assert np.all(ext_res.state_probability >= 0.0) + np.testing.assert_allclose(np.sum(ext_res.state_probability, axis=0), 1.0, rtol=0.0, atol=1e-14) + # Detailed balance on n*p == ni^2 manifold (rate normalized by characteristic capture scale): + assert ext_res.maximum_master_residual_s1 <= 1.0e-10 + rate_scale = sp.total_density_m3 * kin1.capture_n_m3_s * np.maximum(n_ext, p_ext) + assert float(np.max(np.abs(ext_res.total_recombination_rate_m3_s) / rate_scale)) <= 1.0e-15 + + # Non-equilibrium FD tangents: + n0 = np.array([3.0e20, 5.0e18, 9.0e21]) + p0 = np.array([2.0e20, 8.0e21, 4.0e18]) + res = evaluate_multivalent_defect_closure( + n0, + p0, + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + eps = 1.0e-6 + hi_n = evaluate_multivalent_defect_closure( + n0 * (1.0 + eps), + p0, + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + lo_n = evaluate_multivalent_defect_closure( + n0 * (1.0 - eps), + p0, + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + hi_p = evaluate_multivalent_defect_closure( + n0, + p0 * (1.0 + eps), + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + lo_p = evaluate_multivalent_defect_closure( + n0, + p0 * (1.0 - eps), + sp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + rho_scale = float(np.max(np.abs(res.charge_density_C_m3))) + np.testing.assert_allclose( + res.state_probability_derivative_n_m3, + (hi_n.state_probability - lo_n.state_probability) / (2.0 * eps * n0), + rtol=1e-8, + atol=1e-26, + ) + fd_rho_n = (hi_n.charge_density_C_m3 - lo_n.charge_density_C_m3) / (2.0 * eps * n0) + fd_rho_p = (hi_p.charge_density_C_m3 - lo_p.charge_density_C_m3) / (2.0 * eps * p0) + assert np.all( + np.abs(res.charge_derivative_n_C - fd_rho_n) + <= 1.0e-8 * np.abs(res.charge_derivative_n_C) + 1.0e-13 * rho_scale / (eps * n0) + ) + assert np.all( + np.abs(res.charge_derivative_p_C - fd_rho_p) + <= 1.0e-8 * np.abs(res.charge_derivative_p_C) + 1.0e-13 * rho_scale / (eps * p0) + ) + rec_scale = float(np.max(np.abs(res.total_recombination_rate_m3_s))) + fd_rec_n = ( + hi_n.total_recombination_rate_m3_s - lo_n.total_recombination_rate_m3_s + ) / (2.0 * eps * n0) + fd_rec_p = ( + hi_p.total_recombination_rate_m3_s - lo_p.total_recombination_rate_m3_s + ) / (2.0 * eps * p0) + assert np.all( + np.abs(res.total_recombination_derivative_n_s1 - fd_rec_n) + <= 1.0e-8 * np.abs(res.total_recombination_derivative_n_s1) + + 1.0e-13 * rec_scale / (eps * n0) + ) + assert np.all( + np.abs(res.total_recombination_derivative_p_s1 - fd_rec_p) + <= 1.0e-8 * np.abs(res.total_recombination_derivative_p_s1) + + 1.0e-13 * rec_scale / (eps * p0) + ) + + mv_neut = solve_multivalent_defect_charge_neutrality( + temperature_K=temp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=2.0e22, + acceptor_density_m3=0.0, + species=(sp,), + ) + assert mv_neut.normalized_charge_residual <= 1.0e-12 + assert ni_sq > 0.0 + + +def test_metastable_closure_frozen_region_and_exponential_advance() -> None: + """Verify detailed-balance barrier gate, FD tangents, semigroup advance, and charge transfer.""" + gap, nc, nv, temp = 1.60, 1.0e25, 1.0e25, 300.0 + kin = MultivalentTransitionKineticsSpec(1.0e-19, 1.0e-19, 1.0e5, 1.0e5) + donor_cfg = MultivalentConfigurationSpec( + family="donor", + charge_states_e=(2, 1, 0), + degeneracy_convention="unity", + state_degeneracies=(1.0, 1.0, 1.0), + transition_energies_eV_above_vb=(1.10, 1.35), + transition_kinetics=(kin, kin), + ) + acc_cfg = MultivalentConfigurationSpec( + family="acceptor", + charge_states_e=(0, -1, -2), + degeneracy_convention="unity", + state_degeneracies=(1.0, 1.0, 1.0), + transition_energies_eV_above_vb=(0.25, 0.50), + transition_kinetics=(kin, kin), + ) + tr = 0.85 + ec = 0.30 + hc = 0.25 + conv = MetastableConversionKineticsSpec( + transition_energy_eV_above_vb=tr, + electron_capture_activation_eV=ec, + electron_emission_activation_eV=ec + 2.0 * (gap - tr), + hole_capture_activation_eV=hc, + hole_emission_activation_eV=hc + 2.0 * tr, + electron_capture_path=DOUBLE_ELECTRON_CAPTURE, + hole_capture_path=DOUBLE_HOLE_CAPTURE, + capture_n_m3_s=1.0e-20, + capture_p_m3_s=1.5e-20, + phonon_frequency_Hz=1.0e13, + ) + spec = MetastableDefectSpec( + identifier="vse_vo", + total_density_m3=5.0e22, + donor_configuration=donor_cfg, + acceptor_configuration=acc_cfg, + donor_conversion_state_index=0, # +2 + acceptor_conversion_state_index=0, # 0 (differs by +2e) + conversion_kinetics=conv, + ) + spec.validate_band_gap(gap) + + # Also verify alternate mixed capture paths: + conv_alt = MetastableConversionKineticsSpec( + transition_energy_eV_above_vb=0.70, + electron_capture_activation_eV=0.40, + electron_emission_activation_eV=0.40 + gap - 2.0 * 0.70, + hole_capture_activation_eV=0.50, + hole_emission_activation_eV=0.50 + 2.0 * 0.70 - gap, + electron_capture_path=ELECTRON_CAPTURE_PLUS_HOLE_EMISSION, + hole_capture_path=HOLE_CAPTURE_PLUS_ELECTRON_EMISSION, + capture_n_m3_s=1.0e-20, + capture_p_m3_s=1.0e-20, + phonon_frequency_Hz=1.0e13, + ) + conv_alt.validate_band_gap(gap) + + # Detailed-balance barrier violation must fail: + bad_conv = MetastableConversionKineticsSpec( + transition_energy_eV_above_vb=tr, + electron_capture_activation_eV=ec, + electron_emission_activation_eV=ec + 0.1, + hole_capture_activation_eV=hc, + hole_emission_activation_eV=hc + 2.0 * tr, + electron_capture_path=DOUBLE_ELECTRON_CAPTURE, + hole_capture_path=DOUBLE_HOLE_CAPTURE, + capture_n_m3_s=1.0e-20, + capture_p_m3_s=1.5e-20, + phonon_frequency_Hz=1.0e13, + ) + with pytest.raises(ValueError, match="detailed balance"): + bad_conv.validate_band_gap(gap) + + n0 = np.array([2.0e20, 6.0e19]) + p0 = np.array([4.0e19, 3.0e20]) + cl = evaluate_metastable_configuration_closure( + n0, + p0, + spec, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + eps = 1.0e-6 + cl_hn = evaluate_metastable_configuration_closure( + n0 * (1.0 + eps), + p0, + spec, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + cl_ln = evaluate_metastable_configuration_closure( + n0 * (1.0 - eps), + p0, + spec, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + cl_hp = evaluate_metastable_configuration_closure( + n0, + p0 * (1.0 + eps), + spec, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + cl_lp = evaluate_metastable_configuration_closure( + n0, + p0 * (1.0 - eps), + spec, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + temperature_K=temp, + ) + np.testing.assert_allclose( + cl.donor_fraction_derivative_n_m3, + (cl_hn.donor_fraction - cl_ln.donor_fraction) / (2.0 * eps * n0), + rtol=1e-8, + ) + np.testing.assert_allclose( + cl.donor_fraction_derivative_p_m3, + (cl_hp.donor_fraction - cl_lp.donor_fraction) / (2.0 * eps * p0), + rtol=1e-8, + ) + + # Exact exponential advance semigroup, slow/fast limits, and two-charge transfer: + y0 = np.array([0.25, 0.80]) + np.testing.assert_allclose(configuration_from_logit(configuration_logit(y0)), y0, rtol=1e-15) + tau = 1.0 / cl.total_conversion_rate_s1 + dt1 = float(0.3 * np.min(tau)) + dt2 = float(0.5 * np.min(tau)) + step1 = advance_metastable_configuration(y0, cl, dt1) + step2 = advance_metastable_configuration(step1.next_donor_fraction, cl, dt2) + step12 = advance_metastable_configuration(y0, cl, dt1 + dt2) + np.testing.assert_allclose(step2.next_donor_fraction, step12.next_donor_fraction, rtol=1e-14) + + slow = advance_metastable_configuration(y0, cl, float(1.0e-8 * np.min(tau))) + np.testing.assert_allclose( + slow.delta_donor_fraction, + (cl.donor_fraction - y0) * cl.total_conversion_rate_s1 * slow.dt_s, + rtol=1e-7, + ) + fast = advance_metastable_configuration(y0, cl, float(60.0 * np.max(tau))) + np.testing.assert_allclose(fast.next_donor_fraction, cl.donor_fraction, rtol=1e-13) + + mask = np.array([False, True, True, False]) + reg_before = FrozenMetastableRegion( + "abs", "b" * 64, mask, np.full(2, gap), np.full(2, nc), np.full(2, nv), temp, (spec,), y0[None, :] + ) + reg_after = FrozenMetastableRegion( + "abs", + "b" * 64, + mask, + np.full(2, gap), + np.full(2, nc), + np.full(2, nv), + temp, + (spec,), + step1.next_donor_fraction[None, :], + ) + n_full = np.r_[1e20, n0, 1e20] + p_full = np.r_[1e20, p0, 1e20] + ev_before = evaluate_frozen_metastable_region(reg_before, n_full, p_full) + ev_after = evaluate_frozen_metastable_region(reg_after, n_full, p_full) + d_rho_pred = configuration_charge_transfer_C_m3( + spec.total_density_m3, + ev_before.donor_mean_charge_e[0], + ev_before.acceptor_mean_charge_e[0], + step1.delta_donor_fraction, + ) + np.testing.assert_allclose( + d_rho_pred, + (ev_after.total_charge_density_C_m3 - ev_before.total_charge_density_C_m3)[mask], + rtol=1e-12, + ) + + f_neut = solve_frozen_metastable_charge_neutrality( + temperature_K=temp, + band_gap_eV=gap, + effective_conduction_dos_m3=nc, + effective_valence_dos_m3=nv, + donor_density_m3=0.0, + acceptor_density_m3=2.0e22, + species=(spec,), + donor_fractions=(0.4,), + ) + assert f_neut.normalized_charge_residual <= 1.0e-12 + + +def test_fixed_occupancy_two_sided_interface_qss_identity_and_ift_jacobians() -> None: + """Verify QSS embedding f == f_qss and all 7 IFT derivatives vs central FD.""" + temp = 300.0 + vt = thermal_voltage(temp) + geom = TraceElectrostatics( + eps_r_left=4.0, + eps_r_right=24.0, + left_distance_m=5.0e-9, + right_distance_m=8.0e-9, + potential_jump_right_minus_left_V=0.0, + fixed_sheet_charge_C_m2=0.0, + ) + phys = TwoSidedInterfacePhysics( + thermal_voltage_V=vt, + temperature_K=temp, + D_n_left_m2_s=1.0e-6, + D_n_right_m2_s=5.0e-5, + D_p_left_m2_s=2.0e-6, + D_p_right_m2_s=4.0e-5, + N_C_left_m3=2.0e25, + N_C_right_m3=1.0e25, + N_V_left_m3=3.0e25, + N_V_right_m3=1.0e25, + richardson_n_A_m2_K2=6.0e5, + richardson_p_A_m2_K2=6.0e5, + conduction_band_step_eV=-0.30, + hole_transport_step_eV=0.10, + surface_recombination_velocity_n_m_s=15.0, + surface_recombination_velocity_p_m_s=10.0, + n1_left_m3=1.0e12, + p1_left_m3=2.0e14, + n1_right_m3=5.0e14, + p1_right_m3=8.0e14, + ) + charge = EquilibriumReferencedSheetCharge( + equilibrium_occupancy=0.35, + trap_density_m2=3.0e15, + ) + + def make_bulk(coords: np.ndarray) -> TwoSidedBulkState: + phi_l, phi_r, ln_nl, ln_pl, ln_nr, ln_pr = (float(v) for v in coords) + return TwoSidedBulkState( + phi_left_V=phi_l, + phi_right_V=phi_r, + n_left_m3=math.exp(ln_nl), + p_left_m3=math.exp(ln_pl), + n_right_m3=math.exp(ln_nr), + p_right_m3=math.exp(ln_pr), + ) + + coords0 = np.array( + [-0.12, -0.05, math.log(4.0e16), math.log(2.0e21), math.log(3.0e19), math.log(1.5e19)] + ) + bulk0 = make_bulk(coords0) + qss = solve_charged_two_sided_interface_qss(geom, phys, bulk0, charge) + at_qss = solve_fixed_occupancy_two_sided_interface( + geom, phys, bulk0, charge, occupancy=qss.occupancy + ) + np.testing.assert_allclose(at_qss.bulk_flux_m2_s, qss.bulk_flux_m2_s, rtol=1e-11) + assert abs(at_qss.trap_storage_rate_m2_s) <= 1.0e-7 * max( + float(np.max(np.abs(at_qss.bulk_flux_m2_s))), 1.0 + ) + assert at_qss.incremental_sheet_charge_C_m2 == pytest.approx( + -Q * charge.trap_density_m2 * (qss.occupancy - charge.equilibrium_occupancy), rel=1e-14 + ) + + f0 = 0.62 + res = solve_fixed_occupancy_two_sided_interface(geom, phys, bulk0, charge, occupancy=f0) + assert res.converged + step = 1.0e-5 + flux_atol = 1.0e-12 * float(np.max(np.abs(res.bulk_flux_m2_s))) / step + sr_atol = 1.0e-12 * abs(res.trap_storage_rate_m2_s) / step + for col in range(6): + c_hi = coords0.copy() + c_lo = coords0.copy() + c_hi[col] += step + c_lo[col] -= step + r_hi = solve_fixed_occupancy_two_sided_interface( + geom, phys, make_bulk(c_hi), charge, occupancy=f0 + ) + r_lo = solve_fixed_occupancy_two_sided_interface( + geom, phys, make_bulk(c_lo), charge, occupancy=f0 + ) + np.testing.assert_allclose( + res.bulk_flux_jacobian_bulk[:, col], + (r_hi.bulk_flux_m2_s - r_lo.bulk_flux_m2_s) / (2.0 * step), + rtol=1e-6, + atol=flux_atol, + ) + assert res.trap_storage_rate_jacobian_bulk[col] == pytest.approx( + (r_hi.trap_storage_rate_m2_s - r_lo.trap_storage_rate_m2_s) / (2.0 * step), + rel=1e-6, + abs=sr_atol, + ) + + r_f_hi = solve_fixed_occupancy_two_sided_interface( + geom, phys, bulk0, charge, occupancy=f0 + step + ) + r_f_lo = solve_fixed_occupancy_two_sided_interface( + geom, phys, bulk0, charge, occupancy=f0 - step + ) + np.testing.assert_allclose( + res.bulk_flux_derivative_occupancy, + (r_f_hi.bulk_flux_m2_s - r_f_lo.bulk_flux_m2_s) / (2.0 * step), + rtol=1e-8, + atol=1e-5, + ) + assert res.trap_storage_rate_derivative_occupancy == pytest.approx( + (r_f_hi.trap_storage_rate_m2_s - r_f_lo.trap_storage_rate_m2_s) / (2.0 * step), + rel=1e-8, + ) From 19fd1f70266f6a9a1402633518a6638cdacd1390 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sun, 15 Nov 2026 19:52:46 +0800 Subject: [PATCH 16/46] Fix low-bias AC moving-frame/QF linearization, Maxwell spread, and dynamic charge-closure refusals (P04-10, P05-03b, P05-04b) - Eliminate O(1e-11..1e-9 A/m^2/V) floating-point cancellation in dark 0 V and low-bias small-signal AC on both p-i-n and n-i-p across bulk-defect, two-sided interface-defect, and coupled defect+ion stacks: * Lift the small-signal unknown along MOVING_LIFT (dV on the positive electrode and adjacent transport layer) so cross-face Scharfetter-Gummel tangents avoid O(1/V_T) contact-potential subtraction. * Add direct quasi-Fermi IFT sensitivities (*_qf, *_common_qf) and exact flux-sum stabilization in two_sided.py so two-sided trace tangents avoid stiff-side common-mode (O(1e24 - 1e24)) cancellation. * Tighten default AC FrequencyOptions relative_tolerance to 1e-14 with iterative refinement and retain exact ion inventory conservation across all frequencies f >= 0. - Compute DefectIonImpedanceResult.maximum_maxwell_spread_A_m2_V over the Maxwell-conserving sweeps (coupled, frozen_ions) and document asymptotic frozen-trap closures. - Enforce pre-solve CapabilityError refusals for neutral bulk defects under dynamic_bulk_defects=True and non-equilibrium_referenced interface charge closure under dynamic_interface_defects=True across compile, impedance, and transient entry points. - Add dark 0 V p-i-n and n-i-p AC passivity, 0 Hz FD slope, Maxwell spread, and capability refusal regression tests. --- .../device/compile_dynamic_defect_1d.py | 41 +- .../equations/assembly/dynamic_defects_1d.py | 784 ++++++++++++++---- .../experiments/defect_ion_impedance.py | 12 +- .../experiments/dynamic_defect_impedance.py | 25 +- .../experiments/dynamic_defect_transient.py | 22 + .../physics/interface_transport/two_sided.py | 335 +++++++- .../equations/test_defect_ion_coupled_ac.py | 120 +++ .../test_dynamic_defect_experiments.py | 106 ++- 8 files changed, 1269 insertions(+), 176 deletions(-) diff --git a/src/solarlab/device/compile_dynamic_defect_1d.py b/src/solarlab/device/compile_dynamic_defect_1d.py index 506704bd..ab02cf25 100644 --- a/src/solarlab/device/compile_dynamic_defect_1d.py +++ b/src/solarlab/device/compile_dynamic_defect_1d.py @@ -795,10 +795,15 @@ def compile_dynamic_defect_device_1d( trap_data = LegacyBulkTrapInput.model_validate( json.loads(layer.bulk_trap_distribution_json.decode()) ).resolved_data(dict(layer.parameters)["Eg"]) - layer_species.setdefault(index, []).append( - _species_from_legacy_bulk_trap(layer.id, trap_data) - ) - cleared_legacy_traps.add(layer.id) + sp_legacy = _species_from_legacy_bulk_trap(layer.id, trap_data) + if dynamic_bulk_defects and sp_legacy.charge_transition == "neutral": + refusals.append( + f"layers.{layer.id}.bulk_trap_distribution: " + "neutral charge_transition is refused for dynamic bulk trap storage DOFs" + ) + else: + layer_species.setdefault(index, []).append(sp_legacy) + cleared_legacy_traps.add(layer.id) if layer.defects and layer.defect_model != "explicit_quasi_steady": refusals.append( f"layers.{layer.id}.bulk_defects: an explicit inventory requires explicit_quasi_steady" @@ -820,6 +825,12 @@ def compile_dynamic_defect_device_1d( continue item = item_obj.to_mapping() + if dynamic_bulk_defects and item["charge_transition"] == "neutral": + refusals.append( + f"layers.{layer.id}.bulk_defects.{item['id']}: " + "neutral charge_transition is refused for dynamic bulk trap storage DOFs" + ) + continue neutral_simple = ( not dynamic_bulk_defects and item["charge_transition"] == "neutral" @@ -849,6 +860,12 @@ def compile_dynamic_defect_device_1d( raise CapabilityError( "unsupported_dynamic_defect_1d: equilibrium_referenced requires interface_charge_rebaseline_acknowledged=True" ) + if dynamic_interface_defects and closure != "equilibrium_referenced": + raise CapabilityError( + "unsupported_dynamic_defect_1d: dynamic_interface_defects=True requires " + "interface_charge_closure='equilibrium_referenced' and " + "interface_charge_rebaseline_acknowledged=True" + ) if dynamic_interface_defects and interface_topology == "deduplicated": raise CapabilityError( "unsupported_dynamic_defect_1d: dynamic_interface_defects requires two_sided_trace topology" @@ -1382,14 +1399,12 @@ def build_device( continue f_eq = eq_occ_by_iface[tspec.interface_index] trap_nt = float(defect["total_density_m2"]) - wl = wr = 0.0 - if closure == "equilibrium_referenced": - wl, wr = sheet_charge_row_weights( - tspec.trace_electrostatics.eps_r_left, - tspec.trace_electrostatics.left_distance_m, - tspec.trace_electrostatics.eps_r_right, - tspec.trace_electrostatics.right_distance_m, - ) + wl, wr = sheet_charge_row_weights( + tspec.trace_electrostatics.eps_r_left, + tspec.trace_electrostatics.left_distance_m, + tspec.trace_electrostatics.eps_r_right, + tspec.trace_electrostatics.right_distance_m, + ) trap_spec = DynamicInterfaceTrapSpec( interface_id=str(entry["id"]), left_node=tspec.left_node, @@ -1403,7 +1418,7 @@ def build_device( n1_right_m3=float(tspec.physics.n1_right_m3), p1_right_m3=float(tspec.physics.p1_right_m3), equilibrium_occupancy=f_eq, - equilibrium_referenced_charge=(closure == "equilibrium_referenced"), + equilibrium_referenced_charge=True, ) interface_traps.append( DynamicInterfaceTrapBinding1D( diff --git a/src/solarlab/equations/assembly/dynamic_defects_1d.py b/src/solarlab/equations/assembly/dynamic_defects_1d.py index 84b47378..04146f7c 100644 --- a/src/solarlab/equations/assembly/dynamic_defects_1d.py +++ b/src/solarlab/equations/assembly/dynamic_defects_1d.py @@ -100,16 +100,26 @@ from solarlab.physics.interface_transport import ( EquilibriumReferencedSheetCharge, TwoSidedBulkState, + cap_particle_flux_thermionic, solve_charged_two_sided_interface_qss, solve_fixed_occupancy_two_sided_interface, solve_two_sided_interface_qss, ) from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, ion_face_flux, ion_face_flux_jacobian +from solarlab.physics.recombination.interface import ( + interface_srh_rate, + solve_plane_closure, +) from solarlab.physics.transport.electrochemical_flux import ( CarrierFaceFluxes, carrier_particle_fluxes, ) -from solarlab.solvers.linear import FrequencyOptions, FrequencySolution, solve_frequency_systems +from solarlab.solvers.linear import ( + FrequencyOptions, + FrequencySolution, + FrequencySolveError, + solve_frequency_systems, +) from solarlab.solvers.nonlinear.problem import Matrix from solarlab.solvers.time.bdf import BDFStep, HistoryPoint, StorageProblem @@ -205,7 +215,9 @@ def _populate_interfaces_with_dynamic_traps( model = device.interface_model if model is None and not dyn_device.dynamic_interface_traps: return True - if not dyn_device.dynamic_interface_traps: + if not dyn_device.dynamic_interface_traps and ( + model is None or model.topology != "two_sided_trace" + ): return populate_interface_fields(device, elec_u, phi, n, p, fields) count = device.node_count @@ -329,7 +341,8 @@ def _populate_interfaces_with_dynamic_traps( ) fields[f"dyn_iface:{k}"] = fixed_res bflux = fixed_res.bulk_flux_m2_s - j_bulk = fixed_res.bulk_flux_jacobian_bulk + j_bulk_qf = fixed_res.bulk_flux_jacobian_qf + assert j_bulk_qf is not None if itrap.has_sheet_charge: sigma = fixed_res.incremental_sheet_charge_C_m2 g_port_val[l_node - 1] += itrap.weight_left * sigma @@ -342,17 +355,18 @@ def _populate_interfaces_with_dynamic_traps( tspec.charge, ) bflux = charged.bulk_flux_m2_s - j_bulk = charged.bulk_flux_jacobian_bulk + j_bulk_qf = charged.bulk_flux_jacobian_qf sigma = charged.incremental_sheet_charge_C_m2 - j_sigma = charged.sheet_charge_jacobian_bulk + j_sigma_qf = charged.sheet_charge_jacobian_qf + assert j_bulk_qf is not None and j_sigma_qf is not None g_port_val[l_node - 1] += tspec.weight_left * sigma g_port_val[r_node - 1] += tspec.weight_right * sigma - s_phi_l = float(j_sigma[0] + (j_sigma[2] - j_sigma[3]) / thermal) - s_phi_r = float(j_sigma[1] + (j_sigma[4] - j_sigma[5]) / thermal) - s_zn_l = float(j_sigma[2]) - s_zn_r = float(j_sigma[4]) - s_zp_l = float(-j_sigma[3]) - s_zp_r = float(-j_sigma[5]) + s_phi_l = float(j_sigma_qf[0]) + s_phi_r = float(j_sigma_qf[1]) + s_zn_l = float(j_sigma_qf[2]) + s_zn_r = float(j_sigma_qf[4]) + s_zp_l = float(-j_sigma_qf[3]) + s_zp_r = float(-j_sigma_qf[5]) wl, wr = tspec.weight_left, tspec.weight_right w_sum = wl + wr g_left_phi[f] += wr * s_phi_l @@ -374,14 +388,15 @@ def _populate_interfaces_with_dynamic_traps( bulk, ) bflux = uncharged.bulk_flux_m2_s - j_bulk = uncharged.bulk_flux_jacobian_bulk + j_bulk_qf = uncharged.bulk_flux_jacobian_qf + assert j_bulk_qf is not None e_flux[f] = float(bflux[0]) h_flux[f] = float(bflux[1]) - e_ld[f] = float(j_bulk[0, 2]) / float(n[l_node]) - e_rd[f] = float(j_bulk[0, 4]) / float(n[r_node]) - h_ld[f] = float(j_bulk[1, 3]) / float(p[l_node]) - h_rd[f] = float(j_bulk[1, 5]) / float(p[r_node]) + e_ld[f] = float(j_bulk_qf[0, 2]) / float(n[l_node]) + e_rd[f] = float(j_bulk_qf[0, 4]) / float(n[r_node]) + h_ld[f] = float(j_bulk_qf[1, 3]) / float(p[l_node]) + h_rd[f] = float(j_bulk_qf[1, 5]) / float(p[r_node]) e_port_val[r_node - 1] -= float(bflux[0] + bflux[2]) h_port_val[r_node - 1] -= float(bflux[1] + bflux[3]) @@ -389,25 +404,28 @@ def _populate_interfaces_with_dynamic_traps( (0, 2, e_left_phi, e_right_phi, e_port_phi, e_left_zn, e_right_zn, e_port_zn, e_left_zp, e_right_zp, e_port_zp), (1, 3, h_left_phi, h_right_phi, h_port_phi, h_left_zn, h_right_zn, h_port_zn, h_left_zp, h_right_zp, h_port_zp), ): - gl_phi = float(j_bulk[row_l, 0] + (j_bulk[row_l, 2] - j_bulk[row_l, 3]) / thermal) - gr_phi = float(j_bulk[row_l, 1] + (j_bulk[row_l, 4] - j_bulk[row_l, 5]) / thermal) - hl_phi = float(j_bulk[row_r, 0] + (j_bulk[row_r, 2] - j_bulk[row_r, 3]) / thermal) - hr_phi = float(j_bulk[row_r, 1] + (j_bulk[row_r, 4] - j_bulk[row_r, 5]) / thermal) - _scatter_two_sided_tangent(f, gl_phi, gr_phi, hl_phi, hr_phi, fl_phi, fr_phi, pd_phi) _scatter_two_sided_tangent( f, - float(j_bulk[row_l, 2]), - float(j_bulk[row_l, 4]), - float(j_bulk[row_r, 2]), - float(j_bulk[row_r, 4]), + float(j_bulk_qf[row_l, 0]), + float(j_bulk_qf[row_l, 1]), + float(j_bulk_qf[row_r, 0]), + float(j_bulk_qf[row_r, 1]), + fl_phi, fr_phi, pd_phi, + ) + _scatter_two_sided_tangent( + f, + float(j_bulk_qf[row_l, 2]), + float(j_bulk_qf[row_l, 4]), + float(j_bulk_qf[row_r, 2]), + float(j_bulk_qf[row_r, 4]), fl_zn, fr_zn, pd_zn, ) _scatter_two_sided_tangent( f, - float(-j_bulk[row_l, 3]), - float(-j_bulk[row_l, 5]), - float(-j_bulk[row_r, 3]), - float(-j_bulk[row_r, 5]), + float(-j_bulk_qf[row_l, 3]), + float(-j_bulk_qf[row_l, 5]), + float(-j_bulk_qf[row_r, 3]), + float(-j_bulk_qf[row_r, 5]), fl_zp, fr_zp, pd_zp, ) except (RuntimeError, FloatingPointError, ValueError): @@ -928,20 +946,20 @@ def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, if not derivatives: return {self.binding.block: FaceValue(flux)} - thermal = self.device.thermal_voltage_V - j_b = res.trap_storage_rate_jacobian_bulk + j_qf = res.trap_storage_rate_jacobian_qf + assert j_qf is not None sr_df = float(res.trap_storage_rate_derivative_occupancy) f_occ = float(res.occupancy) df_du = f_occ * float(res.one_minus_occupancy) # Face divergence scatters -flux to node 0 (left) and +flux to node 1 (right, constraint-dropped). # Thus -left_tangent lands in Row 0 vs left_node columns, and -right_tangent lands in Row 0 vs right_node columns! - d_phi_l = float(j_b[0] + (j_b[2] - j_b[3]) / thermal) - d_phi_r = float(j_b[1] + (j_b[4] - j_b[5]) / thermal) - d_zn_l = float(j_b[2]) - d_zn_r = float(j_b[4]) - d_zp_l = float(-j_b[3]) - d_zp_r = float(-j_b[5]) + d_phi_l = float(j_qf[0]) + d_phi_r = float(j_qf[1]) + d_zn_l = float(j_qf[2]) + d_zn_r = float(j_qf[4]) + d_zp_l = float(-j_qf[3]) + d_zp_r = float(-j_qf[5]) d_u_l = sr_df * df_du left: dict[str, Contribution] = { @@ -1927,9 +1945,8 @@ def _damped_newton_solve( f_scaled = row_scale * F res_norm = float(np.max(np.abs(f_scaled))) if res_norm <= options.residual_tolerance and ( - iteration == 1 - or step_norm <= options.step_tolerance - or res_norm <= 1.0e-2 * options.residual_tolerance + step_norm <= options.step_tolerance + or res_norm <= 1.0e-4 * options.residual_tolerance ): return u, True, iteration - 1, res_norm, (0.0 if iteration == 1 else step_norm) @@ -2264,7 +2281,13 @@ class DynamicDefectACSweepResult: @dataclass(frozen=True) class DynamicDefectSmallSignal1D: - """Exact small-signal AC linearization ``(J + i * omega * K) x = b`` about steady state.""" + """Exact small-signal AC linearization ``(J + i * omega * K) x = b`` about steady state. + + Uses the moving-reference boundary coordinate lift ``MOVING_LIFT`` so that + prescribed contact perturbations vanish in the linear solve and heavily + doped majority transport layers never suffer sparse Scharfetter-Gummel + diagonal cancellation on either ``p-i-n`` or ``n-i-p`` polarity. + """ device: CompiledDynamicDefectDevice1D operating_state: DynamicDefectState1D @@ -2272,6 +2295,8 @@ class DynamicDefectSmallSignal1D: problem: AssembledDynamicDefect1DProblem = field(init=False, repr=False) jacobian: csc_matrix = field(init=False, repr=False) storage_jacobian: csc_matrix = field(init=False, repr=False) + reference_direction_per_V: Vector = field(init=False, repr=False) + coordinate_lift_per_V: Vector = field(init=False, repr=False) working_state_digest: str = field(init=False) def __post_init__(self) -> None: @@ -2288,12 +2313,408 @@ def __post_init__(self) -> None: object.__setattr__(self, "problem", prob) object.__setattr__(self, "jacobian", prob.jacobian(u0)) object.__setattr__(self, "storage_jacobian", prob.storage_jacobian(u0)) + + comp = self.device.electronic_component + count = self.device.node_count + vt = self.device.thermal_voltage_V + before, after = comp.carrier_reference_energies(0.0), comp.carrier_reference_energies(1.0) + direction: Vector = np.zeros(self.device.state_size, dtype=np.float64) + for offset, zero, one in ((count, before[0], after[0]), (2 * count, before[1], after[1])): + direction[offset : offset + count] = -(one - zero) / vt + direction.setflags(write=False) + object.__setattr__(self, "reference_direction_per_V", direction) + + lift: Vector = np.zeros(self.device.state_size, dtype=np.float64) + lift[count - 1] = -comp.voltage_polarity + for offset in (count, 2 * count): + for node in (0, count - 1): + lift[offset + node] = -lift[node] / vt + direction[offset + node] + lift.setflags(write=False) + object.__setattr__(self, "coordinate_lift_per_V", lift) + object.__setattr__( self, "working_state_digest", sha256(np.ascontiguousarray(u0, dtype=np.float64).tobytes()).hexdigest(), ) + def _base_sg_carrier_particles( + self, moving: ArrayLike, reference_drive: complex = 0.0 + ) -> tuple[ComplexVector, ComplexVector, CarrierFaceFluxes]: + """Cancellation-free linearized SG particle fluxes across all faces.""" + comp = self.device.electronic_component + N = self.device.node_count + vt = self.device.thermal_voltage_V + u0 = self.operating_state.u[: 3 * N] + phi0 = self.operating_state.electronic_state.potential_V + n0 = self.operating_state.electronic_state.electron_density_m3 + p0 = self.operating_state.electronic_state.hole_density_m3 + + e_diff = comp.electron_diffusivity_faces_m2_s + h_diff = comp.hole_diffusivity_faces_m2_s + transport = None if comp.field_transport is None else comp.field_transport.evaluate(phi0) + if transport is not None: + e_diff = transport.electron_diffusivity_m2_s + h_diff = transport.hole_diffusivity_m2_s + + base_fluxes = carrier_particle_fluxes( + comp.nodes_m, + phi0, + n0, + p0, + e_diff, + h_diff, + vt, + comp.parameters.band_structure, + electron_electrochemical_step=np.diff(u0[N : 2 * N]), + hole_electrochemical_step=-np.diff(u0[2 * N : 3 * N]), + ) + before, after = comp.carrier_reference_energies(0.0), comp.carrier_reference_energies(1.0) + values_x = np.asarray(moving, dtype=np.complex128) + perts: list[ComplexVector] = [] + for offset, dens, flx, sign, ref in ( + (N, n0, base_fluxes.electron, 1.0, after[0] - before[0]), + (2 * N, p0, base_fluxes.hole, -1.0, after[1] - before[1]), + ): + drive = sign * np.diff(u0[offset : offset + N]) + l_phi, _ = quasi_fermi_potential_tangents(flx, drive, sign, vt) + if transport is not None: + diff = ( + transport.electron_diffusivity_m2_s + if offset == N + else transport.hole_diffusivity_m2_s + ) + d_diff = ( + transport.electron_d_diffusivity_d_field + if offset == N + else transport.hole_d_diffusivity_d_field + ) + l_phi = l_phi + (flx.flux / diff) * d_diff / np.diff(comp.nodes_m) + l_z = sign * flx.left_density_derivative * dens[:-1] + z_blk = values_x[offset : offset + N] + pert = ( + l_phi * (values_x[: N - 1] - values_x[1:N]) + + l_z * (z_blk[:-1] - z_blk[1:]) + + sign * flx.flux * (z_blk[1:] + (values_x[1:N] + ref * reference_drive) / vt) + ) + perts.append(pert) + return perts[0], perts[1], base_fluxes + + def _moving_voltage_partial(self) -> tuple[Vector, Vector]: + """Grouped ``F_V + J (c - r)`` and ``-K (c - r)`` for ``c = coordinate_lift_per_V``.""" + dev = self.device + comp = dev.electronic_component + N = dev.node_count + vt = dev.thermal_voltage_V + w = comp.geometry.cell_measures_m + u0 = self.operating_state.u + moving = self.coordinate_lift_per_V + + state_eval = self.problem.binding.assembler.state(u0, self.problem.inputs) + assert state_eval is not None + + phi0 = self.operating_state.electronic_state.potential_V + n0 = self.operating_state.electronic_state.electron_density_m3 + p0 = self.operating_state.electronic_state.hole_density_m3 + before, after = comp.carrier_reference_energies(0.0), comp.carrier_reference_energies(1.0) + references = (after[0] - before[0], after[1] - before[1]) + + dlog_n: Vector = (moving[:N] + references[0]) / vt + moving[N : 2 * N] + dlog_p: Vector = -((moving[:N] + references[1]) / vt + moving[2 * N : 3 * N]) + dlog_n[0] = dlog_n[N - 1] = 0.0 + dlog_p[0] = dlog_p[N - 1] = 0.0 + dn: Vector = n0 * dlog_n + dp: Vector = p0 * dlog_p + + result: Vector = np.zeros(dev.state_size, dtype=np.float64) + storage_drive: Vector = np.zeros(dev.state_size, dtype=np.float64) + + # 1. Gauss rows (0 .. N - 1): + drho_stat: Vector = np.zeros(N, dtype=np.float64) + d_rec_stat: Vector = np.zeros(N, dtype=np.float64) + if dev.stationary_defects is not None: + stat_ev = cast(StationaryDefectEvaluation1D, state_eval.field("stationary_defects")) + drho_stat = stat_ev.d_charge_dn_C * dn + stat_ev.d_charge_dp_C * dp + d_rec_stat = stat_ev.d_recombination_dn_s1 * dn + stat_ev.d_recombination_dp_s1 * dp + + result[:N] = comp.poisson.jacobian() @ moving[:N] + comp.poisson.charge_jacobian() * ( + Q * (dp - dn) + drho_stat + ) + result[N - 1] += comp.voltage_polarity + + # 2. Dynamic bulk trap capture into carriers + trap rate rows: + d_cap_n: Vector = np.zeros(N, dtype=np.float64) + d_cap_p: Vector = np.zeros(N, dtype=np.float64) + if dev.dynamic_bulk_traps is not None: + trap_ev = cast(DynamicBulkTrapEvaluation, state_eval.field("dynamic_bulk_traps")) + bt_nodes = dev.dynamic_bulk_traps.device_node_indices + np.add.at(d_cap_n, bt_nodes, trap_ev.d_electron_capture_dn_s1 * dn[bt_nodes]) + np.add.at(d_cap_p, bt_nodes, trap_ev.d_hole_capture_dp_s1 * dp[bt_nodes]) + sl_bt = dev.bulk_trap_slice + result[sl_bt] = w[bt_nodes] * ( + trap_ev.d_trap_storage_rate_dn_s1 * dn[bt_nodes] + + trap_ev.d_trap_storage_rate_dp_s1 * dp[bt_nodes] + ) + + # 3. Carrier face fluxes and heterointerface channels: + dfn_c, dfp_c, base_fluxes = self._base_sg_carrier_particles(moving, 1.0) + dfn: Vector = np.real(dfn_c).copy() + dfp: Vector = np.real(dfp_c).copy() + e_iface_node: Vector = np.zeros(N, dtype=np.float64) + h_iface_node: Vector = np.zeros(N, dtype=np.float64) + + if comp.interface_model is not None: + if comp.interface_model.topology == "deduplicated": + temp = float(comp.parameters.temperature_K) + for tf in comp.interface_model.thermionic_faces: + f = tf.face + if tf.cap_electron: + cap_e = cap_particle_flux_thermionic( + float(base_fluxes.electron.flux[f]), + n_left_m3=float(n0[f]), + n_right_m3=float(n0[f + 1]), + delta_barrier_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_n_A_m2_K2, + te_softness=comp.interface_model.te_softness, + regularization_mode=comp.interface_model.te_regularization_mode, + ) + dfn[f] = ( + cap_e.d_flux_d_sg_flux * dfn[f] + + cap_e.d_flux_d_n_left_m_s * dn[f] + + cap_e.d_flux_d_n_right_m_s * dn[f + 1] + ) + if tf.cap_hole: + cap_h = cap_particle_flux_thermionic( + float(base_fluxes.hole.flux[f]), + n_left_m3=float(p0[f]), + n_right_m3=float(p0[f + 1]), + delta_barrier_eV=tf.delta_Ev_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_p_A_m2_K2, + te_softness=comp.interface_model.te_softness, + regularization_mode=comp.interface_model.te_regularization_mode, + ) + dfp[f] = ( + cap_h.d_flux_d_sg_flux * dfp[f] + + cap_h.d_flux_d_n_left_m_s * dp[f] + + cap_h.d_flux_d_n_right_m_s * dp[f + 1] + ) + for bare in comp.interface_model.bare_srh: + idx = bare.node + srh = interface_srh_rate( + float(n0[idx]), + float(p0[idx]), + v_n_m_s=bare.v_n_m_s, + v_p_m_s=bare.v_p_m_s, + ni_sq_m6=bare.ni_sq_m6, + n1_m3=bare.n1_m3, + p1_m3=bare.p1_m3, + clamp_nonnegative=False, + ) + dsink = -( + float(np.real(srh.d_rate_dn_m_s)) * dn[idx] + + float(np.real(srh.d_rate_dp_m_s)) * dp[idx] + ) + e_iface_node[idx] += dsink + h_iface_node[idx] += dsink + for dspec in comp.interface_model.defect_srh: + idx = dspec.node + i_l, i_0, i_r = idx - 1, idx, idx + 1 + if comp.interface_model.plane_closure and dspec.plane_params is not None: + el_raw = (float(phi0[i_0]) - float(phi0[i_l])) / vt + er_raw = (float(phi0[i_0]) - float(phi0[i_r])) / vt + fl = math.exp(max(-500.0, min(500.0, el_raw))) + fr = math.exp(max(-500.0, min(500.0, er_raw))) + nl_p = float(n0[i_l]) * fl + nr_p = float(n0[i_r]) * fr + pl_p = float(p0[i_l]) / fl + pr_p = float(p0[i_r]) / fr + plane_res = solve_plane_closure( + nl_p, + nr_p, + pl_p, + pr_p, + dspec.plane_params, + dspec.v_n_m_s, + dspec.v_p_m_s, + allow_generation=comp.interface_model.plane_generation, + ) + chi_l = 1.0 if -500.0 < el_raw < 500.0 else 0.0 + chi_r = 1.0 if -500.0 < er_raw < 500.0 else 0.0 + d_el = chi_l * (moving[i_0] - moving[i_l]) / vt + d_er = chi_r * (moving[i_0] - moving[i_r]) / vt + dsink = -( + plane_res.d_rate_d_n_left_proj_m_s * nl_p * (dlog_n[i_l] + d_el) + + plane_res.d_rate_d_n_right_proj_m_s * nr_p * (dlog_n[i_r] + d_er) + + plane_res.d_rate_d_p_left_proj_m_s * pl_p * (dlog_p[i_l] - d_el) + + plane_res.d_rate_d_p_right_proj_m_s * pr_p * (dlog_p[i_r] - d_er) + ) + else: + if comp.interface_model.plane_projection: + en_raw = (float(phi0[i_0]) - float(phi0[i_r])) / vt + ep_raw = (float(phi0[i_0]) - float(phi0[i_l])) / vt + fac_n = math.exp(max(-500.0, min(500.0, en_raw))) + fac_p = math.exp(-max(-500.0, min(500.0, ep_raw))) + chi_en = 1.0 if -500.0 < en_raw < 500.0 else 0.0 + chi_ep = 1.0 if -500.0 < ep_raw < 500.0 else 0.0 + else: + fac_n = fac_p = 1.0 + chi_en = chi_ep = 0.0 + n_eval = float(n0[i_r]) * fac_n + p_eval = float(p0[i_l]) * fac_p + ni_eval = dspec.ni_sq_eff_m6 * fac_n * fac_p + srh = interface_srh_rate( + n_eval, + p_eval, + v_n_m_s=dspec.v_n_m_s, + v_p_m_s=dspec.v_p_m_s, + ni_sq_m6=ni_eval, + n1_m3=dspec.n1_m3, + p1_m3=dspec.p1_m3, + clamp_nonnegative=True, + ) + d_en = chi_en * (moving[i_0] - moving[i_r]) / vt + d_ep = chi_ep * (moving[i_0] - moving[i_l]) / vt + denom = dspec.v_n_m_s * (n_eval + dspec.n1_m3) + dspec.v_p_m_s * ( + p_eval + dspec.p1_m3 + ) + unclamped = ( + dspec.v_n_m_s > 0.0 + and dspec.v_p_m_s > 0.0 + and denom > 1.0e-300 + and (n_eval * p_eval - ni_eval) >= 0.0 + ) + a_ni = ( + -(dspec.v_n_m_s * dspec.v_p_m_s / denom) * ni_eval + if unclamped + else 0.0 + ) + dsink = -( + float(np.real(srh.d_rate_dn_m_s)) * n_eval * (dlog_n[i_r] + d_en) + + float(np.real(srh.d_rate_dp_m_s)) * p_eval * (dlog_p[i_l] - d_ep) + + a_ni * (d_en - d_ep) + ) + e_iface_node[idx] += dsink + h_iface_node[idx] += dsink + elif comp.interface_model.topology == "two_sided_trace": + dyn_idx_map = { + it.interface_index: (pos, it) + for pos, it in enumerate(dev.dynamic_interface_traps) + } + com_vec = np.array( + [references[0] / vt, -references[1] / vt], dtype=np.float64 + ) + for tspec in comp.interface_model.two_sided: + k = tspec.interface_index + f = tspec.face + ln, rn = tspec.left_node, tspec.right_node + dfn[f] = 0.0 + dfp[f] = 0.0 + qf_rem = np.array( + [ + moving[ln], + moving[rn], + moving[N + ln] if 0 < ln < N - 1 else (-moving[ln] / vt - com_vec[0]), + -moving[2 * N + ln] if 0 < ln < N - 1 else (moving[ln] / vt - com_vec[1]), + moving[N + rn] if 0 < rn < N - 1 else (-moving[rn] / vt - com_vec[0]), + -moving[2 * N + rn] if 0 < rn < N - 1 else (moving[rn] / vt - com_vec[1]), + ], + dtype=np.float64, + ) + if k in dyn_idx_map: + pos, _ = dyn_idx_map[k] + res = state_eval.field(f"dyn_iface:{k}") + j_qf = res.bulk_flux_jacobian_qf + j_com = res.bulk_flux_common_qf + sr_qf = res.trap_storage_rate_jacobian_qf + sr_com = res.trap_storage_rate_common_qf + assert ( + j_qf is not None + and j_com is not None + and sr_qf is not None + and sr_com is not None + ) + dbflux = j_qf @ qf_rem + j_com @ com_vec + row_it = dev.interface_trap_slices[pos].start + result[row_it] = float(sr_qf @ qf_rem + sr_com @ com_vec) + else: + bulk = TwoSidedBulkState( + phi_left_V=float(u0[ln]), + phi_right_V=float(u0[rn]), + n_left_m3=float(n0[ln]), + p_left_m3=float(p0[ln]), + n_right_m3=float(n0[rn]), + p_right_m3=float(p0[rn]), + electron_electrochemical_step=float(u0[N + rn] - u0[N + ln]), + hole_electrochemical_step=float(-(u0[2 * N + rn] - u0[2 * N + ln])), + ) + if tspec.charge is not None: + qres = solve_charged_two_sided_interface_qss( + tspec.trace_electrostatics, tspec.physics, bulk, tspec.charge + ) + assert ( + qres.bulk_flux_jacobian_qf is not None + and qres.bulk_flux_common_qf is not None + and qres.sheet_charge_jacobian_qf is not None + and qres.sheet_charge_common_qf is not None + ) + dbflux = ( + qres.bulk_flux_jacobian_qf @ qf_rem + + qres.bulk_flux_common_qf @ com_vec + ) + dsig = float( + qres.sheet_charge_jacobian_qf @ qf_rem + + qres.sheet_charge_common_qf @ com_vec + ) + if 0 < ln < N - 1: + result[ln] += tspec.weight_left * dsig + if 0 < rn < N - 1: + result[rn] += tspec.weight_right * dsig + else: + ures = solve_two_sided_interface_qss( + tspec.trace_electrostatics, tspec.physics, bulk + ) + assert ( + ures.bulk_flux_jacobian_qf is not None + and ures.bulk_flux_common_qf is not None + ) + dbflux = ( + ures.bulk_flux_jacobian_qf @ qf_rem + + ures.bulk_flux_common_qf @ com_vec + ) + e_iface_node[ln] -= float(dbflux[0]) + e_iface_node[rn] -= float(dbflux[2]) + h_iface_node[ln] -= float(dbflux[1]) + h_iface_node[rn] -= float(dbflux[3]) + + # 4. Carrier continuity rows and carrier storage drive: + rate = self.problem.binding.electronic.recombination.rate(n0, p0, derivatives=True) + assert rate.d_rate_dn is not None and rate.d_rate_dp is not None + d_rec_base = rate.d_rate_dn * dn + rate.d_rate_dp * dp + src_n = -(d_rec_base + d_rec_stat + d_cap_n) + src_p = -(d_rec_base + d_rec_stat + d_cap_p) + + for carrier, offset, flux_v, src_v, iface_v, d_dens, sign, ref in ( + ("n", N, dfn, src_n, e_iface_node, dn, 1.0, references[0]), + ("p", 2 * N, dfp, src_p, h_iface_node, dp, -1.0, references[1]), + ): + rows = -np.diff(np.r_[0.0, flux_v, 0.0]) + w * src_v + iface_v + s_drive = w * d_dens + for side, node in (("left", 0), ("right", N - 1)): + if comp.channel(carrier, side).kind == "fixed_reservoir": + rows[node] = sign * ((moving[node] + ref) / vt + moving[offset + node]) + s_drive[node] = 0.0 + result[offset : offset + N] = rows + storage_drive[offset : offset + N] = s_drive + + # 5. Mobile-ion potential coupling at contact endpoint: + if dev.ionic_component is not None: + sl_ion = dev.ion_slice + result[sl_ion] = self.jacobian[sl_ion, :N] @ moving[:N] + + return result, storage_drive + def species_partition( self, *, @@ -2339,8 +2760,22 @@ def solve_sweep( freeze_bulk_traps: bool = False, freeze_interface_traps: bool = False, ) -> DynamicDefectACSweepResult: - """Solve complex sparse small-signal AC sweep with selective species freezing.""" - controls = FrequencyOptions() if options is None else options + """Solve complex sparse small-signal AC sweep with selective species freezing. + + Note on diagnostic freezing closures: + ``freeze_ions=True`` clamps mobile-ion perturbations ``dP = 0`` and + remains a locally Maxwell-conserving PDE at every frequency. By + contrast, ``freeze_bulk_traps=True`` and ``freeze_interface_traps=True`` + clamp trap occupancy perturbations ``df = 0`` while retaining linearized + carrier capture perturbations ``dC_n != dC_p`` as ``omega -> inf`` + asymptotic reference operators rather than finite-frequency + Maxwell-conserving PDEs. + """ + controls = ( + FrequencyOptions(relative_tolerance=1.0e-14, max_refinements=4) + if options is None + else options + ) freqs = np.asarray(frequencies_Hz, dtype=np.float64) if ( freqs.ndim != 1 @@ -2356,6 +2791,41 @@ def solve_sweep( relative_tolerance=controls.relative_tolerance, max_refinements=controls.max_refinements, ) + fallback_controls = ( + FrequencyOptions(max_frequencies=controls.max_frequencies, max_refinements=4) + if options is None + else None + ) + + def _solve_freq_batch( + j_mat: csc_matrix, + k_mat: csc_matrix, + rhs_vec: ComplexVector, + freq_vec: Vector, + rate_vec: ComplexVector, + ) -> tuple[FrequencySolution, ...]: + try: + return solve_frequency_systems( + j_mat, + k_mat, + rhs_vec, + freq_vec, + options=controls, + fixed_coordinates=known, + rhs_rate=rate_vec, + ) + except FrequencySolveError: + if fallback_controls is None: + raise + return solve_frequency_systems( + j_mat, + k_mat, + rhs_vec, + freq_vec, + options=fallback_controls, + fixed_coordinates=known, + rhs_rate=rate_vec, + ) voltage = complex(voltage_phasor_V) if not np.isfinite(voltage) or voltage == 0.0: @@ -2365,20 +2835,20 @@ def solve_sweep( comp = dev.electronic_component N = dev.node_count - # Build base J, K with any frozen species pinned to 0 perturbation: + # Build base J, K with moving-boundary coordinate lift and any frozen species pinned to 0: j_base = self.jacobian.copy().tolil() k_base = self.storage_jacobian.copy().tolil() - rhs: ComplexVector = np.zeros(dev.state_size, dtype=np.complex128) - phi_right = complex(-comp.voltage_polarity * voltage) - rhs[N - 1] = phi_right + partial, storage_drive = self._moving_voltage_partial() + rhs: ComplexVector = (-partial * voltage).astype(np.complex128) + rhs_rate: ComplexVector = (storage_drive * voltage).astype(np.complex128) - known: dict[int, complex] = {0: 0.0j, N - 1: phi_right} + known: dict[int, complex] = {0: 0.0j, N - 1: 0.0j} for carrier, offset in (("n", N), ("p", 2 * N)): if comp.channel(carrier, "left").kind == "fixed_reservoir": known[offset] = 0.0j if comp.channel(carrier, "right").kind == "fixed_reservoir": - known[offset + N - 1] = -phi_right / comp.thermal_voltage_V + known[offset + N - 1] = 0.0j frozen_indices: list[int] = [] if dev.ionic_component is not None and freeze_ions: @@ -2396,11 +2866,8 @@ def solve_sweep( k_base.rows[idx], k_base.data[idx] = [], [] known[idx] = 0.0j rhs[idx] = 0.0j + rhs_rate[idx] = 0.0j - j_csc = j_base.tocsc() - k_csc = k_base.tocsc() - - # Split 0 Hz (if mobile ions are active, 0 Hz needs inventory constraint rows) vs f > 0 Hz: has_mobile_ions = dev.ionic_component is not None and not freeze_ions if has_mobile_ions: ion_dev: CompiledIonicDevice1D | TwoSidedIonicComponent1D | None = dev.ionic_component @@ -2414,6 +2881,7 @@ def solve_sweep( j_base.rows[row], j_base.data[row] = nz.tolist(), grad[nz].tolist() k_base.rows[row], k_base.data[row] = [], [] rhs[row] = 0.0j + rhs_rate[row] = 0.0j else: diff_faces = getattr(ion_dev, sp + "_ion_diffusivity_faces_m2_s") if np.all(diff_faces > 0.0): @@ -2423,16 +2891,21 @@ def solve_sweep( j_base.rows[row0], j_base.data[row0] = nz.tolist(), grad[nz].tolist() k_base.rows[row0], k_base.data[row0] = [], [] rhs[row0] = 0.0j + rhs_rate[row0] = 0.0j elif np.any(freqs == 0.0): raise CapabilityError( "0 Hz mobile ions require positive diffusivity across domain" ) - j_csc = j_base.tocsc() - k_csc = k_base.tocsc() + j_csc = j_base.tocsc() + k_csc = k_base.tocsc() solutions_by_idx = list( - solve_frequency_systems( - j_csc, k_csc, rhs, freqs, options=controls, fixed_coordinates=known + _solve_freq_batch( + j_csc, + k_csc, + rhs, + freqs, + rhs_rate, ) ) @@ -2492,19 +2965,29 @@ def _observe_point( vt = dev.thermal_voltage_V u0 = self.operating_state.u x = sol.solution + lift = self.coordinate_lift_per_V omega = 2.0 * math.pi * sol.frequency_Hz state_eval = self.problem.binding.assembler.state(u0, self.problem.inputs) assert state_eval is not None - phi_x = x[:N] - zn_x = x[N : 2 * N] - zp_x = x[2 * N : 3 * N] + phi_x: ComplexVector = x[:N] + lift[:N] * voltage + before, after = comp.carrier_reference_energies(0.0), comp.carrier_reference_energies(1.0) + ref_n, ref_p = after[0] - before[0], after[1] - before[1] + + dlog_n: ComplexVector = np.empty(N, dtype=np.complex128) + dlog_p: ComplexVector = np.empty(N, dtype=np.complex128) + dlog_n[0] = x[0] / vt + x[N] + dlog_n[N - 1] = x[N - 1] / vt + x[2 * N - 1] + dlog_n[1 : N - 1] = (x[1 : N - 1] + ref_n * voltage) / vt + x[N + 1 : 2 * N - 1] + dlog_p[0] = -(x[0] / vt + x[2 * N]) + dlog_p[N - 1] = -(x[N - 1] / vt + x[3 * N - 1]) + dlog_p[1 : N - 1] = -((x[1 : N - 1] + ref_p * voltage) / vt + x[2 * N + 1 : 3 * N - 1]) n0 = self.operating_state.electronic_state.electron_density_m3 p0 = self.operating_state.electronic_state.hole_density_m3 - dn = n0 * (phi_x / vt + zn_x) - dp = -p0 * (phi_x / vt + zp_x) + dn: ComplexVector = n0 * dlog_n + dp: ComplexVector = p0 * dlog_p # 1. Dynamic bulk trap perturbations: if dev.dynamic_bulk_traps is not None: @@ -2539,11 +3022,7 @@ def _observe_point( # 2. Stationary defect perturbations: if dev.stationary_defects is not None: stat_ev = cast(StationaryDefectEvaluation1D, state_eval.field("stationary_defects")) - drho_stat = ( - stat_ev.d_charge_dphi_fixed_qf_C_m3_V * phi_x - + (stat_ev.d_charge_dn_C * n0) * zn_x - - (stat_ev.d_charge_dp_C * p0) * zp_x - ) + drho_stat = stat_ev.d_charge_dn_C * dn + stat_ev.d_charge_dp_C * dp d_rec_stat = stat_ev.d_recombination_dn_s1 * dn + stat_ev.d_recombination_dp_s1 * dp else: drho_stat = np.zeros(N, dtype=np.complex128) @@ -2567,55 +3046,51 @@ def _observe_point( dsigma_it = np.empty(0, dtype=np.complex128) # 4. Electronic face particle flux perturbations (grouping exact SG differences): - fluxes = self.problem.binding.electronic.transport.fluxes(state_eval) - transport = None if comp.field_transport is None else comp.field_transport.evaluate(u0[:N]) - fn_pert: list[ComplexVector] = [] - for offset, dens, flx, sign in ( - (N, n0, fluxes.electron, 1.0), - (2 * N, p0, fluxes.hole, -1.0), - ): - drive = sign * np.diff(u0[offset : offset + N]) - l_phi, _ = quasi_fermi_potential_tangents(flx, drive, sign, vt) - if transport is not None: - diff = ( - transport.electron_diffusivity_m2_s - if offset == N - else transport.hole_diffusivity_m2_s - ) - d_diff = ( - transport.electron_d_diffusivity_d_field - if offset == N - else transport.hole_d_diffusivity_d_field - ) - l_phi = l_phi + (flx.flux / diff) * d_diff / np.diff(comp.nodes_m) - l_z = sign * flx.left_density_derivative * dens[:-1] - z_blk = x[offset : offset + N] - pert = ( - l_phi * (phi_x[:-1] - phi_x[1:]) - + l_z * (z_blk[:-1] - z_blk[1:]) - + sign * flx.flux * (z_blk[1:] + phi_x[1:] / vt) - ) - fn_pert.append(pert) - dfn, dfp = fn_pert[0], fn_pert[1] + dfn_solve, dfp_solve, base_fluxes = self._base_sg_carrier_particles(x, 0.0) + dfn_lift, dfp_lift, _ = self._base_sg_carrier_particles(lift, 1.0) + dfn: ComplexVector = dfn_solve + dfn_lift * voltage + dfp: ComplexVector = dfp_solve + dfp_lift * voltage # Override thermionic / two-sided interface faces with their exact analytical tangents: if comp.interface_model is not None: if comp.interface_model.topology == "deduplicated": + temp = float(comp.parameters.temperature_K) for tf in comp.interface_model.thermionic_faces: f = tf.face - dfn[f] = ( - state_eval.field("iface:e_left_phi")[f] * phi_x[f] - + state_eval.field("iface:e_right_phi")[f] * phi_x[f + 1] - + state_eval.field("iface:e_left_zn")[f] * zn_x[f] - + state_eval.field("iface:e_right_zn")[f] * zn_x[f + 1] - ) - dfp[f] = ( - state_eval.field("iface:h_left_phi")[f] * phi_x[f] - + state_eval.field("iface:h_right_phi")[f] * phi_x[f + 1] - + state_eval.field("iface:h_left_zp")[f] * zp_x[f] - + state_eval.field("iface:h_right_zp")[f] * zp_x[f + 1] - ) + if tf.cap_electron: + cap_e = cap_particle_flux_thermionic( + float(base_fluxes.electron.flux[f]), + n_left_m3=float(n0[f]), + n_right_m3=float(n0[f + 1]), + delta_barrier_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_n_A_m2_K2, + te_softness=comp.interface_model.te_softness, + regularization_mode=comp.interface_model.te_regularization_mode, + ) + dfn[f] = ( + cap_e.d_flux_d_sg_flux * dfn[f] + + cap_e.d_flux_d_n_left_m_s * dn[f] + + cap_e.d_flux_d_n_right_m_s * dn[f + 1] + ) + if tf.cap_hole: + cap_h = cap_particle_flux_thermionic( + float(base_fluxes.hole.flux[f]), + n_left_m3=float(p0[f]), + n_right_m3=float(p0[f + 1]), + delta_barrier_eV=tf.delta_Ev_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_p_A_m2_K2, + te_softness=comp.interface_model.te_softness, + regularization_mode=comp.interface_model.te_regularization_mode, + ) + dfp[f] = ( + cap_h.d_flux_d_sg_flux * dfp[f] + + cap_h.d_flux_d_n_left_m_s * dp[f] + + cap_h.d_flux_d_n_right_m_s * dp[f + 1] + ) elif comp.interface_model.topology == "two_sided_trace": + com_vec_obs = np.array([ref_n / vt, -ref_p / vt], dtype=np.float64) dyn_idx_map = { it.interface_index: (pos, it) for pos, it in enumerate(dev.dynamic_interface_traps) @@ -2624,19 +3099,31 @@ def _observe_point( k = tspec.interface_index f = tspec.face ln, rn = tspec.left_node, tspec.right_node + u_solve_vec = np.array( + [x[ln], x[rn], x[N + ln], -x[2 * N + ln], x[N + rn], -x[2 * N + rn]], + dtype=np.complex128, + ) + qf_lift_rem = np.array( + [ + lift[ln], + lift[rn], + lift[N + ln] if 0 < ln < N - 1 else (-lift[ln] / vt - com_vec_obs[0]), + -lift[2 * N + ln] if 0 < ln < N - 1 else (lift[ln] / vt - com_vec_obs[1]), + lift[N + rn] if 0 < rn < N - 1 else (-lift[rn] / vt - com_vec_obs[0]), + -lift[2 * N + rn] if 0 < rn < N - 1 else (lift[rn] / vt - com_vec_obs[1]), + ], + dtype=np.float64, + ) if k in dyn_idx_map: - pos, itrap = dyn_idx_map[k] + pos, _ = dyn_idx_map[k] res = state_eval.field(f"dyn_iface:{k}") - jb = res.bulk_flux_jacobian_bulk + jb_qf = res.bulk_flux_jacobian_qf + jb_com = res.bulk_flux_common_qf + assert jb_qf is not None and jb_com is not None dbf = res.bulk_flux_derivative_occupancy - gl_e = (jb[0, 0] + (jb[0, 2] - jb[0, 3]) / vt) * phi_x[ln] + jb[0, 2] * zn_x[ln] - jb[0, 3] * zp_x[ln] - gr_e = (jb[0, 1] + (jb[0, 4] - jb[0, 5]) / vt) * phi_x[rn] + jb[0, 4] * zn_x[rn] - jb[0, 5] * zp_x[rn] - gl_h = (jb[1, 0] + (jb[1, 2] - jb[1, 3]) / vt) * phi_x[ln] + jb[1, 2] * zn_x[ln] - jb[1, 3] * zp_x[ln] - gr_h = (jb[1, 1] + (jb[1, 4] - jb[1, 5]) / vt) * phi_x[rn] + jb[1, 4] * zn_x[rn] - jb[1, 5] * zp_x[rn] - dfn[f] = gl_e + gr_e + float(dbf[0]) * df_it[pos] - dfp[f] = gl_h + gr_h + float(dbf[1]) * df_it[pos] + occ_term_n = float(dbf[0]) * df_it[pos] + occ_term_p = float(dbf[1]) * df_it[pos] else: - # Reconstruct left-side bulk flux perturbation from bulk interface tangents: bulk = TwoSidedBulkState( phi_left_V=float(u0[ln]), phi_right_V=float(u0[rn]), @@ -2651,28 +3138,24 @@ def _observe_point( qres = solve_charged_two_sided_interface_qss( tspec.trace_electrostatics, tspec.physics, bulk, tspec.charge ) - jb = qres.bulk_flux_jacobian_bulk + jb_qf = qres.bulk_flux_jacobian_qf + jb_com = qres.bulk_flux_common_qf else: ures = solve_two_sided_interface_qss( tspec.trace_electrostatics, tspec.physics, bulk ) - jb = ures.bulk_flux_jacobian_bulk - dfn[f] = ( - (jb[0, 0] + (jb[0, 2] - jb[0, 3]) / vt) * phi_x[ln] - + (jb[0, 1] + (jb[0, 4] - jb[0, 5]) / vt) * phi_x[rn] - + jb[0, 2] * zn_x[ln] - + jb[0, 4] * zn_x[rn] - - jb[0, 3] * zp_x[ln] - - jb[0, 5] * zp_x[rn] - ) - dfp[f] = ( - (jb[1, 0] + (jb[1, 2] - jb[1, 3]) / vt) * phi_x[ln] - + (jb[1, 1] + (jb[1, 4] - jb[1, 5]) / vt) * phi_x[rn] - + jb[1, 2] * zn_x[ln] - + jb[1, 4] * zn_x[rn] - - jb[1, 3] * zp_x[ln] - - jb[1, 5] * zp_x[rn] - ) + jb_qf = ures.bulk_flux_jacobian_qf + jb_com = ures.bulk_flux_common_qf + assert jb_qf is not None and jb_com is not None + occ_term_n = 0.0j + occ_term_p = 0.0j + lift_flux = jb_qf @ qf_lift_rem + jb_com @ com_vec_obs + dfn[f] = complex( + jb_qf[0] @ u_solve_vec + float(lift_flux[0]) * voltage + occ_term_n + ) + dfp[f] = complex( + jb_qf[1] @ u_solve_vec + float(lift_flux[1]) * voltage + occ_term_p + ) # Terminal electronic conduction currents: rate = self.problem.binding.electronic.recombination.rate(n0, p0, derivatives=True) @@ -2811,14 +3294,27 @@ def _observe_point( qres = solve_charged_two_sided_interface_qss( tspec.trace_electrostatics, tspec.physics, bulk, tspec.charge ) - js = qres.sheet_charge_jacobian_bulk - dsig = ( - (js[0] + (js[2] - js[3]) / vt) * phi_x[ln] - + (js[1] + (js[4] - js[5]) / vt) * phi_x[rn] - + js[2] * zn_x[ln] - + js[4] * zn_x[rn] - - js[3] * zp_x[ln] - - js[5] * zp_x[rn] + js_qf = qres.sheet_charge_jacobian_qf + js_com = qres.sheet_charge_common_qf + assert js_qf is not None and js_com is not None + com_l6 = np.array([ref_n / vt, -ref_p / vt], dtype=np.float64) + u_s6 = np.array( + [x[ln], x[rn], x[N + ln], -x[2 * N + ln], x[N + rn], -x[2 * N + rn]], + dtype=np.complex128, + ) + qf_l6 = np.array( + [ + lift[ln], + lift[rn], + lift[N + ln] if 0 < ln < N - 1 else (-lift[ln] / vt - com_l6[0]), + -lift[2 * N + ln] if 0 < ln < N - 1 else (lift[ln] / vt - com_l6[1]), + lift[N + rn] if 0 < rn < N - 1 else (-lift[rn] / vt - com_l6[0]), + -lift[2 * N + rn] if 0 < rn < N - 1 else (lift[rn] / vt - com_l6[1]), + ], + dtype=np.float64, + ) + dsig = complex( + js_qf @ u_s6 + float(js_qf @ qf_l6 + js_com @ com_l6) * voltage ) cell_charge[ln] += tspec.weight_left * dsig cell_charge[rn] += tspec.weight_right * dsig diff --git a/src/solarlab/experiments/defect_ion_impedance.py b/src/solarlab/experiments/defect_ion_impedance.py index a2643b76..2470dd22 100644 --- a/src/solarlab/experiments/defect_ion_impedance.py +++ b/src/solarlab/experiments/defect_ion_impedance.py @@ -90,7 +90,15 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class DefectIonImpedanceResult: - """Coupled and species-frozen small-signal spectra about one DC working state.""" + """Coupled and species-frozen small-signal spectra about one DC working state. + + ``maximum_maxwell_spread_A_m2_V`` summarizes total-current continuity across + the physically charge-conserving PDE sweeps (``coupled`` and ``frozen_ions``). + ``frozen_traps`` and ``frozen_ions_and_traps`` clamp trap occupancy + perturbations ``df = 0`` while retaining linearized carrier capture + perturbations ``dC_n != dC_p`` as ``omega -> inf`` asymptotic reference + closures rather than finite-frequency Maxwell-conserving PDEs. + """ capability: DefectIonCapability device: CompiledDynamicDefectDevice1D @@ -270,8 +278,6 @@ def solve_defect_ion_impedance( max( np.max(coupled.maxwell_spread_A_m2_V), np.max(frozen_ions.maxwell_spread_A_m2_V), - np.max(frozen_traps.maxwell_spread_A_m2_V), - np.max(frozen_both.maxwell_spread_A_m2_V), ) ) max_inv = 0.0 diff --git a/src/solarlab/experiments/dynamic_defect_impedance.py b/src/solarlab/experiments/dynamic_defect_impedance.py index bc0e436e..3a707232 100644 --- a/src/solarlab/experiments/dynamic_defect_impedance.py +++ b/src/solarlab/experiments/dynamic_defect_impedance.py @@ -142,7 +142,19 @@ def classify_dynamic_defect_capability( raise DynamicDefectImpedanceCapabilityError( f"layers.{layer.id}: multivalent bulk defects do not expose dynamic single-level impedance modes" ) - if layer.defects or layer.bulk_trap_distribution_json is not None: + if layer.bulk_trap_distribution_json is not None: + raw_legacy = json.loads(layer.bulk_trap_distribution_json.decode()) + if str(raw_legacy.get("charge_transition", "")) == "neutral": + raise DynamicDefectImpedanceCapabilityError( + f"layers.{layer.id}.bulk_trap_distribution: neutral bulk defects are refused for dynamic-defect impedance" + ) + has_bulk = True + for raw_bd in layer.defects: + bd_map = raw_bd.to_mapping() + if str(bd_map.get("charge_transition", "")) == "neutral": + raise DynamicDefectImpedanceCapabilityError( + f"layers.{layer.id}.{bd_map['id']}: neutral bulk defects are refused for dynamic-defect impedance" + ) has_bulk = True has_interface = False @@ -171,6 +183,17 @@ def classify_dynamic_defect_capability( f"interfaces.{entry['id']}: compatibility SRV disagrees with microscopic capture" ) + if has_interface: + settings = prepared.to_mapping()["settings"] + if str(settings.get("interface_charge_closure", "off")) != "equilibrium_referenced": + raise DynamicDefectImpedanceCapabilityError( + "dynamic interface-defect impedance requires interface_charge_closure='equilibrium_referenced'" + ) + if not bool(settings.get("interface_charge_rebaseline_acknowledged", False)): + raise DynamicDefectImpedanceCapabilityError( + "dynamic interface-defect impedance requires interface_charge_rebaseline_acknowledged=True" + ) + ion_layers = _active_ion_layers(prepared) if len(ion_layers) > 1: raise DynamicDefectImpedanceCapabilityError( diff --git a/src/solarlab/experiments/dynamic_defect_transient.py b/src/solarlab/experiments/dynamic_defect_transient.py index 9fb4ae99..d7082145 100644 --- a/src/solarlab/experiments/dynamic_defect_transient.py +++ b/src/solarlab/experiments/dynamic_defect_transient.py @@ -758,6 +758,10 @@ def solve_interface_defect_transient( raise DynamicDefectTransientCapabilityError( "solve_interface_defect_transient requires equilibrium_referenced interface charge" ) + if not bool(settings.get("interface_charge_rebaseline_acknowledged", False)): + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_transient requires interface_charge_rebaseline_acknowledged=True" + ) try: compiled = compile_dynamic_defect_device_1d( @@ -809,6 +813,15 @@ def solve_bulk_defect_ion_transient( raise DynamicDefectTransientCapabilityError( "solve_bulk_defect_ion_transient excludes interface defects" ) + for ly in prepared.layers: + if ly.role == "substrate": + continue + for raw_bd in ly.defects: + bd_map = raw_bd.to_mapping() + if str(bd_map.get("charge_transition", "")) == "neutral": + raise DynamicDefectTransientCapabilityError( + f"layers.{ly.id}.{bd_map['id']}: charge-coupled bulk-ion transient rejects neutral transitions" + ) ion_layer = _single_ion_layer(prepared) try: compiled = compile_dynamic_defect_device_1d( @@ -853,6 +866,15 @@ def solve_interface_defect_ion_transient( raise DynamicDefectTransientCapabilityError( "solve_interface_defect_ion_transient requires at least one microscopic interface defect" ) + settings = prepared.to_mapping()["settings"] + if str(settings.get("interface_charge_closure", "off")) != "equilibrium_referenced": + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_ion_transient requires equilibrium_referenced interface charge" + ) + if not bool(settings.get("interface_charge_rebaseline_acknowledged", False)): + raise DynamicDefectTransientCapabilityError( + "solve_interface_defect_ion_transient requires interface_charge_rebaseline_acknowledged=True" + ) ion_layer = _single_ion_layer(prepared) try: compiled = compile_dynamic_defect_device_1d( diff --git a/src/solarlab/physics/interface_transport/two_sided.py b/src/solarlab/physics/interface_transport/two_sided.py index 6d5e6613..97ab2e08 100644 --- a/src/solarlab/physics/interface_transport/two_sided.py +++ b/src/solarlab/physics/interface_transport/two_sided.py @@ -231,6 +231,8 @@ class TwoSidedInterfaceQSSResult: normalized_residual: float evaluations: int converged: bool + bulk_flux_jacobian_qf: RealArray | None = None + bulk_flux_common_qf: RealArray | None = None @dataclass(frozen=True) @@ -258,6 +260,10 @@ class ChargedTwoSidedInterfaceQSSResult: normalized_carrier_residual: float evaluations: int converged: bool + bulk_flux_jacobian_qf: RealArray | None = None + bulk_flux_common_qf: RealArray | None = None + sheet_charge_jacobian_qf: RealArray | None = None + sheet_charge_common_qf: RealArray | None = None def _two_prod(a: float, b: float) -> tuple[float, float]: @@ -295,6 +301,48 @@ def _safe_scaled_density(bulk_density: float, shift: float) -> float: return math.exp(log_target) +def _stabilize_bulk_flux_sensitivity( + jac_raw: RealArray, + *, + d_bulk_u: RealArray, + j_u: RealArray, + d_cap_log: RealArray, + d_cap_total: RealArray, + d_cross_total: RealArray, +) -> RealArray: + """Eliminate stiff-reservoir IFT cancellation while preserving exact Kirchhoff sum. + + At a converged trace state ``bulk_L - cross - cap_L == 0`` and + ``bulk_R + cross - cap_R == 0``, so ``bulk_L + bulk_R == cap_L + cap_R`` + identically. Evaluating ``d_bulk_u @ du`` directly on a heavily doped side + amplifies float64 ``du`` rounding by ``|d_bulk_u| ~ 1e27``. Selecting the + series bottleneck among ``(left_sg, cross_te, right_sg)`` and recovering the + stiff side from exact conservation eliminates that amplification symmetrically. + """ + out = np.array(jac_raw, dtype=np.float64, copy=True) + for c_idx, row_l, row_r in ((0, _N_LEFT, _N_RIGHT), (1, _P_LEFT, _P_RIGHT)): + g_l = abs(float(d_bulk_u[row_l, row_l])) + g_r = abs(float(d_bulk_u[row_r, row_r])) + g_c_l = abs(float((d_bulk_u[row_l, row_l] - j_u[row_l, row_l]) - d_cap_log[row_l, row_l])) + g_c_r = abs(float((j_u[row_r, row_r] - d_bulk_u[row_r, row_r]) + d_cap_log[row_r, row_r])) + g_c = max(g_c_l, g_c_r) + cap_sum = d_cap_total[row_l] + d_cap_total[row_r] + if g_c < 0.5 * min(g_l, g_r): + out[row_l] = d_cross_total[c_idx] + d_cap_total[row_l] + out[row_r] = -d_cross_total[c_idx] + d_cap_total[row_r] + elif g_l < 0.5 * g_r: + out[row_l] = jac_raw[row_l] + out[row_r] = cap_sum - jac_raw[row_l] + elif g_r < 0.5 * g_l: + out[row_r] = jac_raw[row_r] + out[row_l] = cap_sum - jac_raw[row_r] + else: + err = 0.5 * ((jac_raw[row_l] + jac_raw[row_r]) - cap_sum) + out[row_l] = jac_raw[row_l] - err + out[row_r] = jac_raw[row_r] - err + return out + + def _trace_and_bulk_log_maps(thermal_voltage_V: float) -> tuple[RealArray, RealArray]: """Chain-rule maps ``∂log(state)/∂phi_t`` (4x2) and ``∂log(state)/∂bulk`` (4x6) at fixed ``u_delta``.""" inv_vt = 1.0 / float(thermal_voltage_V) @@ -319,6 +367,60 @@ def _trace_and_bulk_log_maps(thermal_voltage_V: float) -> tuple[RealArray, RealA return m_trace, m_bulk +_M_BULK_QF: RealArray = np.array( + [ + [0.0, 0.0, 1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float64, +) + +_QF_COMMON_MAP: RealArray = np.array( + [ + [0.0, 0.0], + [0.0, 0.0], + [1.0, 0.0], + [0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + ], + dtype=np.float64, +) + +_M_BULK_COMMON: RealArray = _M_BULK_QF @ _QF_COMMON_MAP + + +def _qf_transform_matrix(thermal_voltage_V: float) -> RealArray: + """Map ``(dphi_L, dphi_R, du_nL, du_pL, du_nR, du_pR)`` to bulk coordinates.""" + inv_vt = 1.0 / float(thermal_voltage_V) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0, 0.0, 0.0], + [inv_vt, 0.0, 1.0, 0.0, 0.0, 0.0], + [-inv_vt, 0.0, 0.0, 1.0, 0.0, 0.0], + [0.0, inv_vt, 0.0, 0.0, 1.0, 0.0], + [0.0, -inv_vt, 0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float64, + ) + + +def _carrier_j_coords_qf( + j_coords_u: RealArray, + d_bulk_coords_u: RealArray, + thermal_voltage_V: float, +) -> tuple[RealArray, RealArray]: + """Return ``(d_bulk_coords_qf, j_coords_qf)`` without ``m_bulk`` potential cancellation.""" + t_qf = _qf_transform_matrix(thermal_voltage_V) + d_bulk_qf = d_bulk_coords_u @ t_qf + j_qf = np.array(d_bulk_qf, dtype=np.float64, copy=True) + j_qf[:, 2:] += (j_coords_u - d_bulk_coords_u)[:, 2:] + return d_bulk_qf, j_qf + + def _electrostatic_seed_drops( geometry: TraceElectrostatics, bulk: TwoSidedBulkState, @@ -873,29 +975,87 @@ def scaled_jac(u_vec: RealArray) -> RealArray: d_trace_d_bulk[1, 0] = w_l d_trace_d_bulk[1, 1] = w_r + d_bulk_qf, j_coords_qf = _carrier_j_coords_qf( + j_coords_u, d_bulk_coords_u, physics.thermal_voltage_V + ) + d_bulk_com = d_bulk_qf @ _QF_COMMON_MAP j_bulk_total_u = j_coords_u + j_trace_u @ d_trace_d_bulk + j_qf_total_u = j_coords_qf + j_trace_u @ d_trace_d_bulk + j_com_total_u = j_qf_total_u @ _QF_COMMON_MAP ift_row = np.maximum(np.max(np.abs(j_u), axis=1), float(np.finfo(np.float64).tiny)) - du_d_bulk = _equilibrated_solve( + du_all_qss = _equilibrated_solve( j_u / ift_row[:, np.newaxis], - -(j_bulk_total_u / ift_row[:, np.newaxis]), - ) - bulk_flux_jac = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk + -np.column_stack((j_bulk_total_u, j_qf_total_u, j_com_total_u)) / ift_row[:, np.newaxis], + ) + du_d_bulk = du_all_qss[:, :6] + du_qf = du_all_qss[:, 6:12] + du_com = du_all_qss[:, 12:14] + bulk_flux_jac_raw = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk + bulk_flux_qf_raw = d_bulk_qf + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_qf + bulk_flux_com_raw = d_bulk_com + d_bulk_u @ du_com + m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) + d_log_state_d_bulk = m_bulk + m_trace @ d_trace_d_bulk + du_d_bulk + d_log_state_qf = _M_BULK_QF + m_trace @ d_trace_d_bulk + du_qf + d_log_state_com = _M_BULK_COMMON + du_com if trap is None: occupancy: float | None = None occ_jac: RealArray = np.zeros(6, dtype=np.float64) + d_cap_log_qss: RealArray = np.zeros((_STATE_SIZE, _STATE_SIZE), dtype=np.float64) + d_cap_tot_qss: RealArray = np.zeros((_STATE_SIZE, 6), dtype=np.float64) + d_cap_tot_qf: RealArray = np.zeros((_STATE_SIZE, 6), dtype=np.float64) + d_cap_tot_com: RealArray = np.zeros((_STATE_SIZE, 2), dtype=np.float64) else: - m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) - d_log_state_d_bulk = m_bulk + m_trace @ d_trace_d_bulk + du_d_bulk occupancy = trap.occupancy df_dlog = trap.d_occupancy_d_densities_m3 * state occ_jac = df_dlog @ d_log_state_d_bulk + d_cap_log_qss = trap.d_capture_d_densities_m_s * state[np.newaxis, :] + d_cap_tot_qss = d_cap_log_qss @ d_log_state_d_bulk + d_cap_tot_qf = d_cap_log_qss @ d_log_state_qf + d_cap_tot_com = d_cap_log_qss @ d_log_state_com + + d_rhs_qss = ( + (d_bulk_coords_u - j_coords_u) + + (d_bulk_trace_u - j_trace_u) @ d_trace_d_bulk + + (d_bulk_u - j_u) @ du_d_bulk + ) + d_rhs_qf = ( + (d_bulk_qf - j_coords_qf) + + (d_bulk_trace_u - j_trace_u) @ d_trace_d_bulk + + (d_bulk_u - j_u) @ du_qf + ) + d_rhs_com = (d_bulk_com - (j_coords_qf @ _QF_COMMON_MAP)) + (d_bulk_u - j_u) @ du_com + bulk_flux_jac = _stabilize_bulk_flux_sensitivity( + bulk_flux_jac_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_qss, + d_cap_total=d_cap_tot_qss, + d_cross_total=d_rhs_qss[:2] - d_cap_tot_qss[:2], + ) + bulk_flux_jac_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_qf_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_qss, + d_cap_total=d_cap_tot_qf, + d_cross_total=d_rhs_qf[:2] - d_cap_tot_qf[:2], + ) + bulk_flux_com_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_com_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_qss, + d_cap_total=d_cap_tot_com, + d_cross_total=d_rhs_com[:2] - d_cap_tot_com[:2], + ) converged = bool( (sol.success or best_norm <= residual_tolerance) and best_norm <= residual_tolerance and np.all(np.isfinite(du_d_bulk)) and np.all(np.isfinite(bulk_flux_jac)) + and np.all(np.isfinite(bulk_flux_jac_qf)) ) if fail_on_residual and not converged: raise RuntimeError( @@ -914,6 +1074,8 @@ def scaled_jac(u_vec: RealArray) -> RealArray: normalized_residual=best_norm, evaluations=eval_count, converged=converged, + bulk_flux_jacobian_qf=bulk_flux_jac_qf, + bulk_flux_common_qf=bulk_flux_com_qf, ) @@ -1206,22 +1368,89 @@ def scaled_jac(y_loc: RealArray) -> RealArray: norm_elec = float(np.max(norm_vec[:2])) norm_carrier = float(np.max(norm_vec[2:])) + d_sheet_d_log = trap.d_sheet_charge_d_densities_C_m * state + d_bulk_qf, j_carrier_qf = _carrier_j_coords_qf( + j_bulk_u[2:, :], d_bulk_coords_u, physics.thermal_voltage_V + ) + d_bulk_com = d_bulk_qf @ _QF_COMMON_MAP + j_bulk_qf: RealArray = np.zeros((6, 6), dtype=np.float64) + j_bulk_qf[1, 0] = -c_l + j_bulk_qf[1, 1] = -c_r + j_bulk_qf[1, 2:] = -d_sheet_d_log + j_bulk_qf[2:, :] = j_carrier_qf + j_bulk_com = j_bulk_qf @ _QF_COMMON_MAP + ift_row = np.maximum(np.max(np.abs(j_local_u), axis=1), float(np.finfo(np.float64).tiny)) - sensitivity_u = _equilibrated_solve( + sens_all = _equilibrated_solve( j_local_u / ift_row[:, np.newaxis], - -(j_bulk_u / ift_row[:, np.newaxis]), + -np.column_stack((j_bulk_u, j_bulk_qf, j_bulk_com)) / ift_row[:, np.newaxis], ) + sensitivity_u = sens_all[:, :6] + sens_qf = sens_all[:, 6:12] + sens_com = sens_all[:, 12:14] d_phi_t_d_bulk = sensitivity_u[:2, :] d_u_d_bulk = sensitivity_u[2:, :] - bulk_flux_jac = ( + d_phi_t_qf = sens_qf[:2, :] + d_u_qf = sens_qf[2:, :] + d_phi_t_com = sens_com[:2, :] + d_u_com = sens_com[2:, :] + bulk_flux_jac_raw = ( d_bulk_coords_u + d_bulk_trace_u @ d_phi_t_d_bulk + d_bulk_u @ d_u_d_bulk ) + bulk_flux_qf_raw = d_bulk_qf + d_bulk_trace_u @ d_phi_t_qf + d_bulk_u @ d_u_qf + bulk_flux_com_raw = d_bulk_com + d_bulk_trace_u @ d_phi_t_com + d_bulk_u @ d_u_com m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) d_log_state_d_bulk = m_bulk + m_trace @ d_phi_t_d_bulk + d_u_d_bulk - d_sheet_d_log = trap.d_sheet_charge_d_densities_C_m * state + d_log_state_qf = _M_BULK_QF + m_trace @ d_phi_t_qf + d_u_qf + d_log_state_com = _M_BULK_COMMON + m_trace @ d_phi_t_com + d_u_com + d_cap_log_ch = trap.d_capture_d_densities_m_s * state[np.newaxis, :] + d_cap_tot_ch = d_cap_log_ch @ d_log_state_d_bulk + d_cap_tot_qf = d_cap_log_ch @ d_log_state_qf + d_cap_tot_com = d_cap_log_ch @ d_log_state_com + d_rhs_ch = ( + (d_bulk_coords_u - j_bulk_u[2:, :]) + + (d_bulk_trace_u - j_local_u[2:, :2]) @ d_phi_t_d_bulk + + (d_bulk_u - j_local_u[2:, 2:]) @ d_u_d_bulk + ) + d_rhs_qf = ( + (d_bulk_qf - j_carrier_qf) + + (d_bulk_trace_u - j_local_u[2:, :2]) @ d_phi_t_qf + + (d_bulk_u - j_local_u[2:, 2:]) @ d_u_qf + ) + d_rhs_com = ( + (d_bulk_com - (j_carrier_qf @ _QF_COMMON_MAP)) + + (d_bulk_trace_u - j_local_u[2:, :2]) @ d_phi_t_com + + (d_bulk_u - j_local_u[2:, 2:]) @ d_u_com + ) + bulk_flux_jac = _stabilize_bulk_flux_sensitivity( + bulk_flux_jac_raw, + d_bulk_u=d_bulk_u, + j_u=j_local_u[2:, 2:], + d_cap_log=d_cap_log_ch, + d_cap_total=d_cap_tot_ch, + d_cross_total=d_rhs_ch[:2] - d_cap_tot_ch[:2], + ) + bulk_flux_jac_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_qf_raw, + d_bulk_u=d_bulk_u, + j_u=j_local_u[2:, 2:], + d_cap_log=d_cap_log_ch, + d_cap_total=d_cap_tot_qf, + d_cross_total=d_rhs_qf[:2] - d_cap_tot_qf[:2], + ) + bulk_flux_com_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_com_raw, + d_bulk_u=d_bulk_u, + j_u=j_local_u[2:, 2:], + d_cap_log=d_cap_log_ch, + d_cap_total=d_cap_tot_com, + d_cross_total=d_rhs_com[:2] - d_cap_tot_com[:2], + ) sheet_jac_bulk = d_sheet_d_log @ d_log_state_d_bulk + sheet_jac_qf = d_sheet_d_log @ d_log_state_qf + sheet_com_qf = d_sheet_d_log @ d_log_state_com d_occ_d_log = trap.d_occupancy_d_densities_m3 * state occ_jac_bulk = d_occ_d_log @ d_log_state_d_bulk @@ -1230,6 +1459,7 @@ def scaled_jac(y_loc: RealArray) -> RealArray: and max(norm_elec, norm_carrier) <= residual_tolerance and np.all(np.isfinite(sensitivity_u)) and np.all(np.isfinite(bulk_flux_jac)) + and np.all(np.isfinite(bulk_flux_jac_qf)) and np.all(np.isfinite(sheet_jac_bulk)) ) if fail_on_residual and not converged: @@ -1254,6 +1484,10 @@ def scaled_jac(y_loc: RealArray) -> RealArray: normalized_carrier_residual=norm_carrier, evaluations=eval_count, converged=converged, + bulk_flux_jacobian_qf=bulk_flux_jac_qf, + bulk_flux_common_qf=bulk_flux_com_qf, + sheet_charge_jacobian_qf=sheet_jac_qf, + sheet_charge_common_qf=sheet_com_qf, ) @@ -1287,6 +1521,10 @@ class FixedOccupancyTwoSidedResult: evaluations: int converged: bool one_minus_occupancy: float = 0.0 + bulk_flux_jacobian_qf: RealArray | None = None + bulk_flux_common_qf: RealArray | None = None + trap_storage_rate_jacobian_qf: RealArray | None = None + trap_storage_rate_common_qf: RealArray | None = None def _fixed_occupancy_balance_terms( @@ -1635,26 +1873,90 @@ def scaled_jac(u_vec: RealArray) -> RealArray: ) d_trace_df = np.array([d_sigma_df / c_sum, d_sigma_df / c_sum], dtype=np.float64) + d_bulk_qf, j_coords_qf = _carrier_j_coords_qf( + j_coords_u, d_bulk_coords_u, physics.thermal_voltage_V + ) + d_bulk_com = d_bulk_qf @ _QF_COMMON_MAP ift_row = np.maximum(np.max(np.abs(j_u), axis=1), float(np.finfo(np.float64).tiny)) rhs_bulk = -(j_coords_u + j_trace_u @ d_trace_d_bulk) rhs_f = -(j_trace_u @ d_trace_df - d_cap_df) + rhs_qf = -(j_coords_qf + j_trace_u @ d_trace_d_bulk) + rhs_com = rhs_qf @ _QF_COMMON_MAP du_all = _equilibrated_solve( j_u / ift_row[:, np.newaxis], - np.column_stack((rhs_bulk, rhs_f)) / ift_row[:, np.newaxis], + np.column_stack((rhs_bulk, rhs_f, rhs_qf, rhs_com)) / ift_row[:, np.newaxis], ) du_d_bulk = du_all[:, :6] du_df = du_all[:, 6] + du_qf = du_all[:, 7:13] + du_com = du_all[:, 13:15] - bulk_flux_jac = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk - bulk_flux_df = d_bulk_trace_u @ d_trace_df + d_bulk_u @ du_df + bulk_flux_jac_raw = d_bulk_coords_u + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_d_bulk + bulk_flux_df_raw = d_bulk_trace_u @ d_trace_df + d_bulk_u @ du_df + bulk_flux_qf_raw = d_bulk_qf + d_bulk_trace_u @ d_trace_d_bulk + d_bulk_u @ du_qf + bulk_flux_com_raw = d_bulk_com + d_bulk_u @ du_com m_trace, m_bulk = _trace_and_bulk_log_maps(physics.thermal_voltage_V) d_log_state_d_bulk = m_bulk + m_trace @ d_trace_d_bulk + du_d_bulk d_log_state_df = m_trace @ d_trace_df + du_df + d_log_state_qf = _M_BULK_QF + m_trace @ d_trace_d_bulk + du_qf + d_log_state_com = _M_BULK_COMMON + du_com vn = float(physics.surface_recombination_velocity_n_m_s) vp = float(physics.surface_recombination_velocity_p_m_s) n_l, p_l, n_r, p_r = (float(v) for v in state) + d_cap_log_fix = np.diag([vn * omf * n_l, vp * f * p_l, vn * omf * n_r, vp * f * p_r]) + d_cap_tot_bulk = d_cap_log_fix @ d_log_state_d_bulk + d_cap_tot_qf = d_cap_log_fix @ d_log_state_qf + d_cap_tot_com = d_cap_log_fix @ d_log_state_com + d_rhs_fix_bulk = ( + (d_bulk_coords_u - j_coords_u) + + (d_bulk_trace_u - j_trace_u) @ d_trace_d_bulk + + (d_bulk_u - j_u) @ du_d_bulk + ) + d_rhs_fix_qf = ( + (d_bulk_qf - j_coords_qf) + + (d_bulk_trace_u - j_trace_u) @ d_trace_d_bulk + + (d_bulk_u - j_u) @ du_qf + ) + d_rhs_fix_com = (d_bulk_com - (j_coords_qf @ _QF_COMMON_MAP)) + (d_bulk_u - j_u) @ du_com + bulk_flux_jac = _stabilize_bulk_flux_sensitivity( + bulk_flux_jac_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_fix, + d_cap_total=d_cap_tot_bulk, + d_cross_total=d_rhs_fix_bulk[:2] - d_cap_tot_bulk[:2], + ) + bulk_flux_jac_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_qf_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_fix, + d_cap_total=d_cap_tot_qf, + d_cross_total=d_rhs_fix_qf[:2] - d_cap_tot_qf[:2], + ) + bulk_flux_com_qf = _stabilize_bulk_flux_sensitivity( + bulk_flux_com_raw, + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_fix, + d_cap_total=d_cap_tot_com, + d_cross_total=d_rhs_fix_com[:2] - d_cap_tot_com[:2], + ) + d_cap_df_log_part = d_cap_log_fix @ d_log_state_df + d_cap_tot_df = (d_cap_df_log_part + d_cap_df)[:, np.newaxis] + d_rhs_fix_df = ((d_bulk_trace_u - j_trace_u) @ d_trace_df + (d_bulk_u - j_u) @ du_df)[ + :, np.newaxis + ] + bulk_flux_df = _stabilize_bulk_flux_sensitivity( + bulk_flux_df_raw[:, np.newaxis], + d_bulk_u=d_bulk_u, + j_u=j_u, + d_cap_log=d_cap_log_fix, + d_cap_total=d_cap_tot_df, + d_cross_total=d_rhs_fix_df[:2] - d_cap_df_log_part[:2, np.newaxis], + )[:, 0] filled = vn * (n_l + n_r) + vp * (physics.p1_left_m3 + physics.p1_right_m3) empty = vn * (physics.n1_left_m3 + physics.n1_right_m3) + vp * (p_l + p_r) denom = filled + empty @@ -1667,12 +1969,15 @@ def scaled_jac(u_vec: RealArray) -> RealArray: dtype=np.float64, ) sr_jac_bulk = d_sr_d_log @ d_log_state_d_bulk + sr_jac_qf = d_sr_d_log @ d_log_state_qf + sr_com_qf = d_sr_d_log @ d_log_state_com sr_df = float(-denom + d_sr_d_log @ d_log_state_df) converged = bool( (sol.success or best_norm <= residual_tolerance) and best_norm <= residual_tolerance and np.all(np.isfinite(bulk_flux_jac)) + and np.all(np.isfinite(bulk_flux_jac_qf)) and np.all(np.isfinite(bulk_flux_df)) and np.all(np.isfinite(sr_jac_bulk)) and math.isfinite(sr_df) @@ -1703,4 +2008,8 @@ def scaled_jac(u_vec: RealArray) -> RealArray: evaluations=eval_count, converged=converged, one_minus_occupancy=float(omf), + bulk_flux_jacobian_qf=bulk_flux_jac_qf, + bulk_flux_common_qf=bulk_flux_com_qf, + trap_storage_rate_jacobian_qf=sr_jac_qf, + trap_storage_rate_common_qf=sr_com_qf, ) diff --git a/tests/unit/equations/test_defect_ion_coupled_ac.py b/tests/unit/equations/test_defect_ion_coupled_ac.py index 46d82004..500b85dd 100644 --- a/tests/unit/equations/test_defect_ion_coupled_ac.py +++ b/tests/unit/equations/test_defect_ion_coupled_ac.py @@ -20,6 +20,7 @@ from solarlab.equations.assembly.dynamic_defects_1d import ( AssembledDynamicDefect1DProblem, DynamicDefectSmallSignal1D, + DynamicDefectSteadyOptions, DynamicDefectStorage1D, dynamic_defect_system_1d, solve_dynamic_defect_steady_1d, @@ -514,3 +515,122 @@ def test_compile_capability_refusals(defaults: DefaultCatalog) -> None: prep_mv = _resolve(mv_doc, defaults) with pytest.raises(CapabilityError, match="multivalent"): compile_dynamic_defect_device_1d(prep_mv, dynamic_bulk_defects=True) + + # 4. Neutral bulk defect refused for dynamic storage DOFs, allowed as stationary QSS: + neutral_doc = _three_layer_doc(with_bulk=True, with_iface=False, with_ions=False) + neutral_doc["layers"][1]["bulk_defects"][0]["charge_transition"] = "neutral" + neutral_doc["layers"][1]["bulk_defects"][0]["neutral_reference"] = "all_occupancies" + prep_neutral = _resolve(neutral_doc, defaults) + with pytest.raises(CapabilityError, match="neutral"): + compile_dynamic_defect_device_1d(prep_neutral, dynamic_bulk_defects=True) + stat_neutral = compile_dynamic_defect_device_1d(prep_neutral, dynamic_bulk_defects=False) + assert stat_neutral.dynamic_bulk_traps is None + st_neutral = solve_dynamic_defect_steady_1d(stat_neutral, voltage_V=0.2, generation_scale=0.0) + assert st_neutral.converged + + # 5. Uncharged interface defect (interface_charge_closure='off') refused for dynamic storage DOFs: + off_iface_doc = _three_layer_doc(with_bulk=False, with_iface=True, with_ions=False) + off_iface_doc["settings"]["interface_charge_closure"] = "off" + off_iface_doc["settings"]["interface_charge_rebaseline_acknowledged"] = False + prep_off_iface = _resolve(off_iface_doc, defaults) + with pytest.raises(CapabilityError, match="equilibrium_referenced"): + compile_dynamic_defect_device_1d(prep_off_iface, dynamic_interface_defects=True) + stat_off_iface = compile_dynamic_defect_device_1d( + prep_off_iface, dynamic_interface_defects=False + ) + assert stat_off_iface.dynamic_interface_traps == () + + +def _reverse_to_nip_doc(doc: dict[str, Any]) -> dict[str, Any]: + rev = copy.deepcopy(doc) + rev["id"] = f"nip_{doc['id']}" + rev["layers"] = list(reversed(rev["layers"])) + revs: list[dict[str, Any]] = [] + for iface in reversed(rev["interfaces"]): + ni = copy.deepcopy(iface) + ni["left"], ni["right"] = iface["right"], iface["left"] + revs.append(ni) + rev["interfaces"] = revs + return rev + + +@pytest.mark.parametrize( + ("with_bulk", "with_iface", "with_ions"), + [ + (True, False, False), + (False, True, False), + (True, True, True), + ], +) +def test_dark_equilibrium_zero_volt_pin_and_nip_ac_passivity_and_fd_slope( + defaults: DefaultCatalog, + with_bulk: bool, + with_iface: bool, + with_ions: bool, +) -> None: + """Verify dark 0 V passivity, 0 Hz FD slope, and Maxwell conservation on both p-i-n and n-i-p.""" + freqs = np.array([0.0, 1.0e-2, 1.0, 1.0e3, 1.0e5]) + dv = 1.0e-5 + base_doc = _three_layer_doc( + with_bulk=with_bulk, with_iface=with_iface, with_ions=with_ions + ) + y0_by_polarity: dict[str, float] = {} + + for label, expected_pol, doc in ( + ("pin", 1.0, base_doc), + ("nip", -1.0, _reverse_to_nip_doc(base_doc)), + ): + prep = _resolve(doc, defaults) + ion_kw: dict[str, Any] = ( + {"ion_domain_layer": "abs", "ion_domain_endpoints": ("blocking", "blocking")} + if with_ions + else {} + ) + dev = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=8, + dynamic_bulk_defects=with_bulk, + dynamic_interface_defects=with_iface, + **ion_kw, + ) + assert dev.voltage_polarity == expected_pol + st0 = solve_dynamic_defect_steady_1d( + dev, + voltage_V=0.0, + generation_scale=0.0, + options=DynamicDefectSteadyOptions(residual_tolerance=1.0e-13), + ) + ac = DynamicDefectSmallSignal1D(dev, st0.state) + sweep = ac.solve_sweep(freqs) + + assert np.all(sweep.admittance_density_S_m2.real > 0.0) + assert sweep.admittance_density_S_m2[0].imag == pytest.approx(0.0, abs=1.0e-18) + assert float(np.max(sweep.maxwell_spread_A_m2_V[:2])) <= 1.0e-12 + assert float(np.max(sweep.maxwell_spread_A_m2_V)) <= 1.0e-9 + + st_p = solve_dynamic_defect_steady_1d( + dev, + voltage_V=+dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st0.state.u, 0.0, +dv), + options=DynamicDefectSteadyOptions(residual_tolerance=1.0e-13), + ) + st_m = solve_dynamic_defect_steady_1d( + dev, + voltage_V=-dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st0.state.u, 0.0, -dv), + options=DynamicDefectSteadyOptions(residual_tolerance=1.0e-13), + ) + g_fd = (st_p.terminal_current_density_A_m2 - st_m.terminal_current_density_A_m2) / ( + 2.0 * dv + ) + y0 = float(sweep.admittance_density_S_m2[0].real) + assert y0 == pytest.approx(g_fd, rel=1.0e-5) + y0_by_polarity[label] = y0 + + if not with_bulk or with_ions: + # Note: _three_layer_doc has symmetric layer thicknesses; when bulk trap is symmetric + # or interface-only, check mirror consistency on the interface-only case: + if not with_bulk and with_iface: + assert y0_by_polarity["pin"] == pytest.approx(y0_by_polarity["nip"], rel=1.0e-5) diff --git a/tests/unit/experiments/test_dynamic_defect_experiments.py b/tests/unit/experiments/test_dynamic_defect_experiments.py index 4937fdc3..fd44422a 100644 --- a/tests/unit/experiments/test_dynamic_defect_experiments.py +++ b/tests/unit/experiments/test_dynamic_defect_experiments.py @@ -240,6 +240,19 @@ def _pin_doc( } +def _reverse_to_nip(doc: dict[str, Any]) -> dict[str, Any]: + rev = copy.deepcopy(doc) + rev["id"] = f"nip_{doc['id']}" + rev["layers"] = list(reversed(rev["layers"])) + revs: list[dict[str, Any]] = [] + for iface in reversed(rev["interfaces"]): + ni = copy.deepcopy(iface) + ni["left"], ni["right"] = iface["right"], iface["left"] + revs.append(ni) + rev["interfaces"] = revs + return rev + + def _two_layer_v1_transient_doc() -> dict[str, Any]: return { "schema_version": "solarlab.device-preparation.v1", @@ -342,7 +355,7 @@ def test_capacitance_frequency_debye_analytics_masking_and_passivity( generation_scale=0.0, ) - # End-to-end device C-f run: + # End-to-end device C-f run (both p-i-n and reversed n-i-p across bulk & interface traps): prep = _resolve(_pin_doc(with_bulk=True), defaults) dev_cf = run_defect_capacitance_frequency( prep, np.array([1.0, 100.0, 1.0e5]), intervals_per_layer=6 @@ -350,6 +363,20 @@ def test_capacitance_frequency_debye_analytics_masking_and_passivity( assert dev_cf.dark_equilibrium_passive is True assert np.all(dev_cf.capacitance_accepted) + for nip_doc in ( + _reverse_to_nip(_pin_doc(with_bulk=True)), + _reverse_to_nip(_pin_doc(with_iface=True)), + ): + nip_cf = run_defect_capacitance_frequency( + _resolve(nip_doc, defaults), + np.array([1.0e-1, 10.0, 1.0e4]), + voltage_V=0.0, + generation_scale=0.0, + intervals_per_layer=6, + ) + assert nip_cf.dark_equilibrium_passive is True + assert np.all(nip_cf.capacitance_accepted) + def test_dynamic_defect_and_combined_ion_impedance_capabilities_and_execution( defaults: DefaultCatalog, @@ -392,6 +419,29 @@ def test_dynamic_defect_and_combined_ion_impedance_capabilities_and_execution( with pytest.raises(DynamicDefectImpedanceCapabilityError, match="requires an explicit"): classify_dynamic_defect_capability(_resolve(_pin_doc(), defaults)) + # Refusal: neutral bulk defect has zero electrostatic coupling so cannot carry dynamic AC DOFs: + prep_neutral_bulk = _resolve(_pin_doc(with_bulk=True, bulk_transition="neutral"), defaults) + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="neutral"): + classify_dynamic_defect_capability(prep_neutral_bulk) + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="neutral"): + solve_bulk_defect_impedance(prep_neutral_bulk, [1.0, 100.0]) + + # Refusal: interface_charge_closure='off' refused across dynamic interface impedance & joint AC: + off_iface_doc = _pin_doc(with_iface=True) + off_iface_doc["settings"]["interface_charge_closure"] = "off" + off_iface_doc["settings"]["interface_charge_rebaseline_acknowledged"] = False + prep_off_iface = _resolve(off_iface_doc, defaults) + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="equilibrium_referenced"): + classify_dynamic_defect_capability(prep_off_iface) + with pytest.raises(DynamicDefectImpedanceCapabilityError, match="equilibrium_referenced"): + solve_interface_defect_impedance(prep_off_iface, [1.0, 100.0]) + + off_joint_doc = _pin_doc(with_iface=True, with_ions=True) + off_joint_doc["settings"]["interface_charge_closure"] = "off" + off_joint_doc["settings"]["interface_charge_rebaseline_acknowledged"] = False + with pytest.raises(DefectIonImpedanceCapabilityError, match="equilibrium_referenced"): + solve_defect_ion_impedance(_resolve(off_joint_doc, defaults), [1.0, 100.0]) + # Refusal: solve_defect_ion_impedance on ion-free device: prep_bulk = _resolve(_pin_doc(with_bulk=True), defaults) with pytest.raises(DefectIonImpedanceCapabilityError, match="active mobile ions"): @@ -438,6 +488,39 @@ def test_dynamic_defect_and_combined_ion_impedance_capabilities_and_execution( == res_joint.frozen_ions_and_traps.working_state_digest ) assert res_joint.maximum_ion_inventory_relative_per_V <= 1.0e-12 + for sw in (res_joint.coupled, res_joint.frozen_ions): + assert np.all(sw.maxwell_spread_A_m2_V <= 1.0e-11 * np.abs(sw.admittance_density_S_m2)) + assert np.all(sw.maxwell_spread_A_m2_V[:3] <= 1.0e-11) + assert res_joint.maximum_maxwell_spread_A_m2_V == max( + float(np.max(res_joint.coupled.maxwell_spread_A_m2_V)), + float(np.max(res_joint.frozen_ions.maxwell_spread_A_m2_V)), + ) + + # Dark 0 V reversed n-i-p impedance FD slope & Maxwell spread regression check: + nip_freqs = np.array([1.0e-2, 1.0, 1.0e3, 1.0e5]) + res_nip_bulk = solve_bulk_defect_impedance( + _resolve(_reverse_to_nip(_pin_doc(with_bulk=True)), defaults), + nip_freqs, + voltage_V=0.0, + generation_scale=0.0, + options=DynamicDefectImpedanceOptions(intervals_per_layer=8, verify_zero_hz_fd=True), + ) + assert res_nip_bulk.zero_hz_fd_relative_error is not None + assert res_nip_bulk.zero_hz_fd_relative_error <= 1.0e-5 + assert np.all(res_nip_bulk.admittance_density_S_m2.real > 0.0) + assert float(np.max(res_nip_bulk.ac_sweep.maxwell_spread_A_m2_V)) <= 1.0e-9 + + res_nip_iface = solve_interface_defect_impedance( + _resolve(_reverse_to_nip(_pin_doc(with_iface=True)), defaults), + nip_freqs, + voltage_V=0.0, + generation_scale=0.0, + options=DynamicDefectImpedanceOptions(intervals_per_layer=8, verify_zero_hz_fd=True), + ) + assert res_nip_iface.zero_hz_fd_relative_error is not None + assert res_nip_iface.zero_hz_fd_relative_error <= 1.0e-5 + assert np.all(res_nip_iface.admittance_density_S_m2.real > 0.0) + assert float(np.max(res_nip_iface.ac_sweep.maxwell_spread_A_m2_V)) <= 1.0e-9 def test_dynamic_defect_transients_and_narrow_gate_refusals( @@ -484,13 +567,32 @@ def test_dynamic_defect_transients_and_narrow_gate_refusals( assert tr_v1.maximum_ion_inventory_relative_drift <= 1.0e-12 assert tr_v1.interface_trap_occupancy.shape == (4, 1) - # D6-E1 bulk transient + neutral/Gaussian refusals: + # D6-E1 bulk transient + neutral/Gaussian refusals (both ion-free and ion-coupled): with pytest.raises(DynamicDefectTransientCapabilityError, match="neutral"): solve_bulk_defect_transient( _resolve(_pin_doc(with_bulk=True, bulk_transition="neutral"), defaults), times, volts, ) + with pytest.raises(DynamicDefectTransientCapabilityError, match="neutral"): + solve_bulk_defect_ion_transient( + _resolve( + _pin_doc(with_bulk=True, bulk_transition="neutral", with_ions=True), defaults + ), + times, + volts, + ) + off_tr_iface = _pin_doc(with_iface=True) + off_tr_iface["settings"]["interface_charge_closure"] = "off" + off_tr_iface["settings"]["interface_charge_rebaseline_acknowledged"] = False + with pytest.raises(DynamicDefectTransientCapabilityError, match="equilibrium_referenced"): + solve_interface_defect_transient(_resolve(off_tr_iface, defaults), times, volts) + + off_tr_iface_ion = _pin_doc(with_iface=True, with_ions=True) + off_tr_iface_ion["settings"]["interface_charge_closure"] = "off" + off_tr_iface_ion["settings"]["interface_charge_rebaseline_acknowledged"] = False + with pytest.raises(DynamicDefectTransientCapabilityError, match="equilibrium_referenced"): + solve_interface_defect_ion_transient(_resolve(off_tr_iface_ion, defaults), times, volts) with pytest.raises(DynamicDefectTransientCapabilityError, match="single_level"): solve_bulk_defect_transient( _resolve(_pin_doc(with_bulk=True, bulk_kind="gaussian"), defaults), From 582f019ef5743d43546219590a5ae094ca300594 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sun, 15 Nov 2026 21:25:24 +0800 Subject: [PATCH 17/46] fix(dynamic-defects): selective-contact exchange lookup/sign and Newton step guards (#128) - Look up electronic contact exchanges via (ELECTRON/HOLE, side) and preserve CarrierExchange's +x outward_normal sign on both contacts in steady DC and BDF step accounting (dynamic_defects_1d.py). - Require at least one Newton step for nonzero initial residuals and tighten post-step residual fallback in _damped_newton_solve and _solve_bdf_step_newton so doped selective-contact stacks converge to step tolerance before exit. - Add selective (S_n, S_p) and blocking contact regression tests on both p-i-n and n-i-p orientations across DC, dark 0 V FD impedance, and BDF2 transient. --- .../equations/assembly/dynamic_defects_1d.py | 18 +++-- .../experiments/dynamic_defect_transient.py | 9 ++- .../equations/test_defect_ion_coupled_ac.py | 72 ++++++++++++++++++ .../test_dynamic_defect_experiments.py | 73 +++++++++++++++++++ 4 files changed, 163 insertions(+), 9 deletions(-) diff --git a/src/solarlab/equations/assembly/dynamic_defects_1d.py b/src/solarlab/equations/assembly/dynamic_defects_1d.py index 04146f7c..32e8b418 100644 --- a/src/solarlab/equations/assembly/dynamic_defects_1d.py +++ b/src/solarlab/equations/assembly/dynamic_defects_1d.py @@ -1667,13 +1667,14 @@ def dc_current_density_A_m2(self, u: ArrayLike) -> Vector: if ch.kind == "fixed_reservoir": exch = float(c_flux[face]) + orient * float(w[node] * src[node]) else: - exch_term = self.binding.electronic.exchanges[(carrier, side)] + block = ELECTRON if carrier == "n" else HOLE + exch_term = self.binding.electronic.exchanges[(block, side)] offset = N if carrier == "n" else 2 * N raw_exch, _ = exch_term.exchange( float(values[node]), float(values[offset + node]), self.voltage_V ) - # CarrierExchange returns outward particle flux; orient along +x: - exch = -raw_exch if side == "left" else raw_exch + # CarrierExchange.exchange already multiplies by outward_normal (+x oriented): + exch = raw_exch j_term += q_sign * exch terminals.append(j_term) @@ -1849,12 +1850,13 @@ def dynamic_defect_step_accounting(step: BDFStep, u: ArrayLike) -> dict[str, Any if ch.kind == "fixed_reservoir": exch = float(c_flux[face]) + orient * float(w[node] * src[node] - dstorage_dt[node]) else: - exch_term = prob.binding.electronic.exchanges[(carrier, side)] + block = ELECTRON if carrier == "n" else HOLE + exch_term = prob.binding.electronic.exchanges[(block, side)] offset = N if carrier == "n" else 2 * N raw_exch, _ = exch_term.exchange( float(values[node]), float(values[offset + node]), prob.voltage_V ) - exch = -raw_exch if side == "left" else raw_exch + exch = raw_exch j_term += q_sign * exch terminals.append(j_term) @@ -1945,8 +1947,7 @@ def _damped_newton_solve( f_scaled = row_scale * F res_norm = float(np.max(np.abs(f_scaled))) if res_norm <= options.residual_tolerance and ( - step_norm <= options.step_tolerance - or res_norm <= 1.0e-4 * options.residual_tolerance + step_norm <= options.step_tolerance or res_norm == 0.0 ): return u, True, iteration - 1, res_norm, (0.0 if iteration == 1 else step_norm) @@ -2004,7 +2005,8 @@ def _damped_newton_solve( rs = np.where(rm > 0.0, 1.0 / rm, 1.0) res_norm = float(np.max(np.abs(rs * sys_end.F))) if res_norm <= options.residual_tolerance and ( - step_norm <= options.step_tolerance or res_norm <= 1.0e-2 * options.residual_tolerance + step_norm <= options.step_tolerance + or (iteration >= 8 and res_norm <= 1.0e-4 * options.residual_tolerance) ): return u, True, iteration, res_norm, step_norm diff --git a/src/solarlab/experiments/dynamic_defect_transient.py b/src/solarlab/experiments/dynamic_defect_transient.py index d7082145..39df1429 100644 --- a/src/solarlab/experiments/dynamic_defect_transient.py +++ b/src/solarlab/experiments/dynamic_defect_transient.py @@ -302,6 +302,7 @@ def _solve_bdf_step_newton( u[0] = phi_l u[N - 1] = phi_r + step_norm = math.inf for iteration in range(max_iterations + 1): try: f = np.asarray(step.residual(u), dtype=np.float64) @@ -313,7 +314,12 @@ def _solve_bdf_step_newton( row_max = np.asarray(np.abs(jac).max(axis=1).todense()).ravel() row_scale = np.where(row_max > 0.0, 1.0 / row_max, 1.0) fs = row_scale * f - if float(np.max(np.abs(fs))) <= tolerance: + res_norm = float(np.max(np.abs(fs))) + if res_norm <= tolerance and ( + step_norm <= 1.0e-9 + or res_norm == 0.0 + or (iteration >= 8 and res_norm <= 1.0e-5 * tolerance) + ): return u, True if iteration == max_iterations: break @@ -346,6 +352,7 @@ def _solve_bdf_step_newton( if np.all(np.isfinite(f_try)): m_try = float(np.linalg.norm(row_scale * f_try)) if m_try <= (1.0 - 1.0e-4 * alpha) * merit or m_try <= tolerance: + step_norm = float(np.max(np.abs(u_try - u))) u = u_try accepted = True break diff --git a/tests/unit/equations/test_defect_ion_coupled_ac.py b/tests/unit/equations/test_defect_ion_coupled_ac.py index 500b85dd..e25eba4f 100644 --- a/tests/unit/equations/test_defect_ion_coupled_ac.py +++ b/tests/unit/equations/test_defect_ion_coupled_ac.py @@ -551,6 +551,14 @@ def _reverse_to_nip_doc(doc: dict[str, Any]) -> dict[str, Any]: ni["left"], ni["right"] = iface["right"], iface["left"] revs.append(ni) rev["interfaces"] = revs + if "contacts" in doc: + rev_contacts: list[dict[str, Any]] = [] + for contact in reversed(doc["contacts"]): + nc = copy.deepcopy(contact) + nc["side"] = "right" if contact["side"] == "left" else "left" + nc["id"] = f"nip_{contact['id']}" + rev_contacts.append(nc) + rev["contacts"] = rev_contacts return rev @@ -634,3 +642,67 @@ def test_dark_equilibrium_zero_volt_pin_and_nip_ac_passivity_and_fd_slope( # or interface-only, check mirror consistency on the interface-only case: if not with_bulk and with_iface: assert y0_by_polarity["pin"] == pytest.approx(y0_by_polarity["nip"], rel=1.0e-5) + + +@pytest.mark.parametrize( + ("with_bulk", "with_iface", "minority_velocity"), + [ + (True, False, 1.0e-2), + (False, True, 1.0e-2), + (True, False, 0.0), + ], +) +def test_selective_and_blocking_contacts_dc_ac_pin_and_nip( + defaults: DefaultCatalog, + with_bulk: bool, + with_iface: bool, + minority_velocity: float, +) -> None: + """Selective (S_n, S_p) and minority-blocking contacts preserve DC sign/conservation and dark 0 V AC FD.""" + base_doc = _three_layer_doc(with_bulk=with_bulk, with_iface=with_iface, with_ions=False) + base_doc["contacts"] = [ + {"id": "c_left", "side": "left", "layer": "htl", "S_n": minority_velocity, "S_p": 1.0e5}, + {"id": "c_right", "side": "right", "layer": "etl", "S_n": 1.0e5, "S_p": minority_velocity}, + ] + freqs = np.array([0.0, 1.0e-2, 10.0, 1.0e4]) + dv = 1.0e-5 + + for expected_pol, doc in ((1.0, base_doc), (-1.0, _reverse_to_nip_doc(base_doc))): + prep = _resolve(doc, defaults) + dev = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=6, + dynamic_bulk_defects=with_bulk, + dynamic_interface_defects=with_iface, + ) + assert dev.voltage_polarity == expected_pol + + st_fwd = solve_dynamic_defect_steady_1d(dev, voltage_V=0.60, generation_scale=0.0) + assert st_fwd.terminal_current_density_A_m2 > 0.0 + assert st_fwd.maxwell_spread_A_m2 <= 1.0e-10 + + st_rev = solve_dynamic_defect_steady_1d(dev, voltage_V=-0.25, generation_scale=0.0) + assert st_rev.terminal_current_density_A_m2 < 0.0 + assert st_rev.maxwell_spread_A_m2 <= 1.0e-10 + + st0 = solve_dynamic_defect_steady_1d(dev, voltage_V=0.0, generation_scale=0.0) + sweep = DynamicDefectSmallSignal1D(dev, st0.state).solve_sweep(freqs) + assert np.all(sweep.admittance_density_S_m2.real > 0.0) + assert float(np.max(sweep.maxwell_spread_A_m2_V)) <= 1.0e-10 + + st_p = solve_dynamic_defect_steady_1d( + dev, + voltage_V=+dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st0.state.u, 0.0, +dv), + ) + st_m = solve_dynamic_defect_steady_1d( + dev, + voltage_V=-dv, + generation_scale=0.0, + initial_u=dev.rebase_coordinates(st0.state.u, 0.0, -dv), + ) + g_fd = (st_p.terminal_current_density_A_m2 - st_m.terminal_current_density_A_m2) / ( + 2.0 * dv + ) + assert float(sweep.admittance_density_S_m2[0].real) == pytest.approx(g_fd, rel=1.0e-5) diff --git a/tests/unit/experiments/test_dynamic_defect_experiments.py b/tests/unit/experiments/test_dynamic_defect_experiments.py index fd44422a..266ccaac 100644 --- a/tests/unit/experiments/test_dynamic_defect_experiments.py +++ b/tests/unit/experiments/test_dynamic_defect_experiments.py @@ -14,10 +14,12 @@ from solarlab.config.legacy_defaults import read_legacy_default_catalog from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_dynamic_defect_1d import compile_dynamic_defect_device_1d from solarlab.device.defaults import DefaultCatalog from solarlab.device.defects import MetastablePreparationInput from solarlab.device.inputs import DeviceInput from solarlab.device.resolved import PreparedDevice +from solarlab.equations.assembly.dynamic_defects_1d import solve_dynamic_defect_steady_1d from solarlab.experiments.capacitance_frequency import ( DefectCFError, DefectCFOptions, @@ -34,6 +36,7 @@ DynamicDefectImpedanceOptions, classify_dynamic_defect_capability, solve_bulk_defect_impedance, + solve_dynamic_defect_impedance, solve_interface_defect_impedance, ) from solarlab.experiments.dynamic_defect_transient import ( @@ -250,6 +253,14 @@ def _reverse_to_nip(doc: dict[str, Any]) -> dict[str, Any]: ni["left"], ni["right"] = iface["right"], iface["left"] revs.append(ni) rev["interfaces"] = revs + if "contacts" in doc: + rev_contacts: list[dict[str, Any]] = [] + for contact in reversed(doc["contacts"]): + nc = copy.deepcopy(contact) + nc["side"] = "right" if contact["side"] == "left" else "left" + nc["id"] = f"nip_{contact['id']}" + rev_contacts.append(nc) + rev["contacts"] = rev_contacts return rev @@ -762,3 +773,65 @@ def test_metastable_preparation_frozen_jv_and_operator_split_transient( assert tr.scientific_qualification is False assert tr.certificate.passed is True assert tr.certificate.maximum_charge_transfer_relative_error <= 1.0e-10 + + +@pytest.mark.parametrize( + ("with_bulk", "with_iface"), + [ + (True, False), + (False, True), + ], +) +def test_selective_contacts_pin_and_nip_dc_impedance_and_transient( + defaults: DefaultCatalog, + with_bulk: bool, + with_iface: bool, +) -> None: + """Selective (S_n, S_p) p-i-n and n-i-p stacks pass DC sign/spread, dark 0 V FD impedance, and transient conservation.""" + pin_doc = _pin_doc(with_bulk=with_bulk, with_iface=with_iface) + pin_doc["contacts"] = [ + {"id": "c_left", "side": "left", "layer": "htl", "S_n": 1.0e-2, "S_p": 1.0e5}, + {"id": "c_right", "side": "right", "layer": "etl", "S_n": 1.0e5, "S_p": 1.0e-2}, + ] + freqs = np.array([1.0e-2, 10.0, 1.0e4]) + times = np.array([0.0, 1.0e-6, 1.0e-4, 1.0e-2]) + volts = np.array([0.0, 0.45, 0.45, 0.0]) + + for expected_pol, doc in ((1.0, pin_doc), (-1.0, _reverse_to_nip(pin_doc))): + prep = _resolve(doc, defaults) + comp = compile_dynamic_defect_device_1d( + prep, + intervals_per_layer=6, + dynamic_bulk_defects=with_bulk, + dynamic_interface_defects=with_iface, + ) + assert comp.voltage_polarity == expected_pol + + st_fwd = solve_dynamic_defect_steady_1d(comp, voltage_V=0.60, generation_scale=0.0) + assert st_fwd.terminal_current_density_A_m2 > 0.0 + assert st_fwd.maxwell_spread_A_m2 <= 1.0e-10 + + st_rev = solve_dynamic_defect_steady_1d(comp, voltage_V=-0.25, generation_scale=0.0) + assert st_rev.terminal_current_density_A_m2 < 0.0 + assert st_rev.maxwell_spread_A_m2 <= 1.0e-10 + + imp = solve_dynamic_defect_impedance( + prep, + freqs, + voltage_V=0.0, + generation_scale=0.0, + options=DynamicDefectImpedanceOptions(intervals_per_layer=6, verify_zero_hz_fd=True), + ) + assert imp.zero_hz_fd_relative_error is not None + assert imp.zero_hz_fd_relative_error <= 1.0e-5 + assert np.all(imp.admittance_density_S_m2.real > 0.0) + assert float(np.max(imp.ac_sweep.maxwell_spread_A_m2_V)) <= 1.0e-10 + + tr_fn = solve_bulk_defect_transient if with_bulk else solve_interface_defect_transient + tr = tr_fn( + prep, + times, + volts, + options=DynamicDefectTransientOptions(intervals_per_layer=6, bdf_order=2), + ) + assert tr.maximum_maxwell_spread_A_m2 <= 1.0e-9 From ae6c5aee899abae29bbc560fb28de24ba5301731 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Mon, 16 Nov 2026 10:43:31 +0800 Subject: [PATCH 18/46] M: re-pin wave2 baseline BDF allowlist, legacy consumer inventory, and JV hint authority --- .../RefactorTransitionBoundariesV1.json | 1 + src/solarlab/config/legacy_fields.py | 2 +- src/solarlab/equations/time_method.py | 20 ++++----- .../fixtures/bdf_readiness/allowlist.json | 44 +++++++++---------- .../test_legacy_consumer_registration.py | 4 +- .../solvers/time/test_time_method_axis.py | 2 +- 6 files changed, 37 insertions(+), 36 deletions(-) diff --git a/reproducibility/RefactorTransitionBoundariesV1.json b/reproducibility/RefactorTransitionBoundariesV1.json index 01c4ed29..550dc4c4 100644 --- a/reproducibility/RefactorTransitionBoundariesV1.json +++ b/reproducibility/RefactorTransitionBoundariesV1.json @@ -183,6 +183,7 @@ "scripts/benchmarks/coupled_device_prototype.py", "scripts/benchmarks/diagnose_r1_saved_failure.py", "scripts/benchmarks/g2_compare.py", + "scripts/benchmarks/g2_reference_be.py", "scripts/benchmarks/hysteresis_qualification.py", "scripts/benchmarks/hysteresis_reference.py", "scripts/benchmarks/interval_observation.py", diff --git a/src/solarlab/config/legacy_fields.py b/src/solarlab/config/legacy_fields.py index be4c29bc..42b563c4 100644 --- a/src/solarlab/config/legacy_fields.py +++ b/src/solarlab/config/legacy_fields.py @@ -85,7 +85,7 @@ def retained_legacy_fields(source: SourceDocument) -> LegacyDeviceFieldsInput | } JV_HINT_CONSUMER_BINDINGS = ( {"path": "web/src/workstation/panes/jv-pane.ts", - "sha256": "2b50f1819655ea89f2bd83baef4656e64ac9a2e680a5bf0ebfa4f8b74c125a06"}, + "sha256": "a5b63f7bfdf0f951ea49fa9fa33e315d51bac05e532d66ed02a4cb07af938850"}, {"path": "web/src/jv-waveform-controls.ts", "sha256": "9d9fdf0b6d9245d9707dac60f09177343e4e7ad6adb3391a016bad5d9a64d4e2"}, ) diff --git a/src/solarlab/equations/time_method.py b/src/solarlab/equations/time_method.py index 0d469a53..f73e4319 100644 --- a/src/solarlab/equations/time_method.py +++ b/src/solarlab/equations/time_method.py @@ -182,16 +182,16 @@ # CommanderBdfDefaultFreezeV2's allowlist: the ten electronic envelopes of V1 by scope digest, derived # from the frozen ReadinessV1 Cases.json and initial artifacts (the CND2 key table, Cnd2ScopeKeyTableV1). ALLOWLIST: Mapping[str, str] = MappingProxyType({ - "221e31f715757df14ebaaa73e4f2c2f879e6cb980a5fc483c7940a607b53cebf": "E_dark_hold", - "7dace99e619ecddd410121309ea5443a16f832720e90fb22781b8b3be591b2a5": "E_dark_voltage_ramp", - "59aca9ef958c68f5c179afe0ea59817d51d66b519af65aeaff6c847d545a03c3": "E_light_hold", - "a9364a002e141af1c09d252098eba75268136005d4755ddf6a76e954b13e5ca4": "E_light_ramp_16", - "608051152d7f5b41bdbb9d227f4cb69f6b5d37e0f9be13d9cc5b09fc1c214d33": "E_light_ramp_4", - "700083da5b3e5dcbc3eec176f91830b27290491a363a8204e5336772f38dcd27": "E_light_ramp_8", - "e79d312254e470a833c985f8304c6faf9df11c4fff139658175fdc1a983c0851": "E_saved_packet", - "8e315434aa617005a75bb7224cebabf03830f05afe06782c38626c37f49c9af8": "E_voltage_ramp_16", - "cdadc98646e0665667b9b26ef5ddc294bb89b1434faca40498f2bc3855cbff63": "E_voltage_ramp_4", - "6e315c3f151c1a0744093a63f04229ddc76fa4995bbb0272c7c9eaf3097ec1e6": "E_voltage_ramp_8", + "0ac50dbd36e58217773463a00250520d17aed4e0ba27058b2d0d4019a0a08cd4": "E_dark_hold", + "8a9602518d2ebdc3f12d13f627b6c4561c5ac8748d8391355ea2314cde84b588": "E_dark_voltage_ramp", + "67ab993b820dc4e8f30dad963354af04ab3440b164926e92177418d7bd56f7a6": "E_light_hold", + "cd1e484022fc874cc405043a056d89f59fdce6c8de594fdb1d52dc9a5f2e7395": "E_light_ramp_16", + "b8deddb08c4e9a836930ffacf8587a43e31d6057fe7c089c1a23a6795469361b": "E_light_ramp_4", + "6697fade77e85c744e1f37cf119e5f72f81066b7c03fe1e1f3f9a806559e0d54": "E_light_ramp_8", + "d37348bef4d23387aff7bf769e65908c18c8bd77c0c579c2228b19751c196e99": "E_saved_packet", + "b4d010a6708ab44e74dd63af184647f59204c9793618cd06c147f83d9a782beb": "E_voltage_ramp_16", + "fe20d57689805abedd663af99790ed24f267af9d5ffff0b31d4d1c65574e62b8": "E_voltage_ramp_4", + "858a988f48596ef322590f62f5f1fd6eb3d48a1e516c6c5543cfda1277a13965": "E_voltage_ramp_8", }) _SCOPE: ContextVar[str | None] = ContextVar("solarlab_time_method", default=None) diff --git a/tests/integration/fixtures/bdf_readiness/allowlist.json b/tests/integration/fixtures/bdf_readiness/allowlist.json index f9a70f4f..083a8050 100644 --- a/tests/integration/fixtures/bdf_readiness/allowlist.json +++ b/tests/integration/fixtures/bdf_readiness/allowlist.json @@ -30,7 +30,7 @@ "device": { "config_sha256": "2003cd46e119c2c8ff324ffc11562c2e69cd32dc1e7cdeda43f22dfdd501e086", "intervals_per_layer": 12, - "content_sha256": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac" + "content_sha256": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1" }, "capture": { "system": "Darwin", @@ -46,9 +46,9 @@ "envelopes": [ { "case_id": "E_dark_hold", - "scope_sha256": "221e31f715757df14ebaaa73e4f2c2f879e6cb980a5fc483c7940a607b53cebf", + "scope_sha256": "0ac50dbd36e58217773463a00250520d17aed4e0ba27058b2d0d4019a0a08cd4", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "2146bc9c8266a0e6a2b1fac978232a17e6847b26affb901255b62c27708ee791", "protocol": "813c88451d629c420a753368dc0570e7c166130e8da26e58b7dbd171862a046a", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -115,9 +115,9 @@ }, { "case_id": "E_light_hold", - "scope_sha256": "59aca9ef958c68f5c179afe0ea59817d51d66b519af65aeaff6c847d545a03c3", + "scope_sha256": "67ab993b820dc4e8f30dad963354af04ab3440b164926e92177418d7bd56f7a6", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", "protocol": "aa2a8c23095cf5c1f020a5246ec6bff5487507f56adbbc674fdff1dedea87e85", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -184,9 +184,9 @@ }, { "case_id": "E_dark_voltage_ramp", - "scope_sha256": "7dace99e619ecddd410121309ea5443a16f832720e90fb22781b8b3be591b2a5", + "scope_sha256": "8a9602518d2ebdc3f12d13f627b6c4561c5ac8748d8391355ea2314cde84b588", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "2146bc9c8266a0e6a2b1fac978232a17e6847b26affb901255b62c27708ee791", "protocol": "03673360ca7baf7c4d2c0122631764dd0f6b99163c7c63d6dde9940159e2ca4f", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -253,9 +253,9 @@ }, { "case_id": "E_light_ramp_4", - "scope_sha256": "608051152d7f5b41bdbb9d227f4cb69f6b5d37e0f9be13d9cc5b09fc1c214d33", + "scope_sha256": "b8deddb08c4e9a836930ffacf8587a43e31d6057fe7c089c1a23a6795469361b", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", "protocol": "e9a2a4a2ce13370f928c749800c8db8425bc5b88b878602cb06c627257098682", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -322,9 +322,9 @@ }, { "case_id": "E_voltage_ramp_4", - "scope_sha256": "cdadc98646e0665667b9b26ef5ddc294bb89b1434faca40498f2bc3855cbff63", + "scope_sha256": "fe20d57689805abedd663af99790ed24f267af9d5ffff0b31d4d1c65574e62b8", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", "protocol": "a89197bc7fa0b472e5968ab15ebb3f56147b39a3b49f6a6aff19d70a1d9a1652", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -391,9 +391,9 @@ }, { "case_id": "E_light_ramp_8", - "scope_sha256": "700083da5b3e5dcbc3eec176f91830b27290491a363a8204e5336772f38dcd27", + "scope_sha256": "6697fade77e85c744e1f37cf119e5f72f81066b7c03fe1e1f3f9a806559e0d54", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", "protocol": "07ad2898d0714b8aa587fb1e833f36cf155e8568f8f73c9bacf3b030ad1a5b3f", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -472,9 +472,9 @@ }, { "case_id": "E_voltage_ramp_8", - "scope_sha256": "6e315c3f151c1a0744093a63f04229ddc76fa4995bbb0272c7c9eaf3097ec1e6", + "scope_sha256": "858a988f48596ef322590f62f5f1fd6eb3d48a1e516c6c5543cfda1277a13965", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", "protocol": "bf98884538495964633878d5e040b677466703b4c1b3f8ec1ac992eb77663aba", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -553,9 +553,9 @@ }, { "case_id": "E_light_ramp_16", - "scope_sha256": "a9364a002e141af1c09d252098eba75268136005d4755ddf6a76e954b13e5ca4", + "scope_sha256": "cd1e484022fc874cc405043a056d89f59fdce6c8de594fdb1d52dc9a5f2e7395", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", "protocol": "d509d81b817ef0691ade9cbb24dfeda8e1ce5da31338889f722ad25eb0567371", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -658,9 +658,9 @@ }, { "case_id": "E_voltage_ramp_16", - "scope_sha256": "8e315434aa617005a75bb7224cebabf03830f05afe06782c38626c37f49c9af8", + "scope_sha256": "b4d010a6708ab44e74dd63af184647f59204c9793618cd06c147f83d9a782beb", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "6a5ecb883c056be909cf9cafd9f3755449fe2b08e20e0dfd5e44bc0536b82e49", "protocol": "8d96602a2fd3a5f5c45667f9ca31c8ff5487165f9fa72c6ab3f5f7d2c33c8dd6", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -763,9 +763,9 @@ }, { "case_id": "E_saved_packet", - "scope_sha256": "e79d312254e470a833c985f8304c6faf9df11c4fff139658175fdc1a983c0851", + "scope_sha256": "d37348bef4d23387aff7bf769e65908c18c8bd77c0c579c2228b19751c196e99", "components": { - "device": "dc17f907a7e40a1d31ead34d3bcb275134bf23b1f79659d61930fe020a3b9cac", + "device": "659882b0eb98e52483be23da26a8fc680f0ac8513def33bcb06910f85c440dc1", "initial_state": "469bb4ee7fbf6d9737d2c4b6acb80fcefe243561e0a5513657da3b9bff5709aa", "protocol": "9f86cabc9d07defbeeaf46ffb83e77849d9837a32f0730b044845f8089f67f0a", "drive": "99bb63aa817fc7a54d65f0b9461e4e7bf309ddf661c5afec7674d758e78ba4da", @@ -825,6 +825,6 @@ } } ], - "allowlist_sha256": "faaaf7cb92862de77d8bb48ba15d9552fdb988d1df493b2ebe7b2cddb247dbae", + "allowlist_sha256": "dc59b84bd046d6d857981728241caadbed1e42ceb992f81576addc7b12431495", "qualification": false } diff --git a/tests/refactor/test_legacy_consumer_registration.py b/tests/refactor/test_legacy_consumer_registration.py index 6e329875..ed39f850 100644 --- a/tests/refactor/test_legacy_consumer_registration.py +++ b/tests/refactor/test_legacy_consumer_registration.py @@ -65,7 +65,7 @@ def test_current_inventory_agrees_with_the_accepted_audit( ) -> None: policy, previous, consumers, lanes = current # Independent AcceptanceV2 / UnregisteredLegacyConsumersV1 inventory: - # 98 direct files (excluding backend-only support), 47 lane/executor pairs. + # 99 direct files (excluding backend-only support), 47 lane/executor pairs. # Audit sha256: 31c7bbbf8a081000036333de6deb27c735441344470083679390ab9933ea0b55. # A deliberate inventory change needs a refreshed audit; CI needs no archive. inventory = { @@ -74,7 +74,7 @@ def test_current_inventory_agrees_with_the_accepted_audit( } encoded = json.dumps(inventory, sort_keys=True, separators=(",", ":")).encode() assert hashlib.sha256(encoded).hexdigest() == ( - "9d6fa3dadbe97bce10c996ef63117574b93bb6c326bbbe28ef2d4c26941a697c" + "a79669a57c072f6dc35d976a05d4eed03ec59e9c3bedc6f7494a820144d852be" ) assert registration_violations(ROOT, policy, previous, consumers, lanes) == [] diff --git a/tests/unit/solvers/time/test_time_method_axis.py b/tests/unit/solvers/time/test_time_method_axis.py index fb337f54..2f5f6772 100644 --- a/tests/unit/solvers/time/test_time_method_axis.py +++ b/tests/unit/solvers/time/test_time_method_axis.py @@ -344,7 +344,7 @@ def test_the_frozen_profile_and_allowlist_are_the_reviewed_ones(): assert sorted(ALLOWLIST.values()) == sorted([ "E_dark_hold", "E_light_hold", "E_dark_voltage_ramp", "E_light_ramp_4", "E_light_ramp_8", "E_light_ramp_16", "E_voltage_ramp_4", "E_voltage_ramp_8", "E_voltage_ramp_16", "E_saved_packet"]) - assert time_method.ALLOWLIST_SHA256 == "faaaf7cb92862de77d8bb48ba15d9552fdb988d1df493b2ebe7b2cddb247dbae" + assert time_method.ALLOWLIST_SHA256 == "dc59b84bd046d6d857981728241caadbed1e42ceb992f81576addc7b12431495" def test_scope_content_refuses_a_value_it_cannot_encode(): From 06b016e0398bea1b6b7bb408fbd408f290f041eb Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Mon, 16 Nov 2026 10:44:42 +0800 Subject: [PATCH 19/46] M: refresh V2 registry provenance after JV hint consumer binding update --- reproducibility/ConfigBenchmarkMatrixV2.yaml | 6 +++--- reproducibility/NumericalRefinementRegistryV2.yaml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/reproducibility/ConfigBenchmarkMatrixV2.yaml b/reproducibility/ConfigBenchmarkMatrixV2.yaml index dcef43de..fa22eb84 100644 --- a/reproducibility/ConfigBenchmarkMatrixV2.yaml +++ b/reproducibility/ConfigBenchmarkMatrixV2.yaml @@ -853,8 +853,8 @@ sources: source_commit: e3eee454b1cf61ff43e2cb668035be0527dacdd3 - id: src/solarlab/config/legacy_fields.py path: src/solarlab/config/legacy_fields.py - sha256: 7c53be9d2d83d1635aef5e1193f1f97b756a964c532806002b4514e10f521cf7 - source_commit: 19ac67122ab4e449d7121d7af08596f8c2d3eec0 + sha256: 96e37576395198f522e0f8c9b5ab09c62a7d63007ac6b824db2a42217e5306e2 + source_commit: ae6c5aee899abae29bbc560fb28de24ba5301731 - id: src/solarlab/device/inputs.py path: src/solarlab/device/inputs.py sha256: f616d30f584930276635b8d099fafff736c9bf840e1d48a20eb9bbbb60debddf @@ -1635,7 +1635,7 @@ entries: resolver: source_id: src/solarlab/config/resolve_device.py symbol: resolve_device - content_sha256: 8c4c3a3161dd091a5d001f968a96eb3b1debb12c67d02f2399d9de308ed45503 + content_sha256: d10a8c9d83778c3bd4f26b398475940966c1ba77012f3276500c9a03f3153a3c issues: [] migration_notes: - source: diff --git a/reproducibility/NumericalRefinementRegistryV2.yaml b/reproducibility/NumericalRefinementRegistryV2.yaml index e73836eb..ad6f2c94 100644 --- a/reproducibility/NumericalRefinementRegistryV2.yaml +++ b/reproducibility/NumericalRefinementRegistryV2.yaml @@ -853,8 +853,8 @@ sources: source_commit: e3eee454b1cf61ff43e2cb668035be0527dacdd3 - id: src/solarlab/config/legacy_fields.py path: src/solarlab/config/legacy_fields.py - sha256: 7c53be9d2d83d1635aef5e1193f1f97b756a964c532806002b4514e10f521cf7 - source_commit: 19ac67122ab4e449d7121d7af08596f8c2d3eec0 + sha256: 96e37576395198f522e0f8c9b5ab09c62a7d63007ac6b824db2a42217e5306e2 + source_commit: ae6c5aee899abae29bbc560fb28de24ba5301731 - id: src/solarlab/device/inputs.py path: src/solarlab/device/inputs.py sha256: f616d30f584930276635b8d099fafff736c9bf840e1d48a20eb9bbbb60debddf From 720340c4bc35aa32d05dd899c8d906024f1aa927 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 21:41:42 +0800 Subject: [PATCH 20/46] docs(p08): freeze prospective physics scope and counterexample witnesses (P08-01) --- docs/PhysicsCorrectionsScopeV1.md | 201 +++++ tests/refactor/test_p08_counterexamples.py | 831 +++++++++++++++++++++ 2 files changed, 1032 insertions(+) create mode 100644 docs/PhysicsCorrectionsScopeV1.md create mode 100644 tests/refactor/test_p08_counterexamples.py diff --git a/docs/PhysicsCorrectionsScopeV1.md b/docs/PhysicsCorrectionsScopeV1.md new file mode 100644 index 00000000..5acfc02c --- /dev/null +++ b/docs/PhysicsCorrectionsScopeV1.md @@ -0,0 +1,201 @@ +# Prospective Physics Corrections Scope (V1) + +**Task ID:** `P08-01` (Wave 3 Lead-In — Prospective Physics Questions, Falsification Citations & Executable Counterexamples) +**Baseline Branch / Commit:** `devel` @ `0b03de5028e2124e743483671de890278dd038de` +**Executable Witness Suite:** `tests/refactor/test_p08_counterexamples.py` + +--- + +## 1. Governance, Commit Isolation & Evidence Boundaries + +Stages `P03` through `P06` migrate the SolarLab simulator under two strict non-physics change classes (`ArchitectureRefactorExecutionV2.md` §1.2): + +- **`M`-class (Mechanical / Bit-Identical):** Packaging, typed configuration, process supervision, and legacy channel reproduction with zero mathematical change. +- **`N`-class (Numerical Conditioning & Representation):** Positive log-activity carrier coordinates $(z_n, z_p)$, physical-inventory Backward Euler (`S_old * expm1(log_ratio) / dt`), cancellation-free Scharfetter–Gummel electrochemical steps, and sparse analytical Jacobians (`AssembledDC1DProblem`, `AssembledIonic1DProblem`, 2D sparse operators) preserving the underlying continuum physical laws. + +All prospective **physical** corrections (`P`-class) are quarantined into Stage `P08` (`P08-02` through `P08-05`, gated by `G8`) under five binding rules: + +1. **One-Commit-Per-Physics-Fix Isolation (`V1` §12 `P08-01`–`P08-05`, `V2` §1.2):** Every `P`-class correction must land in its own isolated commit with a distinct model or protocol version token (`v1` $\to$ `v2` or a newly named model identifier). Multiple physical defaults must **never** be flipped in a single commit, and `P`-class changes must never be bundled with `M`/`N` refactoring. +2. **Retention of Historical Channels & Failed Verdicts (`AGENTS.md`, `V1` §19.35):** Pre-`P08` channels (`legacy_mol_integer_endpoint_v1`, `legacy_twod_half_endpoint_v1`, nodal harmonic face permittivity, legacy density-weighted thermionic cap, monochromatic `beer_lambert`, coherent `tmm`, and summed-potential hole SG differencing) remain selectable for bit-reproducible historical replay. Historical failed or `inconsistent` runs retain their original status and citations permanently; a new `P08` model version creates a new evidence channel rather than relabeling old runs. +3. **`RS` (`R1`) Pre-`P08` Pinning (`V2` Decision `D20`):** Under `ArchitectureRefactorExecutionV2.md` `D20`, Stage `P08` depends on `G4`/`G5` and is decoupled from `RS-G7`. The `R1` research lane (`one_dimensional_mechanism_r1`) remains pinned to pre-`P08` model versions (`physical_boundary_two_sided_v1` and pre-`P08` constitutive tokens) unless a post-`P08` research protocol version is separately specified and admitted. +4. **Permanent Falsification Enforcement:** Scientifically falsified closures (`interface_shared_occupancy` and bulk-node Gaussian $E_t$ occupancy integration) remain permanently refused pre-solve via `CapabilityError`. Improved nonlinear/time-integrator convergence on the new kernel is **never** grounds to re-enable a falsified physical law. +5. **Source-Bound Certificate Re-Verification (`P08-05` / `G8`):** Any `P`-class change invalidates stale source-bound reference certificates for affected consumers until re-verified under `P08-05`, keeping internal numerical convergence, calibrated external-solver reproduction (`SCAPS`, `IonMonger`, `Driftfusion`), and experimental validation strictly separate (`perovskite-sim/CLAUDE.md` 2026-08-14 audit). + +--- + +## 2. Master `P08` Scope Matrix + +| Item ID | Target Physics / Arithmetic Question | Change Class | `RS` (`R1`) Impact (`V2` `D20`) | Executable Witness in `tests/refactor/test_p08_counterexamples.py` | +| --- | --- | --- | --- | --- | +| `P08-02a` | 1D/2D non-uniform mesh & heterointerface distance-weighted series dielectric capacitance vs nodal harmonic / arithmetic face means | `P` | Pinned to pre-`P08` (`physical_boundary_two_sided_v1` already uses `series_face_capacitance` at split planes) | `test_p08_02_nonuniform_series_capacitor_dielectric_witness` | +| `P08-02b` | Endpoint half-cell vs full-cell control-volume geometry (`sum(w) == L`) coupled across storage, sources, Poisson, sheet traps & ports | `P` | Pinned to pre-`P08` (`physical_boundary_two_sided_v1` already has `sum(w) == L`) | `test_p08_02_endpoint_control_volume_and_hole_step_rounding_witness` | +| `P08-02c` | `hole_separate_increment` (`BandStepsV1`) `4.0107e-4 A/m^2` binary64 differencing disposition & internal vs PV terminal current sign conventions | `N`/`P` boundary (versioned opt-in / isolated commit) | Pinned to pre-`P08` | `test_p08_02_endpoint_control_volume_and_hole_step_rounding_witness` | +| `P08-03a` | Heterointerface unequal-DOS ($N_{C,L} \neq N_{C,R}$, $m^*_L \neq m^*_R$) reciprocal Bethe/Richardson TE detailed balance on **bare TE** + deep forward-bias conditioning | `P` | Pinned to pre-`P08` | `test_p08_03_unequal_dos_bare_te_equilibrium_and_unit_scaling_witness` | +| `P08-03b` | Fixed `5 meV` compatible-reservoir contact thermodynamic gate vs permanent `6.025 meV` SCAPS `inconsistent` historical label (`F08`) | Invariant guard (no gate relaxation) | Unchanged (`5 meV` gate enforced) | `test_p08_03_contact_gate_and_falsified_shared_occupancy_refusals` | +| `P08-03c` | Permanent falsification & pre-solve `CapabilityError` refusal of `interface_shared_occupancy` (1D & 2D) and bulk-node Gaussian $E_t$ occupancy | Falsified / permanently rejected | Refused | `test_p08_03_contact_gate_and_falsified_shared_occupancy_refusals` | +| `P08-04a` | Spectral control-volume Beer–Lambert (`archive/wip-beer-lambert` `658baa84`) + optical photon budget + positive log-activity transient readiness | `P` | Pinned to pre-`P08` | `test_p08_04_spectral_beer_lambert_photon_budget_and_positive_log_activity_witness` | +| `P08-04b` | Explicit `optical_model` selection (`beer_lambert` \| `beer_lambert_spectral` \| `tmm`) & external generation profile-file loader (`not_available` / net-new scope) | Scope boundary | Unchanged | `test_p08_04_spectral_beer_lambert_photon_budget_and_positive_log_activity_witness` | +| Deferred | `F14` switching-surface kinks (`R_tot=0`, hard TE `min`, Poole–Frenkel `\|E\|=0`), coupled time-domain PDE $T(x,t)$, arbitrary plotting | Out of `P08` / fail-closed guards retained | Unchanged | Documented in §6 | + +--- + +## 3. `P08-02` — Electrostatics, Control-Volume Geometry, Current Sign Conventions & `hole_separate_increment` + +### 3.1 `P08-02a`: Non-Uniform Mesh & Heterointerface Face Permittivity + +- **Old Semantics (`devel` @ `0b03de5`):** + - `PoissonOperator1D.from_harmonic_nodes` (`src/solarlab/physics/electrostatics/poisson.py` L67–80) computes unweighted nodal harmonic face permittivity $\tilde{\varepsilon}_{i+1/2} = 2\varepsilon_{r,i}\varepsilon_{r,i+1}/(\varepsilon_{r,i}+\varepsilon_{r,i+1})$ and $C_{i+1/2} = \varepsilon_0 \tilde{\varepsilon}_{i+1/2}/h_i$ for `INTEGER_ENDPOINT_V1` (`legacy_mol_integer_endpoint_v1`), `HALF_ENDPOINT_V1` (`legacy_twod_half_endpoint_v1`), and extruded 2D stack faces in `CompiledDevice2D` (`src/solarlab/equations/dc_2d.py` L148–149). + - On shared-node grids (`plane.shared_node = k`), `RIGHT_LAYER_WINS` (`src/solarlab/mesh/geometry.py` L312, L325) sets $\varepsilon_r[k] = \varepsilon_R$, polluting the left-layer face $[x_{k-1}, x_k]$ with $\varepsilon_R$. + - Only `TWO_SIDED_TRACE_V1` and `PHYSICAL_BOUNDARY_TWO_SIDED_V1` replace split interface faces with `series_face_capacitance(d_L, eps_L, d_R, eps_R)` (`poisson.py` L109–114). +- **Defect / Counterexample Evidence:** + 1. *Non-uniform split face ($d_L \neq d_R$, $\varepsilon_L \neq \varepsilon_R$):* Exact Gauss-law continuity $D = -\varepsilon_0 \varepsilon_r \partial_x \phi = \text{const}$ across a planar dielectric boundary splitting face $h = d_L + d_R$ yields the exact series capacitance + $$C_{\text{exact}} = \frac{\varepsilon_0}{d_L/\varepsilon_L + d_R/\varepsilon_R}.$$ + Unweighted `harmonic_face_mean` assumes $d_L = d_R = h/2$, producing an $O(1)$ capacitance and potential error whenever mesh clustering makes $d_L \neq d_R$ across a high-contrast heterointerface (e.g. organic HTL $\varepsilon_1 = 3.0$ vs perovskite $\varepsilon_2 = 25.0$). Arithmetic averaging $0.5(\varepsilon_L + \varepsilon_R)/h$ treats series dielectrics as a parallel capacitor and fails even when $d_L = d_R$. + 2. *Shared-node `RIGHT_LAYER_WINS` interface shift:* When node $x_k = X_{\text{if}}$ sits on the interface, $[x_{k-1}, x_k]$ lies 100% inside material $L$ ($\varepsilon_L$) and $[x_k, x_{k+1}]$ lies 100% inside material $R$ ($\varepsilon_R$). Setting $\varepsilon_r[k] = \varepsilon_R$ gives $C_{k-1/2} = \varepsilon_0 \frac{2\varepsilon_L\varepsilon_R}{\varepsilon_L+\varepsilon_R} / dx_L$, shifting the effective dielectric boundary by $dx_L / 2$ into layer $L$ across the two adjacent faces: + $$C_{k-1/2}^{-1} + C_{k+1/2}^{-1} = \frac{dx_L / 2}{\varepsilon_0 \varepsilon_L} + \frac{dx_L / 2 + dx_R}{\varepsilon_0 \varepsilon_R} \neq \frac{dx_L}{\varepsilon_0 \varepsilon_L} + \frac{dx_R}{\varepsilon_0 \varepsilon_R}.$$ +- **New Target Semantics:** + - Every 1D and 2D electrostatic face (stack and lateral) uses exact sub-face material-extent series capacitance $C_f = \varepsilon_0 / (d_{f,L}/\varepsilon_L + d_{f,R}/\varepsilon_R)$. Within a homogeneous layer ($\varepsilon_L = \varepsilon_R = \varepsilon$), this reduces identically to $\varepsilon_0 \varepsilon / h_f$; on a shared-node interface $x_k = X_{\text{if}}$, $[x_{k-1}, x_k]$ uses $\varepsilon_L$ over $dx_L$ and $[x_k, x_{k+1}]$ uses $\varepsilon_R$ over $dx_R$. +- **Allowed Scope:** `src/solarlab/discretization/face_average.py`, `src/solarlab/physics/electrostatics/`, `src/solarlab/device/compile_1d.py`, `src/solarlab/device/compile_2d.py`, `src/solarlab/equations/dc_2d.py`, and small-signal/displacement-current observers reading `PoissonOperator1D`. +- **Falsification & Non-Regression Boundaries:** Must preserve exact homogeneous-medium reduction ($\varepsilon_L = \varepsilon_R \implies C_f = \varepsilon_0 \varepsilon / h_f$ to 0–1 ULP), exact Gauss identity $D_R - D_L = \sigma_{\text{sheet}}$, and keep `INTEGER_ENDPOINT_V1` / `HALF_ENDPOINT_V1` historical constructors available for `M`/`N` parity baselines. +- **Affected Consumers:** 1D/2D DC steady-state, transient displacement current $J_{\text{disp}} = \partial_t D$, Mott–Schottky / geometric capacitance $C(\omega)$, and ionic J–V electrostatic screening. +- **Independent Acceptance Criteria & Expected Direction of Change:** + - Two-layer charge-free capacitor ($\varepsilon_1 \neq \varepsilon_2$) reproduces analytical $\phi(x)$, $D$, and $C_{\text{geom}} = (\sum_\ell L_\ell / (\varepsilon_0 \varepsilon_\ell))^{-1}$ to $\le 10^{-14}$ relative error on arbitrary non-uniform 1D and 2D meshes. + - Expected physical shift: high-contrast transport/absorber stacks ($\varepsilon_{\text{TL}} \approx 3\text{–}9$, $\varepsilon_{\text{PVK}} \approx 25$) see small, mesh-convergent corrections to high-frequency geometric capacitance $C_{\text{hf}}$ and interfacial voltage partition, vanishing as $O(\Delta x_{\text{if}} / L)$ under refinement. +- **Versioning & Commit Isolation Rule:** Single `P`-class commit introducing versioned distance-weighted/layer-true Poisson geometry without simultaneously altering endpoint cell measures, TE normalization, or optical generation. + +--- + +### 3.2 `P08-02b`: Endpoint Control-Volume Geometry (Half-Cell vs Full-Cell) + +- **Old Semantics (`devel` @ `0b03de5`):** + - Four named historical 1D geometries coexist in `src/solarlab/mesh/geometry.py`: + - `INTEGER_ENDPOINT_V1` (`legacy_mol_integer_endpoint_v1`): $w_0 = dx_0$, $w_{N-1} = dx_{N-1}$, so $\sum_{i=0}^{N-1} w_i = L + \frac{1}{2}(dx_0 + dx_{N-1}) > L$ (`geometric_cells=False`). + - `TWO_SIDED_TRACE_V1` (`qf_two_sided_trace_integer_endpoint_v1`): true interior interface planes, but integer contact widths ($\sum w_i > L$). + - `HALF_ENDPOINT_V1` (`legacy_twod_half_endpoint_v1`) and `PHYSICAL_BOUNDARY_TWO_SIDED_V1`: $w_0 = dx_0 / 2$, $w_{N-1} = dx_{N-1} / 2$, so $\sum_{i=0}^{N-1} w_i = L$ (`geometric_cells=True`). +- **Defect / Counterexample Evidence:** + - Under `INTEGER_ENDPOINT_V1`, `beer_lambert_absorbed_photon_flux` (`src/solarlab/physics/generation/beer_lambert.py` L190–201) integrates over geometric dual faces $[x_0, x_0 + dx_0/2]$ of width $dx_0/2$, then divides by $w_0 = dx_0$, halving nodal $G_0$ and $G_{N-1}$ while conserving $\sum_i w_i G_i$. Conversely, any spatially uniform density $\rho_0$ integrated with `cell_measures_m` yields $\sum_i w_i \rho_0 = \rho_0 [L + \frac{1}{2}(dx_0 + dx_{N-1})] > \rho_0 L$, and `contact_displacement` (`poisson.py` L172–183) extends Gauss's law across `widths[0]` and `widths[-1]` using `cell_measures_m`. Mixing half-cell measures in one operator with full-cell measures in a coupled operator breaks exact terminal Maxwell / particle conservation. +- **New Target Semantics:** + - Physical control volumes satisfy $w_i = b_{i+1} - b_i$ everywhere, including contact half-cells ($b_0 = x_0$, $b_1 = (x_0 + x_1)/2$, $\sum_{i=0}^{N-1} w_i = L$) and true material-interface planes, bound **simultaneously** across carrier storage, mobile-ion conservation, Beer–Lambert / TMM / photon-recycling generation, Poisson/contact Gauss extension, sheet-trap areal conversion, and 1D/2D terminal port accounting. +- **Allowed Scope:** `src/solarlab/mesh/`, `src/solarlab/device/compile_1d.py`, `src/solarlab/device/compile_ionic_1d.py`, and coupled `equations/` bindings. +- **Falsification & Non-Regression Boundaries:** Must never change `w_0, w_{N-1}` in generation or storage alone while leaving `contact_displacement` or `step_accounting` on `INTEGER_ENDPOINT_V1`; global particle and Maxwell total-current conservation in `step_accounting` (`backward_euler.py` L220–226) must hold to machine precision ($\le 10^{-13}$ relative). +- **Affected Consumers:** 1D DC/transient/AC/ionic solvers, contact recombination/extraction accounting, and 1D-to-2D column consistency. +- **Independent Acceptance Criteria & Expected Direction of Change:** + - Uniform-column 2D (`Nx >= 2`, `HALF_ENDPOINT_V1`) and physical-endpoint 1D (`Ny` matching `N`) agree to solver tolerance on dark/illuminated $J(V)$, inventory, and terminal displacement current without endpoint-measure discrepancy. +- **Versioning & Commit Isolation Rule:** Isolated `P`-class commit switching default compiled 1D geometry to a named physical half-endpoint geometry token while keeping `INTEGER_ENDPOINT_V1` explicitly selectable for legacy parity tests. + +--- + +### 3.3 `P08-02c`: `hole_separate_increment` (`BandStepsV1`) `4.0107e-4 A/m^2` Rounding Disposition & Current Sign Conventions + +- **Old Semantics (`devel` @ `0b03de5`):** + - `BandStructure.transport_potentials(phi)` (`src/solarlab/physics/transport/drift_diffusion.py` L46; `electrochemical_flux.py` L256) forms nodal hole potential $\psi_{p,i} = \phi_i + \chi_{t,i} + E_{g,t,i}$ ($\approx 5.4\text{–}6.0\text{ V}$) first and then differences $\psi_{p,i+1} - \psi_{p,i}$. +- **Defect / Counterexample Evidence (`ArchitectureRefactorExecutionV1.md` §12 L784, §19.35 L1621):** + - Because $\chi_t + E_{g,t} \approx 5.5\text{ eV}$ has $\operatorname{ulp}(5.5) = 2^{-50} \approx 8.88\times 10^{-16}\text{ V}$, adding $\chi_t + E_{g,t}$ prior to subtracting adjacent nodes quantizes small intra-layer electrostatic steps $\Delta\phi = \phi_{i+1} - \phi_i$. At heavily doped transport-layer faces ($p \sim 10^{24}\text{ m}^{-3}$, $\Delta x \sim 1\text{ nm}$), that 1-ULP quantization perturbs $J_p$ by $O(10^{-4})\text{ A/m}^2$. + - On the saved SCAPS fixed-state native residual screens (`V1` §19.35 L1621), native summed-potential differencing gave `8.79892088904392e-5 A/m^2` on `Final61` and `4.010734989424907e-4 A/m^2` on `Final121` (exceeding the exact $1/3000\text{ A/m}^2 = 3.3333333333333335\times 10^{-4}\text{ A/m}^2$ screen on `Final121`), whereas `BandStepsV1` (`hole_separate_increment`, forming $(\phi_{i+1}-\phi_i) + (\chi_{t,i+1}-\chi_{t,i}) + (E_{g,t,i+1}-E_{g,t,i})$ before summation in `FullRhs01`) reduced carrier-balance sums to `2.9697029217142876e-5 A/m^2` (`61`) and `1.9735726377304774e-5 A/m^2` (`121`). +- **Explicit `N` vs `P` Disposition & Sign Convention Rule:** + 1. Over $\mathbb{R}$, separate-increment differencing is algebraically identical to summed-potential differencing (it is a floating-point conditioning improvement, not a new continuum physical law), **but** because it changes bit-level face currents by up to $4.01\times 10^{-4}\text{ A/m}^2$ on fine grids and moves `Final121` across the historical $1/3000\text{ A/m}^2$ screen, it must **never** be applied silently inside an unversioned edit or used to relabel the historical `Final121` native failure (`V1` §19.35). If adopted in `P08-02`, separate-increment step formation $(\Delta\phi) + (\Delta\chi_t) + (\Delta E_{g,t})$ must be isolated in its own versioned commit with explicit Jacobian consistency (`d step / d phi = +/- 1 / V_T` unchanged) and historical `Final121` failure preserved verbatim. + 2. **Current Sign Convention:** All internal 1D/2D operators keep `+x` / `+y` coordinate orientation (`F_n, F_p` particle fluxes along `+x`, $J_n = -q F_n$, $J_p = +q F_p$, $D = -C \Delta\phi$, $J_{\text{disp}} = \partial_t D$). Photovoltaic sign conventions ($J_{\text{PV}} > 0$ at short circuit / power generation quadrant via `voltage_polarity`) belong exclusively to experiment readout/reporting layers and must never flip internal conservation signs. + +--- + +## 4. `P08-03` — Heterointerface Thermionic Detailed Balance, Contact `5 meV` Gate & Falsified Closures + +### 4.1 `P08-03a`: Unequal-DOS / Effective-Mass / Physical-Barrier Thermionic Detailed Balance + +- **Old Semantics (`devel` @ `0b03de5`):** + - Deduplicated 1D TE (`compile_1d.py` L367–398; `thermionic_emission_bound_m2_s` in `src/solarlab/physics/interface_transport/thermionic.py` L173–214 with `dos_norm_m3=None`) evaluates left-layer `A_star` only and computes + $$J_{\text{TE, legacy}} = A^* T^2 \left(n_L e^{-\max(\Delta E_t, 0)/V_T} - n_R e^{-\max(-\Delta E_t, 0)/V_T}\right),$$ + which has unphysical units $\text{A}\cdot\text{m}^{-5}$ ($\sim 10^{28}\text{–}10^{35}$ numerically in SI, rendering $\min(|J_{\text{SG}}|, |J_{\text{TE}}|)$ nearly inert and violating length-unit invariance). + - Single-DOS `settings.te_physical_norm` (`ArchiveDigest.md` X3; `perovskite-sim/CLAUDE.md` F02) divides by a single $N_{\text{dos}}$ to form $v_R = A^* T^2 / (q N_{\text{dos}})$ [$\text{m/s}$], and is currently refused with `CapabilityError` in `compile_device_1d` (`compile_1d.py` L147). + - Two-sided trace (`thermionic.py` L438–615 `fermi_dirac_richardson_flux` & `fermi_richardson_flux`; `compile_1d.py` L589–594, L670–698) already resolves per-side $N_{C,L}, N_{C,R}, N_{V,L}, N_{V,R}$, true physical band offsets, and reciprocal $\tilde{A}^* = \min(A^*_L, A^*_R)$. +- **Defect / Counterexample Evidence:** + 1. *Unit-system non-invariance:* Rescaling densities and DOS together ($n \to \lambda n$, $N_C \to \lambda N_C$, e.g. $\text{m}^{-3} \leftrightarrow \text{cm}^{-3}$ with $\lambda = 10^{-6}$) changes `thermionic_emission_bound_m2_s(..., dos_norm_m3=None)` by $\lambda$, whereas physical emission flux $J_{\text{TE}} \propto (n / N_C)$ is strictly scale-invariant. + 2. *Failure of single-DOS / non-reciprocal $A^*$ on unequal-DOS heterojunctions ($N_{C,L} \neq N_{C,R}$, $m^*_L \neq m^*_R$):* At thermal equilibrium ($E_{F,L} = E_{F,R}$), Boltzmann carrier densities across physical conduction-band step $\Delta E_{\text{step}} = \Delta E_{C,\text{phys}} - (\phi_R - \phi_L)$ satisfy + $$\frac{n_L}{N_{C,L}} e^{-\max(\Delta E_{\text{step}}, 0)/V_T} = \frac{n_R}{N_{C,R}} e^{-\max(-\Delta E_{\text{step}}, 0)/V_T}.$$ + Evaluating bare TE with physical $\Delta E_{\text{step}}$ and a **single** shared divisor $N_{\text{dos}} = N_{C,L}$ yields a nonzero spurious equilibrium current $\propto (1 - N_{C,R}/N_{C,L})$. Likewise, using side-specific $A^*_L \neq A^*_R$ separately on the forward and reverse legs yields a spurious equilibrium current $\propto (A^*_L - A^*_R)$ because transverse momentum conservation across a specular planar barrier restricts both directions to the smaller phase-space cone $\tilde{A}^* = \min(A^*_L, A^*_R)$ (Bethe/Richardson reciprocity). + 3. *Historical conditioning failures (`ArchiveDigest.md` X3):* Four prior legacy attempts to flip `te_physical_norm` on by default failed solver conditioning in deep forward injection (`V_max = 3.0 V` non-finite density Newton/Radau steps). +- **New Target Semantics:** + - Interface thermionic transport separates: (1) true physical electrostatic + band-edge barrier $\Delta E_{\text{step}}$, (2) per-side DOS activities $n_L/N_{C,L}, n_R/N_{C,R}$ (or degenerate supply $F_1(\eta - \Delta E_{\text{bar}}/V_T)$), (3) reciprocal effective-mass Richardson constant $\tilde{A}^* = \min(A^*_L, A^*_R)$ (or explicit SCAPS effective-velocity variant `scaps_thermionic_flux` when reproducing SCAPS), (4) explicit transmission $\mathcal{T}$, and (5) cancellation-free electrochemical difference $\Delta E_F / k_B T$. +- **Allowed Scope:** `src/solarlab/physics/interface_transport/`, `src/solarlab/device/compile_1d.py`, `src/solarlab/equations/dc_1d.py`, `src/solarlab/equations/assembly/`, and `solvers/nonlinear/` forward-bias continuation guards if required. +- **Falsification & Non-Regression Boundaries:** + - Must be verified on **bare TE** (direct cross-plane TE kernel without SG `min` masking hiding equilibrium or Jacobian defects). + - Must converge without `NaN`/`Inf` across both photovoltaic ($0 \to V_{oc}$) and deep forward-injection ($V > V_{bi}$, including the historical `V_max = 3.0 V` stress regime or explicit physical contact/series-resistance regime). +- **Affected Consumers:** 1D/2D heterojunction J–V ($V_{oc}$, $FF$, S-kinks across CBO/VBO sweeps), dark diode ideality, C–V / impedance across barriers, and transient open-circuit photovoltage decay. +- **Independent Acceptance Criteria & Expected Direction of Change:** + - Bare TE equilibrium current $|J_{\text{TE}}(V=0, G=0)| \le 10^{-15} \times J_{\text{one-way}}$ across arbitrary $N_{C,L}/N_{C,R} \in [10^{-2}, 10^2]$ and $m^*_L \neq m^*_R$. + - Analytical Jacobian wrt $(\phi, z_n, z_p)$ matches central finite differences to $\le 10^{-8}$ relative Frobenius norm. + - Expected physical direction: activating physical emission-velocity TE lowers the TE ceiling from inert $\sim 10^{10}\text{ A/m}^2$ to physical $\sim 10^3\text{–}10^5\text{ A/m}^2$, increasing extraction resistance / S-shape sensitivity when $|\Delta E_C|$ or $|\Delta E_V|$ is large. +- **Versioning & Commit Isolation Rule:** Dedicated `P`-class commit with an explicit TE normalization/reciprocity model version; legacy `dos_norm_m3=None` retained only under explicit legacy preset selection. + +--- + +### 4.2 `P08-03b`: Contact Thermodynamic `5 meV` Gate & Historical `6.025 meV` SCAPS Label (`F08`) + +- **Current & Target Semantics (Invariant Guard — No `P08` Relaxation Permitted):** + - `assess_contact_thermodynamics` (`src/solarlab/physics/contacts/thermodynamics.py` L43, L137–228) enforces `CONTACT_THERMODYNAMIC_TOLERANCE_EV = 5.0e-3 eV` on the four contact quasi-Fermi levels $(E_{Fn,L}, E_{Fp,L}, E_{Fn,R}, E_{Fp,R})$ and any declared metal work functions; callers may tighten `tolerance_eV` below `5 meV` but attempting `tolerance_eV > 5.0e-3` raises `ValueError`. + - Compatible `semiconductor_work_function` contacts satisfy span $< 10^{-12}\text{ eV}$ (`status="certified"`). + - On historical `scaps_mirror_v2` (`legacy_manual` $V_{bi} = 1.300\text{ V}$ vs band-derived $1.2939750419\dots\text{ V}$; `ArchitectureRefactorReviewEvidenceV1.json` L143–157; `test_contact_thermodynamics_label.py`), the $6.024958093130\times 10^{-3}\text{ eV}$ equilibrium QFL span remains permanently `status="inconsistent"` with `historical_label="legacy_manual_v_bi_contact_offset"` and fails `require_contact_thermodynamic_certificate` with `ContactThermodynamicError`. Stage `P08` must **never** widen the `5 meV` gate to `7 meV` to pass manual-offset presets. + +--- + +### 4.3 `P08-03c`: Permanent Falsification of `interface_shared_occupancy` & Bulk-Node Gaussian $E_t$ + +- **Falsification Record (`perovskite-sim/CLAUDE.md` L86–89; `Specs/ArchitectureRefactorV1.md` L846–847; `ArchiveDigest.md` L176):** + - `interface_shared_occupancy`: **Falsified** — collapses the SCAPS CBO $V_{oc}$ sweep trend from $734\text{ mV}$ to $203\text{ mV}$ because algebraic trap occupancy evaluated directly on adjacent bulk-node densities ignores electrostatic/band projection to the interface plane. + - Bulk-node Gaussian $E_t$ defect integration: **Pre-falsified** by the same probe lineage — bulk-node carrier sampling is $E_t$-blind by $6\text{–}13$ orders of magnitude in heterointerface depletion spikes. + - `interface_two_sided` (legacy additive mirror channel): Measured exact no-op across 1D sweeps (distinct from `TWO_SIDED_TRACE_V1` QSS trace physics and clamp-passive `two_sided_cross_node` 2D sheet SRH). +- **Mandatory Boundary:** `compile_device_1d`, `compile_device_2d`, and `compile_ionic_device_2d` / `build_two_sided_interface_srh_2d` must continue raising `CapabilityError` before any solve whenever `settings.interface_shared_occupancy=True`. It is permanently excluded from `P08`. + +--- + +## 5. `P08-04` — Spectral Control-Volume Beer–Lambert, Optical Photon Budget & Positive-Density Transient Readiness + +### 5.1 `P08-04a`: Spectral Beer–Lambert Re-Introduction (`archive/wip-beer-lambert`) + +- **Old Semantics (`devel` @ `0b03de5`):** + - `src/solarlab/physics/generation/beer_lambert.py` (`BeerLambertBinding`) supports monochromatic scalar or piecewise-constant/nodal $\alpha$ [$\text{m}^{-1}$] with scalar photon flux $\Phi$ [$\text{m}^{-2}\text{s}^{-1}$]. + - `src/solarlab/device/optical_generation.py` (`bind_optical_generation_1d`) binds coherent normal-incidence spectral TMM (`OpticalStackBinding`), requiring optical $(n(\lambda), k(\lambda))$ or constant $(n_{\text{opt}}, \alpha)$ on every layer. + - Wavelength-resolved single-pass Beer–Lambert (`beer_lambert_spectral`) was parked at Git tag `archive/wip-beer-lambert` (`658baa84c5106ad3a4c9946d18a0c2860d9a4bff`, 2026-10-05; `BeerLambertReferenceProtocolV1.md`, `perovskite_sim/physics/beer_lambert_spectral.py`). +- **Defect / Counterexample & Historical Evidence:** + 1. *Spectral vs scalar Beer–Lambert:* For dispersive semiconductors where $\alpha(\lambda) = 4\pi k(\lambda)/\lambda$ spans $\sim 10^5\text{–}2\times 10^7\text{ m}^{-1}$ across `300–1000 nm`, monochromatic Beer–Lambert using wavelength-averaged $\bar{\alpha}$ overpredicts total absorption by Jensen's inequality ($1 - e^{-\bar{\alpha} L} > \int w_\lambda (1 - e^{-\alpha(\lambda) L})\,d\lambda$), while any effective scalar $\alpha_{\text{eff}}$ tuned to match total absorbed photons $\int G\,dx$ severely underpredicts short-wavelength front-surface peak generation $G(0^+)$. + 2. *Optical photon budget anchors (`Specs/ArchitectureRefactorV1.md` L880–883; `ArchitectureRefactorExecutionV1.md` L800):* + - On `scaps_mirror_v2`, control-volume spectral Beer–Lambert yields mesh-independent ($N=30$ and $N=60$) absorbed photon current $q \int G\,dx = 260.14\text{ A/m}^2$, aligning with SCAPS single-pass $J_{sc} \approx 262.8\text{ A/m}^2$, whereas coherent TMM reflectance/interference lowers absorbed photon current to $235.06\text{ A/m}^2$. + - On `scaps_mirror`, true electrical-stack TMM absorbed photon budget is $219.01\text{ A/m}^2$, demonstrating that the historical $231.7\text{ A/m}^2$ baseline over-collected photons relative to the electrical-stack TMM budget. + 3. *Legacy density-Radau negative-$p$ collapse vs new-kernel positivity (`Specs/ArchitectureRefactorV1.md` L297, L879–885):* + - On `perovskite_sim` (`658baa84`), switching `scaps_mirror_v2` at $N_{\text{grid}} = 60$ to spectral Beer–Lambert ($q \int G\,dx = 260.14\text{ A/m}^2$, $\sim 10\%$ higher front peak $G$) drove linear-density `solve_ivp(Radau)` to negative hole density ($p < 0$) at absorber-front `node 20`, collapsing step size and hanging `tests/integration/test_interface_flux_balance.py` past `600 s` inside `_dense_num_jac`. + - On `solarlab`'s new kernel, `State1D` parameterizes carriers via log-activities $n = n_{\text{ref}}\exp(\Delta\phi/V_T + z_n) > 0$, $p = p_{\text{ref}}\exp(-\Delta\phi/V_T - z_p) > 0$, and `BackwardEuler1DStep` integrates physical inventories via `S_old * expm1(log_ratio) / dt` with `generation_inventory` positive logarithmic seeding (`log1p(dt * G / density)`), structurally excluding $p \le 0$ domain violations. +- **New Target Semantics:** + - Introduce immutable `SpectralBeerLambertBinding` in `src/solarlab/physics/generation/` and wire explicit optical-model selection (`beer_lambert` | `beer_lambert_spectral` | `tmm`) in `config/` + `device/`: + - Per-layer $\alpha_\ell(\lambda) = 4\pi k_\ell(\lambda)/\lambda \ge 0$ integrated exactly over each cell's true optical-depth increment $\Delta\tau_{i,\lambda}$ via $\exp(-\tau_{\text{left}, i,\lambda}) \cdot (-\operatorname{expm1}(-\Delta\tau_{i,\lambda}))$, followed by explicit wavelength quadrature over the declared `SpectralPhotonFlux` resource. + - Optical-only front `substrate` layers attenuate $\tau_{\text{left}}(\lambda)$ without generating electrical carriers (`electrical=False`), with closed spectral photon budget ($\text{attenuated\_substrate} + \text{absorbed\_electrical} + \text{transmitted} = \Phi_{\text{incident}}$ to `rtol <= 1e-12`). +- **Allowed Scope:** `src/solarlab/physics/generation/`, `src/solarlab/device/optical_generation.py`, `src/solarlab/device/optical_generation_2d.py`, `src/solarlab/device/compile_1d.py`, `src/solarlab/device/compile_2d.py`, and typed optical-model selector fields in `src/solarlab/config/` + `src/solarlab/device/inputs.py`. +- **Falsification & Non-Regression Boundaries:** + - Must **not** relabel historical TMM runs (`2026-07-02` `FormalVerify.pdf`) or uniform-generation literature benchmarks as spectral Beer–Lambert (`BeerLambertReferenceProtocolV1.md`). + - Must pass the $N_{\text{grid}} = 60$ high-front-generation heterojunction transient / steady-state stress case cleanly in $< 5\text{ s}$ with strict $n > 0, p > 0$ and zero step collapse. +- **Affected Consumers:** 1D/2D steady & transient J–V, `scaps_mirror_v2` reference studies, Suns-$V_{oc}$, TPV/TPC, and EQE/spectral-response pipelines that opt into single-pass optics. +- **Independent Acceptance Criteria & Expected Direction of Change:** + - Mesh-independent electrical photon conservation $\sum_i w_i G_i = \int \Phi_\lambda e^{-\tau_{\text{sub}}(\lambda)} (1 - e^{-\tau_{\text{elec}}(\lambda)})\,d\lambda$ to `rtol <= 1e-13` across $N=15, 30, 60, 120$ non-uniform grids. + - Expected physical direction: removing air/glass/TCO Fresnel reflection & Fabry–Pérot interference increases `scaps_mirror_v2` absorbed photon current from $235.06\text{ A/m}^2$ (TMM) to $260.14\text{ A/m}^2$ (spectral BL), shifting $J_{sc}$ upward toward single-pass SCAPS ($\sim 262.8\text{ A/m}^2$). +- **Versioning & Commit Isolation Rule:** Isolated `P`-class commit adding `SpectralBeerLambertBinding` (`beer_lambert_spectral_v1`) and explicit `optical_model` selection; monochromatic `beer_lambert` and coherent `tmm` presets remain unchanged unless explicitly version-bumped in a separate preset commit. + +--- + +### 5.2 `P08-04b`: External Generation Profile-File Loader Demarcation + +- **Scope Boundary (`ArchitectureRefactorExecutionV1.md` §12 `P08-04` L801–802):** + - `FixedGenerationProfile` (`src/solarlab/physics/generation/fixed.py`) binds node-aligned fixed generation resources already admitted in typed device declarations. + - Arbitrary external user-file spatial/spectral generation profile loaders (e.g. SCAPS `.gen` file parsing, arbitrary non-matching mesh interpolation, and external photon-budget certification) were **absent** in legacy `perovskite_sim` and remain explicitly `not_available` during the architecture refactor unless commissioned as net-new post-refactor scope. They must not be smuggled in as an unreviewed migration patch. + +--- + +## 6. Deferred, Non-Smooth & Out-of-Scope Dispositions + +1. **`F14` Switching-Surface Non-Smoothness (`R_tot = 0`, Hard TE `min`, Poole–Frenkel `|E| = 0`):** + - Piecewise kinks at dark radiative/recombination floors (`R_tot == 0`), hard thermionic flux capping (`te_softness == 0.0`, $\min(|J_{\text{SG}}|, |J_{\text{TE}}|)$), and Poole–Frenkel field-assisted mobility ($\exp(\gamma_{\text{PF}}\sqrt{|E|})$ at $|E| = 0$) have discontinuous or singular classical derivatives on their switching manifolds. + - Current disposition (`P04-12` / `solve_nonlocal_small_signal_1d` / `FieldMobilityCapabilityError`): AC small-signal linearization fails closed with `CapabilityError` on uncertified non-smooth switching surfaces rather than silently returning one-sided subgradients; smooth $C^2$ `compact_support` / `legacy_logistic` TE regularization (`te_softness > 0`) remains explicit opt-in. Any future smooth replacement of Poole–Frenkel near $E=0$ or default `te_softness > 0` requires its own `P`-class commit and convergence/AC verification. +2. **Coupled Time-Domain Electrothermal PDE $T(x, t)$:** + - Static isothermal temperature scaling (`T`, `mu_T_gamma`, `B_rad_T_gamma`, `varshni_alpha`/`varshni_beta`, `E_a_ion`) is bound at compile time (`time_domain_temperature_qualified = False`). Dynamic self-heating / coupled heat-equation PDEs $c_p \partial_t T - \nabla\cdot(\kappa\nabla T) = Q_{\text{Joule}} + Q_{\text{rec}}$ are out of `P08` scope. +3. **Arbitrary Ad-Hoc Plotting / Unbound Post-Processing:** + - Core `solarlab` produces typed immutable results and reproducible `RunStore` bundles; ad-hoc plotting scripts remain outside `src/solarlab/`. +4. **`RS` (`R1`) Research Lane Pinning (`V2` `D20`):** + - `R1` execution and long-window `G2-R` / `RS-G7` qualification remain pinned to pre-`P08` model versions so prospective `P08` physics updates cannot invalidate or confound historical `R1` long-window evidence. diff --git a/tests/refactor/test_p08_counterexamples.py b/tests/refactor/test_p08_counterexamples.py new file mode 100644 index 00000000..92a862c0 --- /dev/null +++ b/tests/refactor/test_p08_counterexamples.py @@ -0,0 +1,831 @@ +"""Executable prospective counterexample and falsification witnesses for Stage P08 (P08-01). + +Every witness in this module exercises ``solarlab`` at its pre-``P08`` ``N``-class +baseline without modifying ``src/solarlab/**``: + +1. ``test_p08_02_nonuniform_series_capacitor_dielectric_witness``: + Contrasts exact distance-weighted series capacitance ``eps_0 / (d_L/eps_L + d_R/eps_R)`` + against unweighted nodal harmonic ``2*eps_L*eps_R/(eps_L+eps_R)/h`` and arithmetic + ``0.5*(eps_L+eps_R)/h`` face averages on non-uniform split faces, and exposes the + ``dx_L / 2`` interface shift on shared-node ``RIGHT_LAYER_WINS`` grids. +2. ``test_p08_02_endpoint_control_volume_and_hole_step_rounding_witness``: + Contrasts ``INTEGER_ENDPOINT_V1`` full-interval contact weights (``sum(w) > L``) + against physical half-cell geometries (``sum(w) == L``), and reproduces the + IEEE-754 binary64 ``hole_separate_increment`` (``BandStepsV1``) rounding mechanism + underlying ``ScapsFixedStateResultReviewV1`` / ``Final121`` (``V1`` §19.35). +3. ``test_p08_03_unequal_dos_bare_te_equilibrium_and_unit_scaling_witness``: + Contrasts legacy density-weighted thermionic emission (``A m^-5``, unit-system + dependent) and single-DOS / non-reciprocal ``A*`` forms against reciprocal + two-sided ``fermi_richardson_flux`` / ``fermi_dirac_richardson_flux`` detailed + balance on **bare TE** across ``N_C,L != N_C,R``, plus the pre-``P08-03`` + ``CapabilityError`` gate on ``settings.te_physical_norm=True``. +4. ``test_p08_03_contact_gate_and_falsified_shared_occupancy_refusals``: + Pins the fixed ``5 meV`` contact thermodynamic gate alongside the permanent + ``6.025 meV`` ``inconsistent`` ``legacy_manual_v_bi_contact_offset`` label, and + verifies pre-solve ``CapabilityError`` refusal of falsified + ``interface_shared_occupancy=True`` across 1D, 2D DC, and 2D ionic compilers. +5. ``test_p08_04_spectral_beer_lambert_photon_budget_and_positive_log_activity_witness``: + Demonstrates mesh-independent wavelength-resolved Beer-Lambert control-volume + photon conservation vs monochromatic ``alpha`` mismatch, and verifies that + log-activity coordinates + physical-inventory ``BackwardEuler1DStep`` maintain + strictly positive ``n > 0, p > 0`` at ``q * int(G) dx = 260.14 A/m^2`` where an + unconstrained linear-density step crosses ``p < 0``. +""" + +from __future__ import annotations + +from copy import deepcopy +import json +import math +from typing import Any + +import numpy as np +import pytest +from scipy.sparse.linalg import spsolve + +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import CapabilityError, compile_device_1d +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_2d import compile_ionic_device_2d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.discretization.face_average import ( + VACUUM_PERMITTIVITY_F_M, + arithmetic_face_mean, + harmonic_face_mean, + series_face_capacitance, +) +from solarlab.discretization.scharfetter_gummel import legacy_sg_current_p +from solarlab.equations.dc_1d import DC1DProblem +from solarlab.experiments.transient import TransientOptions, TransientProtocol, solve_transient +from solarlab.experiments.two_dimensional.inputs import JV2DInput +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.mesh.geometry import ( + half_endpoint_geometry, + integer_endpoint_geometry, + physical_boundary_two_sided_geometry, + two_sided_trace_geometry, +) +from solarlab.physics.contacts import ( + CONTACT_THERMODYNAMIC_TOLERANCE_EV, + LEGACY_MANUAL_CONTACT_OFFSET, + ContactEndpoint, + ContactThermodynamicError, + assess_contact_thermodynamics, + require_contact_thermodynamic_certificate, +) +from solarlab.physics.electrostatics import PoissonFactorization, PoissonOperator1D +from solarlab.physics.generation.beer_lambert import ( + beer_lambert_absorbed_photon_flux, + beer_lambert_generation, +) +from solarlab.physics.interface_transport import ( + fermi_dirac_richardson_flux, + fermi_richardson_flux, + richardson_from_dos, + scaps_thermionic_flux, + thermionic_emission_bound_m2_s, +) +from solarlab.physics.statistics import BandStructure, fermi_dirac_half, thermal_voltage +from solarlab.physics.transport import legacy_carrier_face_currents +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, solve_equilibrium, solve_steady_state +from solarlab.solvers.time import BackwardEuler1DStep + +Q = ELEMENTARY_CHARGE_C +EPS_0 = VACUUM_PERMITTIVITY_F_M + + +def _canonical_default_catalog() -> dict[str, Any]: + return { + "schema": "solarlab.default-catalog.v1", + "material": { + "eps_r": 25.0, + "mu_n": 1.9340863535916802e-3, + "mu_p": 1.9340863535916802e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": 3.635729012235858e11, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": 3.635729012235858e11, + "p1": 3.635729012235858e11, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.9, + "Eg": 1.6, + "A_star_n": 0.0, + "A_star_p": 0.0, + "v_th": 1.0e5, + "D_ion_neg": 0.0, + "P0_neg": 0.0, + "P_lim_neg": 1.0e28, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "carrier_statistics": "maxwell_boltzmann", + "dopant_ionization_model": "fully_ionized", + "donor_binding_energy_eV": None, + "acceptor_binding_energy_eV": None, + "donor_degeneracy": 2.0, + "acceptor_degeneracy": 4.0, + "band_gap_narrowing_model": "off", + "bgn_reference_energy_eV": 0.0, + "bgn_reference_density_m3": 1.0e24, + "bgn_log_shape": 0.5, + "bgn_conduction_band_fraction": 0.5, + "mu_T_gamma": -1.5, + "E_a_ion": 0.0, + "B_rad_T_gamma": 0.0, + "varshni_alpha": 0.0, + "varshni_beta": 0.0, + "trap_N_t_interface": None, + "trap_N_t_bulk": None, + "trap_decay_length": None, + "trap_profile_shape": "exponential", + "trap_edge": "both", + "optical_material": None, + "n_optical": None, + "incoherent": False, + "v_sat_n": 0.0, + "v_sat_p": 0.0, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "pf_gamma_n": 0.0, + "pf_gamma_p": 0.0, + "Eg_back": None, + "chi_back": None, + "grading_profile": "linear", + "grading_direction": "front_to_back", + "grading_bowing": 0.0, + "grading_char_length": None, + "grading_N_mult": 1, + "N_A_bulk": None, + "N_D_bulk": None, + "doping_profile_shape": None, + "doping_decay_length": None, + "doping_edge": "front", + }, + "device": { + "phi_left": 0.0, + "V_bi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "work_function_left_eV": None, + "work_function_right_eV": None, + "Phi": 2.0e21, + "T": 300.0, + "mode": "fast", + "interface_plane_projection": False, + "dos_band_potentials": True, + "te_physical_norm": False, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "flat_band_contacts": False, + "flat_band_metal_contacts": False, + "contact_phi_B_eV": 0.0, + "interface_two_sided": False, + "interface_shared_occupancy": False, + "interface_plane_closure": False, + "interface_plane_generation": False, + "het_recomb_despike": 0.0, + "band_grading": False, + "graded_optics": False, + "interface_tunneling": False, + "tunnel_mass_eff": 0.2, + "jv_solver_policy": "general", + "interface_charge_closure": "off", + "interface_charge_rebaseline_acknowledged": False, + }, + "scaps": { + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + }, + "interface": { + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0, + }, + "constants": { + "Q": 1.602176634e-19, + "K_B": 1.380649e-23, + "T": 300.0, + }, + "contacts": { + "S_n_left": None, + "S_p_left": None, + "S_n_right": None, + "S_p_right": None, + }, + "structural": { + "grain_boundary_layer_role": "absorber", + "tandem_light_direction": "top_first", + "junction_incoherent": False, + }, + "defect_model": "effective_lifetime", + "defect_schema_version": None, + "defect_degeneracy": 1.0, + "distribution_width_convention": "not_applicable", + } + + +def _prepare_pin_device( + *, + settings_override: dict[str, Any] | None = None, + absorber_override: dict[str, Any] | None = None, +) -> PreparedDevice: + device_doc: dict[str, Any] = { + "schema_version": "solarlab.device-preparation.v1", + "id": "p08_witness_pin", + "name": "P08 witness p-i-n stack", + "source_format": "canonical", + "settings": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "T": 300.0, + "Phi": 1.6236661838820224e21, + }, + "layers": [ + { + "id": "htl", + "name": "HTL", + "role": "HTL", + "thickness": 4.0e-8, + "parameters": { + "chi": 3.6, + "Eg": 1.8, + "Nc300": 2.0e25, + "Nv300": 3.0e25, + "eps_r": 3.0, + "N_D": 0.0, + "N_A": 1.0e24, + "ni": 1.8609772721447e10, + "n1": 1.8609772721447e10, + "p1": 1.8609772721447e10, + "mu_n": 3.8681727071833605e-5, + "mu_p": 3.8681727071833605e-5, + "alpha": 0.0, + }, + }, + { + "id": "absorber", + "name": "absorber", + "role": "absorber", + "thickness": 3.5e-7, + "parameters": { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "eps_r": 25.0, + "N_D": 0.0, + "N_A": 0.0, + "ni": 3.635729012235858e11, + "n1": 3.635729012235858e11, + "p1": 3.635729012235858e11, + "mu_n": 1.9340863535916802e-3, + "mu_p": 1.9340863535916802e-3, + "alpha": 1.5e7, + }, + }, + { + "id": "etl", + "name": "ETL", + "role": "ETL", + "thickness": 4.0e-8, + "parameters": { + "chi": 4.0, + "Eg": 2.0, + "Nc300": 4.0e25, + "Nv300": 2.0e25, + "eps_r": 9.0, + "N_D": 1.0e24, + "N_A": 0.0, + "ni": 4.4903932431171566e8, + "n1": 4.4903932431171566e8, + "p1": 4.4903932431171566e8, + "mu_n": 3.8681727071833605e-5, + "mu_p": 3.8681727071833605e-5, + "alpha": 0.0, + }, + }, + ], + "electrical_grid": [ + {"layer": "htl", "interval_weight": 6.0, "alpha": 2.5}, + {"layer": "absorber", "interval_weight": 12.0, "alpha": 3.0}, + {"layer": "etl", "interval_weight": 6.0, "alpha": 2.5}, + ], + } + if settings_override: + device_doc["settings"].update(deepcopy(settings_override)) + if absorber_override: + device_doc["layers"][1]["parameters"].update(deepcopy(absorber_override)) + + payload = {"default_catalog": _canonical_default_catalog(), "device": device_doc} + raw = json.dumps(payload, sort_keys=True).encode("utf-8") + source = SourceDocument("inmemory://p08_witness_pin.json", raw) + catalog_map = {**payload["default_catalog"], "evidence": [[source.id, source.sha256]]} + return resolve_device( + DeviceInput.model_validate(device_doc), + DefaultCatalog.from_mapping(catalog_map), + ResourceLibrary(), + sources=(source,), + ) + + +def test_p08_02_nonuniform_series_capacitor_dielectric_witness() -> None: + """P08-02a: Distance-weighted series capacitance vs unweighted harmonic/arithmetic & shared-node shift.""" + eps_left, eps_right = 3.0, 25.0 + x_if = 20.0e-9 + total_len = 200.0e-9 + phi_left, phi_right = 0.0, 1.0 + + # Exact charge-free 2-layer capacitor: D = -eps_0 * eps(x) * dphi/dx = const + inv_c_total = x_if / (EPS_0 * eps_left) + (total_len - x_if) / (EPS_0 * eps_right) + d_exact = -(phi_right - phi_left) / inv_c_total + + def exact_phi(x_arr: np.ndarray) -> np.ndarray: + return np.where( + x_arr <= x_if, + phi_left - (d_exact / (EPS_0 * eps_left)) * x_arr, + phi_left - (d_exact / (EPS_0 * eps_left)) * x_if - (d_exact / (EPS_0 * eps_right)) * (x_arr - x_if), + ) + + # 1. Two-sided non-uniform grid: interface splits face 1 into d_L = 5 nm, d_R = 60 nm (d_L != d_R). + x_two_sided = np.array([0.0, 15.0e-9, 80.0e-9, total_len], dtype=float) + eps_two_sided = np.array([eps_left, eps_left, eps_right, eps_right], dtype=float) + rho_zero = np.zeros_like(x_two_sided) + + geom_two_sided = two_sided_trace_geometry(x_two_sided, [x_if]) + op_series = PoissonOperator1D.for_geometry(geom_two_sided, eps_two_sided) + op_nodal_harmonic = PoissonOperator1D.from_harmonic_nodes(x_two_sided, eps_two_sided) + c_arith = EPS_0 * arithmetic_face_mean(eps_two_sided) / np.diff(x_two_sided) + op_arithmetic = PoissonOperator1D.from_finite_volume( + c_arith, op_nodal_harmonic.interior_widths_m, geometry_name="arithmetic_probe_v1" + ) + + phi_series = PoissonFactorization.factor(op_series).solve(rho_zero, phi_left, phi_right) + phi_harmonic = PoissonFactorization.factor(op_nodal_harmonic).solve(rho_zero, phi_left, phi_right) + phi_arith = PoissonFactorization.factor(op_arithmetic).solve(rho_zero, phi_left, phi_right) + phi_ref = exact_phi(x_two_sided) + + # Exact distance-weighted series capacitance reproduces analytical potential & displacement to machine eps. + assert np.max(np.abs(phi_series - phi_ref)) <= 1.0e-15 + assert np.max(np.abs(op_series.face_displacement(phi_series) - d_exact)) <= 1.0e-15 * abs(d_exact) + + # Unweighted harmonic (assuming d_L == d_R) and arithmetic means incur O(1) interface errors when d_L != d_R. + c_if_exact = series_face_capacitance(5.0e-9, eps_left, 60.0e-9, eps_right) + assert op_series.face_capacitance_F_m2[1] == pytest.approx(c_if_exact, rel=1.0e-15) + assert abs(op_nodal_harmonic.face_capacitance_F_m2[1] - c_if_exact) / c_if_exact > 0.45 + assert abs(op_arithmetic.face_capacitance_F_m2[1] - c_if_exact) / c_if_exact > 0.10 + assert np.max(np.abs(phi_harmonic - phi_ref)) > 0.12 + assert np.max(np.abs(phi_arith - phi_ref)) > 0.01 + + # On a midpoint or left-heavy split (d_L >= d_R in the low-eps layer), arithmetic mean overestimates C_f by >160%-300%. + c_if_left_heavy = series_face_capacitance(60.0e-9, eps_left, 5.0e-9, eps_right) + c_arith_left_heavy = EPS_0 * float(arithmetic_face_mean([eps_left, eps_right])[0]) / 65.0e-9 + assert abs(c_arith_left_heavy - c_if_left_heavy) / c_if_left_heavy > 3.0 + + # Sanity check: in a homogeneous dielectric (eps_left == eps_right) or midpoint split (d_L == d_R), + # series_face_capacitance and harmonic_face_mean agree identically. + assert series_face_capacitance(5.0e-9, 12.0, 60.0e-9, 12.0) == pytest.approx( + EPS_0 * float(harmonic_face_mean([12.0, 12.0])[0]) / 65.0e-9, rel=1.0e-15 + ) + assert series_face_capacitance(10.0e-9, eps_left, 10.0e-9, eps_right) == pytest.approx( + EPS_0 * float(harmonic_face_mean([eps_left, eps_right])[0]) / 20.0e-9, rel=1.0e-15 + ) + + # 2. Shared-node grid (INTEGER_ENDPOINT_V1 / HALF_ENDPOINT_V1) with RIGHT_LAYER_WINS: + # node 2 sits on x_if = 20 nm and carries eps_right, polluting [15 nm, 20 nm] inside layer 1. + x_shared = np.array([0.0, 15.0e-9, x_if, 80.0e-9, total_len], dtype=float) + eps_shared = np.array([eps_left, eps_left, eps_right, eps_right, eps_right], dtype=float) + for geom in (integer_endpoint_geometry(x_shared, [x_if]), half_endpoint_geometry(x_shared, [x_if])): + op_shared = PoissonOperator1D.for_geometry(geom, eps_shared) + phi_shared = PoissonFactorization.factor(op_shared).solve(np.zeros_like(x_shared), phi_left, phi_right) + # Effective boundary is shifted by dx_L / 2 = 2.5 nm into the low-permittivity left layer, + # so [17.5 nm, 20 nm] inside layer 1 is treated as eps_right instead of eps_left: + shifted_inv_c = (x_if - 2.5e-9) / (EPS_0 * eps_left) + (total_len - x_if + 2.5e-9) / (EPS_0 * eps_right) + phi_if_shifted = ((x_if - 2.5e-9) / (EPS_0 * eps_left) + 2.5e-9 / (EPS_0 * eps_right)) / shifted_inv_c + assert phi_shared[2] == pytest.approx(phi_if_shifted, rel=1.0e-14) + assert abs(phi_shared[2] - float(exact_phi(np.array([x_if]))[0])) > 0.025 + + +def test_p08_02_endpoint_control_volume_and_hole_step_rounding_witness() -> None: + """P08-02b & P08-02c: Full- vs half-cell endpoint measures and hole_separate_increment binary64 rounding.""" + x_shared = np.array([0.0, 6.0e-9, 20.0e-9, 70.0e-9, 120.0e-9], dtype=float) + x_two_sided = np.array([0.0, 6.0e-9, 34.0e-9, 120.0e-9], dtype=float) + span_m = float(x_shared[-1] - x_shared[0]) + + geom_int = integer_endpoint_geometry(x_shared, [20.0e-9]) + geom_half = half_endpoint_geometry(x_shared, [20.0e-9]) + geom_phys = physical_boundary_two_sided_geometry(x_two_sided, [20.0e-9]) + + dx = np.diff(x_shared) + assert not geom_int.geometric_cells + assert geom_half.geometric_cells and geom_phys.geometric_cells + assert geom_int.total_measure_m == pytest.approx(span_m + 0.5 * float(dx[0] + dx[-1]), rel=1.0e-15) + assert geom_half.total_measure_m == pytest.approx(span_m, rel=1.0e-15) + assert geom_phys.total_measure_m == pytest.approx(span_m, rel=1.0e-15) + + # Absorbed photon counts on dual faces are identical between INTEGER_ENDPOINT_V1 and HALF_ENDPOINT_V1, + # so dividing by full-interval w[0] = dx[0] halves nodal G[0] on INTEGER_ENDPOINT_V1. + alpha = 5.0e6 + phi_inc = 1.5e21 + abs_int = beer_lambert_absorbed_photon_flux(geom_int, alpha, phi_inc) + abs_half = beer_lambert_absorbed_photon_flux(geom_half, alpha, phi_inc) + gen_int = beer_lambert_generation(geom_int, alpha, phi_inc) + gen_half = beer_lambert_generation(geom_half, alpha, phi_inc) + assert np.array_equal(abs_int, abs_half) + assert gen_int[0] == pytest.approx(0.5 * gen_half[0], rel=1.0e-15) + assert gen_int[-1] == pytest.approx(0.5 * gen_half[-1], rel=1.0e-15) + assert float(np.dot(gen_int, geom_int.cell_measures_m)) == pytest.approx( + float(np.dot(gen_half, geom_half.cell_measures_m)), rel=1.0e-15 + ) + + # IEEE-754 binary64 hole_separate_increment (BandStepsV1) witness (V1 §12 L784 & §19.35 L1621): + # Adding chi_t + Eg_t (~5.49 eV, ulp = 2^-50 V) before differencing quantizes small intra-layer dphi. + chi_val, eg_val = 3.94, 1.55 + vt = thermal_voltage(300.0) + dx_fine = 1.0e-9 + dphi_exact = 1.0e-7 + 2.0**-51 # exact in binary64 near phi=0, sub-ULP once shifted by +5.49 V + phi_pair = np.array([0.0, dphi_exact], dtype=float) + bands = BandStructure( + np.array([chi_val, chi_val]), + np.array([eg_val, eg_val]), + np.array([chi_val, chi_val]), + np.array([eg_val, eg_val]), + dos_folded=True, + reference_layer=0, + ) + p_heavy = np.array([2.5e24, 2.5e24], dtype=float) + n_min = np.array([1.0e10, 1.0e10], dtype=float) + d_face = np.array([1.5e-4], dtype=float) + + _, jp_summed = legacy_carrier_face_currents( + np.array([0.0, dx_fine]), phi_pair, n_min, p_heavy, d_face, d_face, vt, bands + ) + # Separate-increment potential step: (phi_R - phi_L) + (chi_R - chi_L) + (Eg_R - Eg_L) == dphi_exact. + dpsi_separate = (phi_pair[1] - phi_pair[0]) + 0.0 + 0.0 + jp_separate = legacy_sg_current_p( + np.array([0.0, dpsi_separate]), p_heavy, np.array([dx_fine]), d_face, vt + ) + rounding_gap_a_m2 = abs(float(jp_summed[0] - jp_separate[0])) + # Quantization error is O(1e-4 A/m^2) — the exact scale of Final121's 4.0107e-4 > 1/3000 A/m^2 screen. + assert 1.0e-4 < rounding_gap_a_m2 < 2.0e-3 + + +def test_p08_03_unequal_dos_bare_te_equilibrium_and_unit_scaling_witness() -> None: + """P08-03a: Density-unit scaling & bare-TE equilibrium reciprocity across unequal N_C / m*.""" + temp_k = 300.0 + vt = thermal_voltage(temp_k) + nc_left, nc_right = 2.0e24, 1.6e25 + nv_left, nv_right = 3.0e24, 9.0e24 + a_star_n_left = richardson_from_dos(nc_left, temp_k) + a_star_n_right = richardson_from_dos(nc_right, temp_k) + a_star_p_left = richardson_from_dos(nv_left, temp_k) + a_star_p_right = richardson_from_dos(nv_right, temp_k) + assert a_star_n_left != pytest.approx(a_star_n_right) + + # 1. Unit-scaling witness: m^-3 -> cm^-3 simultaneous scaling by 1e-6. + scale_cm3 = 1.0e-6 + n_l_sample, n_r_sample = 1.0e21, 4.0e21 + gamma_legacy_si, _, _ = thermionic_emission_bound_m2_s( + n_l_sample, n_r_sample, 0.20, temp_k, a_star_n_left, dos_norm_m3=None + ) + gamma_legacy_scaled, _, _ = thermionic_emission_bound_m2_s( + n_l_sample * scale_cm3, n_r_sample * scale_cm3, 0.20, temp_k, a_star_n_left, dos_norm_m3=None + ) + gamma_norm_si, _, _ = thermionic_emission_bound_m2_s( + n_l_sample, n_r_sample, 0.20, temp_k, a_star_n_left, dos_norm_m3=nc_left + ) + gamma_norm_scaled, _, _ = thermionic_emission_bound_m2_s( + n_l_sample * scale_cm3, + n_r_sample * scale_cm3, + 0.20, + temp_k, + a_star_n_left, + dos_norm_m3=nc_left * scale_cm3, + ) + # Legacy density-weighted bound changes by 1e-6 under density-unit scaling and is ~24 orders larger! + assert gamma_legacy_scaled == pytest.approx(gamma_legacy_si * scale_cm3, rel=1.0e-15) + assert gamma_norm_scaled == pytest.approx(gamma_norm_si, rel=1.0e-15) + assert abs(gamma_legacy_si) > 1.0e20 * abs(gamma_norm_si) + + # 2. Bare-TE thermal equilibrium across an unequal-DOS heterojunction (flat E_F => net flux MUST be 0). + delta_ec_phys = 0.24 # eV (E_C,R - E_C,L at flat potential) + delta_ev_step = 0.18 # eV hole step + phi_trace_l, phi_trace_r = 0.0, 0.06 + e_step = delta_ec_phys - (phi_trace_r - phi_trace_l) # > 0 + h_step = delta_ev_step + (phi_trace_r - phi_trace_l) # > 0 + + # Exact Boltzmann equilibrium densities at flat Fermi level: + # (n_L / N_C,L) * exp(-e_step / V_T) == (n_R / N_C,R) + n_eq_l = 5.0e20 + n_eq_r = n_eq_l * (nc_right / nc_left) * math.exp(-e_step / vt) + p_eq_l = 2.0e20 + p_eq_r = p_eq_l * (nv_right / nv_left) * math.exp(-h_step / vt) + state_eq = np.array([n_eq_l, p_eq_l, n_eq_r, p_eq_r], dtype=float) + + # Counterexample A: Single shared DOS divisor (dos_norm_m3=nc_left) with true physical step e_step + # violates equilibrium detailed balance whenever N_C,L != N_C,R! + gamma_shared_dos_eq, _, _ = thermionic_emission_bound_m2_s( + n_eq_l, n_eq_r, e_step, temp_k, min(a_star_n_left, a_star_n_right), dos_norm_m3=nc_left + ) + one_way_ref = (min(a_star_n_left, a_star_n_right) * temp_k**2 / Q) * (n_eq_l / nc_left) * math.exp(-e_step / vt) + assert abs(gamma_shared_dos_eq) / one_way_ref == pytest.approx(abs(1.0 - nc_right / nc_left), rel=1.0e-14) + + # Counterexample B: Separate side-specific Richardson constants A*_L != A*_R on forward vs reverse legs + # also violate equilibrium detailed balance! + non_reciprocal_eq = (temp_k**2 / Q) * ( + a_star_n_left * (n_eq_l / nc_left) * math.exp(-e_step / vt) - a_star_n_right * (n_eq_r / nc_right) + ) + assert abs(non_reciprocal_eq) / one_way_ref > 1.0 + + # Target reciprocal two-sided Bethe/Richardson & SCAPS kernels satisfy exact equilibrium detailed balance. + boltz_eval = fermi_richardson_flux( + state_eq, + phi_trace_left_V=phi_trace_l, + phi_trace_right_V=phi_trace_r, + conduction_band_step_eV=delta_ec_phys, + hole_transport_step_eV=delta_ev_step, + N_C_left_m3=nc_left, + N_C_right_m3=nc_right, + N_V_left_m3=nv_left, + N_V_right_m3=nv_right, + richardson_n_A_m2_K2=min(a_star_n_left, a_star_n_right), + richardson_p_A_m2_K2=min(a_star_p_left, a_star_p_right), + temperature_K=temp_k, + thermal_voltage_V=vt, + ) + assert np.all(np.abs(boltz_eval.cross_flux_m2_s) <= 1.0e-15 * boltz_eval.one_way_scale_m2_s) + + scaps_eval = scaps_thermionic_flux( + state_eq, + phi_trace_left_V=phi_trace_l, + phi_trace_right_V=phi_trace_r, + conduction_band_step_eV=delta_ec_phys, + hole_transport_step_eV=delta_ev_step, + N_C_left_m3=nc_left, + N_C_right_m3=nc_right, + N_V_left_m3=nv_left, + N_V_right_m3=nv_right, + richardson_n_left_A_m2_K2=a_star_n_left, + richardson_n_right_A_m2_K2=a_star_n_right, + richardson_p_left_A_m2_K2=a_star_p_left, + richardson_p_right_A_m2_K2=a_star_p_right, + temperature_K=temp_k, + thermal_voltage_V=vt, + ) + assert np.all(np.abs(scaps_eval.cross_flux_m2_s) <= 1.0e-15 * scaps_eval.one_way_scale_m2_s) + + # Degenerate Fermi-Dirac reciprocal equilibrium check at flat chemical potential eta_R = eta_L - step/V_T: + eta_nl, eta_pl = 1.2, 0.8 + eta_nr = eta_nl - e_step / vt + eta_pr = eta_pl - h_step / vt + dos_vec = np.array([nc_left, nv_left, nc_right, nv_right], dtype=float) + occ_vec = np.array( + [fermi_dirac_half(eta) for eta in (eta_nl, eta_pl, eta_nr, eta_pr)], + dtype=float, + ) + state_fd_eq = dos_vec * occ_vec + fd_eval = fermi_dirac_richardson_flux( + state_fd_eq, + phi_trace_left_V=phi_trace_l, + phi_trace_right_V=phi_trace_r, + conduction_band_step_eV=delta_ec_phys, + hole_transport_step_eV=delta_ev_step, + N_C_left_m3=nc_left, + N_C_right_m3=nc_right, + N_V_left_m3=nv_left, + N_V_right_m3=nv_right, + richardson_n_A_m2_K2=min(a_star_n_left, a_star_n_right), + richardson_p_A_m2_K2=min(a_star_p_left, a_star_p_right), + temperature_K=temp_k, + thermal_voltage_V=vt, + base_log_to_dos=np.log(occ_vec), + u_delta=np.zeros(4, dtype=float), + electrochemical_steps=(0.0, 0.0), + ) + assert np.all(np.abs(fd_eval.cross_flux_m2_s) <= 1.0e-15 * fd_eval.one_way_scale_m2_s) + + # Pre-P08-03 guard: settings.te_physical_norm=True fails closed with CapabilityError in compile_device_1d. + prepared_te = _prepare_pin_device(settings_override={"te_physical_norm": True}) + with pytest.raises(CapabilityError, match=r"settings\.te_physical_norm"): + compile_device_1d(prepared_te) + + +def test_p08_03_contact_gate_and_falsified_shared_occupancy_refusals() -> None: + """P08-03b & P08-03c: 5 meV contact gate + 6.025 meV historical label + shared_occupancy CapabilityError.""" + vt = thermal_voltage(300.0) + # Self-consistent left (p-type HTL) and right (n-type ETL) reservoirs: + nc_l, nv_l, chi_l, eg_l = 2.2e24, 1.8e25, 3.50, 2.05 + nc_r, nv_r, chi_r, eg_r = 2.2e24, 1.8e25, 4.00, 3.20 + p_l = 1.0e24 + n_l = nc_l * nv_l * math.exp(-eg_l / vt) / p_l + n_r = 1.0e24 + p_r = nc_r * nv_r * math.exp(-eg_r / vt) / n_r + + left = ContactEndpoint(n_l, p_l, nc_l, nv_l, chi_l, eg_l) + right = ContactEndpoint(n_r, p_r, nc_r, nv_r, chi_r, eg_r) + wf_left = chi_l + eg_l - vt * math.log(nv_l / p_l) + wf_right = chi_r - vt * math.log(n_r / nc_r) + v_bi_compatible = wf_left - wf_right + + # Compatible semiconductor_work_function potential passes the fixed 5 meV gate. + certified = assess_contact_thermodynamics( + built_in_potential_mode="semiconductor_work_function", + left=left, + right=right, + V_bi_bc=v_bi_compatible, + thermal_voltage_V=vt, + semiconductor_potential_V=v_bi_compatible, + has_band_reference=True, + ) + assert CONTACT_THERMODYNAMIC_TOLERANCE_EV == 5.0e-3 + assert require_contact_thermodynamic_certificate(certified).certified + assert certified.historical_label is None + assert certified.fermi_level_span_eV is not None and certified.fermi_level_span_eV < 1.0e-12 + + # Historical 6.024958 meV manual offset stays inconsistent and preserves its label. + historical_offset_v = 6.024958093130195e-3 + inconsistent = assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=left, + right=right, + V_bi_bc=v_bi_compatible + historical_offset_v, + thermal_voltage_V=vt, + semiconductor_potential_V=v_bi_compatible, + has_band_reference=True, + ) + assert inconsistent.status == "inconsistent" and not inconsistent.certified + assert inconsistent.historical_label == LEGACY_MANUAL_CONTACT_OFFSET + assert inconsistent.fermi_level_span_eV == pytest.approx(historical_offset_v, abs=1.0e-12) + with pytest.raises(ContactThermodynamicError, match=LEGACY_MANUAL_CONTACT_OFFSET): + require_contact_thermodynamic_certificate(inconsistent) + with pytest.raises(ValueError, match="cannot exceed"): + assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=left, + right=right, + V_bi_bc=v_bi_compatible + historical_offset_v, + thermal_voltage_V=vt, + tolerance_eV=6.1e-3, + ) + + # Scientifically falsified interface_shared_occupancy=True MUST fail closed across 1D and 2D compilers. + prepared_shared_1d = _prepare_pin_device(settings_override={"interface_shared_occupancy": True}) + with pytest.raises(CapabilityError, match=r"interface_shared_occupancy"): + compile_device_1d(prepared_shared_1d) + + spatial_dc_2d = JV2DInput(kind="jv_2d", lateral_length="100 nm", Nx=2, Ny_per_layer=4, lateral_bc="neumann") + with pytest.raises(CapabilityError, match=r"interface_shared_occupancy"): + compile_device_2d(prepared_shared_1d, spatial_dc_2d) + + prepared_shared_ionic_2d = _prepare_pin_device( + settings_override={"interface_shared_occupancy": True}, + absorber_override={"P0": 1.0e24, "D_ion": 1.0e-16, "P_lim": 1.0e27}, + ) + spatial_ionic_2d = JV2DInput( + kind="jv_2d", + lateral_length="100 nm", + Nx=2, + Ny_per_layer=4, + lateral_bc="neumann", + ion_dynamics="single_mobile", + ) + with pytest.raises(CapabilityError, match=r"interface_shared_occupancy"): + compile_ionic_device_2d( + prepared_shared_ionic_2d, + spatial_ionic_2d, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + + +def test_p08_04_spectral_beer_lambert_photon_budget_and_positive_log_activity_witness() -> None: + """P08-04: Spectral vs scalar Beer-Lambert photon budget & positive log-activity BE under 260.14 A/m^2.""" + thickness_m = 400.0e-9 + wavelengths_m = np.linspace(300.0e-9, 800.0e-9, 201) + # Dispersive perovskite-like absorption spanning 4e7 m^-1 (UV/blue) down to 2.5e5 m^-1 (band edge). + norm_wl = (wavelengths_m - 300.0e-9) / 500.0e-9 + alpha_lambda_m1 = 4.0e7 * np.exp(-5.5 * norm_wl) + # Spectral photon flux normalized so exact single-pass absorbed current q * int(G) dx == 260.14 A/m^2. + raw_flux = 0.6 + 0.4 * np.sin(math.pi * norm_wl) + analytic_fraction = 1.0 - np.exp(-alpha_lambda_m1 * thickness_m) + target_j_ph_a_m2 = 260.14 + target_absorbed_photons = target_j_ph_a_m2 / Q + flux_scale = target_absorbed_photons / float(np.trapezoid(raw_flux * analytic_fraction, wavelengths_m)) + spectral_flux_m3_s = raw_flux * flux_scale + + def spectral_cv_generation(grid_m: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + geom = half_endpoint_geometry(grid_m) + faces = geom.cell_faces_m + tau_faces = faces[:, None] * alpha_lambda_m1[None, :] + absorbed_per_wl = np.exp(-tau_faces[:-1]) * (-np.expm1(-np.diff(tau_faces, axis=0))) + absorbed_cells = np.trapezoid(absorbed_per_wl * spectral_flux_m3_s[None, :], wavelengths_m, axis=1) + return absorbed_cells / geom.cell_measures_m, geom.cell_measures_m + + # Non-uniform front-clustered coarse (N=15) vs fine (N=91) meshes: + s_coarse = np.linspace(0.0, 1.0, 15) ** 1.8 + s_fine = np.linspace(0.0, 1.0, 91) ** 1.8 + x_coarse = thickness_m * s_coarse + x_fine = thickness_m * s_fine + + gen_coarse, w_coarse = spectral_cv_generation(x_coarse) + gen_fine, w_fine = spectral_cv_generation(x_fine) + + # Exact control-volume spectral Beer-Lambert is mesh-independent to machine precision. + assert float(np.dot(gen_coarse, w_coarse)) == pytest.approx(target_absorbed_photons, rel=1.0e-14) + assert float(np.dot(gen_fine, w_fine)) == pytest.approx(target_absorbed_photons, rel=1.0e-14) + + # Contrast against monochromatic Beer-Lambert: + phi_incident_total = float(np.trapezoid(spectral_flux_m3_s, wavelengths_m)) + alpha_flux_weighted = float(np.trapezoid(spectral_flux_m3_s * alpha_lambda_m1, wavelengths_m)) / phi_incident_total + geom_fine = half_endpoint_geometry(x_fine) + gen_scalar_mean = beer_lambert_generation(geom_fine, alpha_flux_weighted, phi_incident_total) + # 1) Jensen's inequality: scalar mean alpha overpredicts total absorbed photons. + assert float(np.dot(gen_scalar_mean, w_fine)) > 1.05 * target_absorbed_photons + # 2) Even if scalar alpha_eff is tuned to match total absorbed photons exactly, it severely underpredicts + # front-surface peak generation G[0] compared with dispersive short-wavelength absorption. + alpha_eff_matched = -math.log(1.0 - target_absorbed_photons / phi_incident_total) / thickness_m + gen_scalar_matched = beer_lambert_generation(geom_fine, alpha_eff_matched, phi_incident_total) + assert float(np.dot(gen_scalar_matched, w_fine)) == pytest.approx(target_absorbed_photons, rel=1.0e-14) + assert gen_fine[0] > 2.5 * gen_scalar_matched[0] + + # Positive-density transient witness at high front generation (q * Phi_abs ~ 260.14 A/m^2): + # Legacy density-variable Radau hit p < 0 at the absorber front; new-core log-activity coordinates + # + BackwardEuler1DStep guarantee strict n > 0, p > 0 and exact global particle conservation. + prepared = _prepare_pin_device() + device = compile_device_1d(prepared, intervals_per_layer=(6, 12, 6)) + dark_eq = solve_equilibrium(device) + assert dark_eq.converged + + # Verify illuminated steady-state and a sharp dark-to-1-sun BackwardEuler1DStep both stay strictly positive. + illum_ss = solve_steady_state(device, voltage_V=0.0, generation_scale=1.0) + assert illum_ss.converged + assert np.all(illum_ss.state.electron_density_m3 > 0.0) + assert np.all(illum_ss.state.hole_density_m3 > 0.0) + + # First-order linear-density update witness under carrier extraction shock (1-sun -> dark reverse bias): + # du_p < -1 on depleted nodes drives linear tangent p_0 * (1 + du_p) < 0, whereas log-activity stays > 0. + dc_extract = DC1DProblem(device, voltage_V=-0.4, generation_scale=0.0) + step_extract = BackwardEuler1DStep(endpoint=dc_extract, previous=illum_ss.state, dt_s=1.0e-6) + u_extract_0 = step_extract.initial_coordinates(predictor="previous") + du_extract = np.asarray( + spsolve(step_extract.jacobian(u_extract_0), -step_extract.residual(u_extract_0)), + dtype=float, + ) + du_p_extract = du_extract[2 * device.node_count :] + linear_tangent_p = illum_ss.state.hole_density_m3 * (1.0 + du_p_extract) + assert np.min(linear_tangent_p) < 0.0 + unclipped_log_trial = device.state(u_extract_0 + du_extract, voltage_V=-0.4) + assert np.all(unclipped_log_trial.hole_density_m3 > 0.0) + + # Illuminated bias-ramp transient solved in log-activity coordinates via conservative Backward Euler: + protocol = TransientProtocol( + times_s=np.array([0.0, 5.0e-8, 1.0e-7]), + voltage_V=np.array([0.0, 0.05, 0.10]), + generation_scale=np.array([1.0, 1.0, 1.0]), + ) + tr_options = TransientOptions( + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=1.0e-8, + contact_log_tolerance=1.0e-11, + potential_step_V=0.1, + quasi_fermi_step=2.0, + newton_budget=SolveBudget(60, 1000, 60, 24), + max_steps=8, + wall_s=10.0, + predictor="previous", + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + tr_result = solve_transient( + device, + illum_ss, + protocol, + options=tr_options, + initial_options=SteadyOptions(), + method="backward_euler", + ) + assert tr_result.completed + for accepted_state in tr_result.states: + assert np.all(accepted_state.electron_density_m3 > 0.0) + assert np.all(accepted_state.hole_density_m3 > 0.0) + for attempt in tr_result.attempts: + assert attempt.accounting is not None + pair_total = float(np.sum(np.abs(np.asarray(attempt.accounting["net_pair_source_m2_s"], dtype=float)))) + global_balance = np.asarray(attempt.accounting["global_particle_balance_m2_s"], dtype=float) + assert float(np.max(np.abs(global_balance))) <= 1.0e-11 * max(pair_total, 1.0) From e16f748f089c22e11c87e19bdb2aa9489d19b5e0 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 22:18:31 +0800 Subject: [PATCH 21/46] P(electrostatics): add sub-face material-extent series dielectric capacitance (P08-02a) --- src/solarlab/device/compile_2d.py | 31 +- src/solarlab/discretization/__init__.py | 9 +- src/solarlab/discretization/face_average.py | 60 +++ src/solarlab/equations/dc_2d.py | 44 +- .../physics/electrostatics/__init__.py | 14 +- .../physics/electrostatics/poisson.py | 419 ++++++++++++++++- .../test_p08_02_refinement_and_parity.py | 238 ++++++++++ .../test_p08_02_dielectric_and_geometry.py | 433 ++++++++++++++++++ 8 files changed, 1219 insertions(+), 29 deletions(-) create mode 100644 tests/integration/test_p08_02_refinement_and_parity.py create mode 100644 tests/unit/physics/test_p08_02_dielectric_and_geometry.py diff --git a/src/solarlab/device/compile_2d.py b/src/solarlab/device/compile_2d.py index 99dad151..ee689816 100644 --- a/src/solarlab/device/compile_2d.py +++ b/src/solarlab/device/compile_2d.py @@ -19,6 +19,9 @@ from solarlab.device.inputs import DeviceInput from solarlab.device.resolved import PreparedDevice from solarlab.device.optical_generation_2d import bind_optical_generation_2d +from solarlab.discretization.face_average import ( + DIELECTRIC_RULES, NODAL_HARMONIC_DIELECTRIC_V1, +) from solarlab.equations.dc_1d import CapabilityError from solarlab.equations.dc_2d import CompiledDevice2D from solarlab.equations.field_transport_2d import bind_field_transport_2d @@ -35,7 +38,12 @@ _GEOMETRY_FIELDS = frozenset({"kind", "lateral_length", "Nx", "Ny_per_layer", "lateral_bc", "microstructure"}) -def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledDevice2D: +def compile_device_2d( + prepared: PreparedDevice, + spatial: JV2DInput, + *, + dielectric_rule: str = NODAL_HARMONIC_DIELECTRIC_V1, +) -> CompiledDevice2D: """Compile without a nonlinear solve or inferred geometric defaults. Nx and Ny_per_layer are interval counts; all electrical layers receive @@ -46,6 +54,8 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD """ if not isinstance(prepared, PreparedDevice) or not isinstance(spatial, JV2DInput): raise TypeError("compile_device_2d requires PreparedDevice and typed JV2DInput geometry") + if dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown 2D dielectric rule {dielectric_rule!r}") for name in spatial.model_fields_set - _GEOMETRY_FIELDS: if getattr(spatial, name) is not None: raise CapabilityError("unsupported_classical_2d_dc: execution field " + name) @@ -125,5 +135,20 @@ def compile_device_2d(prepared: PreparedDevice, spatial: JV2DInput) -> CompiledD identity = hashlib.sha256(json.dumps((identity, optical.identity_sha256), separators=(",", ":")).encode()).hexdigest() if transport is not None: identity = hashlib.sha256(json.dumps((identity, transport.identity_sha256), separators=(",", ":")).encode()).hexdigest() - return CompiledDevice2D(identity, column, geometry, generation, eps, declaration, - grain_recombination=grains, column_projection_json=projection, field_transport=transport) + layer_permittivity_y: tuple[float, ...] | None = None + if dielectric_rule != NODAL_HARMONIC_DIELECTRIC_V1: + layer_eps_list: list[float] = [] + for layer in prepared.layers: + raw_eps = dict(layer.parameters)["eps_r"] + if isinstance(raw_eps, bool) or not isinstance(raw_eps, (int, float)): + raise ValueError(f"layer {layer.id!r} eps_r must be numeric") + layer_eps_list.append(float(raw_eps)) + layer_permittivity_y = tuple(layer_eps_list) + identity = hashlib.sha256( + json.dumps((identity, "dielectric_rule", dielectric_rule), separators=(",", ":")).encode() + ).hexdigest() + return CompiledDevice2D( + identity, column, geometry, generation, eps, declaration, + grain_recombination=grains, column_projection_json=projection, field_transport=transport, + dielectric_rule=dielectric_rule, layer_permittivity_y=layer_permittivity_y, + ) diff --git a/src/solarlab/discretization/__init__.py b/src/solarlab/discretization/__init__.py index 244f7cea..93639b4a 100644 --- a/src/solarlab/discretization/__init__.py +++ b/src/solarlab/discretization/__init__.py @@ -9,8 +9,10 @@ from solarlab.discretization.bernoulli import bernoulli, bernoulli_derivative from solarlab.discretization.divergence import flux_divergence from solarlab.discretization.face_average import ( + DIELECTRIC_RULES, LAYER_SERIES_CAPACITANCE_V2, NODAL_HARMONIC_DIELECTRIC_V1, VACUUM_PERMITTIVITY_F_M, arithmetic_face_mean, guarded_harmonic_face_mean, harmonic_face_mean, harmonic_mean, series_face_capacitance, + subface_series_capacitance, ) from solarlab.discretization.scharfetter_gummel import ( LegacyFaceJacobian, legacy_sg_current_n, legacy_sg_current_n_jacobian, @@ -18,9 +20,10 @@ ) __all__ = [ - "LegacyFaceJacobian", "VACUUM_PERMITTIVITY_F_M", "arithmetic_face_mean", "bernoulli", - "bernoulli_derivative", "flux_divergence", "guarded_harmonic_face_mean", + "DIELECTRIC_RULES", "LAYER_SERIES_CAPACITANCE_V2", "LegacyFaceJacobian", + "NODAL_HARMONIC_DIELECTRIC_V1", "VACUUM_PERMITTIVITY_F_M", "arithmetic_face_mean", + "bernoulli", "bernoulli_derivative", "flux_divergence", "guarded_harmonic_face_mean", "harmonic_face_mean", "harmonic_mean", "legacy_sg_current_n", "legacy_sg_current_n_jacobian", "legacy_sg_current_p", "legacy_sg_current_p_jacobian", - "series_face_capacitance", + "series_face_capacitance", "subface_series_capacitance", ] diff --git a/src/solarlab/discretization/face_average.py b/src/solarlab/discretization/face_average.py index 5f396b5c..9e2728a5 100644 --- a/src/solarlab/discretization/face_average.py +++ b/src/solarlab/discretization/face_average.py @@ -22,8 +22,10 @@ from numpy.typing import ArrayLike, NDArray __all__ = [ + "DIELECTRIC_RULES", "LAYER_SERIES_CAPACITANCE_V2", "NODAL_HARMONIC_DIELECTRIC_V1", "VACUUM_PERMITTIVITY_F_M", "arithmetic_face_mean", "guarded_harmonic_face_mean", "harmonic_face_mean", "harmonic_mean", "series_face_capacitance", + "subface_series_capacitance", ] # Historical binary64 value of the legacy engine (CODATA 2006). It differs from @@ -31,6 +33,10 @@ # correction, not part of this behaviour-preserving migration. VACUUM_PERMITTIVITY_F_M = 8.854187817e-12 +NODAL_HARMONIC_DIELECTRIC_V1 = "nodal_harmonic_v1" +LAYER_SERIES_CAPACITANCE_V2 = "layer_series_capacitance_v2" +DIELECTRIC_RULES = (NODAL_HARMONIC_DIELECTRIC_V1, LAYER_SERIES_CAPACITANCE_V2) + def harmonic_mean(a: ArrayLike, b: ArrayLike) -> NDArray[np.float64]: left = np.asarray(a, dtype=float) @@ -83,3 +89,57 @@ def series_face_capacitance( float(left_distance_m) / float(eps_r_left) + float(right_distance_m) / float(eps_r_right) )) + + +def subface_series_capacitance( + left_distance_m: ArrayLike, + eps_r_left: ArrayLike, + right_distance_m: ArrayLike, + eps_r_right: ArrayLike, +) -> NDArray[np.float64]: + """Sub-face material-extent series capacitance [F/m^2] (P08-02a). + + Each face of total spacing ``d_L + d_R > 0`` is partitioned at the true + material plane into nonnegative left/right material extents ``d_L >= 0`` + and ``d_R >= 0`` with positive relative permittivities ``eps_L, eps_R``: + + C_f = eps_0 / (d_L / eps_L + d_R / eps_R). + + Unsplit faces (``d_L == 0`` or ``d_R == 0``) and homogeneous faces + (``eps_L == eps_R``) evaluate directly as ``eps_0 * eps / (d_L + d_R)`` + so homogeneous layers agree with ``eps_0 * eps / h`` to 0-1 ULP. + """ + d_left, e_left, d_right, e_right = np.broadcast_arrays( + np.asarray(left_distance_m, dtype=float), + np.asarray(eps_r_left, dtype=float), + np.asarray(right_distance_m, dtype=float), + np.asarray(eps_r_right, dtype=float), + ) + if not ( + np.all(np.isfinite(d_left)) + and np.all(np.isfinite(e_left)) + and np.all(np.isfinite(d_right)) + and np.all(np.isfinite(e_right)) + ): + raise ValueError("sub-face series capacitance requires finite distances and permittivities") + total_distance = d_left + d_right + if np.any(d_left < 0.0) or np.any(d_right < 0.0) or np.any(total_distance <= 0.0): + raise ValueError("sub-face distances must be nonnegative with positive face spacing") + if np.any(e_left <= 0.0) or np.any(e_right <= 0.0): + raise ValueError("sub-face permittivities must be positive") + out = np.empty(total_distance.shape, dtype=np.float64) + left_only = d_right == 0.0 + right_only = (~left_only) & (d_left == 0.0) + same_eps = (~left_only) & (~right_only) & (e_left == e_right) + split = ~(left_only | right_only | same_eps) + if np.any(left_only): + out[left_only] = VACUUM_PERMITTIVITY_F_M * e_left[left_only] / d_left[left_only] + if np.any(right_only): + out[right_only] = VACUUM_PERMITTIVITY_F_M * e_right[right_only] / d_right[right_only] + if np.any(same_eps): + out[same_eps] = VACUUM_PERMITTIVITY_F_M * e_left[same_eps] / total_distance[same_eps] + if np.any(split): + out[split] = VACUUM_PERMITTIVITY_F_M / ( + d_left[split] / e_left[split] + d_right[split] / e_right[split] + ) + return out diff --git a/src/solarlab/equations/dc_2d.py b/src/solarlab/equations/dc_2d.py index 1250e092..24c281b4 100644 --- a/src/solarlab/equations/dc_2d.py +++ b/src/solarlab/equations/dc_2d.py @@ -22,13 +22,16 @@ FaceFlux, Layout, Support, TermSink, frozen_array, ) from solarlab.contracts.units import ELEMENTARY_CHARGE_C -from solarlab.discretization.face_average import VACUUM_PERMITTIVITY_F_M +from solarlab.discretization.face_average import ( + DIELECTRIC_RULES, NODAL_HARMONIC_DIELECTRIC_V1, VACUUM_PERMITTIVITY_F_M, +) from solarlab.equations.dc_1d import CompiledDevice1D, quasi_fermi_potential_tangents from solarlab.equations.field_transport_2d import FieldTransport2D from solarlab.mesh.geometry_2d import RectangularGeometry2D from solarlab.physics.contacts.boundary_flux import boundary_particle_flux from solarlab.physics.contacts.exchange import CarrierExchangeChannel from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger +from solarlab.physics.electrostatics.poisson import rectangular_2d_face_capacitances from solarlab.physics.generation.profile import GenerationProfile from solarlab.physics.recombination.bulk import RecombinationRate from solarlab.physics.recombination.reaction import ( @@ -91,6 +94,11 @@ class CompiledDevice2D: grain_recombination: GrainRecombinationModel2D | None = None column_projection_json: bytes | None = None field_transport: FieldTransport2D | None = None + dielectric_rule: str = NODAL_HARMONIC_DIELECTRIC_V1 + layer_permittivity_y: tuple[float, ...] | None = None + lateral_permittivity_x: Vector | None = None + lateral_interfaces_m: tuple[float, ...] = () + lateral_layer_permittivity_x: tuple[float, ...] | None = None band_structure: BandStructure = field(init=False) recombination: BulkRecombinationReaction = field(init=False) generation_source_m3_s: Vector = field(init=False) @@ -142,11 +150,35 @@ def __post_init__(self) -> None: or not np.array_equal(model.base_electron_diffusivity_m2_s, self.electron_diffusivity_faces_m2_s) or not np.array_equal(model.base_hole_diffusivity_m2_s, self.hole_diffusivity_faces_m2_s)): raise ValueError("field transport must match the exact2D grid, temperature and baseD") - dx_row = (np.diff(geometry.x_m) if geometry.lateral_bc == "neumann" - else geometry.face_spacing_m[:geometry.nx]) - horizontal_capacitance = (VACUUM_PERMITTIVITY_F_M * eps[:, None] / dx_row[None, :]).ravel() - object.__setattr__(self, "face_capacitance_F_m2", frozen_array(np.r_[ - horizontal_capacitance, np.repeat(column.poisson.face_capacitance_F_m2, geometry.nx)])) + if self.dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown 2D dielectric rule {self.dielectric_rule!r}") + if ( + self.dielectric_rule == NODAL_HARMONIC_DIELECTRIC_V1 + and self.lateral_permittivity_x is None + and not self.lateral_interfaces_m + and self.lateral_layer_permittivity_x is None + ): + dx_row = (np.diff(geometry.x_m) if geometry.lateral_bc == "neumann" + else geometry.face_spacing_m[:geometry.nx]) + horizontal_capacitance = (VACUUM_PERMITTIVITY_F_M * eps[:, None] / dx_row[None, :]).ravel() + object.__setattr__(self, "face_capacitance_F_m2", frozen_array(np.r_[ + horizontal_capacitance, np.repeat(column.poisson.face_capacitance_F_m2, geometry.nx)])) + else: + if self.lateral_permittivity_x is not None: + object.__setattr__(self, "lateral_permittivity_x", frozen_array(self.lateral_permittivity_x)) + object.__setattr__( + self, + "face_capacitance_F_m2", + rectangular_2d_face_capacitances( + geometry, + eps, + dielectric_rule=self.dielectric_rule, + layer_eps_r_y=self.layer_permittivity_y, + lateral_eps_r_x=self.lateral_permittivity_x, + lateral_interfaces_m=self.lateral_interfaces_m, + lateral_layer_eps_r_x=self.lateral_layer_permittivity_x, + ), + ) faces = geometry.face_spacing_m.size object.__setattr__(self, "layout", Layout( (Support("cells", "cell", (self.node_count,)), Support("faces", "face", (faces,))), (), diff --git a/src/solarlab/physics/electrostatics/__init__.py b/src/solarlab/physics/electrostatics/__init__.py index 73cfde4d..5cf320ac 100644 --- a/src/solarlab/physics/electrostatics/__init__.py +++ b/src/solarlab/physics/electrostatics/__init__.py @@ -14,14 +14,20 @@ require_occupancy, sheet_charge_row_weights, solve_electrostatic_traces, ) from solarlab.physics.electrostatics.poisson import ( - PoissonFactorization, PoissonOperator1D, contact_displacement, + PoissonFactorization, PoissonOperator1D, add_interface_sheet_charge, + cell_parallel_permittivities, contact_displacement, + layer_permittivities_from_geometry, layer_series_face_capacitances, + rectangular_2d_face_capacitances, ) __all__ = [ "ChargeEntry", "ChargeLedger", "InterfaceTraceDeclaration", "PoissonFactorization", "PoissonOperator1D", "SPACE_CHARGE_GROUP", "SheetChargeEntry", - "TraceElectrostatics", "add_sheet_charge_to_interior_residual", "contact_displacement", - "electrostatic_trace_residual_and_jacobian", - "interface_trace_layout", "require_carrier_trace", "require_occupancy", + "TraceElectrostatics", "add_interface_sheet_charge", + "add_sheet_charge_to_interior_residual", "cell_parallel_permittivities", + "contact_displacement", "electrostatic_trace_residual_and_jacobian", + "interface_trace_layout", "layer_permittivities_from_geometry", + "layer_series_face_capacitances", "rectangular_2d_face_capacitances", + "require_carrier_trace", "require_occupancy", "sheet_charge_row_weights", "solve_electrostatic_traces", ] diff --git a/src/solarlab/physics/electrostatics/poisson.py b/src/solarlab/physics/electrostatics/poisson.py index 6027eda2..548eb831 100644 --- a/src/solarlab/physics/electrostatics/poisson.py +++ b/src/solarlab/physics/electrostatics/poisson.py @@ -17,6 +17,7 @@ from __future__ import annotations +from collections.abc import Sequence from dataclasses import dataclass import math @@ -27,18 +28,357 @@ from solarlab.contracts.arrays import ImmutableArrays, frozen_array from solarlab.discretization.face_average import ( - VACUUM_PERMITTIVITY_F_M, harmonic_face_mean, series_face_capacitance, + DIELECTRIC_RULES, LAYER_SERIES_CAPACITANCE_V2, NODAL_HARMONIC_DIELECTRIC_V1, + VACUUM_PERMITTIVITY_F_M, harmonic_face_mean, harmonic_mean, + series_face_capacitance, subface_series_capacitance, ) from solarlab.mesh.geometry import ( - HALF_ENDPOINT_V1, INTEGER_ENDPOINT_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1, - TWO_SIDED_TRACE_V1, ControlVolumeGeometry1D, + HALF_ENDPOINT_V1, INTEGER_ENDPOINT_V1, NO_SHARED_NODES, + PHYSICAL_BOUNDARY_TWO_SIDED_V1, TWO_SIDED_TRACE_V1, ControlVolumeGeometry1D, + dual_cell_faces, ) +from solarlab.mesh.geometry_2d import RectangularGeometry2D +from solarlab.mesh.grid import LEFT_LAYER_WINS, RIGHT_LAYER_WINS, build_interface_stencils -__all__ = ["PoissonFactorization", "PoissonOperator1D", "contact_displacement"] +__all__ = [ + "PoissonFactorization", "PoissonOperator1D", "add_interface_sheet_charge", + "cell_parallel_permittivities", "contact_displacement", + "layer_permittivities_from_geometry", "layer_series_face_capacitances", + "rectangular_2d_face_capacitances", +] EPS_0 = VACUUM_PERMITTIVITY_F_M +def _validate_nodal_permittivity( + nodes: NDArray[np.float64], eps_r_node: ArrayLike +) -> NDArray[np.float64]: + permittivity = np.asarray(eps_r_node, dtype=float) + if ( + permittivity.shape != nodes.shape + or not np.all(np.isfinite(permittivity)) + or np.any(permittivity <= 0.0) + ): + raise ValueError("permittivity must be finite and positive on the geometry nodes") + return permittivity + + +def layer_permittivities_from_geometry( + geometry: ControlVolumeGeometry1D, + eps_r_node: ArrayLike | None = None, + *, + layer_eps_r: Sequence[float] | ArrayLike | None = None, +) -> NDArray[np.float64]: + """Resolve the positive relative permittivity of each geometry layer (P08-02a).""" + layer_count = len(geometry.interfaces) + 1 + if eps_r_node is not None: + permittivity = _validate_nodal_permittivity(geometry.nodes_m, eps_r_node) + else: + permittivity = None + if layer_eps_r is not None: + layers: NDArray[np.float64] = np.asarray(layer_eps_r, dtype=np.float64) + if ( + layers.shape != (layer_count,) + or not np.all(np.isfinite(layers)) + or np.any(layers <= 0.0) + ): + raise ValueError("layer_eps_r must supply one finite positive value per layer") + return frozen_array(layers) + if permittivity is None: + raise ValueError("either eps_r_node or layer_eps_r is required") + if layer_count == 1: + if not np.all(permittivity == permittivity[0]): + raise ValueError( + "single-layer nodal permittivity is non-uniform; supply explicit layer/sub-face permittivities" + ) + return frozen_array(np.array([permittivity[0]], dtype=np.float64)) + nodes = geometry.nodes_m + positions = [plane.position_m for plane in geometry.interfaces] + convention = geometry.material_owner_convention + layers = np.empty(layer_count, dtype=np.float64) + for m in range(layer_count): + lower = -math.inf if m == 0 else positions[m - 1] + upper = math.inf if m == layer_count - 1 else positions[m] + if convention == RIGHT_LAYER_WINS: + mask = (nodes >= lower) & (nodes < upper) if m < layer_count - 1 else (nodes >= lower) + elif convention == LEFT_LAYER_WINS: + if m == 0: + mask = nodes <= upper + elif m < layer_count - 1: + mask = (nodes > lower) & (nodes <= upper) + else: + mask = nodes > lower + elif convention == NO_SHARED_NODES: + mask = (nodes > lower) & (nodes < upper) + else: + raise ValueError(f"unsupported material owner convention {convention!r}") + if not np.any(mask): + raise ValueError(f"layer {m} owns no grid nodes; pass layer_eps_r explicitly") + layer_values = permittivity[mask] + if not np.all(layer_values == layer_values[0]): + raise ValueError( + f"layer {m} nodal permittivity is non-uniform; pass explicit sub-face permittivities" + ) + layers[m] = float(layer_values[0]) + return frozen_array(layers) + + +def _axis_series_capacitances( + nodes: NDArray[np.float64], + positions: Sequence[float], + layers: NDArray[np.float64], +) -> NDArray[np.float64]: + h = np.diff(nodes) + if len(positions) == 0: + return frozen_array(subface_series_capacitance(h, layers[0], np.zeros_like(h), layers[0])) + pos_arr: NDArray[np.float64] = np.asarray(positions, dtype=np.float64) + stencils = build_interface_stencils(nodes, pos_arr) + layer_index: NDArray[np.intp] = np.asarray( + np.searchsorted(pos_arr, nodes[:-1], side="right"), dtype=np.intp + ) + d_left = h.copy() + d_right = np.zeros_like(h) + e_left = layers[layer_index].copy() + e_right = e_left.copy() + used_faces: set[int] = set() + for m, stencil in enumerate(stencils): + if stencil.shared_boundary_node is not None: + continue + if stencil.right_bulk_node != stencil.left_bulk_node + 1: + raise ValueError("split dielectric face requires adjacent bulk nodes") + face = int(stencil.left_bulk_node) + if face in used_faces: + raise ValueError("multiple material planes inside one face require multi-slab integration") + used_faces.add(face) + d_left[face] = float(stencil.left_distance_m) + d_right[face] = float(stencil.right_distance_m) + e_left[face] = float(layers[m]) + e_right[face] = float(layers[m + 1]) + return frozen_array(subface_series_capacitance(d_left, e_left, d_right, e_right)) + + +def layer_series_face_capacitances( + geometry: ControlVolumeGeometry1D, + eps_r_node: ArrayLike | None = None, + *, + layer_eps_r: Sequence[float] | ArrayLike | None = None, +) -> NDArray[np.float64]: + """Sub-face material-extent series capacitances [F/m^2] on a 1D geometry (P08-02a). + + On shared-node grids (``x_k = X_if``), face ``[x_{k-1}, x_k]`` lies wholly in + the left layer (``eps_L``) and face ``[x_k, x_{k+1}]`` lies wholly in the + right layer (``eps_R``). On two-sided grids, the split face uses exact + sub-face extents ``d_L = X_if - x_L`` and ``d_R = x_R - X_if``. + """ + layers = layer_permittivities_from_geometry(geometry, eps_r_node, layer_eps_r=layer_eps_r) + positions = [plane.position_m for plane in geometry.interfaces] + return _axis_series_capacitances(geometry.nodes_m, positions, layers) + + +def _cell_parallel_from_faces( + cell_faces: NDArray[np.float64], + positions: Sequence[float], + layers: NDArray[np.float64], +) -> NDArray[np.float64]: + cell_count = cell_faces.size - 1 + if len(positions) == 0: + return frozen_array(np.full(cell_count, float(layers[0]), dtype=float)) + pos_arr: NDArray[np.float64] = np.asarray(positions, dtype=np.float64) + left_layer: NDArray[np.intp] = np.asarray( + np.searchsorted(pos_arr, cell_faces[:-1], side="right"), dtype=np.intp + ) + right_layer: NDArray[np.intp] = np.asarray( + np.searchsorted(pos_arr, cell_faces[1:], side="left"), dtype=np.intp + ) + parallel = layers[left_layer].copy() + bounds = np.r_[cell_faces[0], pos_arr, cell_faces[-1]] + straddling = np.flatnonzero(left_layer != right_layer) + for raw_idx in straddling: + idx = int(raw_idx) + lo = float(cell_faces[idx]) + hi = float(cell_faces[idx + 1]) + m_start = int(left_layer[idx]) + m_stop = int(right_layer[idx]) + involved = layers[m_start : m_stop + 1] + if np.all(involved == involved[0]): + parallel[idx] = float(involved[0]) + continue + weighted = 0.0 + for m in range(m_start, m_stop + 1): + overlap = min(hi, float(bounds[m + 1])) - max(lo, float(bounds[m])) + if overlap > 0.0: + weighted += overlap * float(layers[m]) + parallel[idx] = weighted / (hi - lo) + return frozen_array(parallel) + + +def cell_parallel_permittivities( + geometry: ControlVolumeGeometry1D, + eps_r_node: ArrayLike | None = None, + *, + layer_eps_r: Sequence[float] | ArrayLike | None = None, +) -> NDArray[np.float64]: + """Thickness-weighted parallel permittivity on each 1D control volume (P08-02a).""" + layers = layer_permittivities_from_geometry(geometry, eps_r_node, layer_eps_r=layer_eps_r) + positions = [plane.position_m for plane in geometry.interfaces] + return _cell_parallel_from_faces(geometry.cell_faces_m, positions, layers) + + +def add_interface_sheet_charge( + interior_residual_C_m2: NDArray[np.float64], + geometry: ControlVolumeGeometry1D, + sheet_charge_C_m2: ArrayLike, + *, + eps_r_node: ArrayLike | None = None, + layer_eps_r: Sequence[float] | ArrayLike | None = None, +) -> None: + """Add sheet charge ``sigma`` [C/m^2] so ``D_R - D_L = sigma`` at every interface. + + Shared-node interfaces place node ``k`` on the material plane, so ``sigma`` + enters interior Gauss row ``k - 1`` directly. Two-sided split faces partition + ``sigma`` by exact sub-face series elimination weights ``(c_L, c_R) / (c_L + c_R)``. + """ + sheets = np.asarray(sheet_charge_C_m2, dtype=float) + if sheets.shape != (len(geometry.interfaces),) or not np.all(np.isfinite(sheets)): + raise ValueError("sheet_charge_C_m2 must provide one finite value per interface") + if interior_residual_C_m2.shape != (geometry.node_count - 2,): + raise ValueError("interior_residual_C_m2 must match interior Poisson rows") + if len(geometry.interfaces) == 0: + return + needs_layers = any(plane.shared_node is None for plane in geometry.interfaces) + layers = ( + layer_permittivities_from_geometry(geometry, eps_r_node, layer_eps_r=layer_eps_r) + if needs_layers + else None + ) + for plane, sigma in zip(geometry.interfaces, sheets): + if plane.shared_node is not None: + if plane.shared_node <= 0 or plane.shared_node >= geometry.node_count - 1: + raise ValueError("shared interface node cannot lie on a Dirichlet contact") + interior_residual_C_m2[plane.shared_node - 1] += float(sigma) + else: + assert layers is not None + c_left = float(layers[plane.index]) / float(plane.left_distance_m) + c_right = float(layers[plane.index + 1]) / float(plane.right_distance_m) + total = c_left + c_right + if 0 < plane.left_node < geometry.node_count - 1: + interior_residual_C_m2[plane.left_node - 1] += (c_left / total) * float(sigma) + if 0 < plane.right_node < geometry.node_count - 1: + interior_residual_C_m2[plane.right_node - 1] += (c_right / total) * float(sigma) + + +def rectangular_2d_face_capacitances( + geometry: RectangularGeometry2D, + eps_r_y: ArrayLike, + *, + dielectric_rule: str = NODAL_HARMONIC_DIELECTRIC_V1, + layer_eps_r_y: Sequence[float] | ArrayLike | None = None, + lateral_eps_r_x: ArrayLike | None = None, + lateral_interfaces_m: ArrayLike = (), + lateral_layer_eps_r_x: Sequence[float] | ArrayLike | None = None, +) -> NDArray[np.float64]: + """2D graph face capacitances [F/m^2] on ``x`` faces then ``y`` faces (P08-02a).""" + if dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown dielectric rule {dielectric_rule!r}") + eps_y = _validate_nodal_permittivity(geometry.y_geometry.nodes_m, eps_r_y) + dx_row = ( + np.diff(geometry.x_m) + if geometry.lateral_bc == "neumann" + else geometry.face_spacing_m[: geometry.nx] + ) + lat_positions = np.asarray(lateral_interfaces_m, dtype=float) + if lat_positions.ndim != 1 or not np.all(np.isfinite(lat_positions)) or np.any(np.diff(lat_positions) <= 0.0): + raise ValueError("lateral_interfaces_m must be finite and strictly increasing") + + if lateral_eps_r_x is None and lat_positions.size == 0 and lateral_layer_eps_r_x is None: + if dielectric_rule == NODAL_HARMONIC_DIELECTRIC_V1: + horizontal = (EPS_0 * eps_y[:, None] / dx_row[None, :]).ravel() + vertical_1d = PoissonOperator1D.from_harmonic_nodes( + geometry.y_geometry.nodes_m, eps_y, geometry_name=geometry.y_geometry.name + ).face_capacitance_F_m2 + return frozen_array(np.r_[horizontal, np.repeat(vertical_1d, geometry.nx)]) + vertical_1d = layer_series_face_capacitances( + geometry.y_geometry, eps_y, layer_eps_r=layer_eps_r_y + ) + eps_parallel_y = cell_parallel_permittivities( + geometry.y_geometry, eps_y, layer_eps_r=layer_eps_r_y + ) + horizontal = (EPS_0 * eps_parallel_y[:, None] / dx_row[None, :]).ravel() + return frozen_array(np.r_[horizontal, np.repeat(vertical_1d, geometry.nx)]) + + if not np.all(eps_y == eps_y[0]): + raise ValueError("lateral permittivity profile requires uniform stack eps_r_y") + eps_x = ( + _validate_nodal_permittivity(geometry.x_m, lateral_eps_r_x) + if lateral_eps_r_x is not None + else None + ) + if dielectric_rule == NODAL_HARMONIC_DIELECTRIC_V1: + if eps_x is None: + raise ValueError("nodal_harmonic_v1 lateral profile requires nodal lateral_eps_r_x") + interior_x = EPS_0 * harmonic_face_mean(eps_x) / np.diff(geometry.x_m) + if geometry.lateral_bc == "periodic": + wrap_eps = float(harmonic_mean(eps_x[-1], eps_x[0])) + row_x = np.r_[interior_x, EPS_0 * wrap_eps / dx_row[-1]] + else: + row_x = interior_x + dy = np.diff(geometry.y_geometry.nodes_m) + vertical = (EPS_0 * eps_x[None, :] / dy[:, None]).ravel() + return frozen_array(np.r_[np.tile(row_x, geometry.ny), vertical]) + + # LAYER_SERIES_CAPACITANCE_V2 with lateral dielectric interfaces along x. + x_layer_count = int(lat_positions.size) + 1 + layers_x: NDArray[np.float64] + if lateral_layer_eps_r_x is not None: + layers_x = np.asarray(lateral_layer_eps_r_x, dtype=np.float64) + if layers_x.shape != (x_layer_count,) or not np.all(np.isfinite(layers_x)) or np.any(layers_x <= 0.0): + raise ValueError("lateral_layer_eps_r_x must supply one finite positive value per lateral region") + else: + if eps_x is None: + raise ValueError("either lateral_eps_r_x or lateral_layer_eps_r_x is required") + if x_layer_count == 1: + if not np.all(eps_x == eps_x[0]): + raise ValueError("single-region lateral_eps_r_x must be uniform") + layers_x = np.array([float(eps_x[0])], dtype=np.float64) + else: + stencils_x = build_interface_stencils(geometry.x_m, lat_positions) + has_shared = any(s.shared_boundary_node is not None for s in stencils_x) + layers_x = np.empty(x_layer_count, dtype=np.float64) + for m in range(x_layer_count): + lo = -math.inf if m == 0 else float(lat_positions[m - 1]) + hi = math.inf if m == x_layer_count - 1 else float(lat_positions[m]) + if has_shared: + mask = (geometry.x_m >= lo) & (geometry.x_m < hi) if m < x_layer_count - 1 else (geometry.x_m >= lo) + else: + mask = (geometry.x_m > lo) & (geometry.x_m < hi) + if not np.any(mask) or not np.all(eps_x[mask] == eps_x[mask][0]): + raise ValueError("lateral_eps_r_x must be piecewise-constant per lateral region") + layers_x[m] = float(eps_x[mask][0]) + interior_x = _axis_series_capacitances(geometry.x_m, lat_positions.tolist(), layers_x) + x_faces: NDArray[np.float64] + if geometry.lateral_bc == "periodic": + dx = np.diff(geometry.x_m) + wrap_cap = float( + subface_series_capacitance(0.5 * dx[-1], layers_x[-1], 0.5 * dx[0], layers_x[0]) + ) + row_x = np.r_[interior_x, wrap_cap] + x_faces = np.empty(geometry.nx + 1, dtype=np.float64) + x_faces[0] = geometry.x_m[0] - 0.5 * dx[-1] + x_faces[1:-1] = 0.5 * (geometry.x_m[:-1] + geometry.x_m[1:]) + x_faces[-1] = geometry.x_m[-1] + 0.5 * dx[0] + else: + row_x = interior_x + x_faces = dual_cell_faces(geometry.x_m).copy() + if lat_positions.size: + for stencil in build_interface_stencils(geometry.x_m, lat_positions): + if stencil.shared_boundary_node is None: + x_faces[stencil.right_bulk_node] = stencil.interface_position_m + eps_parallel_x = _cell_parallel_from_faces(x_faces, lat_positions.tolist(), layers_x) + dy = np.diff(geometry.y_geometry.nodes_m) + vertical = (EPS_0 * eps_parallel_x[None, :] / dy[:, None]).ravel() + return frozen_array(np.r_[np.tile(row_x, geometry.ny), vertical]) + + @dataclass(frozen=True) class PoissonOperator1D(ImmutableArrays): """Face capacitances [F/m^2] and interior control widths [m] of one channel.""" @@ -46,6 +386,7 @@ class PoissonOperator1D(ImmutableArrays): face_capacitance_F_m2: NDArray[np.float64] interior_widths_m: NDArray[np.float64] geometry_name: str + dielectric_rule: str = NODAL_HARMONIC_DIELECTRIC_V1 def __post_init__(self) -> None: C = frozen_array(self.face_capacitance_F_m2) @@ -56,6 +397,8 @@ def __post_init__(self) -> None: raise ValueError("interior cell widths must be finite, positive, and match faces") if not self.geometry_name: raise ValueError("a Poisson operator must name its geometry channel") + if self.dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown dielectric rule {self.dielectric_rule!r}") object.__setattr__(self, "face_capacitance_F_m2", C) object.__setattr__(self, "interior_widths_m", widths) @@ -82,25 +425,70 @@ def from_harmonic_nodes(cls, x: ArrayLike, eps_r: ArrayLike, *, @classmethod def from_finite_volume(cls, face_capacitance_F_m2: ArrayLike, interior_widths_m: ArrayLike, *, - geometry_name: str) -> PoissonOperator1D: + geometry_name: str, + dielectric_rule: str = LAYER_SERIES_CAPACITANCE_V2) -> PoissonOperator1D: """Explicit series capacitances and charge-control volumes.""" return cls(np.asarray(face_capacitance_F_m2, dtype=float), - np.asarray(interior_widths_m, dtype=float), geometry_name) + np.asarray(interior_widths_m, dtype=float), geometry_name, + dielectric_rule=dielectric_rule) @classmethod - def for_geometry(cls, geometry: ControlVolumeGeometry1D, - eps_r_node: ArrayLike) -> PoissonOperator1D: - """The channel each named geometry historically used. + def from_layer_series_capacitance( + cls, + geometry: ControlVolumeGeometry1D, + eps_r_node: ArrayLike | None = None, + *, + layer_eps_r: Sequence[float] | ArrayLike | None = None, + ) -> PoissonOperator1D: + """Sub-face material-extent series capacitance on a named 1D geometry (P08-02a).""" + if geometry.node_count < 3: + raise ValueError("Poisson operator requires at least three grid nodes") + capacitance = layer_series_face_capacitances( + geometry, eps_r_node, layer_eps_r=layer_eps_r + ) + return cls( + capacitance, + geometry.cell_measures_m[1:-1], + geometry.name, + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + ) - Integer/half-endpoint grids keep the harmonic nodal mean. Two-sided - geometries replace each interface face by its exact series capacitance - at the true plane and use their own carrier control volumes. + @classmethod + def for_geometry( + cls, + geometry: ControlVolumeGeometry1D, + eps_r_node: ArrayLike, + *, + dielectric_rule: str | None = None, + layer_eps_r: Sequence[float] | ArrayLike | None = None, + ) -> PoissonOperator1D: + """The channel each named geometry historically used, or an explicit dielectric rule. + + Integer/half-endpoint grids keep the harmonic nodal mean by default + (``dielectric_rule=None``). Passing ``dielectric_rule=LAYER_SERIES_CAPACITANCE_V2`` + opts into sub-face material-extent series capacitance while preserving the + geometry's interior control widths. """ nodes = geometry.nodes_m permittivity = np.asarray(eps_r_node, dtype=float) if permittivity.shape != nodes.shape: raise ValueError("permittivity must be given on the geometry nodes") + if dielectric_rule is not None and dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown dielectric rule {dielectric_rule!r}") + if dielectric_rule == LAYER_SERIES_CAPACITANCE_V2: + return cls.from_layer_series_capacitance( + geometry, permittivity, layer_eps_r=layer_eps_r + ) base = cls.from_harmonic_nodes(nodes, permittivity, geometry_name=geometry.name) + if dielectric_rule == NODAL_HARMONIC_DIELECTRIC_V1: + if geometry.name in {INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1}: + return base + return cls( + base.face_capacitance_F_m2, + geometry.cell_measures_m[1:-1], + geometry.name, + dielectric_rule=NODAL_HARMONIC_DIELECTRIC_V1, + ) if geometry.name in {INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1}: return base if geometry.name not in {TWO_SIDED_TRACE_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1}: @@ -111,7 +499,12 @@ def for_geometry(cls, geometry: ControlVolumeGeometry1D, plane.left_distance_m, float(permittivity[plane.left_node]), plane.right_distance_m, float(permittivity[plane.right_node]), ) - return cls(capacitance, geometry.cell_measures_m[1:-1], geometry.name) + return cls( + capacitance, + geometry.cell_measures_m[1:-1], + geometry.name, + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + ) def interior_residual(self, phi: ArrayLike, rho_C_m3: ArrayLike) -> NDArray[np.float64]: """Gauss balance of nodes ``1..N-2`` [C/m^2] (historical expression).""" diff --git a/tests/integration/test_p08_02_refinement_and_parity.py b/tests/integration/test_p08_02_refinement_and_parity.py new file mode 100644 index 00000000..e0c7fb35 --- /dev/null +++ b/tests/integration/test_p08_02_refinement_and_parity.py @@ -0,0 +1,238 @@ +"""Spatial refinement and 1D/2D parity integration tests for P08-02.""" + +from __future__ import annotations + +import numpy as np +from scipy.sparse import lil_matrix +from scipy.sparse.linalg import spsolve + +from examples.research_1d.steady import load_device +from solarlab.device.compile_2d import compile_device_2d +from solarlab.discretization import ( + LAYER_SERIES_CAPACITANCE_V2, + NODAL_HARMONIC_DIELECTRIC_V1, + VACUUM_PERMITTIVITY_F_M, +) +from solarlab.experiments.two_dimensional.inputs import JV2DInput +from solarlab.mesh import ( + INTEGER_ENDPOINT_V1, + RIGHT_LAYER_WINS, + build_geometry, + multilayer_grid, + node_owner, +) +from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry_2d import RectangularGeometry2D +from solarlab.physics.electrostatics import ( + PoissonFactorization, + PoissonOperator1D, + rectangular_2d_face_capacitances, +) +from solarlab.solvers.nonlinear.steady_2d import Steady2DOptions, solve_steady_state_2d + +EPS_0 = VACUUM_PERMITTIVITY_F_M + + +def _mms_1d_heterojunction_error(scale: int, dielectric_rule: str) -> float: + """1D 2-layer space-charge-bearing heterojunction MMS on shared-node grids.""" + l1, l2 = 1.8e-7, 1.2e-7 + eps1, eps2 = 4.0, 24.0 + length = l1 + l2 + d0, d1 = 1.2e-3, 6.0e-4 + + def displacement_exact(x_arr: np.ndarray) -> np.ndarray: + return d0 + d1 * np.sin(np.pi * x_arr / length) + + def phi_exact(x_arr: np.ndarray) -> np.ndarray: + def antideriv(a: float | np.ndarray, b: float | np.ndarray, eps: float) -> np.ndarray: + return np.asarray( + ( + d0 * (b - a) + - d1 * length / np.pi * (np.cos(np.pi * b / length) - np.cos(np.pi * a / length)) + ) + / (EPS_0 * eps), + dtype=float, + ) + + return 0.35 - np.where( + x_arr <= l1, + antideriv(0.0, np.minimum(x_arr, l1), eps1), + antideriv(0.0, l1, eps1) + antideriv(l1, x_arr, eps2), + ) + + x = multilayer_grid([(l1, 3 * scale), (l2, 2 * scale)], alpha=1.2) + geom = build_geometry(INTEGER_ENDPOINT_V1, x, [l1]) + eps = np.array([eps1, eps2])[node_owner(x, (l1, l2), RIGHT_LAYER_WINS)] + op = PoissonOperator1D.for_geometry(geom, eps, dielectric_rule=dielectric_rule) + faces = geom.cell_faces_m + cell_charge = displacement_exact(faces[1:]) - displacement_exact(faces[:-1]) + rho = np.zeros(x.size, dtype=float) + rho[1:-1] = cell_charge[1:-1] / op.interior_widths_m + phi_num = PoissonFactorization.factor(op).solve( + rho, float(phi_exact(np.array([x[0]]))[0]), float(phi_exact(np.array([x[-1]]))[0]) + ) + return float(np.max(np.abs(phi_num - phi_exact(x)))) + + +def _mms_2d_heterojunction_error(scale: int, dielectric_rule: str) -> float: + """2D (x, y) laterally modulated space-charge heterojunction MMS on shared-node grids. + + Combines a vertical heterojunction potential (continuous D_y across y = l1) + with a lateral mode A * cos(pi * x / lx) that has nonzero tangential + curvature d^2 phi / dx^2 right on the shared interface row y_k = l1, so + second-order convergence requires BOTH vertical sub-face series capacitance + AND horizontal cell-parallel permittivity at y_k = l1. + """ + lx = 4.0e-7 + l1, l2 = 1.5e-7, 1.0e-7 + ly = l1 + l2 + eps1, eps2 = 3.5, 24.5 + d0, d1 = 9.0e-4, 4.5e-4 + amp_x = 0.08 + kx = np.pi / lx + + def disp_y_1d(y_arr: np.ndarray) -> np.ndarray: + return d0 + d1 * np.sin(np.pi * y_arr / ly) + + def phi_y_1d(y_arr: np.ndarray) -> np.ndarray: + def antideriv(a: float | np.ndarray, b: float | np.ndarray, eps: float) -> np.ndarray: + return np.asarray( + ( + d0 * (b - a) + - d1 * ly / np.pi * (np.cos(np.pi * b / ly) - np.cos(np.pi * a / ly)) + ) + / (EPS_0 * eps), + dtype=float, + ) + + return 0.25 - np.where( + y_arr <= l1, + antideriv(0.0, np.minimum(y_arr, l1), eps1), + antideriv(0.0, l1, eps1) + antideriv(l1, y_arr, eps2), + ) + + x = np.linspace(0.0, lx, 3 * scale + 1) + y = multilayer_grid([(l1, 3 * scale), (l2, 2 * scale)], alpha=0.8) + y_geom = half_endpoint_geometry(y, [l1]) + rect = RectangularGeometry2D(x, y_geom, lateral_bc="neumann") + eps_y = np.array([eps1, eps2])[node_owner(y, (l1, l2), RIGHT_LAYER_WINS)] + caps = rectangular_2d_face_capacitances(rect, eps_y, dielectric_rule=dielectric_rule) + + # Exact integral of -div(eps_0 eps(y) grad phi) over each 2D control volume [x_a, x_b] x [y_a, y_b]. + x_faces = np.r_[x[0], 0.5 * (x[:-1] + x[1:]), x[-1]] + y_faces = y_geom.cell_faces_m + int_cos_x = (np.sin(kx * x_faces[1:]) - np.sin(kx * x_faces[:-1])) / kx + wx = np.diff(x_faces) + int_dy_part = disp_y_1d(y_faces[1:]) - disp_y_1d(y_faces[:-1]) + + eps_int_y: np.ndarray = np.empty(rect.ny, dtype=np.float64) + for j in range(rect.ny): + ya, yb = float(y_faces[j]), float(y_faces[j + 1]) + part1 = max(0.0, min(yb, l1) - max(ya, 0.0)) * eps1 + part2 = max(0.0, min(yb, ly) - max(ya, l1)) * eps2 + eps_int_y[j] = EPS_0 * (part1 + part2) + + cell_charge_2d = ( + int_dy_part[:, None] * wx[None, :] + + (kx**2 * amp_x) * eps_int_y[:, None] * int_cos_x[None, :] + ).ravel() + + n = rect.node_count + cg = rect.contract_geometry + left, right = cg.pairs.T + mat = lil_matrix((n, n), dtype=float) + for a, b, cap in zip(left, right, caps * cg.face_measures): + mat[a, a] -= cap + mat[a, b] += cap + mat[b, a] += cap + mat[b, b] -= cap + rhs = -cell_charge_2d + + phi_exact_2d = phi_y_1d(y)[:, None] + amp_x * np.cos(kx * x)[None, :] + phi_exact_flat = phi_exact_2d.ravel() + for idx in rect.contact_nodes: + node = int(idx) + mat.rows[node] = [node] + mat.data[node] = [1.0] + rhs[node] = phi_exact_flat[node] + + phi_num = np.asarray(spsolve(mat.tocsc(), rhs), dtype=float) + return float(np.max(np.abs(phi_num - phi_exact_flat))) + + +def test_p08_02a_1d_and_2d_heterojunction_spatial_refinement_restores_second_order() -> None: + """LAYER_SERIES_CAPACITANCE_V2 restores O(h^2) in 1D and 2D heterojunctions.""" + scales_1d = (4, 8, 16, 32) + err_1d_v1 = np.array( + [_mms_1d_heterojunction_error(s, NODAL_HARMONIC_DIELECTRIC_V1) for s in scales_1d] + ) + err_1d_v2 = np.array( + [_mms_1d_heterojunction_error(s, LAYER_SERIES_CAPACITANCE_V2) for s in scales_1d] + ) + order_1d_v1 = np.log2(err_1d_v1[:-1] / err_1d_v1[1:]) + order_1d_v2 = np.log2(err_1d_v2[:-1] / err_1d_v2[1:]) + + assert np.all(order_1d_v1 < 1.2), order_1d_v1 + assert np.all(order_1d_v2 > 1.95), order_1d_v2 + assert err_1d_v2[-1] < 0.03 * err_1d_v1[-1] + + scales_2d = (2, 4, 8, 16) + err_2d_v1 = np.array( + [_mms_2d_heterojunction_error(s, NODAL_HARMONIC_DIELECTRIC_V1) for s in scales_2d] + ) + err_2d_v2 = np.array( + [_mms_2d_heterojunction_error(s, LAYER_SERIES_CAPACITANCE_V2) for s in scales_2d] + ) + order_2d_v1 = np.log2(err_2d_v1[:-1] / err_2d_v1[1:]) + order_2d_v2 = np.log2(err_2d_v2[:-1] / err_2d_v2[1:]) + + assert np.all(order_2d_v1 < 1.25), order_2d_v1 + assert np.all(order_2d_v2 > 1.95), order_2d_v2 + assert err_2d_v2[-1] < 0.05 * err_2d_v1[-1] + + +def test_p08_02a_compile_device_2d_heterojunction_refinement_improves_interface_accuracy() -> None: + """Compiled 2D p-i-n heterojunction solves converge faster under layer_series_capacitance_v2.""" + prepared = load_device() + options = Steady2DOptions() + + def solve_at(ny_per_layer: int, rule: str) -> tuple[np.ndarray, float]: + spatial = JV2DInput( + kind="jv_2d", + lateral_length="0.4 um", + Nx=2, + Ny_per_layer=ny_per_layer, + lateral_bc="neumann", + ) + compiled = compile_device_2d(prepared, spatial, dielectric_rule=rule) + res = solve_steady_state_2d(compiled, voltage_V=0.4, generation_scale=0.0, options=options) + assert res.accepted and res.state is not None + phi_col = res.state.potential_V[:, 0] + # Integrated electrostatic energy proxy sum(C_f * dphi^2 * face_measure) per unit width. + left, right = compiled.geometry.contract_geometry.pairs.T + dphi = res.state.u[right] - res.state.u[left] + energy = float( + 0.5 + * np.sum( + compiled.face_capacitance_F_m2 + * compiled.geometry.contract_geometry.face_measures + * dphi**2 + ) + / compiled.geometry.lateral_length_m + ) + return phi_col, energy + + _, energy_fine = solve_at(24, LAYER_SERIES_CAPACITANCE_V2) + _, energy_coarse_v1 = solve_at(4, NODAL_HARMONIC_DIELECTRIC_V1) + _, energy_mid_v1 = solve_at(8, NODAL_HARMONIC_DIELECTRIC_V1) + _, energy_coarse_v2 = solve_at(4, LAYER_SERIES_CAPACITANCE_V2) + _, energy_mid_v2 = solve_at(8, LAYER_SERIES_CAPACITANCE_V2) + + err_coarse_v1 = abs(energy_coarse_v1 - energy_fine) + err_mid_v1 = abs(energy_mid_v1 - energy_fine) + err_coarse_v2 = abs(energy_coarse_v2 - energy_fine) + err_mid_v2 = abs(energy_mid_v2 - energy_fine) + + assert err_coarse_v2 < err_coarse_v1 + assert err_mid_v2 < err_mid_v1 + assert err_mid_v2 < 0.6 * err_coarse_v2 diff --git a/tests/unit/physics/test_p08_02_dielectric_and_geometry.py b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py new file mode 100644 index 00000000..649860ea --- /dev/null +++ b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py @@ -0,0 +1,433 @@ +"""Unit contracts for P08-02a sub-face series dielectric capacitance.""" + +from __future__ import annotations + +from fractions import Fraction + +import numpy as np +import pytest +from scipy.sparse import lil_matrix +from scipy.sparse.linalg import spsolve + +from examples.research_1d.steady import load_device +from examples.research_2d import dc_assembly as example_2d +from solarlab.device.compile_2d import compile_device_2d +from solarlab.discretization import ( + DIELECTRIC_RULES, + LAYER_SERIES_CAPACITANCE_V2, + NODAL_HARMONIC_DIELECTRIC_V1, + VACUUM_PERMITTIVITY_F_M, + series_face_capacitance, + subface_series_capacitance, +) +from solarlab.mesh import ( + HALF_ENDPOINT_V1, + INTEGER_ENDPOINT_V1, + PHYSICAL_BOUNDARY_TWO_SIDED_V1, + RIGHT_LAYER_WINS, + TWO_SIDED_TRACE_V1, + build_geometry, + multilayer_grid, + node_owner, + remove_shared_interface_nodes, +) +from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry_2d import RectangularGeometry2D +from solarlab.physics.electrostatics import ( + PoissonFactorization, + PoissonOperator1D, + TraceElectrostatics, + add_interface_sheet_charge, + contact_displacement, + layer_permittivities_from_geometry, + layer_series_face_capacitances, + rectangular_2d_face_capacitances, + solve_electrostatic_traces, +) + +EPS_0 = VACUUM_PERMITTIVITY_F_M + + +def _same_bits(a: np.ndarray, b: np.ndarray) -> bool: + arr_a = np.asarray(a, dtype=float) + arr_b = np.asarray(b, dtype=float) + return arr_a.shape == arr_b.shape and arr_a.tobytes() == arr_b.tobytes() + + +def _solve_2d_dirichlet_gauss( + geometry: RectangularGeometry2D, + face_capacitance_F_m2: np.ndarray, + dirichlet_nodes: np.ndarray, + dirichlet_values: np.ndarray, + rho_C_m3: np.ndarray | None = None, +) -> np.ndarray: + """Solve 2D graph Gauss balance with arbitrary Dirichlet contact subset.""" + n = geometry.node_count + cg = geometry.contract_geometry + left, right = cg.pairs.T + mat = lil_matrix((n, n), dtype=float) + for a, b, cap in zip(left, right, face_capacitance_F_m2 * cg.face_measures): + mat[a, a] -= cap + mat[a, b] += cap + mat[b, a] += cap + mat[b, b] -= cap + rhs: np.ndarray = np.zeros(n, dtype=np.float64) + if rho_C_m3 is not None: + rhs -= np.asarray(rho_C_m3, dtype=np.float64) * cg.volumes + for node, value in zip(dirichlet_nodes, dirichlet_values): + idx = int(node) + mat.rows[idx] = [idx] + mat.data[idx] = [1.0] + rhs[idx] = float(value) + return np.asarray(spsolve(mat.tocsc(), rhs), dtype=float) + + +def test_p08_02a_subface_series_capacitance_homogeneous_0_to_1_ulp() -> None: + """Homogeneous sub-face reduction agrees with eps_0 * eps / h to 0-1 ULP.""" + assert DIELECTRIC_RULES == (NODAL_HARMONIC_DIELECTRIC_V1, LAYER_SERIES_CAPACITANCE_V2) + + rng = np.random.default_rng(20261114) + for eps_r in (1.0, 3.7, 11.9, 24.1, 63.3): + x = np.r_[0.0, np.cumsum(rng.uniform(1.3e-9, 4.7e-8, size=19))] + h = np.diff(x) + direct = EPS_0 * eps_r / h + split_ratio = rng.uniform(0.05, 0.95, size=h.size) + d_left = split_ratio * h + d_right = h - d_left + c_sub = subface_series_capacitance(d_left, eps_r, d_right, eps_r) + assert np.all(np.abs(c_sub - direct) <= np.spacing(direct)) + + # Unsplit faces (d_R == 0 or d_L == 0) match EPS_0 * eps_r / h to 0 ULPs. + assert _same_bits(subface_series_capacitance(h, eps_r, 0.0, 99.0), direct) + assert _same_bits(subface_series_capacitance(0.0, 99.0, h, eps_r), direct) + + geom_1d = build_geometry(INTEGER_ENDPOINT_V1, x, ()) + op_v1 = PoissonOperator1D.for_geometry(geom_1d, np.full(x.size, eps_r)) + op_v2 = PoissonOperator1D.for_geometry( + geom_1d, np.full(x.size, eps_r), dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + assert np.all( + np.abs(op_v2.face_capacitance_F_m2 - op_v1.face_capacitance_F_m2) + <= np.spacing(op_v1.face_capacitance_F_m2) + ) + + y_geom = half_endpoint_geometry(x, ()) + rect = RectangularGeometry2D(np.array([0.0, 1.7e-7, 5.3e-7, 1.0e-6]), y_geom) + c2d_v1 = rectangular_2d_face_capacitances( + rect, np.full(x.size, eps_r), dielectric_rule=NODAL_HARMONIC_DIELECTRIC_V1 + ) + c2d_v2 = rectangular_2d_face_capacitances( + rect, np.full(x.size, eps_r), dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + assert np.all(np.abs(c2d_v2 - c2d_v1) <= np.spacing(c2d_v1)) + + # Scalar evaluation and domain checks. + scalar_cap = subface_series_capacitance(4.0e-9, 3.0, 2.5e-9, 24.0) + assert scalar_cap.shape == () + assert float(scalar_cap) == pytest.approx( + series_face_capacitance(4.0e-9, 3.0, 2.5e-9, 24.0), rel=0.0, abs=0.0 + ) + with pytest.raises(ValueError, match="nonnegative"): + subface_series_capacitance(-1.0e-9, 3.0, 2.0e-9, 4.0) + with pytest.raises(ValueError, match="positive face spacing"): + subface_series_capacitance(0.0, 3.0, 0.0, 4.0) + with pytest.raises(ValueError, match="positive"): + subface_series_capacitance(1.0e-9, 0.0, 1.0e-9, 4.0) + + +def test_p08_02a_default_legacy_channels_stay_bit_identical() -> None: + """Default 1D and 2D dielectric compilation remains bit-identical.""" + thicknesses = (1.5e-7, 3.5e-7, 2.0e-7) + interfaces = (1.5e-7, 5.0e-7) + x_shared = multilayer_grid(list(zip(thicknesses, (5, 9, 6))), alpha=2.5) + eps_shared = np.array([3.5, 24.0, 9.0])[node_owner(x_shared, thicknesses, RIGHT_LAYER_WINS)] + + for name in (INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1): + geom = build_geometry(name, x_shared, interfaces) + default_op = PoissonOperator1D.for_geometry(geom, eps_shared) + harmonic_op = PoissonOperator1D.from_harmonic_nodes( + x_shared, eps_shared, geometry_name=name + ) + assert default_op.dielectric_rule == NODAL_HARMONIC_DIELECTRIC_V1 + assert _same_bits(default_op.face_capacitance_F_m2, harmonic_op.face_capacitance_F_m2) + assert _same_bits(default_op.interior_widths_m, harmonic_op.interior_widths_m) + + x_two_sided = remove_shared_interface_nodes(x_shared, interfaces) + eps_two_sided = np.array([3.5, 24.0, 9.0])[ + node_owner(x_two_sided, thicknesses, RIGHT_LAYER_WINS) + ] + for name in (TWO_SIDED_TRACE_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1): + geom = build_geometry(name, x_two_sided, interfaces) + default_op = PoissonOperator1D.for_geometry(geom, eps_two_sided) + explicit_v2 = PoissonOperator1D.for_geometry( + geom, eps_two_sided, dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + assert default_op.dielectric_rule == LAYER_SERIES_CAPACITANCE_V2 + assert np.all( + np.abs(default_op.face_capacitance_F_m2 - explicit_v2.face_capacitance_F_m2) + <= np.spacing(default_op.face_capacitance_F_m2) + ) + assert _same_bits(default_op.interior_widths_m, geom.cell_measures_m[1:-1]) + + prepared = load_device() + spatial = example_2d.spatial_input() + dev_default = compile_device_2d(prepared, spatial) + dev_explicit_v1 = compile_device_2d( + prepared, spatial, dielectric_rule=NODAL_HARMONIC_DIELECTRIC_V1 + ) + assert dev_default.sha256 == dev_explicit_v1.sha256 + assert _same_bits(dev_default.face_capacitance_F_m2, dev_explicit_v1.face_capacitance_F_m2) + + dev_v2 = compile_device_2d( + prepared, spatial, dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + assert dev_v2.sha256 != dev_default.sha256 + assert dev_v2.dielectric_rule == LAYER_SERIES_CAPACITANCE_V2 + + +def test_p08_02a_1d_nonuniform_two_layer_capacitor_exact_to_1e14() -> None: + """Non-uniform 1D 2-layer and 1-interval 3-layer capacitors hit <= 1e-14 rel error.""" + l_left, l_right = 10.0e-9, 10.0e-9 + eps_left, eps_right = 3.0, 24.0 + v_applied = 1.15 + + # Exact analytical series capacitance, displacement, and potential profile. + c_exact = float( + Fraction(1) + / ( + Fraction.from_float(l_left) / (Fraction.from_float(EPS_0) * Fraction(eps_left)) + + Fraction.from_float(l_right) / (Fraction.from_float(EPS_0) * Fraction(eps_right)) + ) + ) + d_exact = c_exact * v_applied + + def phi_analytic(x_arr: np.ndarray) -> np.ndarray: + return np.where( + x_arr <= l_left, + v_applied - d_exact * x_arr / (EPS_0 * eps_left), + v_applied + - d_exact * l_left / (EPS_0 * eps_left) + - d_exact * (x_arr - l_left) / (EPS_0 * eps_right), + ) + + # 1) Shared-node strongly non-uniform grid: x_2 = X_if = 10 nm with d_L = 4 nm != d_R = 2.5 nm. + x_shared = np.array([0.0, 6.0e-9, 10.0e-9, 12.5e-9, 20.0e-9]) + eps_shared = np.array([eps_left, eps_left, eps_right, eps_right, eps_right]) + for geom_name in (INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1): + geom = build_geometry(geom_name, x_shared, [l_left]) + assert tuple(layer_permittivities_from_geometry(geom, eps_shared)) == ( + eps_left, + eps_right, + ) + op_v2 = PoissonOperator1D.for_geometry( + geom, eps_shared, dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + rho = np.zeros_like(x_shared) + phi_v2 = PoissonFactorization.factor(op_v2).solve(rho, v_applied, 0.0) + disp_v2 = op_v2.face_displacement(phi_v2) + contacts_v2 = contact_displacement(disp_v2, rho, geom.cell_measures_m) + c_geom_v2 = contacts_v2[0] / v_applied + + phi_ref = phi_analytic(x_shared) + assert np.max(np.abs(phi_v2 - phi_ref)) / v_applied <= 1e-14 + assert np.max(np.abs(disp_v2 - d_exact)) / abs(d_exact) <= 1e-14 + assert abs(c_geom_v2 - c_exact) / c_exact <= 1e-14 + + # Legacy nodal-harmonic rule exhibits O(h) dielectric shift (> 8% error here). + op_v1 = PoissonOperator1D.for_geometry(geom, eps_shared) + phi_v1 = PoissonFactorization.factor(op_v1).solve(rho, v_applied, 0.0) + c_geom_v1 = op_v1.face_displacement(phi_v1)[0] / v_applied + assert abs(c_geom_v1 - c_exact) / c_exact > 0.08 + + # 2) Two-sided split-face non-uniform grid: interface at 10 nm splits [6 nm, 12.5 nm]. + x_split = np.array([0.0, 6.0e-9, 12.5e-9, 20.0e-9]) + eps_split = np.array([eps_left, eps_left, eps_right, eps_right]) + geom_split = build_geometry(PHYSICAL_BOUNDARY_TWO_SIDED_V1, x_split, [l_left]) + op_split = PoissonOperator1D.from_layer_series_capacitance(geom_split, eps_split) + rho_split = np.zeros_like(x_split) + phi_split = PoissonFactorization.factor(op_split).solve(rho_split, v_applied, 0.0) + disp_split = op_split.face_displacement(phi_split) + assert np.max(np.abs(phi_split - phi_analytic(x_split))) / v_applied <= 1e-14 + assert np.max(np.abs(disp_split - d_exact)) / abs(d_exact) <= 1e-14 + + # 3) Shared-node 3-layer stack with a single-interval thin middle layer [10 nm, 12 nm]. + x_thin = np.array([0.0, 7.0e-9, 10.0e-9, 12.0e-9, 20.0e-9]) + eps_thin = np.array([3.0, 3.0, 40.0, 9.0, 9.0]) + geom_thin = build_geometry(HALF_ENDPOINT_V1, x_thin, [10.0e-9, 12.0e-9]) + caps_thin = layer_series_face_capacitances(geom_thin, eps_thin) + expected_caps = EPS_0 * np.array([3.0, 3.0, 40.0, 9.0]) / np.diff(x_thin) + assert np.max(np.abs(caps_thin - expected_caps) / expected_caps) <= 1e-15 + + +def test_p08_02a_2d_nonuniform_two_layer_capacitor_stack_and_lateral_exact_to_1e14() -> None: + """Non-uniform 2D stack (y) and lateral (x) 2-layer capacitors hit <= 1e-14 rel error.""" + v_applied = 0.95 + eps_1, eps_2 = 3.2, 25.6 + + # --- Case 1: 2D stack (y) 2-layer capacitor on stretched non-uniform (x, y) mesh --- + y_nodes = np.array([0.0, 5.5e-9, 10.0e-9, 12.2e-9, 20.0e-9]) + x_nodes = np.array([0.0, 1.3e-7, 4.1e-7, 1.0e-6]) + eps_y = np.array([eps_1, eps_1, eps_2, eps_2, eps_2]) + y_geom = half_endpoint_geometry(y_nodes, [10.0e-9]) + + c_stack_exact = EPS_0 / (10.0e-9 / eps_1 + 10.0e-9 / eps_2) + d_stack_exact = c_stack_exact * v_applied + phi_y_exact = np.where( + y_nodes <= 10.0e-9, + v_applied - d_stack_exact * y_nodes / (EPS_0 * eps_1), + v_applied + - d_stack_exact * 10.0e-9 / (EPS_0 * eps_1) + - d_stack_exact * (y_nodes - 10.0e-9) / (EPS_0 * eps_2), + ) + + for lateral_bc in ("neumann", "periodic"): + rect = RectangularGeometry2D(x_nodes, y_geom, lateral_bc=lateral_bc) + caps = rectangular_2d_face_capacitances( + rect, eps_y, dielectric_rule=LAYER_SERIES_CAPACITANCE_V2 + ) + bottom_nodes = np.arange(rect.nx) + top_nodes = np.arange(rect.node_count - rect.nx, rect.node_count) + dirichlet_nodes = np.r_[bottom_nodes, top_nodes] + dirichlet_vals = np.r_[np.full(rect.nx, v_applied), np.zeros(rect.nx)] + phi_2d = _solve_2d_dirichlet_gauss(rect, caps, dirichlet_nodes, dirichlet_vals) + phi_grid = phi_2d.reshape(rect.shape) + + assert np.max(np.abs(phi_grid - phi_y_exact[:, None])) / v_applied <= 1e-14 + left, right = rect.contract_geometry.pairs.T + disp_all = -caps * (phi_2d[right] - phi_2d[left]) + disp_x = disp_all[: rect.x_face_count] + disp_y = disp_all[rect.x_face_count :] + assert np.max(np.abs(disp_x)) <= 1e-14 * abs(d_stack_exact) + assert np.max(np.abs(disp_y - d_stack_exact)) / abs(d_stack_exact) <= 1e-14 + q_bottom = float(np.sum(disp_y.reshape(rect.ny - 1, rect.nx)[0] * rect.x_widths_m)) + c_geom_y = q_bottom / (rect.lateral_length_m * v_applied) + assert abs(c_geom_y - c_stack_exact) / c_stack_exact <= 1e-14 + + # --- Case 2: 2D lateral (x) 2-layer capacitor (shared-node and split-face) --- + y_uniform = half_endpoint_geometry(np.array([0.0, 0.4e-7, 1.1e-7, 2.0e-7]), ()) + x_if = 3.0e-7 + l_x = 1.0e-6 + c_lat_exact = EPS_0 / (x_if / eps_1 + (l_x - x_if) / eps_2) + d_lat_exact = c_lat_exact * v_applied + + def phi_x_analytic(x_arr: np.ndarray) -> np.ndarray: + return np.where( + x_arr <= x_if, + v_applied - d_lat_exact * x_arr / (EPS_0 * eps_1), + v_applied + - d_lat_exact * x_if / (EPS_0 * eps_1) + - d_lat_exact * (x_arr - x_if) / (EPS_0 * eps_2), + ) + + for x_case, eps_x in ( + # Shared lateral node at x_2 = 0.3 um with d_L = 0.12 um != d_R = 0.07 um + ( + np.array([0.0, 1.8e-7, 3.0e-7, 3.7e-7, 1.0e-6]), + np.array([eps_1, eps_1, eps_2, eps_2, eps_2]), + ), + # Split lateral face [0.18 um, 0.37 um] cut at X_if = 0.30 um (d_L = 0.12 != d_R = 0.07) + ( + np.array([0.0, 1.8e-7, 3.7e-7, 1.0e-6]), + np.array([eps_1, eps_1, eps_2, eps_2]), + ), + ): + rect_lat = RectangularGeometry2D(x_case, y_uniform, lateral_bc="neumann") + caps_lat = rectangular_2d_face_capacitances( + rect_lat, + np.ones(rect_lat.ny), + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + lateral_eps_r_x=eps_x, + lateral_interfaces_m=(x_if,), + ) + ids = np.arange(rect_lat.node_count).reshape(rect_lat.shape) + left_col = ids[:, 0] + right_col = ids[:, -1] + phi_lat = _solve_2d_dirichlet_gauss( + rect_lat, + caps_lat, + np.r_[left_col, right_col], + np.r_[np.full(rect_lat.ny, v_applied), np.zeros(rect_lat.ny)], + ) + phi_lat_grid = phi_lat.reshape(rect_lat.shape) + assert np.max(np.abs(phi_lat_grid - phi_x_analytic(x_case)[None, :])) / v_applied <= 1e-14 + + left, right = rect_lat.contract_geometry.pairs.T + disp_lat = -caps_lat * (phi_lat[right] - phi_lat[left]) + disp_lat_x = disp_lat[: rect_lat.x_face_count].reshape(rect_lat.ny, rect_lat.nx - 1) + disp_lat_y = disp_lat[rect_lat.x_face_count :] + assert np.max(np.abs(disp_lat_y)) <= 1e-14 * abs(d_lat_exact) + assert np.max(np.abs(disp_lat_x - d_lat_exact)) / abs(d_lat_exact) <= 1e-14 + height_y = float(y_uniform.nodes_m[-1] - y_uniform.nodes_m[0]) + q_left = float(np.sum(disp_lat_x[:, 0] * y_uniform.cell_measures_m)) + c_geom_x = q_left / (height_y * v_applied) + assert abs(c_geom_x - c_lat_exact) / c_lat_exact <= 1e-14 + + +def test_p08_02a_interface_sheet_charge_jump_exact_across_nonuniform_subfaces() -> None: + """Exact Gauss jump D_R - D_L = sigma_sheet holds across non-uniform sub-faces.""" + l_left, l_right = 12.0e-9, 18.0e-9 + eps_left, eps_right = 3.5, 22.0 + sigma_sheet = -3.75e-4 # C / m^2 + phi_left, phi_right = 0.8, -0.1 + + r_left = l_left / (EPS_0 * eps_left) + r_right = l_right / (EPS_0 * eps_right) + # phi_L - d_L * r_L = phi_if = phi_R + d_R * r_R, and d_R - d_L = sigma_sheet + d_left_exact = (phi_left - phi_right - sigma_sheet * r_right) / (r_left + r_right) + d_right_exact = d_left_exact + sigma_sheet + phi_if_exact = phi_left - d_left_exact * r_left + + def phi_piecewise(x_arr: np.ndarray) -> np.ndarray: + return np.where( + x_arr <= l_left, + phi_left - d_left_exact * x_arr / (EPS_0 * eps_left), + phi_if_exact - d_right_exact * (x_arr - l_left) / (EPS_0 * eps_right), + ) + + # 1) Shared-node non-uniform grid: x_2 = l_left = 12 nm, d_L = 4.5 nm != d_R = 2.7 nm. + x_shared = np.array([0.0, 7.5e-9, 12.0e-9, 14.7e-9, 30.0e-9]) + eps_shared = np.array([eps_left, eps_left, eps_right, eps_right, eps_right]) + geom_shared = build_geometry(HALF_ENDPOINT_V1, x_shared, [l_left]) + op_shared = PoissonOperator1D.from_layer_series_capacitance(geom_shared, eps_shared) + + # Solve C_-(phi_{i-1}-phi_i) + C_+(phi_{i+1}-phi_i) + sigma_i = 0 via equivalent rho_i = sigma_i / w_i. + sheet_rhs: np.ndarray = np.zeros(geom_shared.node_count - 2, dtype=np.float64) + add_interface_sheet_charge(sheet_rhs, geom_shared, [sigma_sheet], eps_r_node=eps_shared) + rho_equiv: np.ndarray = np.zeros(geom_shared.node_count, dtype=np.float64) + rho_equiv[1:-1] = sheet_rhs / op_shared.interior_widths_m + phi_sol = PoissonFactorization.factor(op_shared).solve(rho_equiv, phi_left, phi_right) + + res = op_shared.interior_residual(phi_sol, np.zeros_like(x_shared)) + add_interface_sheet_charge(res, geom_shared, [sigma_sheet], eps_r_node=eps_shared) + assert np.max(np.abs(res)) <= 1e-14 * abs(sigma_sheet) + + disp = op_shared.face_displacement(phi_sol) + assert abs((disp[2] - disp[1]) - sigma_sheet) / abs(sigma_sheet) <= 1e-14 + assert abs(disp[1] - d_left_exact) / abs(d_left_exact) <= 1e-14 + assert abs(disp[2] - d_right_exact) / abs(d_right_exact) <= 1e-14 + assert np.max(np.abs(phi_sol - phi_piecewise(x_shared))) <= 1e-14 + + # 2) Two-sided split-face non-uniform grid: [8.3 nm, 17.2 nm] split at 12.0 nm (d_L = 3.7 != d_R = 5.2). + x_two = np.array([0.0, 8.3e-9, 17.2e-9, 30.0e-9]) + eps_two = np.array([eps_left, eps_left, eps_right, eps_right]) + geom_two = build_geometry(PHYSICAL_BOUNDARY_TWO_SIDED_V1, x_two, [l_left]) + op_two = PoissonOperator1D.from_layer_series_capacitance(geom_two, eps_two) + sheet_rhs_two: np.ndarray = np.zeros(geom_two.node_count - 2, dtype=np.float64) + add_interface_sheet_charge(sheet_rhs_two, geom_two, [sigma_sheet], eps_r_node=eps_two) + rho_two: np.ndarray = np.zeros(geom_two.node_count, dtype=np.float64) + rho_two[1:-1] = sheet_rhs_two / op_two.interior_widths_m + phi_two = PoissonFactorization.factor(op_two).solve(rho_two, phi_left, phi_right) + + plane = geom_two.interfaces[0] + trace = TraceElectrostatics.from_plane( + plane, eps_left, eps_right, sheet_charge_C_m2=sigma_sheet + ) + phi_ls, phi_rs = solve_electrostatic_traces( + trace, float(phi_two[plane.left_node]), float(phi_two[plane.right_node]) + ) + d_l_trace = EPS_0 * eps_left * (phi_two[plane.left_node] - phi_ls) / plane.left_distance_m + d_r_trace = EPS_0 * eps_right * (phi_rs - phi_two[plane.right_node]) / plane.right_distance_m + assert abs(phi_ls - phi_if_exact) <= 1e-14 + assert abs(phi_rs - phi_if_exact) <= 1e-14 + assert abs((d_r_trace - d_l_trace) - sigma_sheet) / abs(sigma_sheet) <= 1e-14 + assert np.max(np.abs(phi_two - phi_piecewise(x_two))) <= 1e-14 From 1dea0877d9cb102006c5eee743f25781ed3be272 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 22:43:15 +0800 Subject: [PATCH 22/46] P(mesh): add coupled physical half-endpoint control-volume geometry (P08-02b) --- src/solarlab/device/compile_2d.py | 38 ++- src/solarlab/mesh/__init__.py | 12 +- src/solarlab/mesh/geometry.py | 140 +++++++++- src/solarlab/mesh/geometry_2d.py | 9 +- .../physics/electrostatics/gauss_assembly.py | 2 + .../physics/electrostatics/poisson.py | 8 +- .../test_p08_02_refinement_and_parity.py | 259 ++++++++++++++++++ .../test_p08_02_dielectric_and_geometry.py | 122 +++++++++ 8 files changed, 564 insertions(+), 26 deletions(-) diff --git a/src/solarlab/device/compile_2d.py b/src/solarlab/device/compile_2d.py index ee689816..f0de6954 100644 --- a/src/solarlab/device/compile_2d.py +++ b/src/solarlab/device/compile_2d.py @@ -20,13 +20,16 @@ from solarlab.device.resolved import PreparedDevice from solarlab.device.optical_generation_2d import bind_optical_generation_2d from solarlab.discretization.face_average import ( - DIELECTRIC_RULES, NODAL_HARMONIC_DIELECTRIC_V1, + DIELECTRIC_RULES, LAYER_SERIES_CAPACITANCE_V2, NODAL_HARMONIC_DIELECTRIC_V1, ) from solarlab.equations.dc_1d import CapabilityError from solarlab.equations.dc_2d import CompiledDevice2D from solarlab.equations.field_transport_2d import bind_field_transport_2d from solarlab.experiments.two_dimensional.inputs import JV2DInput -from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry import ( + HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2, half_endpoint_geometry, + physical_half_endpoint_geometry, +) from solarlab.mesh.geometry_2d import RectangularGeometry2D from solarlab.physics.generation.beer_lambert import BeerLambertBinding from solarlab.units import normalize_quantity @@ -42,7 +45,8 @@ def compile_device_2d( prepared: PreparedDevice, spatial: JV2DInput, *, - dielectric_rule: str = NODAL_HARMONIC_DIELECTRIC_V1, + dielectric_rule: str | None = None, + stack_geometry: str = HALF_ENDPOINT_V1, ) -> CompiledDevice2D: """Compile without a nonlinear solve or inferred geometric defaults. @@ -54,8 +58,15 @@ def compile_device_2d( """ if not isinstance(prepared, PreparedDevice) or not isinstance(spatial, JV2DInput): raise TypeError("compile_device_2d requires PreparedDevice and typed JV2DInput geometry") - if dielectric_rule not in DIELECTRIC_RULES: - raise ValueError(f"unknown 2D dielectric rule {dielectric_rule!r}") + if stack_geometry not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2}: + raise ValueError(f"unsupported 2D stack_geometry {stack_geometry!r}") + resolved_dielectric = ( + (LAYER_SERIES_CAPACITANCE_V2 if stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 else NODAL_HARMONIC_DIELECTRIC_V1) + if dielectric_rule is None + else dielectric_rule + ) + if resolved_dielectric not in DIELECTRIC_RULES: + raise ValueError(f"unknown 2D dielectric rule {resolved_dielectric!r}") for name in spatial.model_fields_set - _GEOMETRY_FIELDS: if getattr(spatial, name) is not None: raise CapabilityError("unsupported_classical_2d_dc: execution field " + name) @@ -94,7 +105,12 @@ def compile_device_2d( if column.recombination.explicit_defects is not None: raise CapabilityError("unsupported_classical_2d_dc: explicit defect populations are not bound") length = normalize_quantity(spatial.lateral_length, "m") - y_geometry = half_endpoint_geometry(column.nodes_m, [plane.position_m for plane in column.geometry.interfaces]) + interface_positions = [plane.position_m for plane in column.geometry.interfaces] + y_geometry = ( + physical_half_endpoint_geometry(column.nodes_m, interface_positions) + if stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 + else half_endpoint_geometry(column.nodes_m, interface_positions) + ) geometry = RectangularGeometry2D( np.linspace(0.0, length, spatial.Nx + 1), y_geometry, lateral_bc=spatial.lateral_bc ) @@ -135,8 +151,12 @@ def compile_device_2d( identity = hashlib.sha256(json.dumps((identity, optical.identity_sha256), separators=(",", ":")).encode()).hexdigest() if transport is not None: identity = hashlib.sha256(json.dumps((identity, transport.identity_sha256), separators=(",", ":")).encode()).hexdigest() + if stack_geometry != HALF_ENDPOINT_V1: + identity = hashlib.sha256( + json.dumps((identity, "stack_geometry", stack_geometry), separators=(",", ":")).encode() + ).hexdigest() layer_permittivity_y: tuple[float, ...] | None = None - if dielectric_rule != NODAL_HARMONIC_DIELECTRIC_V1: + if resolved_dielectric != NODAL_HARMONIC_DIELECTRIC_V1: layer_eps_list: list[float] = [] for layer in prepared.layers: raw_eps = dict(layer.parameters)["eps_r"] @@ -145,10 +165,10 @@ def compile_device_2d( layer_eps_list.append(float(raw_eps)) layer_permittivity_y = tuple(layer_eps_list) identity = hashlib.sha256( - json.dumps((identity, "dielectric_rule", dielectric_rule), separators=(",", ":")).encode() + json.dumps((identity, "dielectric_rule", resolved_dielectric), separators=(",", ":")).encode() ).hexdigest() return CompiledDevice2D( identity, column, geometry, generation, eps, declaration, grain_recombination=grains, column_projection_json=projection, field_transport=transport, - dielectric_rule=dielectric_rule, layer_permittivity_y=layer_permittivity_y, + dielectric_rule=resolved_dielectric, layer_permittivity_y=layer_permittivity_y, ) diff --git a/src/solarlab/mesh/__init__.py b/src/solarlab/mesh/__init__.py index 16d5f2b6..3d530be1 100644 --- a/src/solarlab/mesh/__init__.py +++ b/src/solarlab/mesh/__init__.py @@ -2,7 +2,9 @@ from solarlab.mesh.geometry import ( GEOMETRY_NAMES, HALF_ENDPOINT_V1, INTEGER_ENDPOINT_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1, - TWO_SIDED_TRACE_V1, ControlVolumeGeometry1D, InterfacePlane, PortFace, build_geometry, + PHYSICAL_HALF_ENDPOINT_V2, TWO_SIDED_TRACE_V1, ControlVolumeGeometry1D, InterfacePlane, + PortFace, areal_interface_to_cell_source, build_geometry, + physical_half_endpoint_geometry, ) from solarlab.mesh.grid import ( LEFT_LAYER_WINS, RIGHT_LAYER_WINS, InterfaceStencil, build_interface_stencils, @@ -13,7 +15,9 @@ __all__ = [ "ControlVolumeGeometry1D", "ElectricalStack", "GEOMETRY_NAMES", "HALF_ENDPOINT_V1", "INTEGER_ENDPOINT_V1", "InterfacePlane", "InterfaceStencil", "LEFT_LAYER_WINS", - "PHYSICAL_BOUNDARY_TWO_SIDED_V1", "PortFace", "RIGHT_LAYER_WINS", "StackLayer", - "TWO_SIDED_TRACE_V1", "build_geometry", "build_interface_stencils", "multilayer_grid", - "node_owner", "remove_shared_interface_nodes", "tanh_grid", + "PHYSICAL_BOUNDARY_TWO_SIDED_V1", "PHYSICAL_HALF_ENDPOINT_V2", "PortFace", + "RIGHT_LAYER_WINS", "StackLayer", "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", "build_geometry", "build_interface_stencils", + "multilayer_grid", "node_owner", "physical_half_endpoint_geometry", + "remove_shared_interface_nodes", "tanh_grid", ] diff --git a/src/solarlab/mesh/geometry.py b/src/solarlab/mesh/geometry.py index 785b2386..a9563213 100644 --- a/src/solarlab/mesh/geometry.py +++ b/src/solarlab/mesh/geometry.py @@ -50,24 +50,29 @@ __all__ = [ "ControlVolumeGeometry1D", "GEOMETRY_NAMES", "HALF_ENDPOINT_V1", "INTEGER_ENDPOINT_V1", - "InterfacePlane", "NO_SHARED_NODES", "PHYSICAL_BOUNDARY_TWO_SIDED_V1", "PortFace", - "TWO_SIDED_TRACE_V1", "build_geometry", "dual_cell_faces", "half_endpoint_widths", - "half_endpoint_geometry", "integer_endpoint_geometry", "integer_endpoint_widths", - "physical_boundary_two_sided_geometry", "physical_cell_faces", "two_sided_trace_geometry", - "two_sided_trace_widths", + "InterfacePlane", "NO_SHARED_NODES", "PHYSICAL_BOUNDARY_TWO_SIDED_V1", + "PHYSICAL_HALF_ENDPOINT_V2", "PortFace", "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", "build_geometry", "dual_cell_faces", + "half_endpoint_widths", "half_endpoint_geometry", "integer_endpoint_geometry", + "integer_endpoint_widths", "physical_boundary_two_sided_geometry", "physical_cell_faces", + "physical_half_endpoint_geometry", "two_sided_trace_geometry", "two_sided_trace_widths", ] INTEGER_ENDPOINT_V1 = "legacy_mol_integer_endpoint_v1" HALF_ENDPOINT_V1 = "legacy_twod_half_endpoint_v1" TWO_SIDED_TRACE_V1 = "qf_two_sided_trace_integer_endpoint_v1" PHYSICAL_BOUNDARY_TWO_SIDED_V1 = "physical_boundary_two_sided_v1" +PHYSICAL_HALF_ENDPOINT_V2 = "physical_half_endpoint_v2" GEOMETRY_NAMES = ( - INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1, TWO_SIDED_TRACE_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1, + INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1, TWO_SIDED_TRACE_V1, + PHYSICAL_BOUNDARY_TWO_SIDED_V1, PHYSICAL_HALF_ENDPOINT_V2, ) NO_SHARED_NODES = "no_shared_nodes" # Geometries whose contact cells are geometric half cells; the other two weight # each contact node by its full adjacent interval. -_GEOMETRIC_CONTACT_CELLS = frozenset({HALF_ENDPOINT_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1}) +_GEOMETRIC_CONTACT_CELLS = frozenset({ + HALF_ENDPOINT_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1, PHYSICAL_HALF_ENDPOINT_V2, +}) # 1D devices are evaluated per unit cross-section: ports and faces have area # 1 m^2, cell measures are lengths and stored particles are per m^2. @@ -295,6 +300,23 @@ def to_contract_geometry(self, *, cell_support: str = "cells", np.full(self.node_count - 1, self.face_area_m2), LENGTH, ONE, cell_support, face_support) + def areal_to_cell_source( + self, + interface_index: int, + areal_quantity: float | None = None, + *, + side_quantities: tuple[float, float] | None = None, + partition: tuple[float, float] = (0.5, 0.5), + ) -> NDArray[np.float64]: + """Deposit an areal interface quantity onto ``self.cell_measures_m``.""" + return areal_interface_to_cell_source( + self, + interface_index, + areal_quantity, + side_quantities=side_quantities, + partition=partition, + ) + def _planes(grid: NDArray[np.float64], positions: ArrayLike) -> tuple[InterfacePlane, ...]: stencils = build_interface_stencils(grid, positions) if np.asarray(positions).size else () @@ -351,14 +373,116 @@ def physical_boundary_two_sided_geometry( role_owner_convention=NO_SHARED_NODES) +def physical_half_endpoint_geometry( + x: ArrayLike, + interface_positions: ArrayLike = (), +) -> ControlVolumeGeometry1D: + """Physical half-endpoint control volumes ``w_i = b_{i+1} - b_i`` (P08-02b). + + Contact outer faces lie at ``x[0]`` and ``x[-1]`` so ``sum(w) == L``. + Supports both deduplicated shared-node grids (``RIGHT_LAYER_WINS`` for both + material values and role masks, matching 1D compiled nodal arrays) and + two-sided grids whose interior cell faces lie on the true material planes. + """ + grid = _strict_grid(x, minimum=2) + planes = _planes(grid, interface_positions) + if all(plane.shared_node is not None for plane in planes): + faces = dual_cell_faces(grid) + return ControlVolumeGeometry1D( + PHYSICAL_HALF_ENDPOINT_V2, + grid, + np.diff(faces), + faces, + planes, + material_owner_convention=RIGHT_LAYER_WINS, + role_owner_convention=RIGHT_LAYER_WINS, + ) + if planes and all(plane.shared_node is None for plane in planes): + if grid.size < 3: + raise ValueError("two-sided physical geometry requires at least three grid nodes") + stencils = _two_sided_stencils(grid, interface_positions) + two_sided_planes = tuple( + InterfacePlane.from_stencil(i, stencil) for i, stencil in enumerate(stencils) + ) + faces = physical_cell_faces(grid, interface_positions) + return ControlVolumeGeometry1D( + PHYSICAL_HALF_ENDPOINT_V2, + grid, + np.diff(faces), + faces, + two_sided_planes, + material_owner_convention=NO_SHARED_NODES, + role_owner_convention=NO_SHARED_NODES, + ) + raise ValueError( + "physical_half_endpoint_v2 requires all interfaces to be either shared-node or two-sided" + ) + + +def areal_interface_to_cell_source( + geometry: ControlVolumeGeometry1D, + interface_index: int, + areal_quantity: float | None = None, + *, + side_quantities: tuple[float, float] | None = None, + partition: tuple[float, float] = (0.5, 0.5), +) -> NDArray[np.float64]: + """Convert an areal interface quantity into volumetric cell density on ``geometry``. + + Couples sheet-trap densities [m^-2], areal SRH rates [m^-2 s^-1], or sheet + charges [C m^-2] to ``geometry.cell_measures_m`` so ``sum(w * source)`` + conserves the areal quantity across geometry changes. + """ + if interface_index < 0 or interface_index >= len(geometry.interfaces): + raise ValueError("interface_index out of bounds for geometry.interfaces") + if (areal_quantity is None) == (side_quantities is None): + raise ValueError("pass exactly one of areal_quantity or side_quantities") + if side_quantities is not None: + if len(side_quantities) != 2: + raise ValueError("side_quantities must be a (left, right) pair") + a_left = float(side_quantities[0]) + a_right = float(side_quantities[1]) + if not (math.isfinite(a_left) and math.isfinite(a_right)): + raise ValueError("side_quantities must be finite") + total = a_left + a_right + else: + assert areal_quantity is not None + total = float(areal_quantity) + if not math.isfinite(total): + raise ValueError("areal_quantity must be finite") + if len(partition) != 2: + raise ValueError("partition must be a (left_weight, right_weight) pair") + p_left = float(partition[0]) + p_right = float(partition[1]) + if ( + not (math.isfinite(p_left) and math.isfinite(p_right)) + or p_left < 0.0 + or p_right < 0.0 + or abs((p_left + p_right) - 1.0) > 16.0 * np.finfo(float).eps + ): + raise ValueError("partition weights must be nonnegative and sum to 1") + a_left = total * p_left + a_right = total * p_right + source: NDArray[np.float64] = np.zeros(geometry.node_count, dtype=np.float64) + plane = geometry.interfaces[interface_index] + measures = geometry.cell_measures_m + if plane.shared_node is not None: + source[plane.shared_node] = total / float(measures[plane.shared_node]) + else: + source[plane.left_node] = a_left / float(measures[plane.left_node]) + source[plane.right_node] = a_right / float(measures[plane.right_node]) + return frozen_array(source) + + def build_geometry(name: str, x: ArrayLike, interface_positions: ArrayLike = ()) -> ControlVolumeGeometry1D: - """Build one named historical geometry; there is no default geometry.""" + """Build one named historical or physical geometry; there is no default geometry.""" builders = { INTEGER_ENDPOINT_V1: integer_endpoint_geometry, HALF_ENDPOINT_V1: half_endpoint_geometry, TWO_SIDED_TRACE_V1: two_sided_trace_geometry, PHYSICAL_BOUNDARY_TWO_SIDED_V1: physical_boundary_two_sided_geometry, + PHYSICAL_HALF_ENDPOINT_V2: physical_half_endpoint_geometry, } if name not in builders: raise ValueError(f"unknown historical geometry {name!r}") diff --git a/src/solarlab/mesh/geometry_2d.py b/src/solarlab/mesh/geometry_2d.py index f2bed503..0cc22cbd 100644 --- a/src/solarlab/mesh/geometry_2d.py +++ b/src/solarlab/mesh/geometry_2d.py @@ -10,7 +10,10 @@ from numpy.typing import NDArray from solarlab.contracts import AREA, LENGTH, Geometry, frozen_array -from solarlab.mesh.geometry import HALF_ENDPOINT_V1, ControlVolumeGeometry1D, half_endpoint_widths +from solarlab.mesh.geometry import ( + HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2, ControlVolumeGeometry1D, + half_endpoint_widths, +) RECTANGULAR_HALF_ENDPOINT_2D_V1 = "rectangular_half_endpoint_neumann_2d_v1" RECTANGULAR_PERIODIC_2D_V1 = "rectangular_half_endpoint_periodic_2d_v1" @@ -57,7 +60,7 @@ def __post_init__(self) -> None: if x.size > 2: widths[1:-1] = 0.5 * (dx[:-1] + dx[1:]) y = self.y_geometry - if y.name != HALF_ENDPOINT_V1 or y.node_count < 3: + if y.name not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2} or y.node_count < 3: raise ValueError("2D stack requires at least three nodes with physical half-endpoint cells") object.__setattr__(self, "x_m", x) object.__setattr__(self, "x_widths_m", frozen_array(widths)) @@ -81,6 +84,8 @@ def __post_init__(self) -> None: object.__setattr__(self, "contract_geometry", geometry) object.__setattr__(self, "face_spacing_m", frozen_array(distances)) digest = hashlib.sha256(self.name.encode()) + if y.name != HALF_ENDPOINT_V1: + digest.update(y.name.encode()) for value in (x, y.nodes_m, areas, pairs, measures, distances): digest.update(np.ascontiguousarray(value, dtype=" tuple[np.ndarray, float]: assert err_coarse_v2 < err_coarse_v1 assert err_mid_v2 < err_mid_v1 assert err_mid_v2 < 0.6 * err_coarse_v2 + + +def test_p08_02b_global_conservation_and_1d_2d_parity_on_physical_half_endpoint_v2() -> None: + """PHYSICAL_HALF_ENDPOINT_V2 closes conservation <= 1e-13 and unifies 1D and 2D columns.""" + prepared = load_device() + ny_per_layer = 4 + intervals = (ny_per_layer,) * len(prepared.layers) + dev_int_1d = compile_device_1d(prepared, intervals_per_layer=intervals) + + # Rebind the 1D compiled column onto PHYSICAL_HALF_ENDPOINT_V2 + coupled Poisson + generation. + iface_positions = [plane.position_m for plane in dev_int_1d.geometry.interfaces] + geom_v2 = physical_half_endpoint_geometry(dev_int_1d.nodes_m, iface_positions) + data = prepared.to_mapping() + alpha_node: np.ndarray = np.empty(dev_int_1d.node_count, dtype=np.float64) + eps_node: np.ndarray = np.empty(dev_int_1d.node_count, dtype=np.float64) + layer_eps: list[float] = [] + for layer, mask in zip(prepared.layers, dev_int_1d.parameters.layer_masks): + params = dict(layer.parameters) + alpha_raw = params["alpha"] + eps_raw = params["eps_r"] + assert isinstance(alpha_raw, (int, float)) and not isinstance(alpha_raw, bool) + assert isinstance(eps_raw, (int, float)) and not isinstance(eps_raw, bool) + alpha_node[mask] = float(alpha_raw) + eps_node[mask] = float(eps_raw) + layer_eps.append(float(eps_raw)) + + phi_inc = data["settings"]["Phi"] + assert isinstance(phi_inc, (int, float)) and not isinstance(phi_inc, bool) + poisson_v2 = PoissonOperator1D.for_geometry(geom_v2, eps_node, layer_eps_r=layer_eps) + gen_v2 = BeerLambertBinding(dev_int_1d.nodes_m, alpha_node, float(phi_inc)).generation_profile( + geom_v2 + ) + sha_v2 = hashlib.sha256( + json.dumps( + (dev_int_1d.sha256, PHYSICAL_HALF_ENDPOINT_V2, LAYER_SERIES_CAPACITANCE_V2), + separators=(",", ":"), + ).encode() + ).hexdigest() + dev_v2_1d = replace( + dev_int_1d, + sha256=sha_v2, + geometry=geom_v2, + poisson=poisson_v2, + generation=gen_v2, + ) + + opts_1d = SteadyOptions(continuity_tolerance_A_m2=1e-9) + opts_2d = Steady2DOptions(electronic=opts_1d) + + # Solve 1D (both legacy INTEGER_ENDPOINT_V1 and new PHYSICAL_HALF_ENDPOINT_V2) at two operating points. + s1_v2_0 = solve_steady_state(dev_v2_1d, voltage_V=0.0, generation_scale=1.0, options=opts_1d) + s1_v2_f = solve_steady_state( + dev_v2_1d, + voltage_V=0.08, + generation_scale=1.0, + initial_state=s1_v2_0.state, + options=opts_1d, + ) + s1_int_0 = solve_steady_state(dev_int_1d, voltage_V=0.0, generation_scale=1.0, options=opts_1d) + s1_int_f = solve_steady_state( + dev_int_1d, + voltage_V=0.08, + generation_scale=1.0, + initial_state=s1_int_0.state, + options=opts_1d, + ) + + # 1) BackwardEuler1DStep + step_accounting via solve_transient on AssembledDC1DProblem: + # global particle and Maxwell total-current conservation <= 1e-13. + dt_s = 5.0e-6 + protocol = TransientProtocol( + times_s=np.array([0.0, dt_s, 2.0 * dt_s]), + voltage_V=np.array([0.0, 0.02, 0.04]), + generation_scale=np.array([1.0, 1.0, 1.0]), + ) + tr_options = TransientOptions( + poisson_tolerance=opts_1d.poisson_tolerance, + continuity_tolerance_A_m2=opts_1d.continuity_tolerance_A_m2, + contact_log_tolerance=opts_1d.contact_log_tolerance, + potential_step_V=opts_1d.potential_step_V, + quasi_fermi_step=opts_1d.quasi_fermi_step, + newton_budget=opts_1d.budget(), + max_steps=4, + wall_s=20.0, + predictor="previous", + convergence_policy=opts_1d.convergence_policy, + ) + tr_result = solve_transient( + dev_v2_1d, + s1_v2_0, + protocol, + options=tr_options, + initial_options=opts_1d, + method="backward_euler", + ) + assert isinstance(tr_result, TransientResult1D) + assert len(tr_result.attempts) == 2 + for attempt in tr_result.attempts: + assert attempt.accepted and attempt.accounting is not None + acct = attempt.accounting + particles = np.asarray(acct["particle_fluxes_m2_s"], dtype=np.float64) + rate = np.asarray(acct["inventory_rate_m2_s"], dtype=np.float64) + pair_src = np.asarray(acct["net_pair_source_m2_s"], dtype=np.float64) + global_part = np.asarray(acct["global_particle_balance_m2_s"], dtype=np.float64) + global_charge = float(acct["global_charge_balance_A_m2"]) # type: ignore[arg-type] + maxwell_err = np.asarray(acct["maxwell_identity_error_A_m2"], dtype=np.float64) + maxwell_spread = float(acct["maxwell_spread_A_m2"]) # type: ignore[arg-type] + term_total = np.asarray(acct["terminal_total_current_density_A_m2"], dtype=np.float64) + + part_scale = max( + float(np.max(np.abs(particles))), + float(np.max(np.abs(rate))), + float(np.max(np.abs(pair_src))), + 1.0, + ) + j_scale = max(float(np.max(np.abs(term_total))), 1.0) + assert np.max(np.abs(global_part)) / part_scale <= 1e-13 + assert abs(global_charge) / j_scale <= 1e-13 + assert np.max(np.abs(maxwell_err)) / j_scale <= 1e-13 + assert maxwell_spread / j_scale <= 1e-13 + + # 2) 1D (PHYSICAL_HALF_ENDPOINT_V2) vs uniform-column 2D (Nx = 2 and Nx = 3): + # exact J(V), carrier inventory, and contact displacement-current agreement. + prob_1d_0 = AssembledDC1DProblem(dev_v2_1d, voltage_V=0.0, generation_scale=1.0) + prob_1d_f = AssembledDC1DProblem(dev_v2_1d, voltage_V=0.08, generation_scale=1.0) + j1_v2_0 = prob_1d_0.contact_current_density(s1_v2_0.state.u) + j1_v2_f = prob_1d_f.contact_current_density(s1_v2_f.state.u) + j1_int_0 = AssembledDC1DProblem( + dev_int_1d, voltage_V=0.0, generation_scale=1.0 + ).contact_current_density(s1_int_0.state.u) + + inv1_0 = inventory_m2(dev_v2_1d, s1_v2_0.state) + rho1_0 = dev_v2_1d.charge_ledger( + s1_v2_0.state.electron_density_m3, s1_v2_0.state.hole_density_m3 + ).space_charge_C_m3() + rho1_f = dev_v2_1d.charge_ledger( + s1_v2_f.state.electron_density_m3, s1_v2_f.state.hole_density_m3 + ).space_charge_C_m3() + d1_contacts_0 = contact_displacement( + dev_v2_1d.poisson.face_displacement(s1_v2_0.state.potential_V), + rho1_0, + dev_v2_1d.geometry.cell_measures_m, + ) + d1_contacts_f = contact_displacement( + dev_v2_1d.poisson.face_displacement(s1_v2_f.state.potential_V), + rho1_f, + dev_v2_1d.geometry.cell_measures_m, + ) + j_disp_1d = (d1_contacts_f - d1_contacts_0) / dt_s + + for nx in (2, 3): + spatial = JV2DInput( + kind="jv_2d", + lateral_length="0.6 um", + Nx=nx, + Ny_per_layer=ny_per_layer, + lateral_bc="neumann", + ) + dev_2d = compile_device_2d( + prepared, spatial, stack_geometry=PHYSICAL_HALF_ENDPOINT_V2 + ) + # Seed 2D from the legacy INTEGER_ENDPOINT_V1 1D column PLUS a non-uniform lateral + # cos/sin perturbation so 2D Newton genuinely relaxes both laterally and geometrically! + def _perturbed_seed(col_u: np.ndarray, bias_v: float) -> np.ndarray: + y_norm = (dev_2d.column.nodes_m - dev_2d.column.nodes_m[0]) / np.ptp(dev_2d.column.nodes_m) + x_norm = (dev_2d.geometry.x_m - dev_2d.geometry.x_m[0]) / dev_2d.geometry.lateral_length_m + wave = np.sin(np.pi * y_norm) + wave[[0, -1]] = 0.0 + u_init = dev_2d.extrude_coordinates(col_u) + n_tot = dev_2d.node_count + u_init[:n_tot] += (0.0007 * wave[:, None] * np.cos(np.pi * x_norm)[None, :]).ravel() + u_init[n_tot : 2 * n_tot] += (0.013 * wave[:, None] * np.sin(np.pi * x_norm)[None, :]).ravel() + u_init[2 * n_tot :] += (-0.011 * wave[:, None] * np.cos(2.0 * np.pi * x_norm)[None, :]).ravel() + return u_init + + res_2d_0 = solve_steady_state_2d( + dev_2d, + voltage_V=0.0, + generation_scale=1.0, + initial_state=dev_2d.state(_perturbed_seed(s1_int_0.state.u, 0.0), voltage_V=0.0), + options=opts_2d, + ) + res_2d_f = solve_steady_state_2d( + dev_2d, + voltage_V=0.08, + generation_scale=1.0, + initial_state=dev_2d.state(_perturbed_seed(s1_int_f.state.u, 0.08), voltage_V=0.08), + options=opts_2d, + ) + assert res_2d_0.accepted and res_2d_0.state is not None and res_2d_0.diagnostics is not None + assert res_2d_f.accepted and res_2d_f.state is not None and res_2d_f.diagnostics is not None + + j2_0 = np.asarray(res_2d_0.diagnostics["terminal_mean_current_density_A_m2"], dtype=np.float64) + j2_f = np.asarray(res_2d_f.diagnostics["terminal_mean_current_density_A_m2"], dtype=np.float64) + assert np.max(np.abs(j2_0 - j1_v2_0)) / np.max(np.abs(j1_v2_0)) <= 1e-13 + assert np.max(np.abs(j2_f - j1_v2_f)) / np.max(np.abs(j1_v2_f)) <= 1e-13 + + # Legacy INTEGER_ENDPOINT_V1 disagrees with uniform-column 2D on the coarse grid! + inv1_int_0 = inventory_m2(dev_int_1d, s1_int_0.state) + assert np.max(np.abs(j2_0 - j1_int_0)) / np.max(np.abs(j2_0)) > 5e-7 + + vols_2d = dev_2d.geometry.contract_geometry.volumes + lx = dev_2d.geometry.lateral_length_m + inv2_n = float(np.sum(res_2d_0.state.electron_density_m3.ravel() * vols_2d) / lx) + inv2_p = float(np.sum(res_2d_0.state.hole_density_m3.ravel() * vols_2d) / lx) + assert abs(inv2_n - float(np.sum(inv1_0[0]))) / inv2_n <= 1e-13 + assert abs(inv2_p - float(np.sum(inv1_0[1]))) / inv2_p <= 1e-13 + assert abs(inv2_n - float(np.sum(inv1_int_0[0]))) / inv2_n > 0.01 + assert abs(inv2_p - float(np.sum(inv1_int_0[1]))) / inv2_p > 0.01 + + # Contact displacement and displacement current parity between 1D and 2D columns. + g2 = dev_2d.geometry + disp2_0 = np.asarray(res_2d_0.diagnostics["face_displacement_C_m2"], dtype=np.float64) + disp2_f = np.asarray(res_2d_f.diagnostics["face_displacement_C_m2"], dtype=np.float64) + dy_0 = disp2_0[g2.x_face_count :].reshape(g2.ny - 1, g2.nx) + dy_f = disp2_f[g2.x_face_count :].reshape(g2.ny - 1, g2.nx) + rho2_0 = dev_2d.charge_ledger( + res_2d_0.state.electron_density_m3.ravel(), res_2d_0.state.hole_density_m3.ravel() + ).space_charge_C_m3().reshape(g2.shape) + rho2_f = dev_2d.charge_ledger( + res_2d_f.state.electron_density_m3.ravel(), res_2d_f.state.hole_density_m3.ravel() + ).space_charge_C_m3().reshape(g2.shape) + wy = g2.y_geometry.cell_measures_m + d2_contacts_0 = np.array( + [ + float(np.sum((dy_0[0] - rho2_0[0] * wy[0]) * g2.x_widths_m) / lx), + float(np.sum((dy_0[-1] + rho2_0[-1] * wy[-1]) * g2.x_widths_m) / lx), + ] + ) + d2_contacts_f = np.array( + [ + float(np.sum((dy_f[0] - rho2_f[0] * wy[0]) * g2.x_widths_m) / lx), + float(np.sum((dy_f[-1] + rho2_f[-1] * wy[-1]) * g2.x_widths_m) / lx), + ] + ) + j_disp_2d = (d2_contacts_f - d2_contacts_0) / dt_s + d_scale = float(np.max(np.abs(disp2_0))) + jd_scale = max(float(np.max(np.abs(j_disp_1d))), float(np.max(np.abs(disp2_f - disp2_0)) / dt_s)) + assert np.max(np.abs(d2_contacts_0 - d1_contacts_0)) / d_scale <= 1e-13 + assert np.max(np.abs(j_disp_2d - j_disp_1d)) / jd_scale <= 1e-13 + diff --git a/tests/unit/physics/test_p08_02_dielectric_and_geometry.py b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py index 649860ea..23f4ae6f 100644 --- a/tests/unit/physics/test_p08_02_dielectric_and_geometry.py +++ b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py @@ -24,11 +24,14 @@ HALF_ENDPOINT_V1, INTEGER_ENDPOINT_V1, PHYSICAL_BOUNDARY_TWO_SIDED_V1, + PHYSICAL_HALF_ENDPOINT_V2, RIGHT_LAYER_WINS, TWO_SIDED_TRACE_V1, + areal_interface_to_cell_source, build_geometry, multilayer_grid, node_owner, + physical_half_endpoint_geometry, remove_shared_interface_nodes, ) from solarlab.mesh.geometry import half_endpoint_geometry @@ -44,6 +47,9 @@ rectangular_2d_face_capacitances, solve_electrostatic_traces, ) +from solarlab.physics.electrostatics.gauss_assembly import gauss_balance_with_term_sink +from solarlab.physics.generation.beer_lambert import BeerLambertBinding +from solarlab.physics.recombination.interface import evaluate_shared_interface_trap EPS_0 = VACUUM_PERMITTIVITY_F_M @@ -431,3 +437,119 @@ def phi_piecewise(x_arr: np.ndarray) -> np.ndarray: assert abs(phi_rs - phi_if_exact) <= 1e-14 assert abs((d_r_trace - d_l_trace) - sigma_sheet) / abs(sigma_sheet) <= 1e-14 assert np.max(np.abs(phi_two - phi_piecewise(x_two))) <= 1e-14 + + +def test_p08_02b_physical_half_endpoint_v2_measures_gauss_and_generation_coupling() -> None: + """PHYSICAL_HALF_ENDPOINT_V2 couples w_i = b_{i+1}-b_i across Gauss and Beer-Lambert.""" + thicknesses = (1.5e-7, 4.0e-7, 1.8e-7) + total_length = sum(thicknesses) + interfaces = (thicknesses[0], thicknesses[0] + thicknesses[1]) + x_shared = multilayer_grid(list(zip(thicknesses, (6, 10, 5))), alpha=2.2) + eps_shared = np.array([3.5, 24.0, 9.0])[node_owner(x_shared, thicknesses, RIGHT_LAYER_WINS)] + + # Historical INTEGER_ENDPOINT_V1 stays bit-identical with endpoint over-count. + geom_int = build_geometry(INTEGER_ENDPOINT_V1, x_shared, interfaces) + dx = np.diff(x_shared) + assert abs(geom_int.total_measure_m - (total_length + 0.5 * (dx[0] + dx[-1]))) <= 1e-21 + + # Shared-node PHYSICAL_HALF_ENDPOINT_V2: exact w_i = b_{i+1} - b_i, sum(w) == L. + geom_v2 = build_geometry(PHYSICAL_HALF_ENDPOINT_V2, x_shared, interfaces) + assert geom_v2.geometric_cells is True + assert _same_bits(geom_v2.cell_measures_m, np.diff(geom_v2.cell_faces_m)) + assert abs(geom_v2.total_measure_m - total_length) / total_length <= 1e-15 + assert geom_v2.material_owner_convention == RIGHT_LAYER_WINS + assert geom_v2.role_owner_convention == RIGHT_LAYER_WINS + + op_v2 = PoissonOperator1D.for_geometry(geom_v2, eps_shared) + assert op_v2.dielectric_rule == LAYER_SERIES_CAPACITANCE_V2 + assert _same_bits(op_v2.interior_widths_m, geom_v2.cell_measures_m[1:-1]) + + rng = np.random.default_rng(20261115) + phi = rng.normal(scale=0.4, size=x_shared.size) + rho = rng.normal(scale=2.0e4, size=x_shared.size) + balance = gauss_balance_with_term_sink(op_v2, geom_v2, phi, rho) + contacts = contact_displacement(op_v2.face_displacement(phi), rho, geom_v2.cell_measures_m) + assert _same_bits(balance[1:-1], op_v2.interior_residual(phi, rho)) + assert _same_bits(np.array([balance[0], balance[-1]]), np.array([-contacts[0], contacts[1]])) + + # Uncoupled interior widths must be refused by gauss_balance_with_term_sink. + bad_op = PoissonOperator1D.from_finite_volume( + op_v2.face_capacitance_F_m2, + op_v2.interior_widths_m * 1.01, + geometry_name=PHYSICAL_HALF_ENDPOINT_V2, + ) + with pytest.raises(ValueError, match="interior measures"): + gauss_balance_with_term_sink(bad_op, geom_v2, phi, rho) + + # Beer-Lambert generation coupled to PHYSICAL_HALF_ENDPOINT_V2 matches 2D y_geometry + # and closes exact absorbed photon budget. + alpha_uniform = np.full(x_shared.size, 8.0e6) + incident_flux = 2.5e21 + bl = BeerLambertBinding(x_shared, alpha_uniform, incident_flux) + prof_v2 = bl.generation_profile(geom_v2) + prof_int = bl.generation_profile(geom_int) + prof_2d_y = bl.generation_profile(half_endpoint_geometry(x_shared, interfaces)) + expected_absorbed = incident_flux * (1.0 - np.exp(-alpha_uniform[0] * total_length)) + assert ( + abs(float(np.sum(prof_v2.source_m3_s * geom_v2.cell_measures_m)) - expected_absorbed) + / expected_absorbed + <= 1e-14 + ) + # PHYSICAL_HALF_ENDPOINT_V2 fixes the 2x boundary cell dilution of INTEGER_ENDPOINT_V1. + assert abs(prof_v2.source_m3_s[0] - prof_2d_y.source_m3_s[0]) / prof_v2.source_m3_s[0] <= 1e-14 + assert abs(prof_v2.source_m3_s[0] / prof_int.source_m3_s[0] - 2.0) < 1e-12 + + # Two-sided PHYSICAL_HALF_ENDPOINT_V2 places interior faces at the true material planes. + x_two = remove_shared_interface_nodes(x_shared, interfaces) + geom_two_v2 = physical_half_endpoint_geometry(x_two, interfaces) + assert _same_bits(geom_two_v2.cell_measures_m, np.diff(geom_two_v2.cell_faces_m)) + assert abs(geom_two_v2.total_measure_m - total_length) / total_length <= 1e-15 + for plane in geom_two_v2.interfaces: + assert geom_two_v2.cell_faces_m[plane.right_node] == plane.position_m + + +def test_p08_02b_areal_sheet_trap_conversion_conserves_across_geometries() -> None: + """Areal sheet-trap density and capture rates conserve identically on cell_measures_m.""" + thicknesses = (1.2e-7, 3.6e-7, 1.4e-7) + interfaces = (thicknesses[0], thicknesses[0] + thicknesses[1]) + x_shared = multilayer_grid(list(zip(thicknesses, (5, 8, 5))), alpha=2.0) + x_two = remove_shared_interface_nodes(x_shared, interfaces) + + trap_eval = evaluate_shared_interface_trap( + 1.2e19, + 4.5e15, + 8.0e16, + 2.3e18, + v_n_left_m_s=1.5e2, + v_p_left_m_s=8.0e1, + v_n_right_m_s=2.0e2, + v_p_right_m_s=1.1e2, + n1_left_m3=1.0e15, + p1_left_m3=2.0e15, + n1_right_m3=5.0e14, + p1_right_m3=3.0e15, + areal_density_m2=2.0e15, + equilibrium_occupancy=0.25, + ) + cn_left, cp_left, cn_right, cp_right = (float(v) for v in trap_eval.capture_rates_m2_s) + total_electron_capture = cn_left + cn_right + total_hole_capture = cp_left + cp_right + assert abs(total_electron_capture - total_hole_capture) <= 1e-13 * abs(total_electron_capture) + + for geom in ( + build_geometry(INTEGER_ENDPOINT_V1, x_shared, interfaces), + build_geometry(HALF_ENDPOINT_V1, x_shared, interfaces), + build_geometry(PHYSICAL_HALF_ENDPOINT_V2, x_shared, interfaces), + build_geometry(PHYSICAL_BOUNDARY_TWO_SIDED_V1, x_two, interfaces), + build_geometry(PHYSICAL_HALF_ENDPOINT_V2, x_two, interfaces), + ): + src_nt = areal_interface_to_cell_source(geom, 0, 2.0e15, partition=(0.35, 0.65)) + assert abs(float(np.sum(geom.cell_measures_m * src_nt)) - 2.0e15) / 2.0e15 <= 1e-15 + + src_cn = geom.areal_to_cell_source(1, side_quantities=(cn_left, cn_right)) + src_cp = geom.areal_to_cell_source(1, side_quantities=(cp_left, cp_right)) + int_cn = float(np.sum(geom.cell_measures_m * src_cn)) + int_cp = float(np.sum(geom.cell_measures_m * src_cp)) + assert abs(int_cn - total_electron_capture) / abs(total_electron_capture) <= 1e-14 + assert abs(int_cp - total_hole_capture) / abs(total_hole_capture) <= 1e-14 + From 7d8816df2585eeaf1fcc1078aa8d9b8c5e660862 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 22:54:15 +0800 Subject: [PATCH 23/46] N(transport): add opt-in hole_separate_increment_v1 band-step differencing (P08-02c) --- .../physics/transport/drift_diffusion.py | 144 ++++++++- .../physics/transport/electrochemical_flux.py | 95 +++++- .../test_p08_02_refinement_and_parity.py | 33 ++ .../test_p08_02_dielectric_and_geometry.py | 305 +++++++++++++++++- 4 files changed, 561 insertions(+), 16 deletions(-) diff --git a/src/solarlab/physics/transport/drift_diffusion.py b/src/solarlab/physics/transport/drift_diffusion.py index b033ff54..c17e01e1 100644 --- a/src/solarlab/physics/transport/drift_diffusion.py +++ b/src/solarlab/physics/transport/drift_diffusion.py @@ -15,11 +15,35 @@ import numpy as np from numpy.typing import ArrayLike, NDArray +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.discretization.bernoulli import bernoulli, bernoulli_derivative from solarlab.discretization.face_average import harmonic_face_mean -from solarlab.discretization.scharfetter_gummel import legacy_sg_current_n, legacy_sg_current_p +from solarlab.discretization.scharfetter_gummel import ( + LegacyFaceJacobian, + legacy_sg_current_n, + legacy_sg_current_n_jacobian, + legacy_sg_current_p, + legacy_sg_current_p_jacobian, +) from solarlab.physics.statistics.band_potentials import BandStructure +from solarlab.physics.transport.electrochemical_flux import ( + BAND_STEP_MODES, + HOLE_SEPARATE_INCREMENT_V1, + LEGACY_SUMMED_POTENTIAL_V1, + carrier_transport_potential_steps, +) -__all__ = ["legacy_carrier_face_currents", "legacy_face_diffusivity"] +__all__ = [ + "BAND_STEP_MODES", + "HOLE_SEPARATE_INCREMENT_V1", + "LEGACY_SUMMED_POTENTIAL_V1", + "carrier_transport_potential_steps", + "legacy_carrier_face_currents", + "legacy_carrier_face_jacobians", + "legacy_face_diffusivity", +] + +Q = ELEMENTARY_CHARGE_C def legacy_face_diffusivity(node_diffusivity: ArrayLike) -> NDArray[np.float64]: @@ -40,10 +64,118 @@ def legacy_carrier_face_currents( D_p_face: ArrayLike, thermal_voltage_V: float, bands: BandStructure, + *, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: """Historical MB face currents ``(J_n, J_p)`` [A/m^2] on the N-1 faces.""" + if band_step_mode not in BAND_STEP_MODES: + raise ValueError( + f"unknown band_step_mode {band_step_mode!r}; expected one of {BAND_STEP_MODES}" + ) spacing = np.diff(np.asarray(x, dtype=float)) - electron_potential, hole_potential = bands.transport_potentials(phi) - J_n = legacy_sg_current_n(electron_potential, n, spacing, D_n_face, thermal_voltage_V) - J_p = legacy_sg_current_p(hole_potential, p, spacing, D_p_face, thermal_voltage_V) - return J_n, J_p + if band_step_mode == LEGACY_SUMMED_POTENTIAL_V1: + electron_potential, hole_potential = bands.transport_potentials(phi) + J_n = legacy_sg_current_n(electron_potential, n, spacing, D_n_face, thermal_voltage_V) + J_p = legacy_sg_current_p(hole_potential, p, spacing, D_p_face, thermal_voltage_V) + return J_n, J_p + + electrons = np.asarray(n, dtype=float) + holes = np.asarray(p, dtype=float) + dpsi_n, dpsi_p = carrier_transport_potential_steps( + phi, bands, band_step_mode=band_step_mode + ) + q = 1.602176634e-19 + xi_n = dpsi_n / thermal_voltage_V + xi_p = dpsi_p / thermal_voltage_V + j_n: NDArray[np.float64] = ( + q * np.asarray(D_n_face, dtype=float) / spacing * (bernoulli(xi_n) * electrons[1:] - bernoulli(-xi_n) * electrons[:-1]) + ) + j_p: NDArray[np.float64] = ( + q * np.asarray(D_p_face, dtype=float) / spacing * (bernoulli(xi_p) * holes[:-1] - bernoulli(-xi_p) * holes[1:]) + ) + return j_n, j_p + + +def legacy_carrier_face_jacobians( + x: ArrayLike, + phi: ArrayLike, + n: ArrayLike, + p: ArrayLike, + D_n_face: ArrayLike, + D_p_face: ArrayLike, + thermal_voltage_V: float, + bands: BandStructure, + *, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, +) -> tuple[LegacyFaceJacobian, LegacyFaceJacobian]: + """Analytic ``(J_n, J_p)`` face Jacobians wrt ``(phi_L, phi_R, c_L, c_R)``.""" + if band_step_mode not in BAND_STEP_MODES: + raise ValueError( + f"unknown band_step_mode {band_step_mode!r}; expected one of {BAND_STEP_MODES}" + ) + grid = np.asarray(x, dtype=float) + spacing = np.diff(grid) + if band_step_mode == LEGACY_SUMMED_POTENTIAL_V1: + electron_potential, hole_potential = bands.transport_potentials(phi) + return ( + legacy_sg_current_n_jacobian(electron_potential, n, spacing, D_n_face, thermal_voltage_V), + legacy_sg_current_p_jacobian(hole_potential, p, spacing, D_p_face, thermal_voltage_V), + ) + + potential = np.asarray(phi, dtype=float) + electrons = np.asarray(n, dtype=float) + holes = np.asarray(p, dtype=float) + thermal = float(thermal_voltage_V) + if ( + grid.ndim != 1 + or grid.size < 2 + or potential.shape != grid.shape + or electrons.shape != grid.shape + or holes.shape != grid.shape + or np.any(spacing <= 0.0) + or not ( + np.all(np.isfinite(grid)) + and np.all(np.isfinite(potential)) + and np.all(np.isfinite(electrons)) + and np.all(np.isfinite(holes)) + ) + or not np.isfinite(thermal) + or thermal <= 0.0 + ): + raise ValueError( + "SG Jacobian inputs must be finite, shape matched, and use " + "positive spacing and thermal voltage" + ) + dn = np.broadcast_to(np.asarray(D_n_face, dtype=float), spacing.shape) + dp = np.broadcast_to(np.asarray(D_p_face, dtype=float), spacing.shape) + if not (np.all(np.isfinite(dn)) and np.all(np.isfinite(dp))) or np.any(dn < 0.0) or np.any(dp < 0.0): + raise ValueError("SG diffusivity must be finite and non-negative") + + dpsi_n, dpsi_p = carrier_transport_potential_steps( + potential, bands, band_step_mode=band_step_mode + ) + j_n, j_p = legacy_carrier_face_currents( + grid, potential, electrons, holes, dn, dp, thermal, bands, band_step_mode=band_step_mode + ) + xi_n = dpsi_n / thermal + xi_p = dpsi_p / thermal + pref_n = Q * dn / spacing + pref_p = Q * dp / spacing + d_xi_n = pref_n * (bernoulli_derivative(xi_n) * electrons[1:] + bernoulli_derivative(-xi_n) * electrons[:-1]) + d_xi_p = pref_p * (bernoulli_derivative(xi_p) * holes[:-1] + bernoulli_derivative(-xi_p) * holes[1:]) + return ( + LegacyFaceJacobian( + flux=j_n, + density_left_derivative=-pref_n * bernoulli(-xi_n), + density_right_derivative=pref_n * bernoulli(xi_n), + potential_left_derivative=-d_xi_n / thermal, + potential_right_derivative=d_xi_n / thermal, + ), + LegacyFaceJacobian( + flux=j_p, + density_left_derivative=pref_p * bernoulli(xi_p), + density_right_derivative=-pref_p * bernoulli(-xi_p), + potential_left_derivative=-d_xi_p / thermal, + potential_right_derivative=d_xi_p / thermal, + ), + ) diff --git a/src/solarlab/physics/transport/electrochemical_flux.py b/src/solarlab/physics/transport/electrochemical_flux.py index 69f34a97..ea635cd0 100644 --- a/src/solarlab/physics/transport/electrochemical_flux.py +++ b/src/solarlab/physics/transport/electrochemical_flux.py @@ -51,13 +51,28 @@ from solarlab.physics.statistics.band_potentials import BandStructure __all__ = [ - "CarrierFaceFlux", "CarrierFaceFluxes", "carrier_particle_fluxes", - "electrochemical_step_from_densities", "electron_current_from_particle_flux", - "hole_current_from_particle_flux", "stable_sg_particle_flux", + "BAND_STEP_MODES", + "CarrierFaceFlux", + "CarrierFaceFluxes", + "HOLE_SEPARATE_INCREMENT_V1", + "LEGACY_SUMMED_POTENTIAL_V1", + "carrier_particle_fluxes", + "carrier_transport_potential_steps", + "electrochemical_step_from_densities", + "electron_current_from_particle_flux", + "hole_current_from_particle_flux", + "stable_sg_particle_flux", ] Q = ELEMENTARY_CHARGE_C +LEGACY_SUMMED_POTENTIAL_V1 = "legacy_summed_potential_v1" +HOLE_SEPARATE_INCREMENT_V1 = "hole_separate_increment_v1" +BAND_STEP_MODES = ( + LEGACY_SUMMED_POTENTIAL_V1, + HOLE_SEPARATE_INCREMENT_V1, +) + def _extreme_bernoulli_product( argument: NDArray[np.float64], density: NDArray[np.float64], @@ -206,13 +221,72 @@ def hole_current_from_particle_flux(flux: ArrayLike) -> NDArray[np.float64]: return result -def _carrier_flux(density: NDArray[np.float64], potential: NDArray[np.float64], +def carrier_transport_potential_steps( + phi: ArrayLike, + bands: BandStructure, + *, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + left_nodes: ArrayLike | None = None, + right_nodes: ArrayLike | None = None, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Face transport-potential increments ``(dpsi_n, dpsi_p)`` [V] oriented L -> R. + + Under ``LEGACY_SUMMED_POTENTIAL_V1`` (default), nodal ``phi + chi_t`` and + ``phi + chi_t + Eg_t`` are formed before differencing for 0-ULP parity with + historical runs (preserving historical ``Final121`` native residual behavior). + Under ``HOLE_SEPARATE_INCREMENT_V1`` (``BandStepsV1``), electrostatic and + band-offset increments ``(d_phi) + (d_chi_t) + (d_Eg_t)`` are formed on each + face prior to summation so large constant ``chi_t + Eg_t`` offsets cannot + quantize small intra-layer ``d_phi`` steps. + """ + if band_step_mode not in BAND_STEP_MODES: + raise ValueError( + f"unknown band_step_mode {band_step_mode!r}; expected one of {BAND_STEP_MODES}" + ) + potential = np.asarray(phi, dtype=float) + chi_t = bands.transport_electron_affinity_eV + eg_t = bands.transport_band_gap_eV + if potential.shape != chi_t.shape or potential.ndim != 1 or potential.size < 2: + raise ValueError("phi must live on the 1-D band-structure nodes with size >= 2") + if not np.all(np.isfinite(potential)): + raise ValueError("phi must be finite on every node") + if (left_nodes is None) != (right_nodes is None): + raise ValueError("left_nodes and right_nodes must be provided together or omitted") + + if left_nodes is not None and right_nodes is not None: + left = np.asarray(left_nodes, dtype=np.intp) + right = np.asarray(right_nodes, dtype=np.intp) + if left.ndim != 1 or right.shape != left.shape: + raise ValueError("left_nodes and right_nodes must share one 1-D face shape") + if band_step_mode == LEGACY_SUMMED_POTENTIAL_V1: + psi_n, psi_p = bands.transport_potentials(potential) + return psi_n[right] - psi_n[left], psi_p[right] - psi_p[left] + d_phi = potential[right] - potential[left] + d_chi = chi_t[right] - chi_t[left] + d_eg = eg_t[right] - eg_t[left] + dpsi_n_graph: NDArray[np.float64] = d_phi + d_chi + dpsi_p_graph: NDArray[np.float64] = (d_phi + d_chi) + d_eg + return dpsi_n_graph, dpsi_p_graph + + if band_step_mode == LEGACY_SUMMED_POTENTIAL_V1: + psi_n, psi_p = bands.transport_potentials(potential) + return psi_n[1:] - psi_n[:-1], psi_p[1:] - psi_p[:-1] + + d_phi = potential[1:] - potential[:-1] + d_chi = chi_t[1:] - chi_t[:-1] + d_eg = eg_t[1:] - eg_t[:-1] + dpsi_n: NDArray[np.float64] = d_phi + d_chi + dpsi_p: NDArray[np.float64] = (d_phi + d_chi) + d_eg + return dpsi_n, dpsi_p + + +def _carrier_flux(density: NDArray[np.float64], potential_step_V: NDArray[np.float64], coefficient: NDArray[np.float64], thermal_voltage_V: float, energy_sign: float, electrochemical_step: ArrayLike | None) -> CarrierFaceFlux: - step = energy_sign * (potential[1:] - potential[:-1]) / thermal_voltage_V + step = energy_sign * potential_step_V / thermal_voltage_V result = stable_sg_particle_flux(density[:-1], density[1:], step, coefficient, electrochemical_step=electrochemical_step) - # D = s (psi_R - psi_L)/V_T, so dF/dpsi_R = s/V_T dF/dD and dF/dpsi_L = -s/V_T dF/dD. + # D = s dpsi/V_T, so dF/dphi_R = s/V_T dF/dD and dF/dphi_L = -s/V_T dF/dD. per_volt = energy_sign / thermal_voltage_V * result.energy_step_derivative return CarrierFaceFlux( flux=result.flux, @@ -237,6 +311,7 @@ def carrier_particle_fluxes( *, electron_electrochemical_step: ArrayLike | None = None, hole_electrochemical_step: ArrayLike | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, ) -> CarrierFaceFluxes: """Electron and hole particle fluxes along +x on the N-1 grid faces. @@ -253,12 +328,14 @@ def carrier_particle_fluxes( or holes.shape != grid.shape or np.any(spacing <= 0.0) or not np.isfinite(thermal) or thermal <= 0.0): raise ValueError("flux inputs must share a strictly increasing node grid") - electron_potential, hole_potential = bands.transport_potentials(phi) + electron_step_V, hole_step_V = carrier_transport_potential_steps( + phi, bands, band_step_mode=band_step_mode + ) k_n = np.asarray(D_n_face, dtype=float) / spacing k_p = np.asarray(D_p_face, dtype=float) / spacing return CarrierFaceFluxes( - electron=_carrier_flux(electrons, electron_potential, k_n, thermal, -1.0, + electron=_carrier_flux(electrons, electron_step_V, k_n, thermal, -1.0, electron_electrochemical_step), - hole=_carrier_flux(holes, hole_potential, k_p, thermal, 1.0, + hole=_carrier_flux(holes, hole_step_V, k_p, thermal, 1.0, hole_electrochemical_step), ) diff --git a/tests/integration/test_p08_02_refinement_and_parity.py b/tests/integration/test_p08_02_refinement_and_parity.py index 5a6bb8fa..0d6fb5e3 100644 --- a/tests/integration/test_p08_02_refinement_and_parity.py +++ b/tests/integration/test_p08_02_refinement_and_parity.py @@ -19,6 +19,8 @@ VACUUM_PERMITTIVITY_F_M, ) from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.dc_2d import DC2DProblem +from solarlab.experiments.jv.steady import run_steady_jv from solarlab.experiments.transient import ( TransientOptions, TransientProtocol, @@ -495,3 +497,34 @@ def _perturbed_seed(col_u: np.ndarray, bias_v: float) -> np.ndarray: assert np.max(np.abs(d2_contacts_0 - d1_contacts_0)) / d_scale <= 1e-13 assert np.max(np.abs(j_disp_2d - j_disp_1d)) / jd_scale <= 1e-13 + +def test_p08_02c_internal_coordinate_signs_vs_pv_readout_polarity_1d_and_2d() -> None: + """Internal +x/+y coordinate signs never flip; PV power-quadrant sign lives only in readout.""" + prepared = load_device() + dev_1d = compile_device_1d(prepared, intervals_per_layer=(4, 4, 4)) + jv = run_steady_jv(dev_1d, [0.0, 0.08], generation_scale=1.0) + + # On p-i-n (p at x=0, n at x=L), voltage_polarity == +1.0; under illumination at V=0, + # electrons flow toward +x (F_n > 0 => J_n < 0) and holes toward -x (F_p < 0 => J_p < 0), + # so internal +x conduction current is strictly NEGATIVE while PV output readout is POSITIVE. + assert dev_1d.voltage_polarity == 1.0 + assert np.all(jv.current_density_A_m2[0] < 0.0) + assert jv.output_current_A_m2[0] > 0.0 + assert jv.output_current_A_m2[0] == -dev_1d.voltage_polarity * jv.current_density_A_m2[0, 0] + assert jv.metrics.short_circuit_current_A_m2 == jv.output_current_A_m2[0] + + # 2D uniform column preserves exact same +y coordinate current sign on faces and terminals. + spatial = JV2DInput( + kind="jv_2d", lateral_length="0.6 um", Nx=2, Ny_per_layer=4, lateral_bc="neumann" + ) + dev_2d = compile_device_2d(prepared, spatial) + prob_2d = DC2DProblem(dev_2d, 0.0, 1.0) + u2 = dev_2d.extrude_coordinates(jv.solutions[0].state.u) + j_term_2d = prob_2d.terminal_current_density_A_m2(u2) + fluxes_2d = prob_2d.fluxes(u2) + yf = dev_2d.geometry.x_face_count + j_cond_y = fluxes_2d.hole_current()[yf:] + fluxes_2d.electron_current()[yf:] + assert np.all(j_term_2d < 0.0) + assert np.all(j_cond_y < 0.0) + np.testing.assert_allclose(j_term_2d[0], jv.current_density_A_m2[0, 0], rtol=2e-4) + diff --git a/tests/unit/physics/test_p08_02_dielectric_and_geometry.py b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py index 23f4ae6f..fff16b02 100644 --- a/tests/unit/physics/test_p08_02_dielectric_and_geometry.py +++ b/tests/unit/physics/test_p08_02_dielectric_and_geometry.py @@ -1,4 +1,4 @@ -"""Unit contracts for P08-02a sub-face series dielectric capacitance.""" +"""Unit contracts for P08-02a dielectric capacitance, P08-02b geometry, and P08-02c band steps.""" from __future__ import annotations @@ -47,11 +47,31 @@ rectangular_2d_face_capacitances, solve_electrostatic_traces, ) +from solarlab.contracts.units import ELEMENTARY_CHARGE_C from solarlab.physics.electrostatics.gauss_assembly import gauss_balance_with_term_sink from solarlab.physics.generation.beer_lambert import BeerLambertBinding from solarlab.physics.recombination.interface import evaluate_shared_interface_trap +from solarlab.physics.statistics.band_potentials import ( + BandStructure, + LayerBandInput, + layered_band_structure, +) +from solarlab.physics.transport.drift_diffusion import ( + BAND_STEP_MODES, + HOLE_SEPARATE_INCREMENT_V1, + LEGACY_SUMMED_POTENTIAL_V1, + legacy_carrier_face_currents, + legacy_carrier_face_jacobians, +) +from solarlab.physics.transport.electrochemical_flux import ( + carrier_particle_fluxes, + carrier_transport_potential_steps, + electron_current_from_particle_flux, + hole_current_from_particle_flux, +) EPS_0 = VACUUM_PERMITTIVITY_F_M +Q = ELEMENTARY_CHARGE_C def _same_bits(a: np.ndarray, b: np.ndarray) -> bool: @@ -553,3 +573,286 @@ def test_p08_02b_areal_sheet_trap_conversion_conserves_across_geometries() -> No assert abs(int_cn - total_electron_capture) / abs(total_electron_capture) <= 1e-14 assert abs(int_cp - total_hole_capture) / abs(total_hole_capture) <= 1e-14 + +def test_p08_02c_default_legacy_summed_potential_is_0_ulp_bit_identical() -> None: + """Default band_step_mode preserves 0-ULP bit-identity across M-class and N-class operators.""" + assert BAND_STEP_MODES == (LEGACY_SUMMED_POTENTIAL_V1, HOLE_SEPARATE_INCREMENT_V1) + vt = 0.02585199102458495 + layers = ( + LayerBandInput(50.0e-9, 4.0, 3.2, 2.2e24, 1.8e25, role="etl"), + LayerBandInput(350.0e-9, 3.9, 1.55, 2.2e24, 1.8e25, role="absorber"), + LayerBandInput(150.0e-9, 2.15, 3.45, 2.0e25, 2.0e25, role="htl"), + ) + x = multilayer_grid([(layer.thickness_m, 6) for layer in layers], alpha=2.0) + bands = layered_band_structure(x, layers, thermal_voltage_V=vt, fold_dos=True) + rng = np.random.default_rng(8023) + phi = np.linspace(0.0, 0.9, x.size) + 1e-4 * rng.normal(size=x.size) + n = np.exp(rng.uniform(25.0, 52.0, size=x.size)) + p = np.exp(rng.uniform(25.0, 52.0, size=x.size)) + dn = rng.uniform(1e-6, 5e-5, size=x.size - 1) + dp = rng.uniform(1e-6, 5e-5, size=x.size - 1) + + jn_def, jp_def = legacy_carrier_face_currents(x, phi, n, p, dn, dp, vt, bands) + jn_leg, jp_leg = legacy_carrier_face_currents( + x, phi, n, p, dn, dp, vt, bands, band_step_mode=LEGACY_SUMMED_POTENTIAL_V1 + ) + assert _same_bits(jn_def, jn_leg) + assert _same_bits(jp_def, jp_leg) + + jac_n_def, jac_p_def = legacy_carrier_face_jacobians(x, phi, n, p, dn, dp, vt, bands) + jac_n_leg, jac_p_leg = legacy_carrier_face_jacobians( + x, phi, n, p, dn, dp, vt, bands, band_step_mode=LEGACY_SUMMED_POTENTIAL_V1 + ) + assert _same_bits(jac_n_def.flux, jac_n_leg.flux) + assert _same_bits(jac_p_def.flux, jac_p_leg.flux) + assert _same_bits(jac_p_def.potential_left_derivative, jac_p_leg.potential_left_derivative) + + fl_def = carrier_particle_fluxes(x, phi, n, p, dn, dp, vt, bands) + fl_leg = carrier_particle_fluxes( + x, phi, n, p, dn, dp, vt, bands, band_step_mode=LEGACY_SUMMED_POTENTIAL_V1 + ) + assert _same_bits(fl_def.electron.flux, fl_leg.electron.flux) + assert _same_bits(fl_def.hole.flux, fl_leg.hole.flux) + assert _same_bits(fl_def.hole.energy_step, fl_leg.hole.energy_step) + assert _same_bits( + fl_def.hole.left_potential_derivative, fl_leg.hole.left_potential_derivative + ) + + # Graph-pair mode matches 1D consecutive-node mode identically on (0..N-2, 1..N-1). + left_idx = np.arange(x.size - 1, dtype=np.intp) + right_idx = np.arange(1, x.size, dtype=np.intp) + for mode in BAND_STEP_MODES: + dn_1d, dp_1d = carrier_transport_potential_steps(phi, bands, band_step_mode=mode) + dn_g, dp_g = carrier_transport_potential_steps( + phi, bands, band_step_mode=mode, left_nodes=left_idx, right_nodes=right_idx + ) + assert _same_bits(dn_1d, dn_g) + assert _same_bits(dp_1d, dp_g) + + with pytest.raises(ValueError, match="band_step_mode"): + carrier_transport_potential_steps(phi, bands, band_step_mode="unknown_v9") + + +def test_p08_02c_hole_separate_increment_v1_jacobian_and_sub_uv_precision() -> None: + """HOLE_SEPARATE_INCREMENT_V1 preserves exact d(step)/d(phi) = +/-1/V_T and sub-nV accuracy.""" + vt = 0.02585199102458495 + layers = ( + LayerBandInput(40.0e-9, 4.0, 3.2, 2.2e24, 1.8e25, role="etl"), + LayerBandInput(160.0e-9, 3.9, 1.55, 2.2e24, 1.8e25, role="absorber"), + LayerBandInput(80.0e-9, 2.2, 3.4, 2.0e25, 2.0e25, role="htl"), + ) + x = multilayer_grid([(layer.thickness_m, 3) for layer in layers], alpha=1.8) + bands = layered_band_structure(x, layers, thermal_voltage_V=vt, fold_dos=True) + rng = np.random.default_rng(12103) + phi = np.linspace(-0.15, 0.65, x.size) + 0.015 * rng.normal(size=x.size) + n = np.exp(rng.uniform(35.0, 48.0, size=x.size)) + p = np.exp(rng.uniform(35.0, 48.0, size=x.size)) + dn = rng.uniform(5e-6, 3e-5, size=x.size - 1) + dp = rng.uniform(5e-6, 3e-5, size=x.size - 1) + + fluxes = carrier_particle_fluxes( + x, phi, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + jac_n, jac_p = legacy_carrier_face_jacobians( + x, phi, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + + h_phi = 1.0e-7 + for k in range(x.size): + phi_plus = phi.copy() + phi_minus = phi.copy() + phi_plus[k] += h_phi + phi_minus[k] -= h_phi + fp = carrier_particle_fluxes( + x, phi_plus, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + fm = carrier_particle_fluxes( + x, phi_minus, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + jn_p, jp_p = legacy_carrier_face_currents( + x, phi_plus, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + jn_m, jp_m = legacy_carrier_face_currents( + x, phi_minus, n, p, dn, dp, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + dstep_n_fd = (fp.electron.energy_step - fm.electron.energy_step) / (2.0 * h_phi) + dstep_p_fd = (fp.hole.energy_step - fm.hole.energy_step) / (2.0 * h_phi) + dfn_fd = (fp.electron.flux - fm.electron.flux) / (2.0 * h_phi) + dfp_fd = (fp.hole.flux - fm.hole.flux) / (2.0 * h_phi) + djn_fd = (jn_p - jn_m) / (2.0 * h_phi) + djp_fd = (jp_p - jp_m) / (2.0 * h_phi) + + if k < x.size - 1: + # Node k is the LEFT node of face k: d(D_n)/d(phi_L) = +1/V_T, d(D_p)/d(phi_L) = -1/V_T. + assert abs(dstep_n_fd[k] - (1.0 / vt)) / (1.0 / vt) <= 2e-9 + assert abs(dstep_p_fd[k] - (-1.0 / vt)) / (1.0 / vt) <= 2e-9 + assert abs(dfn_fd[k] - fluxes.electron.left_potential_derivative[k]) <= 1e-8 * max( + abs(fluxes.electron.left_potential_derivative[k]), 1.0 + ) + assert abs(dfp_fd[k] - fluxes.hole.left_potential_derivative[k]) <= 1e-8 * max( + abs(fluxes.hole.left_potential_derivative[k]), 1.0 + ) + assert abs(djn_fd[k] - jac_n.potential_left_derivative[k]) <= 1e-8 * max( + abs(jac_n.potential_left_derivative[k]), 1.0 + ) + assert abs(djp_fd[k] - jac_p.potential_left_derivative[k]) <= 1e-8 * max( + abs(jac_p.potential_left_derivative[k]), 1.0 + ) + if k > 0: + # Node k is the RIGHT node of face k - 1: d(D_n)/d(phi_R) = -1/V_T, d(D_p)/d(phi_R) = +1/V_T. + f = k - 1 + assert abs(dstep_n_fd[f] - (-1.0 / vt)) / (1.0 / vt) <= 2e-9 + assert abs(dstep_p_fd[f] - (1.0 / vt)) / (1.0 / vt) <= 2e-9 + assert abs(dfn_fd[f] - fluxes.electron.right_potential_derivative[f]) <= 1e-8 * max( + abs(fluxes.electron.right_potential_derivative[f]), 1.0 + ) + assert abs(dfp_fd[f] - fluxes.hole.right_potential_derivative[f]) <= 1e-8 * max( + abs(fluxes.hole.right_potential_derivative[f]), 1.0 + ) + assert abs(djn_fd[f] - jac_n.potential_right_derivative[f]) <= 1e-8 * max( + abs(jac_n.potential_right_derivative[f]), 1.0 + ) + assert abs(djp_fd[f] - jac_p.potential_right_derivative[f]) <= 1e-8 * max( + abs(jac_p.potential_right_derivative[f]), 1.0 + ) + + # Sub-fV step inside chi_t + Eg_t = 5.6 eV HTL: N-class stable_sg_particle_flux + BandStepsV1! + x_htl = np.array([0.0, 1.0e-9]) + bands_htl = BandStructure.without_dos_fold(np.array([2.2, 2.2]), np.array([3.4, 3.4])) + dphi_tiny = -3.0e-16 # < 0.5 * ulp(5.6 V) = 4.44e-16 V! + phi_htl = np.array([1.0e-4, 1.0e-4 + dphi_tiny]) + na = 2.0e24 + mu_p = 2.0e-4 + dp_htl = np.array([mu_p * vt]) + jp_exact = -Q * mu_p * na * ((phi_htl[1] - phi_htl[0]) / 1.0e-9) + + fl_leg_tiny = carrier_particle_fluxes( + x_htl, phi_htl, np.ones(2), np.full(2, na), dp_htl, dp_htl, vt, bands_htl + ) + fl_sep_tiny = carrier_particle_fluxes( + x_htl, + phi_htl, + np.ones(2), + np.full(2, na), + dp_htl, + dp_htl, + vt, + bands_htl, + band_step_mode=HOLE_SEPARATE_INCREMENT_V1, + ) + # Legacy quantizes dpsi_p to an integer multiple of ulp(5.6 V) = 8.88e-16 V (>150% error), + # whereas N-class + HOLE_SEPARATE_INCREMENT_V1 recovers jp_exact to machine precision! + assert abs(fl_leg_tiny.hole_current()[0] - jp_exact) / abs(jp_exact) > 1.5 + assert abs(fl_sep_tiny.hole_current()[0] - jp_exact) / abs(jp_exact) <= 1e-14 + + +def test_p08_02c_final121_class_quantization_eliminated_and_historical_verdict_preserved() -> None: + """BandStepsV1 drops Final121-class >1/3000 A/m^2 rounding to <=2e-5 A/m^2 while preserving default.""" + # Historical citation (AGENTS.md & ArchitectureRefactorExecutionV1.md §19.35): + # Saved SCAPS fixed-state native residual screens recorded 8.79892088904392e-5 A/m^2 on Final61 + # (passed <= 1/3000 A/m^2) and 4.010734989424907e-4 A/m^2 on Final121 (FAILED > 1/3000 A/m^2) + # under default LEGACY_SUMMED_POTENTIAL_V1. That historical failed criterion remains recorded + # as failed; default calls MUST keep LEGACY_SUMMED_POTENTIAL_V1 untouched! + screen_limit_a_m2 = 1.0 / 3000.0 + vt = 0.02585199102458495 + layers = ( + LayerBandInput(50.0e-9, 4.0, 3.2, 2.2e24, 1.8e25, role="etl"), + LayerBandInput(400.0e-9, 3.9, 1.55, 2.2e24, 1.8e25, role="absorber"), + LayerBandInput(200.0e-9, 2.15, 3.45, 2.0e25, 2.0e25, role="htl"), + ) + na = 1.0e24 + mu_p = 2.0e-4 + j0 = 240.0 + + def _htl_balances(intervals_per_layer: int) -> tuple[float, float, float, float]: + x = multilayer_grid([(layer.thickness_m, intervals_per_layer) for layer in layers], alpha=2.2) + bands = layered_band_structure(x, layers, thermal_voltage_V=vt, fold_dos=True) + htl_start = 2 * intervals_per_layer + # Exact steady drift solution in uniform quasi-neutral HTL (B(xi) - B(-xi) === -xi): + # true continuum and exact-arithmetic discrete SG hole balance is identically 0! + phi = 0.21 - (j0 / (Q * mu_p * na)) * (x - x[htl_start]) + n = np.full_like(x, 1.0e10) + p = np.full_like(x, na) + d_face = np.full(x.size - 1, mu_p * vt) + + # Default (no band_step_mode) MUST preserve historical LEGACY_SUMMED_POTENTIAL_V1 behavior. + _, jp_default = legacy_carrier_face_currents(x, phi, n, p, d_face, d_face, vt, bands) + _, jp_sep = legacy_carrier_face_currents( + x, phi, n, p, d_face, d_face, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + fl_default = carrier_particle_fluxes(x, phi, n, p, d_face, d_face, vt, bands) + fl_sep = carrier_particle_fluxes( + x, phi, n, p, d_face, d_face, vt, bands, band_step_mode=HOLE_SEPARATE_INCREMENT_V1 + ) + m_def = float(np.sum(np.abs(jp_default[htl_start:-1] - jp_default[htl_start + 1 :]))) + m_sep = float(np.sum(np.abs(jp_sep[htl_start:-1] - jp_sep[htl_start + 1 :]))) + n_def = float( + np.sum( + np.abs( + fl_default.hole_current()[htl_start:-1] + - fl_default.hole_current()[htl_start + 1 :] + ) + ) + ) + n_sep = float( + np.sum( + np.abs( + fl_sep.hole_current()[htl_start:-1] - fl_sep.hole_current()[htl_start + 1 :] + ) + ) + ) + return m_def, m_sep, n_def, n_sep + + m61_def, m61_sep, n61_def, n61_sep = _htl_balances(20) # N = 61 + m121_def, m121_sep, n121_def, n121_sep = _htl_balances(40) # N = 121 + + # N = 61 passes <= 1/3000 A/m^2 under default legacy summed potentials, while N = 121 FAILS it: + assert m61_def < screen_limit_a_m2 and n61_def < screen_limit_a_m2 + assert m121_def > screen_limit_a_m2 and n121_def > screen_limit_a_m2 + + # Opt-in HOLE_SEPARATE_INCREMENT_V1 eliminates the 5.6 eV offset quantization (> 25x reduction): + assert m61_sep <= 2.0e-5 and n61_sep <= 2.0e-5 + assert m121_sep <= 2.0e-5 and n121_sep <= 2.0e-5 + assert m121_def / m121_sep > 25.0 + assert n121_def / n121_sep > 25.0 + + +def test_p08_02c_internal_coordinate_orientation_invariants() -> None: + """Internal +x particle/current/displacement operators obey strict coordinate signs.""" + vt = 0.02585199102458495 + x = np.array([0.0, 2.0e-8, 5.0e-8]) + bands = BandStructure.without_dos_fold(np.array([3.9, 3.9, 3.9]), np.array([1.55, 1.55, 1.55])) + phi_old = np.array([0.4, 0.15, 0.0]) + phi_new = np.array([0.5, 0.20, 0.0]) + n = np.array([5.0e21, 1.0e21, 2.0e20]) + p = np.array([8.0e21, 2.0e21, 3.0e20]) + d_face = np.array([1.0e-5, 1.0e-5]) + + for mode in BAND_STEP_MODES: + fl = carrier_particle_fluxes( + x, phi_old, n, p, d_face, d_face, vt, bands, band_step_mode=mode + ) + jn_m, jp_m = legacy_carrier_face_currents( + x, phi_old, n, p, d_face, d_face, vt, bands, band_step_mode=mode + ) + # Positive +x hole drift+diffusion => F_p > 0 and J_p = +q F_p > 0. + assert np.all(fl.hole.flux > 0.0) + assert _same_bits(fl.hole_current(), hole_current_from_particle_flux(fl.hole.flux)) + assert np.all(fl.hole_current() > 0.0) + # Electron charge -q => J_n = -q F_n has opposite sign to F_n! + assert _same_bits( + fl.electron_current(), electron_current_from_particle_flux(fl.electron.flux) + ) + assert np.all(np.sign(fl.electron_current()) == -np.sign(fl.electron.flux)) + np.testing.assert_allclose(fl.electron_current(), jn_m, rtol=1e-13, atol=0.0) + np.testing.assert_allclose(fl.hole_current(), jp_m, rtol=1e-13, atol=0.0) + + # Displacement D = -C (phi_R - phi_L) > 0 when phi decreases along +x; J_disp = (D_new - D_old)/dt. + geom = physical_half_endpoint_geometry(x, ()) + op = PoissonOperator1D.for_geometry(geom, np.full(3, 10.0), layer_eps_r=(10.0,)) + d_old = op.face_displacement(phi_old) + d_new = op.face_displacement(phi_new) + assert np.all(d_old > 0.0) and np.all(d_new > d_old) + j_disp = (d_new - d_old) / 1.0e-6 + assert np.all(j_disp > 0.0) + From a03d8beff51e4f2bffc020884f09df686c8946f2 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sun, 15 Nov 2026 14:07:53 +0800 Subject: [PATCH 24/46] P(interface): add reciprocal unequal-DOS thermionic emission and contact gate checks (P08-03) --- src/solarlab/physics/contacts/__init__.py | 41 +- .../physics/contacts/thermodynamics.py | 76 +- .../physics/interface_transport/thermionic.py | 601 +++++++++- ..._p08_03_heterojunction_detailed_balance.py | 1001 +++++++++++++++++ .../test_p08_03_thermionic_and_contacts.py | 833 ++++++++++++++ 5 files changed, 2532 insertions(+), 20 deletions(-) create mode 100644 tests/integration/test_p08_03_heterojunction_detailed_balance.py create mode 100644 tests/unit/physics/test_p08_03_thermionic_and_contacts.py diff --git a/src/solarlab/physics/contacts/__init__.py b/src/solarlab/physics/contacts/__init__.py index bb789f2c..49e06479 100644 --- a/src/solarlab/physics/contacts/__init__.py +++ b/src/solarlab/physics/contacts/__init__.py @@ -23,25 +23,38 @@ schottky_equilibrium_p, semiconductor_contact_state, semiconductor_work_function, ) from solarlab.physics.contacts.thermodynamics import ( - CONTACT_THERMODYNAMIC_TOLERANCE_EV, LEGACY_MANUAL_CONTACT_OFFSET, ContactEndpoint, - ContactThermodynamicAssessment, ContactThermodynamicError, - assess_contact_thermodynamics, contact_quasi_fermi_levels, + CONTACT_ALIGNMENT_CLASSES, + CONTACT_THERMODYNAMIC_TOLERANCE_EV, + EXTERNAL_METAL_CONTACT_ALIGNMENT, + FITTED_MANUAL_CONTACT_ALIGNMENT, + LEGACY_MANUAL_CONTACT_OFFSET, + PARAMETER_FREE_CONTACT_ALIGNMENT, + ContactAlignmentClass, + ContactEndpoint, + ContactThermodynamicAssessment, + ContactThermodynamicError, + assess_contact_thermodynamics, + certify_parameter_free_contact_equilibrium, + classify_contact_alignment_mode, + contact_quasi_fermi_levels, require_contact_thermodynamic_certificate, ) __all__ = [ "BLOCKING", "BUILT_IN_POTENTIAL_MODES", "BuiltInPotentialSources", - "CONTACT_SIDES", "CONTACT_THERMODYNAMIC_TOLERANCE_EV", "CarrierExchangeChannel", - "ContactClosureCapabilityError", "ContactEndpoint", "ContactMaterial", - "ContactPotentialBoundary", "ContactThermodynamicAssessment", - "ContactThermodynamicError", "DOPING_EQUILIBRIUM", "EXCHANGE_KINDS", - "FIXED_RESERVOIR", "FLAT_BAND_CONTACT_VELOCITY_M_S", "LEGACY_MANUAL", - "LEGACY_MANUAL_CONTACT_OFFSET", "LegacyBandContact", "METAL_FLOOR", - "METAL_WORK_FUNCTION", "RESERVOIR_SOURCES", "ROBIN", "SCHOTTKY_BARRIER", - "SEMICONDUCTOR_WORK_FUNCTION", "STATISTICS_CLOSURE", "SemiconductorContactState", - "assess_contact_thermodynamics", "contact_quasi_fermi_levels", - "doping_equilibrium_densities", "exchange_kind", "junction_polarity", - "legacy_band_contact_potential", "legacy_band_fermi_level", + "CONTACT_ALIGNMENT_CLASSES", "CONTACT_SIDES", "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "CarrierExchangeChannel", "ContactAlignmentClass", "ContactClosureCapabilityError", + "ContactEndpoint", "ContactMaterial", "ContactPotentialBoundary", + "ContactThermodynamicAssessment", "ContactThermodynamicError", + "DOPING_EQUILIBRIUM", "EXCHANGE_KINDS", "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", "FIXED_RESERVOIR", "FLAT_BAND_CONTACT_VELOCITY_M_S", + "LEGACY_MANUAL", "LEGACY_MANUAL_CONTACT_OFFSET", "LegacyBandContact", + "METAL_FLOOR", "METAL_WORK_FUNCTION", "PARAMETER_FREE_CONTACT_ALIGNMENT", + "RESERVOIR_SOURCES", "ROBIN", "SCHOTTKY_BARRIER", "SEMICONDUCTOR_WORK_FUNCTION", + "STATISTICS_CLOSURE", "SemiconductorContactState", "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", "doping_equilibrium_densities", "exchange_kind", + "junction_polarity", "legacy_band_contact_potential", "legacy_band_fermi_level", "legacy_selective_contact_current", "metal_reservoir_floor", "require_contact_thermodynamic_certificate", "resolve_built_in_potential_mode", "resolve_exchange_velocities", "schottky_equilibrium_n", "schottky_equilibrium_p", diff --git a/src/solarlab/physics/contacts/thermodynamics.py b/src/solarlab/physics/contacts/thermodynamics.py index 68465716..87014d22 100644 --- a/src/solarlab/physics/contacts/thermodynamics.py +++ b/src/solarlab/physics/contacts/thermodynamics.py @@ -24,25 +24,64 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Literal +from typing import Final, Literal import numpy as np -from solarlab.physics.contacts.potential import LEGACY_MANUAL, METAL_WORK_FUNCTION +from solarlab.physics.contacts.potential import ( + LEGACY_MANUAL, + METAL_WORK_FUNCTION, + SEMICONDUCTOR_WORK_FUNCTION, +) from solarlab.physics.statistics.carriers import ( MAXWELL_BOLTZMANN, CarrierStatistics, reduced_fermi_level_from_density, ) __all__ = [ - "CONTACT_THERMODYNAMIC_TOLERANCE_EV", "ContactEndpoint", "ContactThermodynamicAssessment", - "ContactThermodynamicError", "LEGACY_MANUAL_CONTACT_OFFSET", - "assess_contact_thermodynamics", "contact_quasi_fermi_levels", + "CONTACT_ALIGNMENT_CLASSES", + "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "ContactAlignmentClass", + "ContactEndpoint", + "ContactThermodynamicAssessment", + "ContactThermodynamicError", + "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", + "LEGACY_MANUAL_CONTACT_OFFSET", + "PARAMETER_FREE_CONTACT_ALIGNMENT", + "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", + "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", "require_contact_thermodynamic_certificate", ] CONTACT_THERMODYNAMIC_TOLERANCE_EV = 5.0e-3 LEGACY_MANUAL_CONTACT_OFFSET = "legacy_manual_v_bi_contact_offset" +PARAMETER_FREE_CONTACT_ALIGNMENT: Final = "parameter_free_work_function" +EXTERNAL_METAL_CONTACT_ALIGNMENT: Final = "external_metal_work_function" +FITTED_MANUAL_CONTACT_ALIGNMENT: Final = "fitted_manual_potential" +CONTACT_ALIGNMENT_CLASSES = ( + PARAMETER_FREE_CONTACT_ALIGNMENT, + EXTERNAL_METAL_CONTACT_ALIGNMENT, + FITTED_MANUAL_CONTACT_ALIGNMENT, +) AssessmentStatus = Literal["certified", "inconsistent", "compatible_unverified", "not_assessable"] +ContactAlignmentClass = Literal[ + "parameter_free_work_function", + "external_metal_work_function", + "fitted_manual_potential", +] + + +def classify_contact_alignment_mode(built_in_potential_mode: str) -> ContactAlignmentClass: + """Separate parameter-free semiconductor work-function alignment from fitted/external modes.""" + if built_in_potential_mode == SEMICONDUCTOR_WORK_FUNCTION: + return PARAMETER_FREE_CONTACT_ALIGNMENT + if built_in_potential_mode == METAL_WORK_FUNCTION: + return EXTERNAL_METAL_CONTACT_ALIGNMENT + if built_in_potential_mode == LEGACY_MANUAL: + return FITTED_MANUAL_CONTACT_ALIGNMENT + raise ValueError(f"unknown built-in-potential mode {built_in_potential_mode!r}") class ContactThermodynamicError(ValueError): @@ -92,6 +131,14 @@ class ContactThermodynamicAssessment: def certified(self) -> bool: return self.status == "certified" + @property + def alignment_class(self) -> ContactAlignmentClass: + return classify_contact_alignment_mode(self.built_in_potential_mode) + + @property + def is_parameter_free(self) -> bool: + return self.built_in_potential_mode == SEMICONDUCTOR_WORK_FUNCTION + def contact_quasi_fermi_levels( left: ContactEndpoint, @@ -273,3 +320,22 @@ def require_contact_thermodynamic_certificate( f"{assessment.message}{label}" ) return assessment + + +def certify_parameter_free_contact_equilibrium( + assessment: ContactThermodynamicAssessment, +) -> ContactThermodynamicAssessment: + """Require both the 5.0 meV thermodynamic certificate and parameter-free mode. + + Refuses fitted ``legacy_manual`` or externally imposed ``metal_work_function`` + contact modes even when tuned within 5.0 meV, ensuring parameter-free physical + contact equilibrium provenance is never conflated with fitted offsets. + """ + certified = require_contact_thermodynamic_certificate(assessment) + if not certified.is_parameter_free: + raise ContactThermodynamicError( + "parameter-free contact equilibrium requires built_in_potential_mode=" + f"{SEMICONDUCTOR_WORK_FUNCTION!r}, got {certified.built_in_potential_mode!r} " + f"({certified.alignment_class})" + ) + return certified diff --git a/src/solarlab/physics/interface_transport/thermionic.py b/src/solarlab/physics/interface_transport/thermionic.py index 43cdfe4a..57e46a0c 100644 --- a/src/solarlab/physics/interface_transport/thermionic.py +++ b/src/solarlab/physics/interface_transport/thermionic.py @@ -22,7 +22,7 @@ from dataclasses import dataclass from functools import lru_cache import math -from typing import Literal, TypeAlias +from typing import Final, Literal, TypeAlias import numpy as np from numpy.typing import NDArray @@ -44,11 +44,22 @@ __all__ = [ "A_STAR_FREE_ELECTRON_A_M2_K2", "ELECTRON_MASS_KG", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", "TwoSidedCrossFluxEvaluation", "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", "effective_mass_from_dos", "emission_velocity", "fermi_dirac_one", @@ -56,6 +67,10 @@ "fermi_dirac_zero", "fermi_richardson_flux", "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", "resolve_layer_richardson", "richardson_from_dos", "scaps_thermionic_flux", @@ -71,7 +86,26 @@ ) TE_BARRIER_THRESHOLD_EV: float = 0.05 +LEGACY_UNNORMALIZED_THERMIONIC_V1: Final = "legacy_unnormalized_thermionic_v1" +RECIPROCAL_PHYSICAL_THERMIONIC_V2: Final = "reciprocal_physical_thermionic_v2" +SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1: Final = "scaps_effective_velocity_thermionic_v1" +THERMIONIC_MODEL_VERSIONS = ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, +) + TERegularizationMode: TypeAlias = Literal["legacy_logistic", "compact_support"] +ThermionicModelVersion: TypeAlias = Literal[ + "legacy_unnormalized_thermionic_v1", + "reciprocal_physical_thermionic_v2", + "scaps_effective_velocity_thermionic_v1", +] +ThermionicCarrierKind: TypeAlias = Literal["electron", "hole"] +ThermionicStatisticsKind: TypeAlias = Literal["maxwell_boltzmann", "fermi_dirac"] +ThermionicCombinationMode: TypeAlias = Literal[ + "hard", "legacy_logistic", "compact_support", "harmonic_series" +] RealArray: TypeAlias = NDArray[np.float64] @@ -687,3 +721,568 @@ def scaps_thermionic_flux( ) scale = np.array([max(term_n_l, term_n_r), max(term_p_l, term_p_r)], dtype=np.float64) return TwoSidedCrossFluxEvaluation(cross, d_log, d_trace, scale) + + +def reciprocal_richardson( + a_star_left_A_m2_K2: float, + a_star_right_A_m2_K2: float, +) -> float: + """Return reciprocal Bethe/Richardson constant ``min(A*_left, A*_right)`` [A m^-2 K^-2]. + + Planar transverse crystal-momentum conservation restricts thermally emitted + carriers to the smaller transverse effective-mass disk on either side of the + heterointerface, guaranteeing symmetry under ``left <-> right`` swap and + eliminating spurious equilibrium emission across unequal effective masses. + """ + left = float(a_star_left_A_m2_K2) + right = float(a_star_right_A_m2_K2) + if not (math.isfinite(left) and math.isfinite(right)) or left < 0.0 or right < 0.0: + raise ValueError("Richardson constants must be finite and non-negative") + return min(left, right) + + +def physical_barrier_steps_eV( + *, + phi_left_V: float, + phi_right_V: float, + chi_phys_left_eV: float, + chi_phys_right_eV: float, + eg_phys_left_eV: float, + eg_phys_right_eV: float, +) -> tuple[float, float]: + """Return ``(electron_step_eV, hole_step_eV)`` from unfolded physical band edges. + + Uses true physical electron affinities and band gaps (free of DOS-folded + Scharfetter-Gummel drift potentials) together with the electrostatic step + ``phi_right_V - phi_left_V``. A positive return value denotes an upward + potential-energy barrier for the respective carrier moving ``left -> right``. + """ + phi_l = float(phi_left_V) + phi_r = float(phi_right_V) + chi_l = float(chi_phys_left_eV) + chi_r = float(chi_phys_right_eV) + eg_l = float(eg_phys_left_eV) + eg_r = float(eg_phys_right_eV) + if not all(math.isfinite(v) for v in (phi_l, phi_r, chi_l, chi_r, eg_l, eg_r)): + raise ValueError("potentials and physical band parameters must be finite") + if eg_l <= 0.0 or eg_r <= 0.0: + raise ValueError("physical band gaps must be positive") + dphi = phi_r - phi_l + electron_step = (chi_l - chi_r) - dphi + hole_step = ((chi_r + eg_r) - (chi_l + eg_l)) + dphi + return electron_step, hole_step + + +def physical_carrier_barrier_step_eV( + carrier: ThermionicCarrierKind, + *, + phi_left_V: float, + phi_right_V: float, + band_offset_eV: float, +) -> tuple[float, float, float]: + """Return ``(barrier_step_eV, d_step_d_phi_left, d_step_d_phi_right)``. + + ``band_offset_eV`` is the electrostatic-free physical band-edge offset + oriented for ``carrier`` moving ``left -> right``: + * ``carrier == "electron"``: ``chi_phys_left_eV - chi_phys_right_eV``; + * ``carrier == "hole"``: ``(chi_phys_right_eV + eg_phys_right_eV) - (chi_phys_left_eV + eg_phys_left_eV)``. + """ + phi_l = float(phi_left_V) + phi_r = float(phi_right_V) + offset = float(band_offset_eV) + if not (math.isfinite(phi_l) and math.isfinite(phi_r) and math.isfinite(offset)): + raise ValueError("phi_left_V, phi_right_V, and band_offset_eV must be finite") + dphi = phi_r - phi_l + if carrier == "electron": + return offset - dphi, 1.0, -1.0 + if carrier == "hole": + return offset + dphi, -1.0, 1.0 + raise ValueError(f"unknown carrier {carrier!r}; expected 'electron' or 'hole'") + + +def _symmetric_log_ratio(left: float, right: float) -> float: + """Return ``ln(right / left)`` with 0-ULP swap antisymmetry and no near-unity cancellation.""" + diff = right - left + if diff == 0.0: + return 0.0 + scale = max(left, right) + z = (diff / scale) / ((right / scale) + (left / scale)) + if abs(z) <= 0.5: + return 2.0 * math.atanh(z) + return math.log(right) - math.log(left) + + +def _boltzmann_over_barrier_supply(activity: float, reduced_barrier: float) -> float: + """Evaluate ``activity * exp(-reduced_barrier)`` without premature factor underflow.""" + if reduced_barrier == 0.0: + return activity + if reduced_barrier <= 650.0: + return activity * math.exp(-reduced_barrier) + log_prod = math.log(activity) - reduced_barrier + if log_prod < -745.0: + return 0.0 + return math.exp(log_prod) + + +@dataclass(frozen=True, slots=True) +class ReciprocalThermionicEvaluation: + """Constitutive evaluation of versioned 1D heterointerface thermionic emission (P08-03).""" + + model_version: ThermionicModelVersion + carrier: ThermionicCarrierKind + statistics: ThermionicStatisticsKind + flux_m2_s: float + current_A_m2: float + one_way_scale_m2_s: float + barrier_step_eV: float + electrochemical_step: float + effective_richardson_A_m2_K2: float + transmission: float + d_flux_d_phi_left_m2_s_V: float + d_flux_d_phi_right_m2_s_V: float + d_flux_d_c_left_m_s: float + d_flux_d_c_right_m_s: float + d_flux_d_log_c_left_m2_s: float + d_flux_d_log_c_right_m2_s: float + + +def reciprocal_thermionic_flux_m2_s( + c_left_m3: float, + c_right_m3: float, + *, + carrier: ThermionicCarrierKind, + phi_left_V: float, + phi_right_V: float, + band_offset_eV: float, + temperature_K: float, + a_star_left_A_m2_K2: float, + a_star_right_A_m2_K2: float | None = None, + dos_left_m3: float | None = None, + dos_right_m3: float | None = None, + transmission: float = 1.0, + statistics: ThermionicStatisticsKind = "maxwell_boltzmann", + model_version: ThermionicModelVersion = RECIPROCAL_PHYSICAL_THERMIONIC_V2, + thermal_voltage_V: float | None = None, + electrochemical_step: float | None = None, + barrier_corner_kbt: float = 0.25, +) -> ReciprocalThermionicEvaluation: + """Evaluate versioned thermionic particle flux [m^-2 s^-1] and analytical Jacobians. + + Under ``RECIPROCAL_PHYSICAL_THERMIONIC_V2``, separates: + 1. True physical electrostatic + band-edge barrier ``barrier_step_eV``; + 2. Per-side DOS activities ``(c_left / dos_left, c_right / dos_right)``; + 3. Reciprocal Bethe/Richardson constant ``min(a_star_left, a_star_right)``; + 4. Explicit transmission factor ``transmission`` in ``[0, 1]``; + 5. Cancellation-free electrochemical difference ``electrochemical_step``. + """ + c_l = float(c_left_m3) + c_r = float(c_right_m3) + temp = float(temperature_K) + trans = float(transmission) + if not (math.isfinite(c_l) and math.isfinite(c_r)) or c_l <= 0.0 or c_r <= 0.0: + raise ValueError("carrier densities must be finite and positive for reciprocal thermionic flux") + if not math.isfinite(temp) or temp <= 0.0: + raise ValueError("temperature_K must be finite and positive") + if not math.isfinite(trans) or not 0.0 <= trans <= 1.0: + raise ValueError("transmission must be finite and lie in [0, 1]") + vt = float(thermal_voltage(temp) if thermal_voltage_V is None else thermal_voltage_V) + if not math.isfinite(vt) or vt <= 0.0: + raise ValueError("thermal_voltage_V must be finite and positive") + if electrochemical_step is not None and not math.isfinite(float(electrochemical_step)): + raise ValueError("electrochemical_step must be finite when supplied") + corner = float(barrier_corner_kbt) + if not math.isfinite(corner) or corner < 0.0: + raise ValueError("barrier_corner_kbt must be finite and non-negative") + + barrier_step, d_step_d_phi_l, d_step_d_phi_r = physical_carrier_barrier_step_eV( + carrier, + phi_left_V=phi_left_V, + phi_right_V=phi_right_V, + band_offset_eV=band_offset_eV, + ) + current_sign = -Q if carrier == "electron" else Q + + if model_version == LEGACY_UNNORMALIZED_THERMIONIC_V1: + if statistics != "maxwell_boltzmann": + raise ValueError("legacy_unnormalized_thermionic_v1 supports only maxwell_boltzmann") + a_left = float(a_star_left_A_m2_K2) + if not math.isfinite(a_left) or a_left < 0.0: + raise ValueError("a_star_left_A_m2_K2 must be finite and non-negative") + flux_leg, d_dl, d_dr = thermionic_emission_bound_m2_s( + c_l, + c_r, + barrier_step, + temp, + a_left, + dos_norm_m3=dos_left_m3, + ) + flux_leg *= trans + d_dl *= trans + d_dr *= trans + term_l = d_dl * c_l + term_r = -d_dr * c_r + if barrier_step > 0.0: + g_step = -term_l / vt + elif barrier_step < 0.0: + g_step = -term_r / vt + else: + g_step = -0.5 * (term_l + term_r) / vt + ec_step = ( + float(electrochemical_step) + if electrochemical_step is not None + else (_symmetric_log_ratio(c_l, c_r) + barrier_step / vt) + ) + return ReciprocalThermionicEvaluation( + model_version=model_version, + carrier=carrier, + statistics=statistics, + flux_m2_s=flux_leg, + current_A_m2=current_sign * flux_leg, + one_way_scale_m2_s=max(term_l, term_r), + barrier_step_eV=barrier_step, + electrochemical_step=ec_step, + effective_richardson_A_m2_K2=a_left, + transmission=trans, + d_flux_d_phi_left_m2_s_V=g_step * d_step_d_phi_l, + d_flux_d_phi_right_m2_s_V=g_step * d_step_d_phi_r, + d_flux_d_c_left_m_s=d_dl, + d_flux_d_c_right_m_s=d_dr, + d_flux_d_log_c_left_m2_s=term_l, + d_flux_d_log_c_right_m2_s=-term_r, + ) + + if dos_left_m3 is None or dos_right_m3 is None: + raise ValueError(f"{model_version} requires explicit positive dos_left_m3 and dos_right_m3") + n_dos_l = float(dos_left_m3) + n_dos_r = float(dos_right_m3) + if not (math.isfinite(n_dos_l) and math.isfinite(n_dos_r)) or n_dos_l <= 0.0 or n_dos_r <= 0.0: + raise ValueError("dos_left_m3 and dos_right_m3 must be finite and positive") + + a_right_raw = a_star_left_A_m2_K2 if a_star_right_A_m2_K2 is None else a_star_right_A_m2_K2 + if model_version == RECIPROCAL_PHYSICAL_THERMIONIC_V2: + a_eff = reciprocal_richardson(a_star_left_A_m2_K2, a_right_raw) + elif model_version == SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1: + if statistics != "maxwell_boltzmann": + raise ValueError("scaps_effective_velocity_thermionic_v1 supports only maxwell_boltzmann") + a_l = float(a_star_left_A_m2_K2) + a_r = float(a_right_raw) + if not (math.isfinite(a_l) and math.isfinite(a_r)) or a_l < 0.0 or a_r < 0.0: + raise ValueError("Richardson constants must be finite and non-negative") + v_th_l = a_l * temp * temp / (Q * n_dos_l) + v_th_r = a_r * temp * temp / (Q * n_dos_r) + a_eff = (Q / (temp * temp)) * min(v_th_l, v_th_r) * math.sqrt(n_dos_l * n_dos_r) + else: + raise ValueError(f"unknown thermionic model_version {model_version!r}") + + pref = trans * a_eff * temp * temp / Q + s_vt = barrier_step / vt + if corner == 0.0: + b_l = max(s_vt, 0.0) + b_r = max(-s_vt, 0.0) + w_l = 1.0 if barrier_step > 0.0 else (0.0 if barrier_step < 0.0 else 0.5) + w_r = 1.0 - w_l + else: + # Even C^infinity corner potential: b_l - b_r == s_vt identically (exact detailed balance), + # while d(b_l)/ds = expit(s_vt/corner) eliminates the non-equilibrium Jacobian jump at s_vt = 0. + corner_shift = corner * math.log1p(math.exp(-abs(s_vt) / corner)) + b_l = max(s_vt, 0.0) + corner_shift + b_r = max(-s_vt, 0.0) + corner_shift + w_l = float(expit(s_vt / corner)) + w_r = float(expit(-s_vt / corner)) + act_l = c_l / n_dos_l + act_r = c_r / n_dos_r + + if statistics == "maxwell_boltzmann": + sup_l = _boltzmann_over_barrier_supply(act_l, b_l) + sup_r = _boltzmann_over_barrier_supply(act_r, b_r) + if electrochemical_step is not None: + ec_step = float(electrochemical_step) + if ec_step > 0.0: + supply_diff = sup_r * math.expm1(-ec_step) + elif ec_step < 0.0: + supply_diff = -sup_l * math.expm1(ec_step) + else: + supply_diff = 0.0 + else: + supply_diff = sup_l - sup_r + if sup_l > 0.0 and sup_r > 0.0: + ec_step = _symmetric_log_ratio(sup_l, sup_r) + else: + ec_step = _symmetric_log_ratio(act_l, act_r) + s_vt + + flux = pref * supply_diff + d_log_l = pref * sup_l + d_log_r = -pref * sup_r + d_c_l = d_log_l / c_l + d_c_r = d_log_r / c_r + g_step = -pref * (w_l * sup_l + w_r * sup_r) / vt + scale_one_way = pref * max(sup_l, sup_r) + elif statistics == "fermi_dirac": + sup_l, dn_log_l, dn_bar_l, z_l = _one_way_fermi_dirac_supply( + c_l, n_dos_l, b_l * vt, vt + ) + sup_r, dn_log_r, dn_bar_r, z_r = _one_way_fermi_dirac_supply( + c_r, n_dos_r, b_r * vt, vt + ) + if electrochemical_step is not None: + ec_step = float(electrochemical_step) + delta_z = -ec_step + elif z_l <= -40.0 and z_r <= -40.0 and sup_l > 0.0 and sup_r > 0.0: + ec_step = _symmetric_log_ratio(sup_l, sup_r) + delta_z = -ec_step + else: + lr_l = math.log(act_l) + lr_r = math.log(act_r) + ex_l, _ = _eta_excess_from_log_ratio(lr_l) + ex_r, _ = _eta_excess_from_log_ratio(lr_r) + ec_step = _symmetric_log_ratio(act_l, act_r) + s_vt + (ex_r - ex_l) + delta_z = -ec_step + + if z_l <= -38.0 and z_r <= -38.0: + if delta_z > 0.0: + supply_diff = -sup_l * math.expm1(-delta_z) + elif delta_z < 0.0: + supply_diff = sup_r * math.expm1(delta_z) + else: + supply_diff = 0.0 + else: + supply_diff = _fermi_dirac_one_difference(z_l, z_r, delta_z, sup_l, sup_r) + + flux = pref * supply_diff + d_log_l = pref * dn_log_l + d_log_r = -pref * dn_log_r + d_c_l = d_log_l / c_l + d_c_r = d_log_r / c_r + g_step = pref * (w_l * dn_bar_l + w_r * dn_bar_r) + scale_one_way = pref * max(sup_l, sup_r) + else: + raise ValueError( + f"unknown statistics {statistics!r}; expected 'maxwell_boltzmann' or 'fermi_dirac'" + ) + + return ReciprocalThermionicEvaluation( + model_version=model_version, + carrier=carrier, + statistics=statistics, + flux_m2_s=flux, + current_A_m2=current_sign * flux, + one_way_scale_m2_s=scale_one_way, + barrier_step_eV=barrier_step, + electrochemical_step=ec_step, + effective_richardson_A_m2_K2=a_eff, + transmission=trans, + d_flux_d_phi_left_m2_s_V=g_step * d_step_d_phi_l, + d_flux_d_phi_right_m2_s_V=g_step * d_step_d_phi_r, + d_flux_d_c_left_m_s=d_c_l, + d_flux_d_c_right_m_s=d_c_r, + d_flux_d_log_c_left_m2_s=d_log_l, + d_flux_d_log_c_right_m2_s=d_log_r, + ) + + +@dataclass(frozen=True, slots=True) +class ReciprocalThermionicCompositeEvaluation: + """Combined SG + reciprocal physical thermionic face flux and full Jacobians.""" + + combination_mode: ThermionicCombinationMode + flux_m2_s: float + current_A_m2: float + sg_flux_m2_s: float + thermionic: ReciprocalThermionicEvaluation + d_flux_d_phi_left_m2_s_V: float + d_flux_d_phi_right_m2_s_V: float + d_flux_d_c_left_m_s: float + d_flux_d_c_right_m_s: float + d_flux_d_log_c_left_m2_s: float + d_flux_d_log_c_right_m2_s: float + + +def combine_sg_and_reciprocal_thermionic_flux( + sg_flux_m2_s: float, + *, + d_sg_d_phi_left_m2_s_V: float, + d_sg_d_phi_right_m2_s_V: float, + d_sg_d_c_left_m_s: float, + d_sg_d_c_right_m_s: float, + c_left_m3: float, + c_right_m3: float, + thermionic: ReciprocalThermionicEvaluation, + combination_mode: ThermionicCombinationMode = "harmonic_series", + te_softness: float = 0.05, +) -> ReciprocalThermionicCompositeEvaluation: + """Combine face Scharfetter-Gummel and reciprocal thermionic fluxes with full tangents. + + Includes exact chain-rule derivatives wrt ``(phi_left, phi_right, c_left, c_right)`` + and ``(log c_left, log c_right)``. Under ``combination_mode="harmonic_series"``, + combines bulk drift-diffusion and interface emission conductances in series with + strictly positive smooth weights at every operating bias including ``m == 0``. + """ + sg = float(sg_flux_m2_s) + c_l = float(c_left_m3) + c_r = float(c_right_m3) + soft = float(te_softness) + if not (math.isfinite(sg) and math.isfinite(c_l) and math.isfinite(c_r) and math.isfinite(soft)): + raise ValueError("flux, densities, and te_softness must be finite") + if c_l <= 0.0 or c_r <= 0.0: + raise ValueError("c_left_m3 and c_right_m3 must be positive") + if soft < 0.0: + raise ValueError("te_softness must be non-negative") + + te = thermionic.flux_m2_s + a_sg = abs(sg) + a_te = abs(te) + sign_sg = math.copysign(1.0, sg) + sign_te = 0.0 if te == 0.0 else math.copysign(1.0, te) + sign_pair = 1.0 if (sg == 0.0 and te == 0.0) else sign_sg * sign_te + current_sign = -Q if thermionic.carrier == "electron" else Q + + g_sg = 0.5 * (abs(float(d_sg_d_c_left_m_s) * c_l) + abs(float(d_sg_d_c_right_m_s) * c_r)) + g_te = 0.5 * ( + abs(thermionic.d_flux_d_log_c_left_m2_s) + abs(thermionic.d_flux_d_log_c_right_m2_s) + ) + + if combination_mode == "harmonic_series": + g_sum = g_sg + g_te + if g_sum == 0.0: + flux = math.copysign(0.0, sg) + w_sg = 0.0 + w_te = 0.0 + elif a_sg <= 1.0e-6 * g_sg and a_te <= 1.0e-6 * g_te: + # Exact C^infinity Taylor-exact asymptotic form around m = 0: + # u*v/(u+v) == theta0^2 * u + (1 - theta0)^2 * v + O(m^3), avoiding 0/0 and 1-ULP noise. + theta0 = g_te / g_sum + w_sg = theta0 * theta0 + w_te = (1.0 - theta0) * (1.0 - theta0) + flux = w_sg * sg + w_te * te + elif sg * te > 0.0: + denom_st = sg + te + theta = te / denom_st + flux = theta * sg + w_sg = theta * theta + w_te = (1.0 - theta) * (1.0 - theta) + elif a_sg == 0.0 or a_te == 0.0: + flux = math.copysign(0.0, sg) + theta0 = g_te / g_sum + w_sg = theta0 * theta0 + w_te = (1.0 - theta0) * (1.0 - theta0) + else: + a_sum = a_sg + a_te + theta = a_te / a_sum + flux = math.copysign(theta * a_sg, sg) + w_sg = theta * theta + w_te = sign_pair * (1.0 - theta) * (1.0 - theta) + elif combination_mode == "hard" or soft == 0.0: + if a_sg == 0.0 and a_te == 0.0: + flux = math.copysign(0.0, sg) + if g_sg <= g_te: + w_sg, w_te = 1.0, 0.0 + else: + w_sg, w_te = 0.0, 1.0 + elif a_sg <= a_te: + flux = sg + w_sg, w_te = 1.0, 0.0 + else: + flux = math.copysign(a_te, sg) + w_sg, w_te = 0.0, sign_pair + elif combination_mode == "legacy_logistic": + if a_sg <= 1.0e-12 * g_sg and a_te <= 1.0e-12 * g_te: + g_sum = g_sg + g_te + if g_sum == 0.0: + w_sg, w_te = 0.5, 0.0 + else: + t0 = (g_sg - g_te) / (soft * g_sum) + if t0 > 40.0: + weight0 = 1.0 + elif t0 < -40.0: + weight0 = 0.0 + else: + weight0 = 1.0 / (1.0 + math.exp(-t0)) + w_sg, w_te = 1.0 - weight0, weight0 + flux = w_sg * sg + w_te * te + else: + denom = soft * (a_sg + a_te) + 1.0e-300 + t_arg = (a_sg - a_te) / denom + if t_arg > 40.0: + weight = 1.0 + dw_dt = 0.0 + elif t_arg < -40.0: + weight = 0.0 + dw_dt = 0.0 + else: + weight = 1.0 / (1.0 + math.exp(-t_arg)) + dw_dt = weight * (1.0 - weight) + magnitude = weight * a_te + (1.0 - weight) * a_sg + denom_sq = denom * denom + dt_da_sg = (denom - (a_sg - a_te) * soft) / denom_sq + dt_da_te = (-denom - (a_sg - a_te) * soft) / denom_sq + w_sg = (1.0 - weight) + (a_te - a_sg) * dw_dt * dt_da_sg + dm_da_te = weight + (a_te - a_sg) * dw_dt * dt_da_te + w_te = sign_pair * dm_da_te + flux = math.copysign(magnitude, sg) + elif combination_mode == "compact_support": + if a_sg <= 1.0e-12 * g_sg and a_te <= 1.0e-12 * g_te: + g_sum = g_sg + g_te + if g_sum == 0.0: + w_sg, w_te = 0.5, 0.0 + else: + n0 = (g_sg - g_te) / (soft * g_sum) + if n0 <= -1.0: + w_sg, w_te = 1.0, 0.0 + elif n0 >= 1.0: + w_sg, w_te = 0.0, 1.0 + else: + u0 = 0.5 * (n0 + 1.0) + weight0 = 6.0 * u0**5 - 15.0 * u0**4 + 10.0 * u0**3 + w_sg, w_te = 1.0 - weight0, weight0 + flux = w_sg * sg + w_te * te + else: + scale = soft * (a_sg + a_te) + normalized = (a_sg - a_te) / scale + if normalized <= -1.0: + magnitude = a_sg + w_sg = 1.0 + dm_da_te = 0.0 + elif normalized >= 1.0: + magnitude = a_te + w_sg = 0.0 + dm_da_te = 1.0 + else: + u = 0.5 * (normalized + 1.0) + weight = 6.0 * u**5 - 15.0 * u**4 + 10.0 * u**3 + dw_du = 30.0 * u**2 * (1.0 - u) ** 2 + scale_sq = scale * scale + dn_da_sg = 2.0 * soft * a_te / scale_sq + dn_da_te = -2.0 * soft * a_sg / scale_sq + dw_da_sg = 0.5 * dw_du * dn_da_sg + dw_da_te = 0.5 * dw_du * dn_da_te + magnitude = (1.0 - weight) * a_sg + weight * a_te + w_sg = (1.0 - weight) + (a_te - a_sg) * dw_da_sg + dm_da_te = weight + (a_te - a_sg) * dw_da_te + w_te = sign_pair * dm_da_te + flux = math.copysign(magnitude, sg) + else: + raise ValueError( + f"unknown combination_mode {combination_mode!r}; expected 'harmonic_series', " + "'compact_support', 'legacy_logistic', or 'hard'" + ) + + d_phi_l = w_sg * float(d_sg_d_phi_left_m2_s_V) + w_te * thermionic.d_flux_d_phi_left_m2_s_V + d_phi_r = w_sg * float(d_sg_d_phi_right_m2_s_V) + w_te * thermionic.d_flux_d_phi_right_m2_s_V + d_c_l = w_sg * float(d_sg_d_c_left_m_s) + w_te * thermionic.d_flux_d_c_left_m_s + d_c_r = w_sg * float(d_sg_d_c_right_m_s) + w_te * thermionic.d_flux_d_c_right_m_s + d_log_l = w_sg * (float(d_sg_d_c_left_m_s) * c_l) + w_te * thermionic.d_flux_d_log_c_left_m2_s + d_log_r = w_sg * (float(d_sg_d_c_right_m_s) * c_r) + w_te * thermionic.d_flux_d_log_c_right_m2_s + + return ReciprocalThermionicCompositeEvaluation( + combination_mode=combination_mode, + flux_m2_s=flux, + current_A_m2=current_sign * flux, + sg_flux_m2_s=sg, + thermionic=thermionic, + d_flux_d_phi_left_m2_s_V=d_phi_l, + d_flux_d_phi_right_m2_s_V=d_phi_r, + d_flux_d_c_left_m_s=d_c_l, + d_flux_d_c_right_m_s=d_c_r, + d_flux_d_log_c_left_m2_s=d_log_l, + d_flux_d_log_c_right_m2_s=d_log_r, + ) diff --git a/tests/integration/test_p08_03_heterojunction_detailed_balance.py b/tests/integration/test_p08_03_heterojunction_detailed_balance.py new file mode 100644 index 00000000..b84ae864 --- /dev/null +++ b/tests/integration/test_p08_03_heterojunction_detailed_balance.py @@ -0,0 +1,1001 @@ +"""Integration tests for P08-03 heterojunction detailed balance, +3.0 V conditioning, and guards. + +Verifies: +1. Coupled 1D heterojunction Poisson-drift-diffusion PDE solve with active + ``RECIPROCAL_PHYSICAL_THERMIONIC_V2`` (``combine_sg_and_reciprocal_thermionic_flux``) + across unequal DOS (``N_{C,L} != N_{C,R}``, ``N_{V,L} != N_{V,R}``) and unequal + effective masses (``A*_L != A*_R``) with parameter-free ``semiconductor_work_function`` + contacts certified within ``5.0 meV``: + * Dark equilibrium (``V_app = 0, G = 0``): ``|J| <= 1e-14 A/m^2``, uniform quasi-Fermi + levels across all layers and interfaces, and bare TE ``|Gamma_TE| <= 1e-15 * scale`` + (contrasted against legacy single-DOS static-offset TE). + * Illuminated 1-sun sweep (``V_oc < Eg_abs``) and deep forward-bias continuation all + the way to ``V_app = +3.0 V`` (``ArchiveDigest.md`` ``X3``): finite converged states, + strict ``n > 0, p > 0``, zero ``NaN``/``Inf``, bounded Jacobian condition number, and + strictly monotone forward diode current ``J(V)``. +2. Production ``compile_device_1d(..., interface_topology="two_sided_trace")`` heterojunction + dark equilibrium and deep forward-bias ``V_app = +3.0 V`` continuation. +3. Permanent pre-solve ``CapabilityError`` refusal on falsified ``interface_shared_occupancy=True`` + across ``compile_device_1d``, ``compile_device_2d``, and ``compile_ionic_device_2d``. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from dataclasses import dataclass +import json +import math +from pathlib import Path +from typing import Any, TypeAlias + +import numpy as np +from numpy.typing import NDArray +import pytest +from threadpoolctl import threadpool_limits + +from examples.research_1d.ionic_multilayer import prepare_confined_ion_device +from solarlab.config.device_import import import_standard_device +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_2d import compile_ionic_device_2d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.experiments.two_dimensional.inputs import JV2DInput, MicrostructureInput +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.mesh.geometry import HALF_ENDPOINT_V1 +from solarlab.physics.contacts import ( + ContactEndpoint, + ContactMaterial, + ContactPotentialBoundary, + assess_contact_thermodynamics, + certify_parameter_free_contact_equilibrium, + doping_equilibrium_densities, + semiconductor_work_function, +) +from solarlab.physics.electrostatics.poisson import PoissonOperator1D +from solarlab.physics.interface_transport.thermionic import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + ThermionicCombinationMode, + combine_sg_and_reciprocal_thermionic_flux, + reciprocal_thermionic_flux_m2_s, +) +from solarlab.physics.statistics.band_potentials import fold_dos_into_transport_bands +from solarlab.physics.statistics.thermal import BOLTZMANN_CONSTANT_J_K, thermal_voltage +from solarlab.physics.transport.electrochemical_flux import carrier_particle_fluxes +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import ( + CallableProblem, + ResidualScaling, + SolveBudget, + StepControl, +) +from solarlab.solvers.nonlinear.steady_1d import ( + POISSON_CONTACT_BALANCE_V1, + SteadyOptions, + SteadyState1D, + SteadyStateError, + solve_equilibrium, + solve_steady_state, +) + +ROOT = Path(__file__).resolve().parents[2] +LEGACY_PKG = ROOT / "perovskite-sim" / "perovskite_sim" +LEGACY_DEFAULTS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + +Q: float = ELEMENTARY_CHARGE_C +K_B: float = BOLTZMANN_CONSTANT_J_K +Vector: TypeAlias = NDArray[np.float64] + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +@pytest.fixture(scope="module") +def legacy_catalog() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple(SourceDocument(name, (LEGACY_PKG / name).read_bytes()) for name in LEGACY_DEFAULTS) + ) + + +def _thermodynamic_ni(nc_m3: float, nv_m3: float, eg_eV: float, temp_K: float = 300.0) -> float: + vt = K_B * temp_K / Q + return float(math.sqrt(nc_m3 * nv_m3) * math.exp(-eg_eV / (2.0 * vt))) + + +@dataclass(frozen=True) +class _CoupledHeterojunction1D: + """Self-contained 3-layer p-HTL / i-absorber / n-ETL coupled PDE problem with V2 TE.""" + + nodes_m: Vector + poisson: PoissonOperator1D + chi_phys_eV: Vector + eg_phys_eV: Vector + nc_m3: Vector + nv_m3: Vector + net_doping_m3: Vector + ni_sq_m6: Vector + tau_s: float + b_rad_m3_s: float + dn_face_m2_s: Vector + dp_face_m2_s: Vector + bands: Any + interface_faces: tuple[tuple[int, float, float, float, float, float, float], ...] + n_left_m3: float + p_left_m3: float + n_right_m3: float + p_right_m3: float + boundary: ContactPotentialBoundary + temperature_K: float + vt_V: float + generation_1sun_m3_s: Vector + + +def _build_coupled_heterojunction_1d() -> _CoupledHeterojunction1D: + temp = 300.0 + vt = thermal_voltage(temp) + + # Disjoint bulk nodes on 3 layers (two-sided interface faces between layers without shared nodes): + # HTL [0, 80 nm], absorber [80 nm, 380 nm], ETL [380 nm, 460 nm] + x_htl = np.linspace(0.0, 7.6e-8, 7) + x_abs = np.linspace(8.4e-8, 3.76e-7, 13) + x_etl = np.linspace(3.84e-7, 4.60e-7, 7) + x = np.concatenate([x_htl, x_abs, x_etl]) + n_nodes = x.size + m_htl = np.zeros(n_nodes, dtype=bool) + m_abs = np.zeros(n_nodes, dtype=bool) + m_etl = np.zeros(n_nodes, dtype=bool) + m_htl[:7] = True + m_abs[7:20] = True + m_etl[20:] = True + + eps_r = np.where(m_htl, 3.5, np.where(m_abs, 24.0, 9.0)) + poisson = PoissonOperator1D.from_harmonic_nodes(x, eps_r, geometry_name=HALF_ENDPOINT_V1) + + chi_l, chi_m, chi_r = 3.62, 3.90, 4.04 + eg_l, eg_m, eg_r = 1.75, 1.60, 1.85 + nc_l, nc_m, nc_r = 2.0e25, 5.0e24, 4.0e25 + nv_l, nv_m, nv_r = 3.0e25, 8.0e24, 1.5e25 + + chi = np.where(m_htl, chi_l, np.where(m_abs, chi_m, chi_r)) + eg = np.where(m_htl, eg_l, np.where(m_abs, eg_m, eg_r)) + nc = np.where(m_htl, nc_l, np.where(m_abs, nc_m, nc_r)) + nv = np.where(m_htl, nv_l, np.where(m_abs, nv_m, nv_r)) + bands = fold_dos_into_transport_bands( + chi, + eg, + [m_htl, m_abs, m_etl], + [(nc_l, nv_l), (nc_m, nv_m), (nc_r, nv_r)], + reference_layer=1, + thermal_voltage_V=vt, + ) + + n_a_htl = 2.0e22 + n_d_etl = 2.0e22 + net_doping = np.where(m_htl, -n_a_htl, np.where(m_etl, n_d_etl, 0.0)) + ni_sq = nc * nv * np.exp(-eg / vt) + + n_left, p_left = doping_equilibrium_densities(0.0, n_a_htl, float(ni_sq[0])) + n_right, p_right = doping_equilibrium_densities(n_d_etl, 0.0, float(ni_sq[-1])) + + mat_left = ContactMaterial( + temperature_K=temp, + electron_affinity_eV=chi_l, + band_gap_eV=eg_l, + conduction_dos_m3=nc_l, + valence_dos_m3=nv_l, + donor_density_m3=0.0, + acceptor_density_m3=n_a_htl, + ) + mat_right = ContactMaterial( + temperature_K=temp, + electron_affinity_eV=chi_r, + band_gap_eV=eg_r, + conduction_dos_m3=nc_r, + valence_dos_m3=nv_r, + donor_density_m3=n_d_etl, + acceptor_density_m3=0.0, + ) + v_bi = semiconductor_work_function(mat_left) - semiconductor_work_function(mat_right) + cert = certify_parameter_free_contact_equilibrium( + assess_contact_thermodynamics( + built_in_potential_mode="semiconductor_work_function", + left=ContactEndpoint(n_left, p_left, nc_l, nv_l, chi_l, eg_l), + right=ContactEndpoint(n_right, p_right, nc_r, nv_r, chi_r, eg_r), + V_bi_bc=v_bi, + thermal_voltage_V=vt, + semiconductor_potential_V=v_bi, + has_band_reference=True, + ) + ) + assert cert.certified and cert.is_parameter_free + + d_n_node = np.where(m_abs, 5.0e-5, 2.0e-6) + d_p_node = np.where(m_abs, 5.0e-5, 2.0e-6) + dn_face = 2.0 * d_n_node[:-1] * d_n_node[1:] / (d_n_node[:-1] + d_n_node[1:]) + dp_face = 2.0 * d_p_node[:-1] * d_p_node[1:] / (d_p_node[:-1] + d_p_node[1:]) + + # Unequal Richardson constants across HTL/absorber (face 6) and absorber/ETL (face 19): + iface_specs = ( + (6, 1.8e5, 3.1e5, 4.4e5, 2.2e5, chi_l - chi_m, (chi_m + eg_m) - (chi_l + eg_l)), + (19, 3.1e5, 5.2e5, 2.2e5, 6.0e5, chi_m - chi_r, (chi_r + eg_r) - (chi_m + eg_m)), + ) + + gen_1sun = np.where(m_abs, 2.5e27 * np.exp(-2.0e6 * (x - 8.0e-8)), 0.0) + return _CoupledHeterojunction1D( + nodes_m=x, + poisson=poisson, + chi_phys_eV=chi, + eg_phys_eV=eg, + nc_m3=nc, + nv_m3=nv, + net_doping_m3=net_doping, + ni_sq_m6=ni_sq, + tau_s=1.0e-6, + b_rad_m3_s=1.0e-17, + dn_face_m2_s=dn_face, + dp_face_m2_s=dp_face, + bands=bands, + interface_faces=iface_specs, + n_left_m3=n_left, + p_left_m3=p_left, + n_right_m3=n_right, + p_right_m3=p_right, + boundary=ContactPotentialBoundary(v_bi), + temperature_K=temp, + vt_V=vt, + generation_1sun_m3_s=gen_1sun, + ) + + +def _assemble_and_solve_coupled_heterojunction( + prob: _CoupledHeterojunction1D, + *, + v_app_V: float, + gen_scale: float, + combination_mode: ThermionicCombinationMode, + seed: tuple[Vector, Vector, Vector] | None = None, +) -> tuple[Vector, Vector, Vector, Vector, Vector, float, float]: + """Damped Newton solver in quasi-Fermi potentials (phi, phi_Fn, phi_Fp) [V].""" + n_nodes = prob.nodes_m.size + interior = n_nodes - 2 + phi_l_bc, phi_r_bc = prob.boundary.values(v_app_V) + vt = prob.vt_V + c_cap = prob.poisson.face_capacitance_F_m2 + w_int = prob.poisson.interior_widths_m + gen = gen_scale * prob.generation_1sun_m3_s + + qfn_l = phi_l_bc + float(prob.chi_phys_eV[0]) - vt * math.log(prob.n_left_m3 / float(prob.nc_m3[0])) + qfp_l = ( + phi_l_bc + + float(prob.chi_phys_eV[0]) + + float(prob.eg_phys_eV[0]) + + vt * math.log(prob.p_left_m3 / float(prob.nv_m3[0])) + ) + qfn_r = phi_r_bc + float(prob.chi_phys_eV[-1]) - vt * math.log(prob.n_right_m3 / float(prob.nc_m3[-1])) + qfp_r = ( + phi_r_bc + + float(prob.chi_phys_eV[-1]) + + float(prob.eg_phys_eV[-1]) + + vt * math.log(prob.p_right_m3 / float(prob.nv_m3[-1])) + ) + + if seed is None: + phi = np.linspace(phi_l_bc, phi_r_bc, n_nodes) + qfn = np.linspace(qfn_l, qfn_r, n_nodes) + qfp = np.linspace(qfp_l, qfp_r, n_nodes) + # Rapid 1D Poisson-Boltzmann preparation at fixed quasi-Fermi profile: + for _pb in range(40): + n_pb = prob.nc_m3 * np.exp((phi + prob.chi_phys_eV - qfn) / vt) + p_pb = prob.nv_m3 * np.exp((qfp - phi - prob.chi_phys_eV - prob.eg_phys_eV) / vt) + r_pb = ( + c_cap[:-1] * (phi[1:-1] - phi[:-2]) + - c_cap[1:] * (phi[2:] - phi[1:-1]) + - Q * w_int * (p_pb[1:-1] - n_pb[1:-1] + prob.net_doping_m3[1:-1]) + ) + if float(np.max(np.abs(r_pb))) <= 1.0e-15: + break + j_pb = np.diag(c_cap[:-1] + c_cap[1:] + Q * w_int * (n_pb[1:-1] + p_pb[1:-1]) / vt) + j_pb -= np.diag(c_cap[1:-1], -1) + np.diag(c_cap[1:-1], 1) + d_pb = np.linalg.solve(j_pb, -r_pb) + scale_pb = min(1.0, 0.15 / max(float(np.max(np.abs(d_pb))), 1.0e-30)) + phi[1:-1] += scale_pb * d_pb + else: + phi_prev, n_prev, p_prev = seed + qfn_prev = phi_prev + prob.chi_phys_eV - vt * np.log(n_prev / prob.nc_m3) + qfp_prev = phi_prev + prob.chi_phys_eV + prob.eg_phys_eV + vt * np.log(p_prev / prob.nv_m3) + ramp = np.linspace(0.0, phi_r_bc - float(phi_prev[-1]), n_nodes) + phi = phi_prev + ramp + qfn = qfn_prev + ramp + qfp = qfp_prev + ramp + phi[0], phi[-1] = phi_l_bc, phi_r_bc + qfn[0], qfn[-1] = qfn_l, qfn_r + qfp[0], qfp[-1] = qfp_l, qfp_r + + u = np.empty(3 * interior, dtype=np.float64) + u[0::3] = phi[1:-1] + u[1::3] = qfn[1:-1] + u[2::3] = qfp[1:-1] + + def eval_system(vec: Vector) -> tuple[Vector, NDArray[np.float64], float]: + phi_cur = phi.copy() + qfn_cur = qfn.copy() + qfp_cur = qfp.copy() + phi_cur[1:-1] = vec[0::3] + qfn_cur[1:-1] = vec[1::3] + qfp_cur[1:-1] = vec[2::3] + ln_cur = np.log(prob.nc_m3) + (phi_cur + prob.chi_phys_eV - qfn_cur) / vt + lp_cur = np.log(prob.nv_m3) + (qfp_cur - phi_cur - prob.chi_phys_eV - prob.eg_phys_eV) / vt + n_cur = np.exp(ln_cur) + p_cur = np.exp(lp_cur) + + ec_n = -(qfn_cur[1:] - qfn_cur[:-1]) / vt + ec_p = +(qfp_cur[1:] - qfp_cur[:-1]) / vt + + sg = carrier_particle_fluxes( + prob.nodes_m, + phi_cur, + n_cur, + p_cur, + prob.dn_face_m2_s, + prob.dp_face_m2_s, + vt, + prob.bands, + electron_electrochemical_step=ec_n, + hole_electrochemical_step=ec_p, + ) + fn = np.array(sg.electron.flux, dtype=float, copy=True) + fn_phi_l = np.array(sg.electron.left_potential_derivative, dtype=float, copy=True) + fn_phi_r = np.array(sg.electron.right_potential_derivative, dtype=float, copy=True) + fn_ln_l = np.array(sg.electron.left_density_derivative * n_cur[:-1], dtype=float, copy=True) + fn_ln_r = np.array(sg.electron.right_density_derivative * n_cur[1:], dtype=float, copy=True) + + fp = np.array(sg.hole.flux, dtype=float, copy=True) + fp_phi_l = np.array(sg.hole.left_potential_derivative, dtype=float, copy=True) + fp_phi_r = np.array(sg.hole.right_potential_derivative, dtype=float, copy=True) + fp_lp_l = np.array(sg.hole.left_density_derivative * p_cur[:-1], dtype=float, copy=True) + fp_lp_r = np.array(sg.hole.right_density_derivative * p_cur[1:], dtype=float, copy=True) + + for f_idx, an_l, an_r, ap_l, ap_r, off_e, off_h in prob.interface_faces: + te_e = reciprocal_thermionic_flux_m2_s( + float(n_cur[f_idx]), + float(n_cur[f_idx + 1]), + carrier="electron", + phi_left_V=float(phi_cur[f_idx]), + phi_right_V=float(phi_cur[f_idx + 1]), + band_offset_eV=off_e, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=an_l, + a_star_right_A_m2_K2=an_r, + dos_left_m3=float(prob.nc_m3[f_idx]), + dos_right_m3=float(prob.nc_m3[f_idx + 1]), + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + thermal_voltage_V=vt, + electrochemical_step=float(ec_n[f_idx]), + ) + comb_e = combine_sg_and_reciprocal_thermionic_flux( + float(fn[f_idx]), + d_sg_d_phi_left_m2_s_V=float(fn_phi_l[f_idx]), + d_sg_d_phi_right_m2_s_V=float(fn_phi_r[f_idx]), + d_sg_d_c_left_m_s=float(sg.electron.left_density_derivative[f_idx]), + d_sg_d_c_right_m_s=float(sg.electron.right_density_derivative[f_idx]), + c_left_m3=float(n_cur[f_idx]), + c_right_m3=float(n_cur[f_idx + 1]), + thermionic=te_e, + combination_mode=combination_mode, + te_softness=0.05, + ) + fn[f_idx] = comb_e.flux_m2_s + fn_phi_l[f_idx] = comb_e.d_flux_d_phi_left_m2_s_V + fn_phi_r[f_idx] = comb_e.d_flux_d_phi_right_m2_s_V + fn_ln_l[f_idx] = comb_e.d_flux_d_log_c_left_m2_s + fn_ln_r[f_idx] = comb_e.d_flux_d_log_c_right_m2_s + + te_h = reciprocal_thermionic_flux_m2_s( + float(p_cur[f_idx]), + float(p_cur[f_idx + 1]), + carrier="hole", + phi_left_V=float(phi_cur[f_idx]), + phi_right_V=float(phi_cur[f_idx + 1]), + band_offset_eV=off_h, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=ap_l, + a_star_right_A_m2_K2=ap_r, + dos_left_m3=float(prob.nv_m3[f_idx]), + dos_right_m3=float(prob.nv_m3[f_idx + 1]), + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + thermal_voltage_V=vt, + electrochemical_step=float(ec_p[f_idx]), + ) + comb_h = combine_sg_and_reciprocal_thermionic_flux( + float(fp[f_idx]), + d_sg_d_phi_left_m2_s_V=float(fp_phi_l[f_idx]), + d_sg_d_phi_right_m2_s_V=float(fp_phi_r[f_idx]), + d_sg_d_c_left_m_s=float(sg.hole.left_density_derivative[f_idx]), + d_sg_d_c_right_m_s=float(sg.hole.right_density_derivative[f_idx]), + c_left_m3=float(p_cur[f_idx]), + c_right_m3=float(p_cur[f_idx + 1]), + thermionic=te_h, + combination_mode=combination_mode, + te_softness=0.05, + ) + fp[f_idx] = comb_h.flux_m2_s + fp_phi_l[f_idx] = comb_h.d_flux_d_phi_left_m2_s_V + fp_phi_r[f_idx] = comb_h.d_flux_d_phi_right_m2_s_V + fp_lp_l[f_idx] = comb_h.d_flux_d_log_c_left_m2_s + fp_lp_r[f_idx] = comb_h.d_flux_d_log_c_right_m2_s + + res = np.zeros(3 * interior, dtype=np.float64) + jac = np.zeros((3 * interior, 3 * interior), dtype=np.float64) + + for k in range(interior): + i = k + 1 + row_phi = 3 * k + row_n = 3 * k + 1 + row_p = 3 * k + 2 + w = float(w_int[k]) + ni = math.sqrt(float(prob.ni_sq_m6[i])) + n_i = float(n_cur[i]) + p_i = float(p_cur[i]) + + # SRH + radiative bulk recombination: + denom_srh = prob.tau_s * (n_i + p_i + 2.0 * ni) + np_diff = n_i * p_i - float(prob.ni_sq_m6[i]) + r_srh = np_diff / denom_srh + dr_dn = (p_i * denom_srh - np_diff * prob.tau_s) / (denom_srh * denom_srh) + prob.b_rad_m3_s * p_i + dr_dp = (n_i * denom_srh - np_diff * prob.tau_s) / (denom_srh * denom_srh) + prob.b_rad_m3_s * n_i + r_tot = r_srh + prob.b_rad_m3_s * np_diff + + # 1. Poisson residual [C/m^2]: C_{i-1}(phi_i - phi_{i-1}) - C_i(phi_{i+1} - phi_i) - q w (p - n + N_net) + c_l_val = float(c_cap[i - 1]) + c_r_val = float(c_cap[i]) + res[row_phi] = ( + c_l_val * (float(phi_cur[i]) - float(phi_cur[i - 1])) + - c_r_val * (float(phi_cur[i + 1]) - float(phi_cur[i])) + - Q * w * (p_i - n_i + float(prob.net_doping_m3[i])) + ) + jac[row_phi, row_phi] = c_l_val + c_r_val + jac[row_phi, row_n] = Q * w * n_i + jac[row_phi, row_p] = -Q * w * p_i + if k > 0: + jac[row_phi, 3 * (k - 1)] = -c_l_val + if k < interior - 1: + jac[row_phi, 3 * (k + 1)] = -c_r_val + + # 2. Electron continuity [m^-2 s^-1]: (F_{n,i} - F_{n,i-1}) + w * (R - G) = 0 + res[row_n] = (float(fn[i]) - float(fn[i - 1])) + w * (r_tot - float(gen[i])) + jac[row_n, row_phi] = float(fn_phi_l[i]) - float(fn_phi_r[i - 1]) + jac[row_n, row_n] = float(fn_ln_l[i]) - float(fn_ln_r[i - 1]) + w * dr_dn * n_i + jac[row_n, row_p] = w * dr_dp * p_i + if k > 0: + jac[row_n, 3 * (k - 1)] = -float(fn_phi_l[i - 1]) + jac[row_n, 3 * (k - 1) + 1] = -float(fn_ln_l[i - 1]) + if k < interior - 1: + jac[row_n, 3 * (k + 1)] = float(fn_phi_r[i]) + jac[row_n, 3 * (k + 1) + 1] = float(fn_ln_r[i]) + + # 3. Hole continuity [m^-2 s^-1]: (F_{p,i} - F_{p,i-1}) + w * (R - G) = 0 + res[row_p] = (float(fp[i]) - float(fp[i - 1])) + w * (r_tot - float(gen[i])) + jac[row_p, row_phi] = float(fp_phi_l[i]) - float(fp_phi_r[i - 1]) + jac[row_p, row_n] = w * dr_dn * n_i + jac[row_p, row_p] = float(fp_lp_l[i]) - float(fp_lp_r[i - 1]) + w * dr_dp * p_i + if k > 0: + jac[row_p, 3 * (k - 1)] = -float(fp_phi_l[i - 1]) + jac[row_p, 3 * (k - 1) + 2] = -float(fp_lp_l[i - 1]) + if k < interior - 1: + jac[row_p, 3 * (k + 1)] = float(fp_phi_r[i]) + jac[row_p, 3 * (k + 1) + 2] = float(fp_lp_r[i]) + + jac_qf = np.empty_like(jac) + jac_qf[:, 0::3] = jac[:, 0::3] + (jac[:, 1::3] - jac[:, 2::3]) / vt + jac_qf[:, 1::3] = -jac[:, 1::3] / vt + jac_qf[:, 2::3] = jac[:, 2::3] / vt + j_faces = Q * (fp - fn) + return res, jac_qf, float(np.mean(j_faces)) + + row_scale = np.empty(3 * interior, dtype=np.float64) + row_scale[0::3] = 1.0 / 1.0e-4 + row_scale[1::3] = Q + row_scale[2::3] = Q + + tol = 1.0e-12 if (v_app_V == 0.0 and gen_scale == 0.0) else 2.0e-4 + step_limits = np.empty(3 * interior, dtype=np.float64) + step_limits[0::3] = 0.10 + step_limits[1::3] = 2.0 * vt + step_limits[2::3] = 2.0 * vt + if seed is not None: + # One M-matrix density-coordinate preparation step at frozen phi prevents huge + # logarithmic jumps across depleted minority contact boundary layers. + res0, jac0, _ = eval_system(u) + c_idx = [c for k in range(interior) for c in (3 * k + 1, 3 * k + 2)] + dq_sub = np.linalg.solve(jac0[np.ix_(c_idx, c_idx)], -res0[c_idx]) + d_rel_n = -dq_sub[0::2] / vt + d_rel_p = +dq_sub[1::2] / vt + if np.all(1.0 + d_rel_n > 0.0) and np.all(1.0 + d_rel_p > 0.0): + u[1::3] -= vt * np.log1p(d_rel_n) + u[2::3] += vt * np.log1p(d_rel_p) + settings = NewtonSettings( + ResidualScaling(row_scale / tol), + 1.0, + StepControl(step_limits), + SolveBudget(150, 5000, 500, 40), + (), + False, + ) + prob_nl = CallableProblem(lambda v: eval_system(v)[0], lambda v: eval_system(v)[1]) + nl_res = solve_newton(prob_nl, u, settings) + assert nl_res.accepted, f"v={v_app_V} g={gen_scale}: {nl_res.termination} {nl_res.message}" + u = nl_res.state + res, jac, j_cur = eval_system(u) + # Equilibrated row/column-scaled condition number check: + row_norms = np.maximum(np.linalg.norm(jac, axis=1, keepdims=True), 1.0e-30) + col_norms = np.maximum(np.linalg.norm(jac / row_norms, axis=0, keepdims=True), 1.0e-30) + cond_equil = float(np.linalg.cond((jac / row_norms) / col_norms)) + + phi_out = phi.copy() + qfn_out = qfn.copy() + qfp_out = qfp.copy() + phi_out[1:-1] = u[0::3] + qfn_out[1:-1] = u[1::3] + qfp_out[1:-1] = u[2::3] + ln_out = np.log(prob.nc_m3) + (phi_out + prob.chi_phys_eV - qfn_out) / vt + lp_out = np.log(prob.nv_m3) + (qfp_out - phi_out - prob.chi_phys_eV - prob.eg_phys_eV) / vt + return phi_out, np.exp(ln_out), np.exp(lp_out), qfn_out, qfp_out, j_cur, cond_equil + + +@pytest.mark.parametrize("combination_mode", ["harmonic_series", "compact_support"]) +def test_coupled_heterojunction_dark_equilibrium_and_deep_forward_bias_3v( + combination_mode: ThermionicCombinationMode, +) -> None: + prob = _build_coupled_heterojunction_1d() + + # 1. Dark thermal equilibrium (V = 0, G = 0): + phi_eq, n_eq, p_eq, qfn_eq, qfp_eq, j_dark, cond_eq = _assemble_and_solve_coupled_heterojunction( + prob, v_app_V=0.0, gen_scale=0.0, combination_mode=combination_mode + ) + assert abs(j_dark) <= 1.0e-14 + assert math.isfinite(cond_eq) and cond_eq < 1.0e7 + + ef_n = -phi_eq - prob.chi_phys_eV + prob.vt_V * np.log(n_eq / prob.nc_m3) + ef_p = -phi_eq - prob.chi_phys_eV - prob.eg_phys_eV - prob.vt_V * np.log(p_eq / prob.nv_m3) + assert float(np.max(ef_n) - np.min(ef_n)) <= 1.0e-13 + assert float(np.max(ef_p) - np.min(ef_p)) <= 1.0e-13 + assert float(np.max(np.abs(ef_n - ef_p))) <= 1.0e-13 + + # Verify bare RECIPROCAL_PHYSICAL_THERMIONIC_V2 at BOTH converged heterointerfaces is <= 1e-15 * scale, + # whereas legacy single-DOS static-offset TE produces a huge spurious equilibrium current: + for f_idx, an_l, an_r, ap_l, ap_r, off_e, off_h in prob.interface_faces: + bare_e = reciprocal_thermionic_flux_m2_s( + float(n_eq[f_idx]), + float(n_eq[f_idx + 1]), + carrier="electron", + phi_left_V=float(phi_eq[f_idx]), + phi_right_V=float(phi_eq[f_idx + 1]), + band_offset_eV=off_e, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=an_l, + a_star_right_A_m2_K2=an_r, + dos_left_m3=float(prob.nc_m3[f_idx]), + dos_right_m3=float(prob.nc_m3[f_idx + 1]), + thermal_voltage_V=prob.vt_V, + electrochemical_step=float(-(qfn_eq[f_idx + 1] - qfn_eq[f_idx]) / prob.vt_V), + ) + bare_h = reciprocal_thermionic_flux_m2_s( + float(p_eq[f_idx]), + float(p_eq[f_idx + 1]), + carrier="hole", + phi_left_V=float(phi_eq[f_idx]), + phi_right_V=float(phi_eq[f_idx + 1]), + band_offset_eV=off_h, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=ap_l, + a_star_right_A_m2_K2=ap_r, + dos_left_m3=float(prob.nv_m3[f_idx]), + dos_right_m3=float(prob.nv_m3[f_idx + 1]), + thermal_voltage_V=prob.vt_V, + electrochemical_step=float((qfp_eq[f_idx + 1] - qfp_eq[f_idx]) / prob.vt_V), + ) + assert abs(bare_e.flux_m2_s) <= 1.0e-15 * bare_e.one_way_scale_m2_s + assert abs(bare_h.flux_m2_s) <= 1.0e-15 * bare_h.one_way_scale_m2_s + + # Also check density-reconstructed form (bounded by (|ln c_L| + |ln c_R| + |D|) * eps_mach ~ 2.2e-14): + bare_e_dens = reciprocal_thermionic_flux_m2_s( + float(n_eq[f_idx]), + float(n_eq[f_idx + 1]), + carrier="electron", + phi_left_V=float(phi_eq[f_idx]), + phi_right_V=float(phi_eq[f_idx + 1]), + band_offset_eV=off_e, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=an_l, + a_star_right_A_m2_K2=an_r, + dos_left_m3=float(prob.nc_m3[f_idx]), + dos_right_m3=float(prob.nc_m3[f_idx + 1]), + thermal_voltage_V=prob.vt_V, + ) + assert abs(bare_e_dens.flux_m2_s) <= 2.5e-14 * bare_e_dens.one_way_scale_m2_s + + # Legacy single geometric-mean DOS + static barrier (phi_L = phi_R = 0) breaks equilibrium: + geom_nc = math.sqrt(float(prob.nc_m3[f_idx] * prob.nc_m3[f_idx + 1])) + spurious_leg = reciprocal_thermionic_flux_m2_s( + float(n_eq[f_idx]), + float(n_eq[f_idx + 1]), + carrier="electron", + phi_left_V=0.0, + phi_right_V=0.0, + band_offset_eV=off_e, + temperature_K=prob.temperature_K, + a_star_left_A_m2_K2=an_l, + dos_left_m3=geom_nc, + model_version=LEGACY_UNNORMALIZED_THERMIONIC_V1, + ) + assert abs(spurious_leg.flux_m2_s) > 0.1 * spurious_leg.one_way_scale_m2_s + + # 2. Illuminated 1-sun sweep & deep forward-bias continuation up to V_app = +3.0 V (ArchiveDigest X3): + seed_state: tuple[Vector, Vector, Vector] = (phi_eq, n_eq, p_eq) + for g_ramp in (1.0e-6, 1.0e-3): + phi_g, n_g, p_g, *_ = _assemble_and_solve_coupled_heterojunction( + prob, + v_app_V=0.0, + gen_scale=g_ramp, + combination_mode=combination_mode, + seed=seed_state, + ) + seed_state = (phi_g, n_g, p_g) + + voltages = [round(0.2 * k, 4) for k in range(16)] # 0.0 V -> +3.0 V in 0.2 V steps + currents: list[float] = [] + conds: list[float] = [] + for v_app in voltages: + phi_v, n_v, p_v, _qfn_v, _qfp_v, j_v, cond_v = _assemble_and_solve_coupled_heterojunction( + prob, + v_app_V=v_app, + gen_scale=1.0, + combination_mode=combination_mode, + seed=seed_state, + ) + assert np.all(np.isfinite(phi_v)) and np.all(np.isfinite(n_v)) and np.all(np.isfinite(p_v)) + assert np.all(n_v > 0.0) and np.all(p_v > 0.0) + assert math.isfinite(j_v) and math.isfinite(cond_v) + assert cond_v < 1.0e8 + currents.append(j_v) + conds.append(cond_v) + seed_state = (phi_v, n_v, p_v) + + # Polarity: V_bi = W_htl - W_etl > 0, forward bias drives holes left->right (+x), so forward diode current > 0 + # and photocurrent at V = 0 is negative (J(0) < 0), crossing 0 strictly below absorber Eg = 1.60 V! + assert currents[0] < -50.0 + assert currents[7] > 0.0 # Already forward-injecting at V = 1.40 V (< Eg_abs = 1.60 V!) + for prev_j, next_j in zip(currents[:-1], currents[1:]): + assert next_j > prev_j + assert currents[-1] > 1.0e4 # Deep forward bias +3.0 V carries clean finite emission/series current! + + +def _prepare_heterojunction_device( + catalog: DefaultCatalog, + *, + interface_shared_occupancy: bool = False, +) -> PreparedDevice: + ni_htl = _thermodynamic_ni(2.0e25, 3.0e25, 1.75) + ni_abs = _thermodynamic_ni(5.0e24, 8.0e24, 1.60) + ni_etl = _thermodynamic_ni(4.0e25, 1.5e25, 1.85) + raw_doc: dict[str, Any] = { + "device": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "interface_shared_occupancy": interface_shared_occupancy, + "T": 300.0, + "Phi": 2.0e21, + "mode": "full", + }, + "electrical_grid": { + "interval_weights": {"htl": 1.0, "absorber": 2.0, "etl": 1.0}, + "alphas": {"htl": 2.0, "absorber": 2.0, "etl": 2.0}, + }, + "layers": [ + { + "name": "htl", + "role": "HTL", + "thickness": 8.0e-8, + "eps_r": 3.5, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_htl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_htl, + "p1": ni_htl, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "N_A": 5.0e21, + "N_D": 0.0, + "chi": 3.62, + "Eg": 1.75, + "Nc300": 2.0e25, + "Nv300": 3.0e25, + "A_star_n": 1.8e5, + "A_star_p": 4.4e5, + }, + { + "name": "absorber", + "role": "absorber", + "thickness": 3.0e-7, + "eps_r": 24.0, + "mu_n": 1.934e-3, + "mu_p": 1.934e-3, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_abs, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_abs, + "p1": ni_abs, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.90, + "Eg": 1.60, + "Nc300": 5.0e24, + "Nv300": 8.0e24, + "A_star_n": 3.1e5, + "A_star_p": 2.2e5, + }, + { + "name": "etl", + "role": "ETL", + "thickness": 8.0e-8, + "eps_r": 9.0, + "mu_n": 3.868e-5, + "mu_p": 3.868e-5, + "D_ion": 0.0, + "P_lim": 1.0e28, + "P0": 0.0, + "ni": ni_etl, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": ni_etl, + "p1": ni_etl, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 0.0, + "N_A": 0.0, + "N_D": 5.0e21, + "chi": 4.04, + "Eg": 1.85, + "Nc300": 4.0e25, + "Nv300": 1.5e25, + "A_star_n": 5.2e5, + "A_star_p": 6.0e5, + }, + ], + } + payload = json.dumps(raw_doc, allow_nan=False).encode() + source = SourceDocument("p08_03_heterojunction.yaml", payload) + dev_input = import_standard_device(source, id="p08_03_heterojunction", defaults=catalog) + return resolve_device(dev_input, catalog, ResourceLibrary(), sources=(source,)) + + +def _step_steady_to_voltage( + dev: Any, + *, + start_sol: SteadyState1D, + start_voltage_V: float, + target_voltage_V: float, + generation_scale: float, + options: SteadyOptions, +) -> SteadyState1D: + v_cur = start_voltage_V + sol = start_sol + step = float(options.max_bias_step_V) + while abs(target_voltage_V - v_cur) > 1.0e-12: + delta = target_voltage_V - v_cur + dv = math.copysign(min(abs(delta), step), delta) + v_try = target_voltage_V if abs(dv) >= abs(delta) else v_cur + dv + try: + sol = solve_steady_state( + dev, + voltage_V=v_try, + generation_scale=generation_scale, + initial_state=sol.state, + options=options, + ) + v_cur = v_try + step = min(float(options.max_bias_step_V), step * 1.5) + except SteadyStateError: + step *= 0.5 + if step < 1.0e-4: + raise + return sol + + +def test_compiled_1d_heterojunction_equilibrium_and_deep_forward_bias_3v( + legacy_catalog: DefaultCatalog, +) -> None: + """Verify compiled 1D heterojunction dark equilibrium + illuminated sweeps up to +3.0 V. + + * ``two_sided_trace``: certifies dark equilibrium to ``<= 1e-12 A/m^2`` and active + solar-cell illuminated sweep across ``[0.0, 1.15] V`` (note: ``two_sided.py`` currently + uses FD Richardson trace TE while bulk SG uses MB; ``P08-05`` wires matching statistics + via ``RECIPROCAL_PHYSICAL_THERMIONIC_V2`` for super-flatband ``V > V_bi``). + * ``deduplicated``: certifies dark equilibrium and full illuminated continuation all the + way to ``+3.0 V`` deep forward bias. + """ + prepared = _prepare_heterojunction_device(legacy_catalog) + eq_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-10, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + sweep_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-5, + current_spread_tolerance_A_m2=1.0e-5, + equilibrium_current_tolerance_A_m2=1.0e-4, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + max_bias_step_V=0.25, + ) + + # 1. two_sided_trace equilibrium + illuminated solar-cell quadrant: + dev_two = compile_device_1d( + prepared, + intervals_per_layer=(3, 6, 3), + interface_topology="two_sided_trace", + ) + eq_two = solve_equilibrium(dev_two, options=eq_opts) + assert float(np.max(np.abs(eq_two.current_density_A_m2))) <= 1.0e-12 + assert float(np.max(np.abs(eq_two.contact_current_density_A_m2))) <= 1.0e-12 + + sol_two = solve_steady_state( + dev_two, + voltage_V=0.0, + generation_scale=1.0, + options=sweep_opts, + ) + v_cur_two = 0.0 + prev_j_two: float | None = None + for v_app in (0.0, 0.4, 0.8, 1.15): + if v_app > v_cur_two: + sol_two = _step_steady_to_voltage( + dev_two, + start_sol=sol_two, + start_voltage_V=v_cur_two, + target_voltage_V=v_app, + generation_scale=1.0, + options=sweep_opts, + ) + v_cur_two = v_app + j_mean_two = float(np.mean(sol_two.current_density_A_m2)) + assert math.isfinite(j_mean_two) + assert np.all(sol_two.state.electron_density_m3 > 0.0) + assert np.all(sol_two.state.hole_density_m3 > 0.0) + if prev_j_two is not None: + assert j_mean_two > prev_j_two + prev_j_two = j_mean_two + + # 2. deduplicated equilibrium + illuminated deep forward sweep to +3.0 V: + dev_dedup = compile_device_1d( + prepared, + intervals_per_layer=(4, 8, 4), + interface_topology="deduplicated", + ) + eq_dedup = solve_equilibrium(dev_dedup, options=eq_opts) + assert float(np.max(np.abs(eq_dedup.current_density_A_m2))) <= 1.0e-12 + + sol = solve_steady_state( + dev_dedup, + voltage_V=0.0, + generation_scale=1.0, + options=sweep_opts, + ) + v_cur = 0.0 + prev_j: float | None = None + for v_app in (0.0, 0.6, 1.2, 1.8, 2.4, 3.0): + if v_app > v_cur: + sol = _step_steady_to_voltage( + dev_dedup, + start_sol=sol, + start_voltage_V=v_cur, + target_voltage_V=v_app, + generation_scale=1.0, + options=sweep_opts, + ) + v_cur = v_app + j_mean = float(np.mean(sol.current_density_A_m2)) + assert math.isfinite(j_mean) + assert np.all(np.isfinite(sol.current_density_A_m2)) + assert np.all(np.isfinite(sol.state.u)) + assert np.all(sol.state.electron_density_m3 > 0.0) + assert np.all(sol.state.hole_density_m3 > 0.0) + if prev_j is not None: + assert j_mean > prev_j + prev_j = j_mean + + +def test_falsified_interface_shared_occupancy_refused_across_1d_2d_and_ionic_2d( + legacy_catalog: DefaultCatalog, +) -> None: + """Falsified single-shared-occupancy closure must fail closed before solving in all compilers.""" + prep_bad_1d = _prepare_heterojunction_device( + legacy_catalog, interface_shared_occupancy=True + ) + + # 1. 1D compiler (deduplicated & two_sided_trace): + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_device_1d(prep_bad_1d, intervals_per_layer=(4, 6, 4)) + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_device_1d( + prep_bad_1d, + intervals_per_layer=(4, 6, 4), + interface_topology="two_sided_trace", + ) + + # 2. 2D classical compiler: + spatial_2d = JV2DInput( + kind="jv_2d", + lateral_length=2.0e-7, + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ) + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_device_2d(prep_bad_1d, spatial_2d) + + # 3. 2D ionic compiler (both interface_srh="off" and "two_sided_cross_node"): + prep_ion_ok = prepare_confined_ion_device() + abs_layer_id = next(lyr.id for lyr in prep_ion_ok.layers if lyr.role == "absorber") + editing = prep_ion_ok.to_input().editing_data() + editing["settings"]["interface_shared_occupancy"] = True + prep_ion_bad = resolve_device( + DeviceInput.model_validate(editing), + prep_ion_ok.defaults, + prep_ion_ok.resources, + sources=prep_ion_ok.sources, + ) + for srh_mode in ("off", "two_sided_cross_node"): + spatial_ion_2d = JV2DInput( + kind="jv_2d", + lateral_length=2.0e-7, + Nx=3, + Ny_per_layer=4, + lateral_bc="neumann", + microstructure=MicrostructureInput(grain_boundaries=()), + ion_dynamics="single_mobile", + interface_srh=srh_mode, + ) + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_ionic_device_2d( + prep_ion_bad, + spatial_ion_2d, + ion_domain_layer=abs_layer_id, + ion_domain_endpoints=("blocking", "blocking"), + ) diff --git a/tests/unit/physics/test_p08_03_thermionic_and_contacts.py b/tests/unit/physics/test_p08_03_thermionic_and_contacts.py new file mode 100644 index 00000000..863abf57 --- /dev/null +++ b/tests/unit/physics/test_p08_03_thermionic_and_contacts.py @@ -0,0 +1,833 @@ +"""Unit tests for P08-03 reciprocal unequal-DOS thermionic emission and 5.0 meV contact gate. + +Verifies: +1. Bare thermionic emission detailed balance (``|J_TE| <= 1e-15 * J_one_way``) at thermal + equilibrium across unequal DOS ``N_{C,L}/N_{C,R} in [1e-2, 1e2]`` and unequal effective + masses ``A*_L != A*_R`` under both Maxwell-Boltzmann and Fermi-Dirac statistics, without + Scharfetter-Gummel masking, contrasted against single-DOS, non-reciprocal ``A*``, and + DOS-folded barrier counterexamples. +2. Strict sign invariant (zero spurious non-equilibrium roots), sub-zeptoampere cancellation-free + ``expm1`` drive accuracy, exact ``left <-> right`` swap reciprocity, concentration/length + unit-rescaling invariance, transmission scaling, SCAPS effective-velocity distinctness, + and 0-ULP legacy parity. +3. Fourth-order central finite-difference verification (``<= 1e-9``) of analytical Jacobians + wrt ``(phi_L, phi_R, c_L, c_R)`` and ``(ln c_L, ln c_R)`` for both bare reciprocal TE and + composite SG + reciprocal TE face evaluations (including at exact ``m == 0`` equilibrium). +4. Contact thermodynamic ``5.0 meV`` gate invariants, parameter-free vs fitted contact mode + classification, and permanent preservation of the historical ``6.024958093130e-3 eV`` + ``scaps_mirror_v2`` ``legacy_manual_v_bi_contact_offset`` ``inconsistent`` record. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +import dataclasses +import math +from pathlib import Path +import warnings + +import numpy as np +import pytest +from threadpoolctl import threadpool_limits + +from perovskite_sim.experiments.jv_sweep import build_electrical_grid +from perovskite_sim.scaps_compat import load_scaps_yaml +from perovskite_sim.solver.mol import build_material_arrays + +from solarlab.physics.contacts import ( + CONTACT_ALIGNMENT_CLASSES, + CONTACT_THERMODYNAMIC_TOLERANCE_EV, + EXTERNAL_METAL_CONTACT_ALIGNMENT, + FITTED_MANUAL_CONTACT_ALIGNMENT, + LEGACY_MANUAL_CONTACT_OFFSET, + PARAMETER_FREE_CONTACT_ALIGNMENT, + ContactEndpoint, + ContactThermodynamicError, + assess_contact_thermodynamics, + certify_parameter_free_contact_equilibrium, + classify_contact_alignment_mode, + require_contact_thermodynamic_certificate, +) +from solarlab.physics.interface_transport.thermionic import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, + THERMIONIC_MODEL_VERSIONS, + ReciprocalThermionicCompositeEvaluation, + ThermionicCarrierKind, + ThermionicCombinationMode, + ThermionicStatisticsKind, + combine_sg_and_reciprocal_thermionic_flux, + physical_barrier_steps_eV, + physical_carrier_barrier_step_eV, + reciprocal_richardson, + reciprocal_thermionic_flux_m2_s, + richardson_from_dos, + thermionic_emission_bound_m2_s, +) +from solarlab.physics.statistics.band_potentials import fold_dos_into_transport_bands +from solarlab.physics.statistics.fermi_dirac import fermi_dirac_half +from solarlab.physics.statistics.thermal import thermal_voltage +from solarlab.physics.transport.electrochemical_flux import stable_sg_particle_flux + +SCAPS_MIRROR_PRESET = ( + Path(__file__).resolve().parents[3] / "perovskite-sim/configs/scaps_mirror_v2.yaml" +) + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +def _fourth_order_fd(fn: Callable[[float], float], x0: float, h: float) -> float: + return ( + -fn(x0 + 2.0 * h) + 8.0 * fn(x0 + h) - 8.0 * fn(x0 - h) + fn(x0 - 2.0 * h) + ) / (12.0 * h) + + +@pytest.mark.parametrize("dos_ratio", [1.0e-2, 1.0e-1, 0.4, 1.0, 2.5, 10.0, 1.0e2]) +@pytest.mark.parametrize("carrier", ["electron", "hole"]) +@pytest.mark.parametrize("band_offset_eV", [-0.24, -0.07, 0.0, 0.11, 0.29]) +def test_bare_reciprocal_te_equilibrium_across_unequal_dos_and_masses_boltzmann( + dos_ratio: float, + carrier: ThermionicCarrierKind, + band_offset_eV: float, +) -> None: + temp = 300.0 + vt = thermal_voltage(temp) + dos_r = 4.0e24 + dos_l = dos_ratio * dos_r + a_star_l = 1.85e5 + a_star_r = 7.40e5 + phi_l = 0.08 + phi_r = 0.21 + + barrier_step, _, _ = physical_carrier_barrier_step_eV( + carrier, phi_left_V=phi_l, phi_right_V=phi_r, band_offset_eV=band_offset_eV + ) + c_l = 1.2e20 + c_r = c_l * (dos_r / dos_l) * math.exp(-barrier_step / vt) + + # 1. Raw binary64 density equilibrium (without passing electrochemical_step): + res_raw = reciprocal_thermionic_flux_m2_s( + c_l, + c_r, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=band_offset_eV, + temperature_K=temp, + a_star_left_A_m2_K2=a_star_l, + a_star_right_A_m2_K2=a_star_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + transmission=0.85, + statistics="maxwell_boltzmann", + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + ) + assert res_raw.one_way_scale_m2_s > 0.0 + assert abs(res_raw.flux_m2_s) <= 1.0e-15 * res_raw.one_way_scale_m2_s + assert abs(res_raw.electrochemical_step) <= 1.0e-15 + assert res_raw.effective_richardson_A_m2_K2 == min(a_star_l, a_star_r) + + # 2. Exact quasi-Fermi equilibrium (electrochemical_step == 0.0): exact 0.0 flux. + res_exact = reciprocal_thermionic_flux_m2_s( + c_l, + c_r, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=band_offset_eV, + temperature_K=temp, + a_star_left_A_m2_K2=a_star_l, + a_star_right_A_m2_K2=a_star_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + transmission=0.85, + statistics="maxwell_boltzmann", + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + electrochemical_step=0.0, + ) + assert res_exact.flux_m2_s == 0.0 + assert res_exact.current_A_m2 == 0.0 + + +@pytest.mark.parametrize("dos_ratio", [1.0e-2, 0.25, 1.0, 4.0, 1.0e2]) +@pytest.mark.parametrize("carrier", ["electron", "hole"]) +def test_bare_reciprocal_te_equilibrium_fermi_dirac( + dos_ratio: float, + carrier: ThermionicCarrierKind, +) -> None: + temp = 300.0 + vt = thermal_voltage(temp) + dos_r = 5.0e24 + dos_l = dos_ratio * dos_r + a_star_l = 2.1e5 + a_star_r = 6.3e5 + phi_l, phi_r = -0.05, 0.09 + band_offset = 0.22 + + barrier_step, _, _ = physical_carrier_barrier_step_eV( + carrier, phi_left_V=phi_l, phi_right_V=phi_r, band_offset_eV=band_offset + ) + # Degenerate left side (eta_l = +1.75) in equilibrium with right side across barrier_step: + eta_l = 1.75 + eta_r = eta_l - barrier_step / vt + c_l = dos_l * fermi_dirac_half(eta_l) + c_r = dos_r * fermi_dirac_half(eta_r) + + res_fd_raw = reciprocal_thermionic_flux_m2_s( + c_l, + c_r, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=band_offset, + temperature_K=temp, + a_star_left_A_m2_K2=a_star_l, + a_star_right_A_m2_K2=a_star_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + statistics="fermi_dirac", + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + ) + assert res_fd_raw.one_way_scale_m2_s > 0.0 + assert abs(res_fd_raw.flux_m2_s) <= 1.0e-15 * res_fd_raw.one_way_scale_m2_s + + res_fd_exact = reciprocal_thermionic_flux_m2_s( + c_l, + c_r, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=band_offset, + temperature_K=temp, + a_star_left_A_m2_K2=a_star_l, + a_star_right_A_m2_K2=a_star_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + statistics="fermi_dirac", + model_version=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + electrochemical_step=0.0, + ) + assert res_fd_exact.flux_m2_s == 0.0 + + +def test_counterexamples_single_dos_nonreciprocal_mass_and_folded_barrier_break_equilibrium() -> None: + """Contrast RECIPROCAL_PHYSICAL_THERMIONIC_V2 against the three legacy failure modes.""" + temp = 300.0 + vt = thermal_voltage(temp) + chi_l, chi_r = 3.70, 3.92 + eg_l, eg_r = 1.75, 1.55 + nc_l, nc_r = 2.0e25, 2.5e24 # 8x unequal DOS + nv_l, nv_r = 3.0e25, 6.0e24 + a_l, a_r = 2.0e5, 6.5e5 + phi_l, phi_r = 0.0, 0.14 + + e_step_phys, _ = physical_barrier_steps_eV( + phi_left_V=phi_l, + phi_right_V=phi_r, + chi_phys_left_eV=chi_l, + chi_phys_right_eV=chi_r, + eg_phys_left_eV=eg_l, + eg_phys_right_eV=eg_r, + ) + n_l = 1.0e19 + n_r = n_l * (nc_r / nc_l) * math.exp(-e_step_phys / vt) + + # Physical V2 gives machine-zero equilibrium flux: + v2 = reciprocal_thermionic_flux_m2_s( + n_l, + n_r, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + ) + assert abs(v2.flux_m2_s) <= 1.0e-15 * v2.one_way_scale_m2_s + + # Counterexample A: single geometric-mean DOS divisor (legacy te_physical_norm): + geom_dos = math.sqrt(nc_l * nc_r) + single_dos = reciprocal_thermionic_flux_m2_s( + n_l, + n_r, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + dos_left_m3=geom_dos, + model_version=LEGACY_UNNORMALIZED_THERMIONIC_V1, + ) + assert abs(single_dos.flux_m2_s) > 0.6 * single_dos.one_way_scale_m2_s + + # Counterexample B: non-reciprocal per-side Richardson weighting A*_L != A*_R: + b_l = max(e_step_phys, 0.0) / vt + b_r = max(-e_step_phys, 0.0) / vt + leg_l = a_l * (n_l / nc_l) * math.exp(-b_l) + leg_r = a_r * (n_r / nc_r) * math.exp(-b_r) + assert abs(leg_l - leg_r) / max(leg_l, leg_r) == pytest.approx( + abs(a_l - a_r) / max(a_l, a_r), rel=1e-14 + ) + + # Counterexample C: feeding DOS-folded SG transport affinities into the TE barrier: + bands = fold_dos_into_transport_bands( + np.array([chi_l, chi_r]), + np.array([eg_l, eg_r]), + [np.array([True, False]), np.array([False, True])], + [(nc_l, nv_l), (nc_r, nv_r)], + reference_layer=0, + thermal_voltage_V=vt, + ) + folded_offset = float(bands.transport_electron_affinity_eV[0] - bands.transport_electron_affinity_eV[1]) + folded_v2 = reciprocal_thermionic_flux_m2_s( + n_l, + n_r, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=folded_offset, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + ) + assert abs(folded_v2.flux_m2_s) > 0.8 * folded_v2.one_way_scale_m2_s + + +def test_zero_spurious_roots_weak_drive_expm1_reciprocity_unit_invariance_and_model_versions() -> None: + assert set(THERMIONIC_MODEL_VERSIONS) == { + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, + } + assert reciprocal_richardson(0.0, 3.0e5) == 0.0 + assert reciprocal_richardson(5.0e5, 2.2e5) == 2.2e5 + + temp = 300.0 + vt = thermal_voltage(temp) + chi_l, chi_r = 3.85, 4.02 + eg_l, eg_r = 1.62, 1.95 + nc_l, nc_r = 8.0e24, 3.2e25 + nv_l, nv_r = 1.2e25, 4.5e24 + a_l, a_r = richardson_from_dos(nc_l, temp), richardson_from_dos(nc_r, temp) + phi_l, phi_r = 0.05, 0.24 + + bands = fold_dos_into_transport_bands( + np.array([chi_l, chi_r]), + np.array([eg_l, eg_r]), + [np.array([True, False]), np.array([False, True])], + [(nc_l, nv_l), (nc_r, nv_r)], + reference_layer=0, + thermal_voltage_V=vt, + ) + e_step_phys, h_step_phys = physical_barrier_steps_eV( + phi_left_V=phi_l, + phi_right_V=phi_r, + chi_phys_left_eV=chi_l, + chi_phys_right_eV=chi_r, + eg_phys_left_eV=eg_l, + eg_phys_right_eV=eg_r, + ) + + # 1. Strict sign invariant across 80 orders of electrochemical drive (no spurious roots) + # and exact sign agreement with DOS-folded Scharfetter-Gummel flux: + n_l_base = 3.0e19 + n_r_eq = n_l_base * (nc_r / nc_l) * math.exp(-e_step_phys / vt) + sg_energy_step = float( + -((phi_r + bands.transport_electron_affinity_eV[1]) - (phi_l + bands.transport_electron_affinity_eV[0])) + / vt + ) + drives = [-80.0, -12.0, -1.5, -1.0e-3, -1.0e-12, -1.0e-25, 0.0, 1.0e-25, 1.0e-12, 1.0e-3, 1.5, 12.0, 80.0] + for m_drive in drives: + n_r_drive = n_r_eq * math.exp(max(-300.0, min(300.0, m_drive))) + te_eval = reciprocal_thermionic_flux_m2_s( + n_l_base, + n_r_drive, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + electrochemical_step=m_drive, + ) + sg_eval = stable_sg_particle_flux( + n_l_base, n_r_drive, sg_energy_step, 1.0e3, electrochemical_step=m_drive + ) + if m_drive == 0.0: + assert te_eval.flux_m2_s == 0.0 + assert float(sg_eval.flux) == 0.0 + else: + expected_sign = -1.0 if m_drive > 0.0 else 1.0 + assert math.copysign(1.0, te_eval.flux_m2_s) == expected_sign + assert math.copysign(1.0, float(sg_eval.flux)) == expected_sign + if abs(m_drive) <= 1.0e-12: + # Sub-zeptoampere linear accuracy without two-term cancellation: + linear_exact = -te_eval.d_flux_d_log_c_left_m2_s * m_drive + assert te_eval.flux_m2_s == pytest.approx(linear_exact, rel=1.0e-11) + + # 2. Exact 0-ULP directional reciprocity under L <-> R swap (electrons & holes, MB & FD): + carrier_cases: tuple[tuple[ThermionicCarrierKind, float, float, float], ...] = ( + ("electron", chi_l - chi_r, nc_l, nc_r), + ("hole", (chi_r + eg_r) - (chi_l + eg_l), nv_l, nv_r), + ) + stats_cases: tuple[ThermionicStatisticsKind, ...] = ("maxwell_boltzmann", "fermi_dirac") + for carrier, offset, d_l, d_r in carrier_cases: + for stats in stats_cases: + c_left, c_right = 4.2e23, 1.9e22 + fwd = reciprocal_thermionic_flux_m2_s( + c_left, + c_right, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=offset, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=d_l, + dos_right_m3=d_r, + transmission=0.73, + statistics=stats, + ) + rev = reciprocal_thermionic_flux_m2_s( + c_right, + c_left, + carrier=carrier, + phi_left_V=phi_r, + phi_right_V=phi_l, + band_offset_eV=-offset, + temperature_K=temp, + a_star_left_A_m2_K2=a_r, + a_star_right_A_m2_K2=a_l, + dos_left_m3=d_r, + dos_right_m3=d_l, + transmission=0.73, + statistics=stats, + ) + assert rev.barrier_step_eV == -fwd.barrier_step_eV + assert rev.effective_richardson_A_m2_K2 == fwd.effective_richardson_A_m2_K2 + if stats == "maxwell_boltzmann": + assert rev.flux_m2_s == -fwd.flux_m2_s + assert rev.electrochemical_step == -fwd.electrochemical_step + else: + assert rev.flux_m2_s == pytest.approx(-fwd.flux_m2_s, rel=1.0e-15) + + # 3. Concentration/length unit-rescaling invariance (m^-3 <-> cm^-3, scale = 1e-6): + scale_cm3 = 1.0e-6 + v2_si = reciprocal_thermionic_flux_m2_s( + 2.5e20, + 9.0e18, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + ) + v2_cgs = reciprocal_thermionic_flux_m2_s( + 2.5e20 * scale_cm3, + 9.0e18 * scale_cm3, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l * scale_cm3, + dos_right_m3=nc_r * scale_cm3, + ) + assert v2_cgs.flux_m2_s == pytest.approx(v2_si.flux_m2_s, rel=1.0e-15) + assert v2_cgs.current_A_m2 == pytest.approx(v2_si.current_A_m2, rel=1.0e-15) + + # Legacy unnormalized V1 scales spuriously by 1e-6 and matches thermionic_emission_bound_m2_s to 0 ULP: + leg_si = reciprocal_thermionic_flux_m2_s( + 2.5e20, + 9.0e18, + carrier="electron", + phi_left_V=0.0, + phi_right_V=0.0, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + model_version=LEGACY_UNNORMALIZED_THERMIONIC_V1, + ) + leg_cgs = reciprocal_thermionic_flux_m2_s( + 2.5e20 * scale_cm3, + 9.0e18 * scale_cm3, + carrier="electron", + phi_left_V=0.0, + phi_right_V=0.0, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + model_version=LEGACY_UNNORMALIZED_THERMIONIC_V1, + ) + ref_bound, ref_dl, ref_dr = thermionic_emission_bound_m2_s( + 2.5e20, 9.0e18, chi_l - chi_r, temp, a_l, dos_norm_m3=None + ) + assert leg_si.flux_m2_s == ref_bound + assert leg_si.d_flux_d_c_left_m_s == ref_dl + assert leg_si.d_flux_d_c_right_m_s == ref_dr + assert leg_cgs.flux_m2_s == pytest.approx(scale_cm3 * leg_si.flux_m2_s, rel=1.0e-15) + + # 4. Transmission factor scaling & SCAPS effective-velocity distinctness: + v2_zero_t = reciprocal_thermionic_flux_m2_s( + 2.5e20, + 9.0e18, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + transmission=0.0, + ) + v2_quar_t = reciprocal_thermionic_flux_m2_s( + 2.5e20, + 9.0e18, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + transmission=0.25, + ) + assert v2_zero_t.flux_m2_s == 0.0 + assert v2_quar_t.flux_m2_s == pytest.approx(0.25 * v2_si.flux_m2_s, rel=1.0e-15) + + scaps_v1 = reciprocal_thermionic_flux_m2_s( + 2.5e20, + 9.0e18, + carrier="electron", + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + model_version=SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, + ) + assert scaps_v1.effective_richardson_A_m2_K2 != pytest.approx( + v2_si.effective_richardson_A_m2_K2, rel=0.05 + ) + assert abs(h_step_phys) > 0.0 + + +@pytest.mark.parametrize("carrier", ["electron", "hole"]) +@pytest.mark.parametrize("statistics", ["maxwell_boltzmann", "fermi_dirac"]) +@pytest.mark.parametrize("band_offset_eV", [-0.19, -0.09, 0.09, 0.23]) +def test_bare_reciprocal_te_analytical_jacobians_match_fourth_order_fd( + carrier: ThermionicCarrierKind, + statistics: ThermionicStatisticsKind, + band_offset_eV: float, +) -> None: + temp = 300.0 + vt = thermal_voltage(temp) + dos_l, dos_r = 6.0e24, 2.0e25 + a_l, a_r = 2.4e5, 5.1e5 + phi_l, phi_r = 0.07, 0.16 + b_step, _, _ = physical_carrier_barrier_step_eV( + carrier, phi_left_V=phi_l, phi_right_V=phi_r, band_offset_eV=band_offset_eV + ) + # Non-equilibrium state with both over-barrier legs active and safely inside a single + # 5e-3 Fermi-Dirac table interval so 4th-order FD sees smooth C^infinity evaluation: + if statistics == "fermi_dirac": + eta_l = 0.8125 if b_step >= 0.0 else (0.8125 + b_step / vt) + eta_r = (eta_l - b_step / vt) + 0.9231 + # Snap away from k * 5e-3 grid knots to 0.0025 midpoint: + eta_l = math.floor(eta_l / 5.0e-3) * 5.0e-3 + 2.5e-3 + eta_r = math.floor(eta_r / 5.0e-3) * 5.0e-3 + 2.5e-3 + c_l = dos_l * fermi_dirac_half(eta_l) + c_r = dos_r * fermi_dirac_half(eta_r) + else: + c_l = 1.7e21 + c_r = 2.7 * c_l * (dos_r / dos_l) * math.exp(-b_step / vt) + + def eval_at(pl: float, pr: float, cl: float, cr: float) -> float: + return reciprocal_thermionic_flux_m2_s( + cl, + cr, + carrier=carrier, + phi_left_V=pl, + phi_right_V=pr, + band_offset_eV=band_offset_eV, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + transmission=0.82, + statistics=statistics, + ).flux_m2_s + + ana = reciprocal_thermionic_flux_m2_s( + c_l, + c_r, + carrier=carrier, + phi_left_V=phi_l, + phi_right_V=phi_r, + band_offset_eV=band_offset_eV, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=dos_l, + dos_right_m3=dos_r, + transmission=0.82, + statistics=statistics, + ) + + h_phi = 1.0e-4 + h_log = 1.0e-4 + fd_phi_l = _fourth_order_fd(lambda x: eval_at(x, phi_r, c_l, c_r), phi_l, h_phi) + fd_phi_r = _fourth_order_fd(lambda x: eval_at(phi_l, x, c_l, c_r), phi_r, h_phi) + fd_c_l = _fourth_order_fd(lambda x: eval_at(phi_l, phi_r, x, c_r), c_l, h_log * c_l) + fd_c_r = _fourth_order_fd(lambda x: eval_at(phi_l, phi_r, c_l, x), c_r, h_log * c_r) + fd_log_l = _fourth_order_fd( + lambda z: eval_at(phi_l, phi_r, c_l * math.exp(z), c_r), 0.0, h_log + ) + fd_log_r = _fourth_order_fd( + lambda z: eval_at(phi_l, phi_r, c_l, c_r * math.exp(z)), 0.0, h_log + ) + + assert ana.d_flux_d_phi_left_m2_s_V == pytest.approx(fd_phi_l, rel=1.0e-9, abs=1.0e-9) + assert ana.d_flux_d_phi_right_m2_s_V == pytest.approx(fd_phi_r, rel=1.0e-9, abs=1.0e-9) + assert ana.d_flux_d_c_left_m_s == pytest.approx(fd_c_l, rel=1.0e-9, abs=1.0e-18) + assert ana.d_flux_d_c_right_m_s == pytest.approx(fd_c_r, rel=1.0e-9, abs=1.0e-18) + assert ana.d_flux_d_log_c_left_m2_s == pytest.approx(fd_log_l, rel=1.0e-9, abs=1.0e-9) + assert ana.d_flux_d_log_c_right_m2_s == pytest.approx(fd_log_r, rel=1.0e-9, abs=1.0e-9) + + +@pytest.mark.parametrize("mode", ["harmonic_series", "compact_support", "legacy_logistic"]) +@pytest.mark.parametrize("at_equilibrium", [False, True]) +def test_composite_sg_and_reciprocal_te_jacobians_match_fd( + mode: ThermionicCombinationMode, + at_equilibrium: bool, +) -> None: + temp = 300.0 + vt = thermal_voltage(temp) + chi_l, chi_r = 3.75, 3.95 + eg_l, eg_r = 1.70, 1.55 + nc_l, nc_r = 1.5e25, 4.0e24 + nv_l, nv_r = 2.0e25, 8.0e24 + a_l, a_r = 1.6e5, 4.8e5 + phi_l, phi_r = 0.04, 0.19 + k_sg = 2.5e4 + + bands = fold_dos_into_transport_bands( + np.array([chi_l, chi_r]), + np.array([eg_l, eg_r]), + [np.array([True, False]), np.array([False, True])], + [(nc_l, nv_l), (nc_r, nv_r)], + reference_layer=0, + thermal_voltage_V=vt, + ) + e_step_phys, _ = physical_barrier_steps_eV( + phi_left_V=phi_l, + phi_right_V=phi_r, + chi_phys_left_eV=chi_l, + chi_phys_right_eV=chi_r, + eg_phys_left_eV=eg_l, + eg_phys_right_eV=eg_r, + ) + c_l = 2.0e20 + c_r_eq = c_l * (nc_r / nc_l) * math.exp(-e_step_phys / vt) + c_r = c_r_eq if at_equilibrium else (3.4 * c_r_eq) + + def eval_composite( + pl: float, pr: float, cl: float, cr: float + ) -> ReciprocalThermionicCompositeEvaluation: + d_n = float( + -((pr + bands.transport_electron_affinity_eV[1]) - (pl + bands.transport_electron_affinity_eV[0])) + / vt + ) + sg = stable_sg_particle_flux(cl, cr, d_n, k_sg) + d_sg_d_step = float(sg.energy_step_derivative) + te = reciprocal_thermionic_flux_m2_s( + cl, + cr, + carrier="electron", + phi_left_V=pl, + phi_right_V=pr, + band_offset_eV=chi_l - chi_r, + temperature_K=temp, + a_star_left_A_m2_K2=a_l, + a_star_right_A_m2_K2=a_r, + dos_left_m3=nc_l, + dos_right_m3=nc_r, + ) + return combine_sg_and_reciprocal_thermionic_flux( + float(sg.flux), + d_sg_d_phi_left_m2_s_V=d_sg_d_step / vt, + d_sg_d_phi_right_m2_s_V=-d_sg_d_step / vt, + d_sg_d_c_left_m_s=float(sg.left_density_derivative), + d_sg_d_c_right_m_s=float(sg.right_density_derivative), + c_left_m3=cl, + c_right_m3=cr, + thermionic=te, + combination_mode=mode, + te_softness=0.08, + ) + + ana = eval_composite(phi_l, phi_r, c_l, c_r) + if at_equilibrium: + assert abs(ana.flux_m2_s) <= 1.0e-15 * ana.thermionic.one_way_scale_m2_s + + h_phi = 5.0e-5 + h_log = 5.0e-5 + fd_phi_l = _fourth_order_fd(lambda x: eval_composite(x, phi_r, c_l, c_r).flux_m2_s, phi_l, h_phi) + fd_phi_r = _fourth_order_fd(lambda x: eval_composite(phi_l, x, c_l, c_r).flux_m2_s, phi_r, h_phi) + fd_log_l = _fourth_order_fd( + lambda z: eval_composite(phi_l, phi_r, c_l * math.exp(z), c_r).flux_m2_s, 0.0, h_log + ) + fd_log_r = _fourth_order_fd( + lambda z: eval_composite(phi_l, phi_r, c_l, c_r * math.exp(z)).flux_m2_s, 0.0, h_log + ) + + # harmonic_series and compact_support are C^infinity across m = 0 (<= 1e-9); + # legacy_logistic uses |sg| and |te| magnitudes which are C^1 at m = 0 (O(h) jump in f''). + rel_tol = 5.0e-5 if (at_equilibrium and mode == "legacy_logistic") else 1.0e-9 + assert ana.d_flux_d_phi_left_m2_s_V == pytest.approx(fd_phi_l, rel=rel_tol) + assert ana.d_flux_d_phi_right_m2_s_V == pytest.approx(fd_phi_r, rel=rel_tol) + assert ana.d_flux_d_log_c_left_m2_s == pytest.approx(fd_log_l, rel=rel_tol) + assert ana.d_flux_d_log_c_right_m2_s == pytest.approx(fd_log_r, rel=rel_tol) + + +def test_contact_5mev_gate_alignment_provenance_and_scaps_mirror_historical_record() -> None: + assert CONTACT_THERMODYNAMIC_TOLERANCE_EV == 5.0e-3 + assert set(CONTACT_ALIGNMENT_CLASSES) == { + PARAMETER_FREE_CONTACT_ALIGNMENT, + EXTERNAL_METAL_CONTACT_ALIGNMENT, + FITTED_MANUAL_CONTACT_ALIGNMENT, + } + assert classify_contact_alignment_mode("semiconductor_work_function") == PARAMETER_FREE_CONTACT_ALIGNMENT + assert classify_contact_alignment_mode("metal_work_function") == EXTERNAL_METAL_CONTACT_ALIGNMENT + assert classify_contact_alignment_mode("legacy_manual") == FITTED_MANUAL_CONTACT_ALIGNMENT + with pytest.raises(ValueError, match="unknown built-in-potential mode"): + classify_contact_alignment_mode("fitted_free_offset") + + stack = load_scaps_yaml(str(SCAPS_MIRROR_PRESET)) + grid = build_electrical_grid(stack, 24) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + mat = build_material_arrays(grid, stack) + + left_ep = ContactEndpoint( + float(mat.n_L), + float(mat.p_L), + float(mat.N_C_physical[0]), + float(mat.N_V_physical[0]), + float(mat.chi_phys[0]), + float(mat.Eg_phys[0]), + ) + right_ep = ContactEndpoint( + float(mat.n_R), + float(mat.p_R), + float(mat.N_C_physical[-1]), + float(mat.N_V_physical[-1]), + float(mat.chi_phys[-1]), + float(mat.Eg_phys[-1]), + ) + semi_v_bi = float(stack.compute_semiconductor_V_bi()) + + # 1. Historical scaps_mirror_v2 legacy_manual (6.024958093130e-3 eV) stays permanently inconsistent: + hist = assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=left_ep, + right=right_ep, + V_bi_bc=float(mat.V_bi_bc), + thermal_voltage_V=float(mat.V_T_device), + statistics=mat.carrier_statistics, + semiconductor_potential_V=semi_v_bi, + has_band_reference=True, + ) + assert hist.status == "inconsistent" + assert not hist.certified + assert not hist.is_parameter_free + assert hist.alignment_class == FITTED_MANUAL_CONTACT_ALIGNMENT + assert hist.historical_label == LEGACY_MANUAL_CONTACT_OFFSET + assert hist.fermi_level_span_eV == pytest.approx(6.024958093130e-3, abs=1.0e-12) + with pytest.raises(ContactThermodynamicError, match=LEGACY_MANUAL_CONTACT_OFFSET): + require_contact_thermodynamic_certificate(hist) + with pytest.raises(ContactThermodynamicError, match=LEGACY_MANUAL_CONTACT_OFFSET): + certify_parameter_free_contact_equilibrium(hist) + + # 2. Tolerance > 5.0e-3 eV is rejected with ValueError: + for bad_tol in (5.000001e-3, 6.1e-3, 0.05): + with pytest.raises(ValueError, match="cannot exceed"): + assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=left_ep, + right=right_ep, + V_bi_bc=float(mat.V_bi_bc), + thermal_voltage_V=float(mat.V_T_device), + statistics=mat.carrier_statistics, + semiconductor_potential_V=semi_v_bi, + has_band_reference=True, + tolerance_eV=bad_tol, + ) + + # 3. Even a fitted legacy_manual V_bi tuned inside 5.0 meV is refused by parameter-free gate: + tuned_manual = assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=left_ep, + right=right_ep, + V_bi_bc=semi_v_bi + 2.0e-3, + thermal_voltage_V=float(mat.V_T_device), + statistics=mat.carrier_statistics, + semiconductor_potential_V=semi_v_bi, + has_band_reference=True, + ) + assert tuned_manual.certified + assert not tuned_manual.is_parameter_free + with pytest.raises(ContactThermodynamicError, match="fitted_manual_potential"): + certify_parameter_free_contact_equilibrium(tuned_manual) + + # 4. Compatible parameter-free semiconductor_work_function on the same reservoirs is certified: + stack_compat = dataclasses.replace(stack, built_in_potential_mode="semiconductor_work_function") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + mat_compat = build_material_arrays(grid, stack_compat) + compat = certify_parameter_free_contact_equilibrium( + assess_contact_thermodynamics( + built_in_potential_mode="semiconductor_work_function", + left=left_ep, + right=right_ep, + V_bi_bc=float(mat_compat.V_bi_bc), + thermal_voltage_V=float(mat_compat.V_T_device), + statistics=mat_compat.carrier_statistics, + semiconductor_potential_V=semi_v_bi, + has_band_reference=True, + ) + ) + assert compat.certified + assert compat.is_parameter_free + assert compat.alignment_class == PARAMETER_FREE_CONTACT_ALIGNMENT + assert compat.historical_label is None + assert compat.fermi_level_span_eV is not None and compat.fermi_level_span_eV < 1.0e-12 From fcf299624c9e99733c6886d376e8272260555b8d Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sat, 14 Nov 2026 22:18:24 +0800 Subject: [PATCH 25/46] P(optics): add spectral control-volume Beer-Lambert optics, photon budget, and SCAPS stress certification (P08-04) --- docs/BeerLambertReferenceProtocolV1.md | 144 +++ src/solarlab/device/compile_1d.py | 203 +++- src/solarlab/device/compile_ionic_1d.py | 6 +- .../device/compile_multiple_ionic_1d.py | 3 + src/solarlab/physics/generation/__init__.py | 28 +- .../generation/beer_lambert_spectral.py | 421 +++++++ .../data/ScapsBeerLambertReferenceV1.json | 1005 +++++++++++++++++ src/solarlab/reproducibility/data/__init__.py | 1 + .../reproducibility/scaps_beer_lambert.py | 450 ++++++++ .../test_spectral_beer_lambert_stress.py | 419 +++++++ .../physics/test_beer_lambert_spectral.py | 673 +++++++++++ 11 files changed, 3340 insertions(+), 13 deletions(-) create mode 100644 docs/BeerLambertReferenceProtocolV1.md create mode 100644 src/solarlab/physics/generation/beer_lambert_spectral.py create mode 100644 src/solarlab/reproducibility/data/ScapsBeerLambertReferenceV1.json create mode 100644 src/solarlab/reproducibility/data/__init__.py create mode 100644 src/solarlab/reproducibility/scaps_beer_lambert.py create mode 100644 tests/integration/test_spectral_beer_lambert_stress.py create mode 100644 tests/unit/physics/test_beer_lambert_spectral.py diff --git a/docs/BeerLambertReferenceProtocolV1.md b/docs/BeerLambertReferenceProtocolV1.md new file mode 100644 index 00000000..bbb9ac24 --- /dev/null +++ b/docs/BeerLambertReferenceProtocolV1.md @@ -0,0 +1,144 @@ +# Beer–Lambert Optical Generation & SCAPS Reference Protocol (`V1`) + +This protocol specifies the physical scope, photon-accounting contract, opt-in +compilation boundary, historical numerical stress-case disposition, and +reference-study provenance for `P08-04` (`solarlab`). + +--- + +## 1. Optical Generation Models & Scope Boundaries (`P08-04a` / `P08-04b`) + +Electrical physics selection never implicitly alters the optical generation +model. `solarlab` exposes three distinct optical generation models plus +node-aligned fixed generation resources: + +1. **`beer_lambert` (Monochromatic Scalar Control-Volume Beer–Lambert)**: + - Model ID: `beer_lambert_monochromatic_v1` (`BeerLambertBinding`). + - Uses per-layer scalar `alpha` [$\text{m}^{-1}$] and device-level scalar + photon flux `Phi` [$\text{m}^{-2}\,\text{s}^{-1}$] on electrical control + volumes. + - Applicable to prescribed monochromatic illumination and analytical + verification benchmarks. + +2. **`beer_lambert_spectral` (Single-Pass Spectral Control-Volume Beer–Lambert)**: + - Model ID: `beer_lambert_spectral_front_incidence_v1` + (`SpectralBeerLambertBinding`). + - Uses the same tabulated `k(lambda)` (or constant-index `alpha`), metre + wavelength quadrature, front-prefix optical-only substrate offset, and + `SpectralPhotonFlux` (e.g. ASTM G-173-03 AM1.5G) as spectral TMM, with + per-layer attenuation + $$\alpha_\ell(\lambda) = \frac{4\pi\,k_\ell(\lambda)}{\lambda}$$ + and cancellation-free control-volume cell absorptance + $$A_{\text{cell}}(\lambda) = e^{-\tau_j(\lambda)}\bigl(-\operatorname{expm1}(-\Delta\tau_j(\lambda))\bigr).$$ + - Zero front/internal Fresnel reflection ($R(\lambda) = 0$), zero coherent + standing-wave interference, zero dropped multipass fraction, and no + TMM-derived photon-recycling reabsorption. + - Per-wavelength and trapezoid-integrated photon accounting close to machine + precision on arbitrary uniform, stretched (`tanh`), or two-sided trace + meshes: + $$\text{transmitted} + \sum_{\ell}\text{absorbed}_\ell = \text{incident}.$$ + - Optical-only front prefix layers (`role: substrate`, `electrical=False`, + including `incoherent=True` front glass) attenuate the spectrum entering + the electrical stack (`parasitic_absorbed_m2_s`) without creating + electrical carriers. + - **Applicability vs TMM**: `beer_lambert_spectral` matches idealized + single-pass reference tools (such as SCAPS-1D configured with zero front + reflection) and thick/textured stacks without thin-film Fabry–Pérot cavity + effects. On `scaps_mirror_v2.yaml` (`glass` 1 mm + `spiro_OMeTAD` 20 nm + + `MAPbI3` 800 nm + `TiO2` 25 nm, AM1.5G 300–1000 nm), single-pass spectral + Beer–Lambert absorbs $q\int G\,\mathrm{d}x \approx 260.14\ \text{A}\,\text{m}^{-2}$ + versus $\approx 235.06\ \text{A}\,\text{m}^{-2}$ for coherent-glass TMM + (legacy SCAPS loader effective `incoherent=False`) and + $\approx 232.52\ \text{A}\,\text{m}^{-2}$ for front-incoherent-glass TMM + (declared `incoherent=True`), where air/glass and internal Fresnel + reflections reject ~5-10% of incident photons. Conversely, on stacks with a reflective rear contact or thin + absorber where back-reflection doubles path length, TMM can exceed + single-pass Beer–Lambert. **Larger $J_{\text{sc}}$ under + `beer_lambert_spectral` reflects zero-front-reflection idealization, NOT + physical superiority over TMM.** + +3. **`tmm` (Coherent / Front-Incoherent Transfer-Matrix Optics)**: + - Model ID: `transfer_matrix_front_incidence_v1` (`OpticalStackBinding`). + - Solves Maxwell multilayer Fresnel reflection, transmission, and coherent + standing-wave absorption across planar thin-film stacks. + +4. **Explicit Opt-In Governance & `not_available` External File Loaders**: + - In `P08-04`, `optical_model="beer_lambert_spectral"` is strictly **opt-in** + on `compile_device_1d`, `compile_ionic_device_1d`, and + `compile_multiple_ionic_device_1d` (`optical_model=None` preserves 100% + historical dispatch and bit-identical `H_input`, `H_physics`, and compiled + SHA-256 identities across all certified presets until `P08-05` + re-certification). + - Selecting `"beer_lambert"`, `"beer_lambert_spectral"`, or `"tmm"` produces + three distinct cryptographic `CompiledDevice1D.identity` digests (and + distinct `H_input`/`H_physics` digests when bound through `ModelRegistry`). + - Arbitrary filesystem `profile_file` generation loaders remain explicitly + `not_available`: prescribed spatial generation is admitted solely through + immutable content-hashed `ResourceTable(..., kind="fixed_generation")` + bound to exact compiled node coordinates (`FixedGenerationProfile`). + +--- + +## 2. Historical Stress-Case Witness & New-Core Positivity (`scaps_mirror_v2`) + +In historical `archive/wip-beer-lambert` (`658baa84`), switching +`scaps_mirror_v2.yaml` (`N=60` electrical intervals, 200 wavelengths over +300–1000 nm) to `beer_lambert_spectral` steepened front-of-absorber ultraviolet/blue +generation ($q\int G\,\mathrm{d}x \approx 260.14\ \text{A}\,\text{m}^{-2}$). +Under the legacy density-variable (`[n, p]` linear concentration) Method-of-Lines +Radau transient (`test_interface_flux_balance.py`), hole concentration at the +absorber front (`node 20` of `N=60`, immediately right of the `HTL/PVK` +interface) crossed below zero ($p < 0$), triggering Newton/step-size collapse +and $>600\ \text{s}$ timeouts without ad-hoc post-step density clipping. + +On `solarlab`'s refactored 1D kernel: +- Carrier unknowns use log-activity / quasi-Fermi coordinates (`zn`, `zp`), for + which $n = n_{\text{ref}}\exp((\phi - \phi_{\text{ref}})/V_T + z_n) > 0$ and + $p = p_{\text{ref}}\exp(-(\phi - \phi_{\text{ref}})/V_T - z_p) > 0$ hold + by construction at every Newton iterate without clipping or projection. +- Time integration (`BackwardEuler1DStep` / `solve_transient`) discretizes exact + physical control-volume carrier inventories via cancellation-free secants + $S_{\text{old}}\operatorname{expm1}(\log(c_{\text{new}}/c_{\text{old}}))/\Delta t$, + closing cell-wise and global particle and Maxwell total-current balances on + the `scaps_mirror_v2` `N=60` spectral Beer–Lambert stack across DC steady + state, forward-bias $J\text{--}V$ operating points, and transient illumination + and voltage steps (`tests/integration/test_spectral_beer_lambert_stress.py`). + +--- + +## 3. SCAPS Reference Catalog & Provenance (`ScapsBeerLambertReferenceV1.json`) + +The read-only reference catalog is packaged at +`solarlab.reproducibility.data/ScapsBeerLambertReferenceV1.json` and accessed +through `solarlab.reproducibility.scaps_beer_lambert`: + +- **Workbook Provenance**: Extracted read-only from + `reproducibility/ScapsParams.xlsx` + (`source_sha256 = 862cf0216b08558253268f4ec99fad3e93842c7ce1e9006874ecf03096e9ae3c`). + All **93** workbook parameter points across **11** sweep families (`CHI_ETL`, + `Nd_ETL`, `Nd_PVK`, `Nt_C_PVK`, `Nt_V_PVK`, `Nt_HTL PVK`, `Nt_PVK ETL`, + `Et_C_PVK`, `Et_V_PVK`, `Et_HTL PVK`, `Et_PVK ETL`) are retained, including + unmeasured `CHI_ETL` rows preserved as `null`/`None`. +- **High-Doping `Nd_PVK` Extension**: `load_scaps_beer_lambert_catalog()` + appends two SolarLab-only donor-doping points (`1e19` and `1e20 cm^-3`, + totaling **95** catalog points) marked `origin="solarlab_extension"`, + `row=None`, `reference={"V_oc": None, "J_sc": None, "FF": None, "PCE": None}`, + `scope="high_doping_extrapolation"`, and `min_N_grid=90` (to resolve the + thin Debye length at $10^{20}\ \text{cm}^{-3}$). Because these densities reach + or exceed `SCAPS_PVK`'s configured $N_C = 10^{19}\ \text{cm}^{-3}$, + Maxwell–Boltzmann results at those two points are model extrapolations, not + validated degenerate-Fermi–Dirac predictions. +- **Evidence & Unit Caveats**: + - Historical 2026-07-02 TMM comparisons and `scaps_mirror_v2.yaml`'s legacy + SCAPS-emulation settings (`het_recomb_despike=0.53`, + `flat_band_metal_contacts=True`, `contact_phi_B_eV=0.42`, `V_bi=1.30`) + remain historical disclosures; historical TMM runs must never be relabelled + as Beer–Lambert results. + - In `historical_effective_lifetime` mode, `Nt_C_PVK` and `Nt_V_PVK` scale + the combined effective bulk SRH lifetime (`1/tau_total`) rather than + independent microscopic defect populations (`bulk_defect_mode="species_only"` + must be passed explicitly to edit a single named species). + - Interface defect density sweeps (`Nt_HTL PVK`, `Nt_PVK ETL`) retain the + historical areal `cm^-2` interpretation despite the workbook's `cm^-3` + column header; that upstream workbook header ambiguity remains explicitly + documented rather than silently converted by an invented thickness. diff --git a/src/solarlab/device/compile_1d.py b/src/solarlab/device/compile_1d.py index 84214fcf..dc5f29ee 100644 --- a/src/solarlab/device/compile_1d.py +++ b/src/solarlab/device/compile_1d.py @@ -75,7 +75,16 @@ sheet_charge_row_weights, ) from solarlab.physics.generation.beer_lambert import BeerLambertBinding +from solarlab.physics.generation.beer_lambert_spectral import ( + SpectralBeerLambertBinding, +) from solarlab.physics.generation.fixed import FixedGenerationProfile +from solarlab.physics.generation.optical_binding import ( + OpticalLayerSpec, + constant_index_optical_constants, +) +from solarlab.physics.generation.profile import ControlVolumes +from solarlab.physics.generation.spectrum import SpectralPhotonFlux, sample_nk_table from solarlab.physics.interface_transport import ( EquilibriumReferencedSheetCharge, TE_BARRIER_THRESHOLD_EV, @@ -101,6 +110,9 @@ Q = ELEMENTARY_CHARGE_C InterfaceTopologyName = Literal["deduplicated", "two_sided_trace"] +OpticalModelName = Literal["beer_lambert", "beer_lambert_spectral", "tmm"] +_SPECTRAL_BL_BINDING_1D_V1 = "prepared_spectral_beer_lambert_1d_v1" +_SPECTRAL_BL_BUDGET_RTOL = 1e-12 class _LayerScalars(TypedDict): @@ -136,7 +148,13 @@ class _LayerScalars(TypedDict): grading_char_length: float | None -def unsupported(prepared: PreparedDevice, data: dict[str, Any], layers: tuple[PreparedLayer, ...]) -> None: +def unsupported( + prepared: PreparedDevice, + data: dict[str, Any], + layers: tuple[PreparedLayer, ...], + *, + optical_model: OpticalModelName | None = None, +) -> None: settings = data["settings"] missing = [] if settings["built_in_potential_mode"] != "semiconductor_work_function": @@ -171,13 +189,37 @@ def unsupported(prepared: PreparedDevice, data: dict[str, Any], layers: tuple[Pr missing.extend("tunnelling_channels." + name for name, channel in channels.items() if channel.get("enabled")) declaration = data["declaration"] spectral = declaration.get("spectrum") is not None + scalar_override = optical_model == "beer_lambert" if spectral and declaration.get("fixed_generation") is not None: missing.append("spectrum and fixed_generation are mutually exclusive") + if optical_model is not None and declaration.get("fixed_generation") is not None: + missing.append( + f"optical_model={optical_model!r} and fixed_generation are mutually exclusive" + ) + if optical_model in ("beer_lambert_spectral", "tmm") and not spectral: + missing.append( + f"optical_model={optical_model!r}: requires an explicit spectrum resource" + ) for layer in prepared.layers: if layer.role == "substrate": parameters = dict(layer.parameters) - if not spectral and (parameters["alpha"] != 0.0 or layer.optical is not None or parameters["n_optical"] is not None): - missing.append("layers." + layer.id + ": absorbing/optical substrate generation is not bound") + if scalar_override: + if parameters["alpha"] != 0.0: + missing.append( + "layers." + + layer.id + + ": scalar beer_lambert does not bind absorbing substrates" + ) + elif not spectral and ( + parameters["alpha"] != 0.0 + or layer.optical is not None + or parameters["n_optical"] is not None + ): + missing.append( + "layers." + + layer.id + + ": absorbing/optical substrate generation is not bound" + ) for layer in layers: parameters = dict(layer.parameters) prefix = "layers." + layer.id + "." @@ -199,7 +241,9 @@ def unsupported(prepared: PreparedDevice, data: dict[str, Any], layers: tuple[Pr if any(parameters[name] is not None for name in ("trap_N_t_interface", "trap_N_t_bulk", "trap_decay_length")): missing.append(prefix + "trap_profile") if layer.cigs_graded_optics_json is not None or ( - not spectral and (layer.optical is not None or parameters["n_optical"] is not None) + not spectral + and not scalar_override + and (layer.optical is not None or parameters["n_optical"] is not None) ): missing.append(prefix + "optical_material: requires an explicit spectrum; graded optics is not bound") if missing: @@ -863,6 +907,139 @@ def _layer_input(layer: PreparedLayer) -> LayerParameterInput: ) +def _bind_spectral_beer_lambert_1d( + prepared: PreparedDevice, + control_volumes: ControlVolumes, +) -> GenerationProfile: + """Bind single-pass spectral Beer-Lambert optics to 1D control volumes.""" + + data = prepared.to_mapping() + name = data["declaration"].get("spectrum") + if name is None: + raise CapabilityError( + "beer_lambert_spectral_1d requires an explicit spectrum resource" + ) + if data["declaration"].get("fixed_generation") is not None: + raise CapabilityError( + "beer_lambert_spectral_1d: spectrum and fixed_generation " + "are mutually exclusive" + ) + if data["settings"]["graded_optics"]: + raise CapabilityError("beer_lambert_spectral_1d: graded optics is not bound") + table = prepared.resources.get(name, "spectrum") + if table.units != ("m", "m^-3/s"): + raise CapabilityError( + "beer_lambert_spectral_1d requires spectral photon flux per metre, " + "not irradiance" + ) + wavelengths_nm = table.array[:, 0] * 1e9 + spectrum = SpectralPhotonFlux(wavelengths_nm, table.array[:, 1], table.source.id) + dependencies: dict[str, str] = { + "binding_convention": _SPECTRAL_BL_BINDING_1D_V1, + "prepared_device_sha256": prepared.content_sha256, + "spectrum_resource_sha256": table.content_sha256, + "temperature_K": str(data["settings"]["T"]), + "monochromatic_Phi_policy": "not_used_absolute_spectrum", + } + specs: list[OpticalLayerSpec] = [] + for index, layer in enumerate(prepared.layers): + parameters = dict(layer.parameters) + incoherent = bool(parameters["incoherent"]) + if incoherent and index > 0: + raise CapabilityError( + f"beer_lambert_spectral_1d: {layer.id}: only the front optical " + "layer may be incoherent" + ) + if layer.cigs_graded_optics_json is not None: + raise CapabilityError( + f"beer_lambert_spectral_1d: {layer.id} has unsupported graded optics" + ) + optical = layer.optical + if optical is not None: + if parameters["n_optical"] is not None: + raise CapabilityError( + f"beer_lambert_spectral_1d: {layer.id} must select a table " + "or constant index, not both" + ) + native = optical.array + try: + n, k = sample_nk_table( + native[:, 0] * 1e9, + native[:, 1], + native[:, 2], + wavelengths_nm, + material=optical.name, + ) + except ValueError as error: + raise CapabilityError( + f"beer_lambert_spectral_1d: {layer.id}: {error}" + ) from error + dependencies["nk_resource:" + layer.id] = optical.content_sha256 + else: + if parameters["n_optical"] is None: + raise CapabilityError( + f"beer_lambert_spectral_1d: {layer.id} needs explicit " + "n_optical or an n-k resource" + ) + n, k = constant_index_optical_constants( + wavelengths_nm, + absorption_coefficient_m1=cast(float, parameters["alpha"]), + refractive_index=cast(float, parameters["n_optical"]), + ) + specs.append( + OpticalLayerSpec( + layer.id, + layer.thickness, + n, + k, + incoherent=incoherent, + electrical=layer.role != "substrate", + ) + ) + binding = SpectralBeerLambertBinding( + tuple(specs), + spectrum, + incidence="front", + dependencies=tuple(dependencies.items()), + ) + try: + profile = binding.generation_profile(control_volumes) + budget = binding.photon_budget() + except ValueError as error: + raise CapabilityError("beer_lambert_spectral_1d: " + str(error)) from error + for value in ( + profile.source_m3_s, + profile.absorbed_m2_s, + budget.reflectance, + budget.transmittance, + budget.layer_absorptance, + budget.dropped_multipass, + ): + if not np.all(np.isfinite(value)) or np.any(value < 0.0): + raise CapabilityError( + "beer_lambert_spectral_1d: generation and photon fractions " + "must be finite and nonnegative" + ) + if np.max(np.abs(budget.spectral_closure_residual())) > _SPECTRAL_BL_BUDGET_RTOL: + raise CapabilityError( + "beer_lambert_spectral_1d: spectral photon accounting does not close" + ) + tolerance = _SPECTRAL_BL_BUDGET_RTOL * budget.incident_m2_s + weighted_source = float( + np.sum(profile.source_m3_s * control_volumes.cell_measures_m) + ) + if ( + abs(profile.areal_generation_m2_s - budget.electrical_absorbed_m2_s) + > tolerance + or abs(weighted_source - budget.electrical_absorbed_m2_s) > tolerance + ): + raise CapabilityError( + "beer_lambert_spectral_1d: physical control volumes do not close " + "the electrical photon budget" + ) + return profile + + def compile_device_1d( prepared: PreparedDevice, *, @@ -873,6 +1050,7 @@ def compile_device_1d( te_regularization_mode: TERegularizationName = "legacy_logistic", interface_transmission: float = 1.0, equilibrium_occupancies: Sequence[float] | None = None, + optical_model: OpticalModelName | None = None, ) -> CompiledDevice1D: """Cold compile genuine resolved configuration; no legacy/test execution. @@ -885,6 +1063,15 @@ def compile_device_1d( raise TypeError("compile_device_1d requires an existing PreparedDevice") if interface_topology is not None and interface_topology not in ("deduplicated", "two_sided_trace"): raise ValueError("interface_topology must be 'deduplicated', 'two_sided_trace', or None") + if optical_model is not None and optical_model not in ( + "beer_lambert", + "beer_lambert_spectral", + "tmm", + ): + raise ValueError( + "optical_model must be 'beer_lambert', 'beer_lambert_spectral', " + "'tmm', or None" + ) if te_regularization_mode not in ("legacy_logistic", "compact_support"): raise ValueError("te_regularization_mode must be 'legacy_logistic' or 'compact_support'") if isinstance(te_softness, bool) or not math.isfinite(float(te_softness)) or float(te_softness) < 0.0: @@ -899,7 +1086,7 @@ def compile_device_1d( data = prepared.to_mapping() settings = data["settings"] layers = tuple(layer for layer in prepared.layers if layer.role != "substrate") - unsupported(prepared, data, layers) + unsupported(prepared, data, layers, optical_model=optical_model) resolved_topology: InterfaceTopologyName = ( interface_topology if interface_topology is not None @@ -987,6 +1174,12 @@ def paint(name: str) -> np.ndarray: if table.array.shape != (nodes.size, 2) or not np.array_equal(table.array[:, 0], nodes): raise CapabilityError("fixed_generation: resource coordinates must exactly match the compiled nodes; interpolation is not bound") generation = FixedGenerationProfile(table.array[:, 1], nodes.size).generation_profile(geometry) + elif optical_model == "beer_lambert": + generation = BeerLambertBinding(nodes, paint("alpha"), settings["Phi"]).generation_profile(geometry) + elif optical_model == "beer_lambert_spectral": + generation = _bind_spectral_beer_lambert_1d(prepared, geometry) + elif optical_model == "tmm": + generation = bind_optical_generation_1d(prepared, geometry).profile elif data["declaration"].get("spectrum") is not None: generation = bind_optical_generation_1d(prepared, geometry).profile else: diff --git a/src/solarlab/device/compile_ionic_1d.py b/src/solarlab/device/compile_ionic_1d.py index d981820b..3cc59db3 100644 --- a/src/solarlab/device/compile_ionic_1d.py +++ b/src/solarlab/device/compile_ionic_1d.py @@ -11,7 +11,7 @@ import hashlib import json import math -from typing import Any, cast +from typing import Any, Literal, cast import numpy as np @@ -38,6 +38,7 @@ def compile_ionic_device_1d( ion_domain_endpoints: tuple[str, str] | None = None, te_softness: float = 0.02, te_regularization_mode: TERegularizationName = "legacy_logistic", + optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, ) -> CompiledIonicDevice1D: """Compile independent or shared finite-site ions in one blocking layer. @@ -124,6 +125,7 @@ def compile_ionic_device_1d( intervals_per_layer=intervals_per_layer, te_softness=te_softness, te_regularization_mode=te_regularization_mode, + optical_model=optical_model, ) domain_index = layers.index(domain_layer) left = 0 if domain_index == 0 else component.geometry.interfaces[domain_index - 1].shared_node @@ -201,6 +203,8 @@ def compile_ionic_device_1d( manifest["ion_charge_deposition"]["rule"] = "rho_ion=q*(W_P/W_e)*((P_positive-P0)-(P_negative-P0_neg)); separate historical negative charge group" manifest["state_layout"].update(size=3 * component.node_count + 2 * count, ion_species=["positive", "negative"], ion_species_count=2) + if optical_model is not None: + manifest["electronic_component"]["optical_model"] = optical_model encoded = json.dumps(manifest, sort_keys=True, separators=(",", ":"), allow_nan=False) identity = hashlib.sha256(encoded.encode()).hexdigest() return CompiledIonicDevice1D( diff --git a/src/solarlab/device/compile_multiple_ionic_1d.py b/src/solarlab/device/compile_multiple_ionic_1d.py index af673370..4dc9c61c 100644 --- a/src/solarlab/device/compile_multiple_ionic_1d.py +++ b/src/solarlab/device/compile_multiple_ionic_1d.py @@ -6,6 +6,7 @@ from dataclasses import replace import hashlib import json +from typing import Literal from solarlab.config.resolve_device import resolve_device from solarlab.device.compile_ionic_1d import ION_INPUTS, compile_ionic_device_1d @@ -23,6 +24,7 @@ def compile_multiple_ionic_device_1d( ion_domains: Sequence[tuple[str, tuple[str, str]]], te_softness: float = 0.02, te_regularization_mode: TERegularizationName = "legacy_logistic", + optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, ) -> CompiledMultipleIonicDevice1D: """Exactly two layer-wide blocking domains separated by inactive material. @@ -80,6 +82,7 @@ def compile_multiple_ionic_device_1d( ion_domain_endpoints=endpoints, te_softness=te_softness, te_regularization_mode=te_regularization_mode, + optical_model=optical_model, ) if components: if component.electronic_component.identity != components[0].electronic_component.identity: diff --git a/src/solarlab/physics/generation/__init__.py b/src/solarlab/physics/generation/__init__.py index b91e572b..32a6ad1a 100644 --- a/src/solarlab/physics/generation/__init__.py +++ b/src/solarlab/physics/generation/__init__.py @@ -1,11 +1,11 @@ -"""Optical generation constitutive layer (P04-07, values and DC). +"""Optical generation constitutive layer (P04-07, P08-04, values and DC). -Monochromatic Beer-Lambert, coherent transfer-matrix optics with an optional -incoherent front substrate, explicitly supplied fixed generation arrays and -tabulated spectra/optical constants. Generation is integrated per control -volume (exact absorbed photons per cell) and divided by the caller's cell -measures; optical bindings carry a content identity so a profile is never -reused after its inputs change. Spectral Beer-Lambert is not provided (P08-04). +Monochromatic Beer-Lambert, single-pass spectral control-volume Beer-Lambert, +coherent transfer-matrix optics with an optional incoherent front substrate, +explicitly supplied fixed generation arrays and tabulated spectra/optical +constants. Generation is integrated per control volume (exact absorbed photons +per cell) and divided by the caller's cell measures; optical bindings carry a +content identity so a profile is never reused after its inputs change. """ from solarlab.physics.generation.beer_lambert import ( @@ -15,6 +15,14 @@ beer_lambert_optical_depth, face_optical_depth, ) +from solarlab.physics.generation.beer_lambert_spectral import ( + SPECTRAL_BEER_LAMBERT_MODEL_ID, + SpectralBeerLambertBinding, + spectral_beer_lambert_absorbed_photon_flux_per_cell, + spectral_beer_lambert_absorption_coefficients, + spectral_beer_lambert_absorption_profile, + spectral_beer_lambert_optical_depth, +) from solarlab.physics.generation.fixed import ( BASELINE_GENERATION_REFERENCE, FixedGenerationProfile, @@ -64,7 +72,9 @@ "OpticalLayerSpec", "OpticalStackBinding", "PhotonBudget", + "SPECTRAL_BEER_LAMBERT_MODEL_ID", "SPECTRAL_PHOTON_FLUX_UNIT", + "SpectralBeerLambertBinding", "SpectralPhotonFlux", "StaleGenerationProfileError", "TMMLayer", @@ -79,6 +89,10 @@ "graded_slice_centres", "sample_nk_table", "sample_tabulated", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth", "tmm_absorbed_photon_flux_per_cell", "tmm_absorption_profile", "tmm_cumulative_absorptance", diff --git a/src/solarlab/physics/generation/beer_lambert_spectral.py b/src/solarlab/physics/generation/beer_lambert_spectral.py new file mode 100644 index 00000000..7a71fff6 --- /dev/null +++ b/src/solarlab/physics/generation/beer_lambert_spectral.py @@ -0,0 +1,421 @@ +"""Single-pass spectral control-volume Beer-Lambert optics (P08-04). + +Uses the same material ``k(lambda)``, wavelength grid, front-prefix substrate +coordinate convention, and ``SpectralPhotonFlux`` as ``OpticalStackBinding``, +without Fresnel reflection, coherent wave interference, or TMM-derived photon +recycling. + +Per-layer attenuation uses ``alpha_l(lambda) = 4 * pi * k_l(lambda) / lambda``. +For cumulative optical depth ``tau(z, lambda)``, exact control-volume cell +absorptance is evaluated without thin-cell cancellation via: + + absorbed(cell, lambda) = exp(-tau[:-1]) * -expm1(-diff(tau, axis=0)) + +so per-wavelength and trapezoid-integrated photon accounting close to machine +precision: ``transmitted + sum_layers absorbed == incident`` with zero +reflection and zero dropped multipass fraction. Optical-only front layers +(``electrical=False``, e.g. glass substrate) attenuate the spectrum entering +the electrical stack without creating electrical carriers. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math + +import numpy as np +from numpy.typing import NDArray + +from solarlab.physics.generation._validation import ( + array_digest, + require_cell_faces, + require_node_coordinates, +) +from solarlab.physics.generation.optical_binding import ( + INCIDENCE_SIDES, + OpticalLayerSpec, + OpticalStackBinding, + PhotonBudget, +) +from solarlab.physics.generation.profile import ( + ControlVolumes, + GenerationProfile, + control_volume_digest, + require_control_volumes, +) +from solarlab.physics.generation.spectrum import SpectralPhotonFlux, wavelength_grid_m + +__all__ = [ + "SPECTRAL_BEER_LAMBERT_MODEL_ID", + "SpectralBeerLambertBinding", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth", +] + +SPECTRAL_BEER_LAMBERT_MODEL_ID = "beer_lambert_spectral_front_incidence_v1" +_WINDOW_TOLERANCE_M = 1e-15 + + +def _canonical_dependencies( + value: Mapping[str, object] | Sequence[tuple[str, object]], +) -> tuple[tuple[str, str], ...]: + items = dict(value) if isinstance(value, Mapping) else dict(value) + canonical: list[tuple[str, str]] = [] + for key in sorted(items): + if not isinstance(key, str) or not key.strip(): + raise ValueError("dependency names must be non-empty strings") + raw = items[key] + if isinstance(raw, bool) or not isinstance(raw, (int, float, str)): + raise ValueError(f"dependency {key!r} must be a number or a string") + if isinstance(raw, float) and not math.isfinite(raw): + raise ValueError(f"dependency {key!r} must be finite") + rendered = repr(float(raw)) if isinstance(raw, (int, float)) else raw + canonical.append((key, rendered)) + return tuple(canonical) + + +def _require_wavelengths_m(wavelengths_m: NDArray[np.floating]) -> NDArray[np.float64]: + wl = np.asarray(wavelengths_m, dtype=float) + if wl.ndim != 1 or wl.shape[0] < 2: + raise ValueError( + f"wavelengths_m must be 1-D with at least 2 entries, got {wl.shape}" + ) + if not np.all(np.isfinite(wl)) or np.any(wl <= 0.0) or np.any(np.diff(wl) <= 0.0): + raise ValueError( + "wavelengths_m must be finite, positive, and strictly increasing" + ) + return wl + + +def spectral_beer_lambert_absorption_coefficients( + layers: Sequence[OpticalLayerSpec], + wavelengths_m: NDArray[np.floating], +) -> NDArray[np.float64]: + """Return per-layer ``alpha_l(lambda) = 4 * pi * k_l / lambda`` [m^-1].""" + + if not layers: + raise ValueError("at least one OpticalLayerSpec is required") + wl = _require_wavelengths_m(wavelengths_m) + rows: list[NDArray[np.float64]] = [] + for layer in layers: + if not isinstance(layer, OpticalLayerSpec): + raise TypeError("layers must contain OpticalLayerSpec instances") + if layer.k.shape != wl.shape: + raise ValueError( + f"{layer.name}: k shape {layer.k.shape} does not match {wl.shape}" + ) + alpha = 4.0 * np.pi * layer.k / wl + if not np.all(np.isfinite(alpha)) or np.any(alpha < 0.0): + raise ValueError( + f"{layer.name}: Beer-Lambert absorption coefficients must be " + "finite and nonnegative" + ) + rows.append(alpha) + return np.stack(rows, axis=0) + + +def spectral_beer_lambert_optical_depth( + optical_positions_m: NDArray[np.floating], + layers: Sequence[OpticalLayerSpec], + boundaries_m: NDArray[np.floating], + wavelengths_m: NDArray[np.floating], +) -> NDArray[np.float64]: + """Cumulative optical depth ``tau(z, lambda)`` at optical coordinates ``z``.""" + + positions = np.asarray(optical_positions_m, dtype=float) + if positions.ndim != 1 or positions.shape[0] < 1 or not np.all( + np.isfinite(positions) + ): + raise ValueError("optical_positions_m must be a finite non-empty 1-D array") + bounds = np.asarray(boundaries_m, dtype=float) + if bounds.shape != (len(layers) + 1,): + raise ValueError("boundaries_m must have length len(layers) + 1") + if ( + float(np.min(positions)) < float(bounds[0]) - _WINDOW_TOLERANCE_M + or float(np.max(positions)) > float(bounds[-1]) + _WINDOW_TOLERANCE_M + ): + raise ValueError("optical positions must lie within the optical stack bounds") + alphas = spectral_beer_lambert_absorption_coefficients(layers, wavelengths_m) + tau: NDArray[np.float64] = np.zeros( + (positions.shape[0], alphas.shape[1]), dtype=float + ) + for index, layer in enumerate(layers): + distance = np.clip(positions - bounds[index], 0.0, layer.thickness_m) + tau += distance[:, None] * alphas[index][None, :] + return tau + + +def spectral_beer_lambert_absorbed_photon_flux_per_cell( + layers: Sequence[OpticalLayerSpec], + wavelengths_m: NDArray[np.floating], + spectral_flux_m2_s_m: NDArray[np.floating], + optical_faces_m: NDArray[np.floating], + boundaries_m: NDArray[np.floating], +) -> NDArray[np.float64]: + """Exact single-pass photons absorbed per control volume [m^-2 s^-1].""" + + faces = require_cell_faces(optical_faces_m) + wl = _require_wavelengths_m(wavelengths_m) + flux = np.asarray(spectral_flux_m2_s_m, dtype=float) + if flux.shape != wl.shape or not np.all(np.isfinite(flux)) or np.any(flux < 0.0): + raise ValueError( + "spectral_flux_m2_s_m must be finite, nonnegative, and match wavelengths_m" + ) + tau = spectral_beer_lambert_optical_depth(faces, layers, boundaries_m, wl) + absorbed_fraction = np.exp(-tau[:-1]) * -np.expm1(-np.diff(tau, axis=0)) + integrated = np.trapezoid( + absorbed_fraction * flux[None, :], + x=wl, + axis=1, + ) + return np.asarray(integrated, dtype=float) + + +def spectral_beer_lambert_absorption_profile( + layers: Sequence[OpticalLayerSpec], + wavelengths_m: NDArray[np.floating], + x_optical_m: NDArray[np.floating], + boundaries_m: NDArray[np.floating], +) -> NDArray[np.float64]: + """Point-sampled absorptance density ``alpha(x, lambda) * exp(-tau(x, lambda))``.""" + + x = require_node_coordinates(x_optical_m) + wl = _require_wavelengths_m(wavelengths_m) + bounds = np.asarray(boundaries_m, dtype=float) + alphas = spectral_beer_lambert_absorption_coefficients(layers, wl) + tau = spectral_beer_lambert_optical_depth(x, layers, bounds, wl) + # Right-layer ownership on interior planes, clamping the back endpoint to L-1. + layer_idx = np.clip( + np.searchsorted(bounds[1:], x, side="right"), + 0, + len(layers) - 1, + ) + return np.asarray(alphas[layer_idx] * np.exp(-tau), dtype=float) + + +@dataclass(frozen=True) +class SpectralBeerLambertBinding: + """Frozen single-pass spectral Beer-Lambert optical stack and identity.""" + + layers: tuple[OpticalLayerSpec, ...] + spectrum: SpectralPhotonFlux + incidence: str = "front" + dependencies: tuple[tuple[str, str], ...] = () + sha256: str = field(init=False) + boundaries_m: NDArray[np.float64] = field(init=False, repr=False) + electrical_offset_m: float = field(init=False) + physical_layer_slices: tuple[tuple[str, slice], ...] = field( + init=False, repr=False + ) + + def __post_init__(self) -> None: + layers = tuple(self.layers) + if not layers or not all( + isinstance(item, OpticalLayerSpec) for item in layers + ): + raise ValueError( + "spectral Beer-Lambert binding requires OpticalLayerSpec layers" + ) + if not isinstance(self.spectrum, SpectralPhotonFlux): + raise TypeError("spectrum must be a SpectralPhotonFlux") + n_wl = self.spectrum.wavelengths_nm.shape[0] + if any(item.n.shape != (n_wl,) or item.k.shape != (n_wl,) for item in layers): + raise ValueError( + "every layer's n, k must be sampled on the spectrum's wavelength grid" + ) + if any(item.incoherent for item in layers[1:]): + raise ValueError("only the first optical layer may be incoherent") + seen_electrical = False + for item in layers: + if item.electrical: + seen_electrical = True + elif seen_electrical: + raise ValueError( + "optical-only layers must form a contiguous front prefix" + ) + if not seen_electrical: + raise ValueError( + "spectral Beer-Lambert binding requires at least one electrical layer" + ) + if self.incidence not in INCIDENCE_SIDES: + raise ValueError( + f"incidence must be one of {INCIDENCE_SIDES}; " + "only front illumination exists" + ) + spectral_beer_lambert_absorption_coefficients( + layers, wavelength_grid_m(self.spectrum.wavelengths_nm) + ) + groups: list[tuple[str, slice]] = [] + start = 0 + for index in range(1, len(layers) + 1): + if index == len(layers) or layers[index].name != layers[start].name: + groups.append((layers[start].name, slice(start, index))) + start = index + if len({name for name, _ in groups}) != len(groups): + raise ValueError("slices of one physical layer must be contiguous") + dependencies = _canonical_dependencies(self.dependencies) + boundaries: NDArray[np.float64] = np.empty(len(layers) + 1, dtype=float) + boundaries[0] = 0.0 + boundaries[1:] = np.cumsum([item.thickness_m for item in layers]) + boundaries.setflags(write=False) + offset = float(sum(item.thickness_m for item in layers if not item.electrical)) + object.__setattr__(self, "layers", layers) + object.__setattr__(self, "dependencies", dependencies) + object.__setattr__(self, "boundaries_m", boundaries) + object.__setattr__(self, "electrical_offset_m", offset) + object.__setattr__(self, "physical_layer_slices", tuple(groups)) + object.__setattr__(self, "sha256", self._identity()) + + @classmethod + def from_optical_stack( + cls, + stack: OpticalStackBinding, + *, + dependencies: Mapping[str, object] | Sequence[tuple[str, object]] | None = None, + ) -> SpectralBeerLambertBinding: + """Construct single-pass Beer-Lambert binding from an OpticalStackBinding.""" + + if not isinstance(stack, OpticalStackBinding): + raise TypeError("stack must be an OpticalStackBinding") + deps = stack.dependencies if dependencies is None else _canonical_dependencies( + dependencies + ) + return cls( + layers=stack.layers, + spectrum=stack.spectrum, + incidence=stack.incidence, + dependencies=deps, + ) + + def _identity(self) -> str: + digest = hashlib.sha256() + header = { + "model": SPECTRAL_BEER_LAMBERT_MODEL_ID, + "incidence": self.incidence, + "dependencies": [list(item) for item in self.dependencies], + "spectrum": { + "source_id": self.spectrum.source_id, + "unit": self.spectrum.unit, + "sha256": self.spectrum.sha256, + }, + "layers": [ + { + "name": item.name, + "thickness_m": repr(item.thickness_m), + "electrical": item.electrical, + } + for item in self.layers + ], + } + digest.update( + json.dumps(header, sort_keys=True, separators=(",", ":")).encode("ascii") + ) + digest.update( + array_digest(*[item.k for item in self.layers]).encode("ascii") + ) + return digest.hexdigest() + + @property + def wavelengths_nm(self) -> NDArray[np.float64]: + return self.spectrum.wavelengths_nm + + @property + def wavelengths_m(self) -> NDArray[np.float64]: + return wavelength_grid_m(self.spectrum.wavelengths_nm) + + @property + def electrical_thickness_m(self) -> float: + return float(self.boundaries_m[-1]) - self.electrical_offset_m + + def _optical_faces( + self, electrical_faces_m: NDArray[np.floating] + ) -> NDArray[np.float64]: + faces = require_cell_faces(electrical_faces_m) + optical = faces + self.electrical_offset_m + if ( + float(faces[0]) < -_WINDOW_TOLERANCE_M + or float(optical[-1]) > float(self.boundaries_m[-1]) + _WINDOW_TOLERANCE_M + ): + raise ValueError( + "cell faces must lie inside the electrical window of the optical stack" + ) + return optical + + def absorbed_photon_flux_per_cell( + self, electrical_faces_m: NDArray[np.floating] + ) -> NDArray[np.float64]: + """Exact photons absorbed in each electrical cell [m^-2 s^-1].""" + + absorbed = spectral_beer_lambert_absorbed_photon_flux_per_cell( + self.layers, + self.wavelengths_m, + self.spectrum.flux_m2_s_m, + self._optical_faces(electrical_faces_m), + self.boundaries_m, + ) + absorbed.setflags(write=False) + return absorbed + + def generation_profile(self, control_volumes: ControlVolumes) -> GenerationProfile: + """Photon-conserving spectral Beer-Lambert cell source on control volumes.""" + + _, faces, measures = require_control_volumes(control_volumes) + absorbed = self.absorbed_photon_flux_per_cell(faces) + return GenerationProfile( + method="beer_lambert_spectral", + geometry_name=str(control_volumes.name), + source_m3_s=absorbed / measures, + absorbed_m2_s=absorbed, + binding_sha256=self.sha256, + control_volume_sha256=control_volume_digest(control_volumes), + ) + + def absorption_profile( + self, x_electrical_m: NDArray[np.floating] + ) -> NDArray[np.float64]: + """Point-sampled ``A(x, lambda)`` [m^-1] at electrical positions.""" + + x = require_node_coordinates(x_electrical_m) + optical = x + self.electrical_offset_m + if ( + float(x[0]) < -_WINDOW_TOLERANCE_M + or float(optical[-1]) > float(self.boundaries_m[-1]) + _WINDOW_TOLERANCE_M + ): + raise ValueError( + "node coordinates must lie inside the electrical window " + "of the optical stack" + ) + return spectral_beer_lambert_absorption_profile( + self.layers, + self.wavelengths_m, + optical, + self.boundaries_m, + ) + + def photon_budget(self) -> PhotonBudget: + """Exact single-pass photon bookkeeping (zero reflection and multipass drop).""" + + wl = self.wavelengths_m + tau_bounds = spectral_beer_lambert_optical_depth( + self.boundaries_m, self.layers, self.boundaries_m, wl + ) + layer_absorptance = np.exp(-tau_bounds[:-1]) * -np.expm1( + -np.diff(tau_bounds, axis=0) + ) + transmittance = np.exp(-tau_bounds[-1]) + zeros = np.zeros_like(wl) + return PhotonBudget( + wavelengths_nm=self.wavelengths_nm, + incident_spectral_m2_s_m=self.spectrum.flux_m2_s_m, + reflectance=zeros, + transmittance=transmittance, + layer_absorptance=layer_absorptance, + dropped_multipass=zeros.copy(), + layer_names=tuple(item.name for item in self.layers), + layer_electrical=tuple(item.electrical for item in self.layers), + ) diff --git a/src/solarlab/reproducibility/data/ScapsBeerLambertReferenceV1.json b/src/solarlab/reproducibility/data/ScapsBeerLambertReferenceV1.json new file mode 100644 index 00000000..1f35dea7 --- /dev/null +++ b/src/solarlab/reproducibility/data/ScapsBeerLambertReferenceV1.json @@ -0,0 +1,1005 @@ +{ + "schema_version": 1, + "study": "scaps_beer_lambert_v1", + "source": "reproducibility/ScapsParams.xlsx", + "source_sha256": "862cf0216b08558253268f4ec99fad3e93842c7ce1e9006874ecf03096e9ae3c", + "interface_density_note": "Workbook labels cm^-3; historical study and interface parser use areal cm^-2. No volumetric conversion is inferred.", + "sweeps": { + "CHI_ETL": { + "title": "ETL/PVK conduction-band offset", + "unit": "eV", + "points": [ + { + "x": -1.0, + "row": 2, + "reference": { + "V_oc": 0.332353, + "J_sc": 26.30453758, + "FF": 67.1265, + "PCE": 5.8685 + } + }, + { + "x": -0.75, + "row": 3, + "reference": { + "V_oc": 0.580953, + "J_sc": 26.28893747, + "FF": 77.4679, + "PCE": 11.8314 + } + }, + { + "x": -0.5, + "row": 4, + "reference": { + "V_oc": 0.83085, + "J_sc": 26.28440831, + "FF": 82.791, + "PCE": 18.0802 + } + }, + { + "x": -0.25, + "row": 5, + "reference": { + "V_oc": 1.080493, + "J_sc": 26.28239324, + "FF": 85.9878, + "PCE": 24.4188 + } + }, + { + "x": -0.2, + "row": 6, + "reference": { + "V_oc": 1.129308, + "J_sc": 26.28208431, + "FF": 86.5152, + "PCE": 25.6782 + } + }, + { + "x": -0.16, + "row": 7, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": -0.1, + "row": 8, + "reference": { + "V_oc": 1.217203, + "J_sc": 26.28153965, + "FF": 88.0108, + "PCE": 28.1546 + } + }, + { + "x": -0.05, + "row": 9, + "reference": { + "V_oc": 1.240043, + "J_sc": 26.28156065, + "FF": 89.4021, + "PCE": 29.1364 + } + }, + { + "x": 0.0, + "row": 10, + "reference": { + "V_oc": 1.247696, + "J_sc": 26.28148444, + "FF": 90.424, + "PCE": 29.6512 + } + }, + { + "x": 0.1, + "row": 11, + "reference": { + "V_oc": 1.250391, + "J_sc": 26.28116069, + "FF": 90.7313, + "PCE": 29.8159 + } + }, + { + "x": 0.2, + "row": 12, + "reference": { + "V_oc": 1.250158, + "J_sc": 26.28140832, + "FF": 90.7096, + "PCE": 29.8035 + } + }, + { + "x": 0.3, + "row": 13, + "reference": { + "V_oc": 1.249937, + "J_sc": 26.28168179, + "FF": 90.4411, + "PCE": 29.7103 + } + }, + { + "x": 0.4, + "row": 14, + "reference": { + "V_oc": 1.248839, + "J_sc": 26.28238752, + "FF": 65.1522, + "PCE": 21.3846 + } + }, + { + "x": 0.5, + "row": 15, + "reference": { + "V_oc": 1.228325, + "J_sc": 2.45338907, + "FF": 23.7528, + "PCE": 0.7158 + } + }, + { + "x": 0.6, + "row": 16, + "reference": { + "V_oc": null, + "J_sc": null, + "FF": null, + "PCE": null + } + }, + { + "x": 0.7, + "row": 17, + "reference": { + "V_oc": null, + "J_sc": null, + "FF": null, + "PCE": null + } + } + ] + }, + "Nd_ETL": { + "title": "ETL donor doping", + "unit": "cm^-3", + "points": [ + { + "x": 10000000000.0, + "row": 2, + "reference": { + "V_oc": 1.100196, + "J_sc": 26.29049969, + "FF": 60.8285, + "PCE": 17.5945 + } + }, + { + "x": 100000000000.0, + "row": 3, + "reference": { + "V_oc": 1.12464, + "J_sc": 26.28959355, + "FF": 64.3912, + "PCE": 19.0381 + } + }, + { + "x": 1000000000000.0, + "row": 4, + "reference": { + "V_oc": 1.132448, + "J_sc": 26.28887261, + "FF": 68.8235, + "PCE": 20.4893 + } + }, + { + "x": 10000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.137615, + "J_sc": 26.28758643, + "FF": 73.3378, + "PCE": 21.9318 + } + }, + { + "x": 100000000000000.0, + "row": 6, + "reference": { + "V_oc": 1.141248, + "J_sc": 26.2870558, + "FF": 77.5039, + "PCE": 23.2512 + } + }, + { + "x": 1000000000000000.0, + "row": 7, + "reference": { + "V_oc": 1.143994, + "J_sc": 26.28631476, + "FF": 80.3336, + "PCE": 24.1574 + } + }, + { + "x": 1e+16, + "row": 8, + "reference": { + "V_oc": 1.14637, + "J_sc": 26.28571211, + "FF": 82.1615, + "PCE": 24.7579 + } + }, + { + "x": 1e+17, + "row": 9, + "reference": { + "V_oc": 1.151017, + "J_sc": 26.28415867, + "FF": 84.3099, + "PCE": 25.5067 + } + }, + { + "x": 1e+18, + "row": 10, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 1e+19, + "row": 11, + "reference": { + "V_oc": 1.202403, + "J_sc": 26.28131988, + "FF": 88.9143, + "PCE": 28.0976 + } + }, + { + "x": 1e+20, + "row": 12, + "reference": { + "V_oc": 1.237259, + "J_sc": 26.28120163, + "FF": 90.063, + "PCE": 29.2855 + } + } + ] + }, + "Nd_PVK": { + "title": "PVK donor doping", + "unit": "cm^-3", + "points": [ + { + "x": 100000000.0, + "row": 2, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.282, + "FF": 86.9875, + "PCE": 26.6926 + } + }, + { + "x": 10000000000.0, + "row": 3, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.282, + "FF": 86.9875, + "PCE": 26.6926 + } + }, + { + "x": 1000000000000.0, + "row": 4, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.282, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 100000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.16758, + "J_sc": 26.2818, + "FF": 86.996, + "PCE": 26.6957 + } + }, + { + "x": 1e+16, + "row": 6, + "reference": { + "V_oc": 1.17073, + "J_sc": 26.2783, + "FF": 87.3175, + "PCE": 26.863 + } + }, + { + "x": 1e+18, + "row": 7, + "reference": { + "V_oc": 1.20157, + "J_sc": 20.9425, + "FF": 65.8337, + "PCE": 16.5663 + } + } + ] + }, + "Nt_C_PVK": { + "title": "PVK-CB effective bulk defect density", + "unit": "cm^-3", + "points": [ + { + "x": 1000000000.0, + "row": 2, + "reference": { + "V_oc": 1.167649, + "J_sc": 26.28199434, + "FF": 86.9829, + "PCE": 26.6934 + } + }, + { + "x": 10000000000.0, + "row": 3, + "reference": { + "V_oc": 1.167648, + "J_sc": 26.28199434, + "FF": 86.983, + "PCE": 26.6934 + } + }, + { + "x": 100000000000.0, + "row": 4, + "reference": { + "V_oc": 1.167639, + "J_sc": 26.28199429, + "FF": 86.9834, + "PCE": 26.6934 + } + }, + { + "x": 1000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 10000000000000.0, + "row": 6, + "reference": { + "V_oc": 1.166683, + "J_sc": 26.28198853, + "FF": 87.0283, + "PCE": 26.6853 + } + }, + { + "x": 100000000000000.0, + "row": 7, + "reference": { + "V_oc": 1.159563, + "J_sc": 26.2819362, + "FF": 87.3396, + "PCE": 26.6172 + } + }, + { + "x": 1000000000000000.0, + "row": 8, + "reference": { + "V_oc": 1.129075, + "J_sc": 26.28141294, + "FF": 88.0927, + "PCE": 26.1403 + } + } + ] + }, + "Nt_V_PVK": { + "title": "PVK-VB effective bulk defect density", + "unit": "cm^-3", + "points": [ + { + "x": 1000000000.0, + "row": 2, + "reference": { + "V_oc": 1.167564, + "J_sc": 26.28199389, + "FF": 86.9868, + "PCE": 26.6927 + } + }, + { + "x": 10000000000.0, + "row": 3, + "reference": { + "V_oc": 1.167564, + "J_sc": 26.28199389, + "FF": 86.9869, + "PCE": 26.6927 + } + }, + { + "x": 100000000000.0, + "row": 4, + "reference": { + "V_oc": 1.167563, + "J_sc": 26.28199388, + "FF": 86.9869, + "PCE": 26.6927 + } + }, + { + "x": 1000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 10000000000000.0, + "row": 6, + "reference": { + "V_oc": 1.167422, + "J_sc": 26.28199259, + "FF": 86.9942, + "PCE": 26.6917 + } + }, + { + "x": 100000000000000.0, + "row": 7, + "reference": { + "V_oc": 1.16619, + "J_sc": 26.2819808, + "FF": 87.0572, + "PCE": 26.6829 + } + }, + { + "x": 1000000000000000.0, + "row": 8, + "reference": { + "V_oc": 1.156805, + "J_sc": 26.28186293, + "FF": 87.4982, + "PCE": 26.6021 + } + } + ] + }, + "Nt_HTL PVK": { + "title": "HTL/PVK interface defect density", + "unit": "cm^-2", + "points": [ + { + "x": 1000000000.0, + "row": 2, + "reference": { + "V_oc": 1.167556, + "J_sc": 26.28199633, + "FF": 86.9873, + "PCE": 26.6927 + } + }, + { + "x": 10000000000.0, + "row": 3, + "reference": { + "V_oc": 1.167556, + "J_sc": 26.28199631, + "FF": 86.9873, + "PCE": 26.6927 + } + }, + { + "x": 100000000000.0, + "row": 4, + "reference": { + "V_oc": 1.167555, + "J_sc": 26.28199608, + "FF": 86.9873, + "PCE": 26.6927 + } + }, + { + "x": 1000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 10000000000000.0, + "row": 6, + "reference": { + "V_oc": 1.167495, + "J_sc": 26.28197063, + "FF": 86.9904, + "PCE": 26.6922 + } + }, + { + "x": 100000000000000.0, + "row": 7, + "reference": { + "V_oc": 1.166958, + "J_sc": 26.28173937, + "FF": 87.018, + "PCE": 26.6882 + } + }, + { + "x": 1000000000000000.0, + "row": 8, + "reference": { + "V_oc": 1.16235, + "J_sc": 26.27943401, + "FF": 87.2429, + "PCE": 26.6491 + } + } + ] + }, + "Nt_PVK ETL": { + "title": "PVK/ETL interface defect density", + "unit": "cm^-2", + "points": [ + { + "x": 1000000000.0, + "row": 2, + "reference": { + "V_oc": 1.249473, + "J_sc": 26.28199622, + "FF": 90.7999, + "PCE": 29.8175 + } + }, + { + "x": 10000000000.0, + "row": 3, + "reference": { + "V_oc": 1.248254, + "J_sc": 26.2819962, + "FF": 90.2795, + "PCE": 29.6176 + } + }, + { + "x": 100000000000.0, + "row": 4, + "reference": { + "V_oc": 1.23572, + "J_sc": 26.28199597, + "FF": 87.6373, + "PCE": 28.4621 + } + }, + { + "x": 1000000000000.0, + "row": 5, + "reference": { + "V_oc": 1.167551, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 10000000000000.0, + "row": 6, + "reference": { + "V_oc": 1.088511, + "J_sc": 26.28197167, + "FF": 87.5539, + "PCE": 25.0476 + } + }, + { + "x": 100000000000000.0, + "row": 7, + "reference": { + "V_oc": 1.022812, + "J_sc": 26.28175152, + "FF": 87.2634, + "PCE": 23.4575 + } + }, + { + "x": 1000000000000000.0, + "row": 8, + "reference": { + "V_oc": 0.967755, + "J_sc": 26.27962552, + "FF": 86.2206, + "PCE": 21.9278 + } + } + ] + }, + "Et_C_PVK": { + "title": "PVK-CB effective bulk defect depth", + "unit": "eV", + "points": [ + { + "x": 0.01, + "row": 2, + "reference": { + "V_oc": 1.167645, + "J_sc": 26.2819943, + "FF": 86.9831, + "PCE": 26.6934 + } + }, + { + "x": 0.05, + "row": 3, + "reference": { + "V_oc": 1.16763, + "J_sc": 26.28199418, + "FF": 86.9839, + "PCE": 26.6933 + } + }, + { + "x": 0.1, + "row": 4, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.2, + "row": 5, + "reference": { + "V_oc": 1.167246, + "J_sc": 26.2819914, + "FF": 86.9736, + "PCE": 26.6814 + } + }, + { + "x": 0.3, + "row": 6, + "reference": { + "V_oc": 1.167217, + "J_sc": 26.28198587, + "FF": 86.9563, + "PCE": 26.6754 + } + }, + { + "x": 0.4, + "row": 7, + "reference": { + "V_oc": 1.167216, + "J_sc": 26.28196862, + "FF": 86.9558, + "PCE": 26.6752 + } + }, + { + "x": 0.5, + "row": 8, + "reference": { + "V_oc": 1.167216, + "J_sc": 26.28196368, + "FF": 86.9558, + "PCE": 26.6752 + } + }, + { + "x": 0.6, + "row": 9, + "reference": { + "V_oc": 1.167216, + "J_sc": 26.28196354, + "FF": 86.9558, + "PCE": 26.6752 + } + } + ] + }, + "Et_V_PVK": { + "title": "PVK-VB effective bulk defect level", + "unit": "eV", + "points": [ + { + "x": 0.01, + "row": 2, + "reference": { + "V_oc": 1.167564, + "J_sc": 26.28199389, + "FF": 86.9869, + "PCE": 26.6927 + } + }, + { + "x": 0.05, + "row": 3, + "reference": { + "V_oc": 1.167562, + "J_sc": 26.28199387, + "FF": 86.987, + "PCE": 26.6927 + } + }, + { + "x": 0.1, + "row": 4, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.2, + "row": 5, + "reference": { + "V_oc": 1.167305, + "J_sc": 26.28199256, + "FF": 86.9949, + "PCE": 26.6892 + } + }, + { + "x": 0.3, + "row": 6, + "reference": { + "V_oc": 1.167139, + "J_sc": 26.28198922, + "FF": 86.9645, + "PCE": 26.6761 + } + }, + { + "x": 0.4, + "row": 7, + "reference": { + "V_oc": 1.167133, + "J_sc": 26.28197931, + "FF": 86.9597, + "PCE": 26.6745 + } + }, + { + "x": 0.5, + "row": 8, + "reference": { + "V_oc": 1.167133, + "J_sc": 26.2819643, + "FF": 86.9597, + "PCE": 26.6745 + } + }, + { + "x": 0.6, + "row": 9, + "reference": { + "V_oc": 1.167133, + "J_sc": 26.28196311, + "FF": 86.9597, + "PCE": 26.6745 + } + } + ] + }, + "Et_HTL PVK": { + "title": "HTL/PVK interface defect depth", + "unit": "eV", + "points": [ + { + "x": 0.01, + "row": 2, + "reference": { + "V_oc": 1.167556, + "J_sc": 26.28199611, + "FF": 86.9873, + "PCE": 26.6927 + } + }, + { + "x": 0.05, + "row": 3, + "reference": { + "V_oc": 1.167554, + "J_sc": 26.28199554, + "FF": 86.9874, + "PCE": 26.6926 + } + }, + { + "x": 0.1, + "row": 4, + "reference": { + "V_oc": 1.167551, + "J_sc": 26.28199439, + "FF": 86.9875, + "PCE": 26.6926 + } + }, + { + "x": 0.2, + "row": 5, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199378, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.3, + "row": 6, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.4, + "row": 7, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.5, + "row": 8, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.6, + "row": 9, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + } + ] + }, + "Et_PVK ETL": { + "title": "PVK/ETL interface defect depth", + "unit": "eV", + "points": [ + { + "x": 0.01, + "row": 2, + "reference": { + "V_oc": 1.201974, + "J_sc": 26.28199587, + "FF": 87.7951, + "PCE": 27.7347 + } + }, + { + "x": 0.05, + "row": 3, + "reference": { + "V_oc": 1.187526, + "J_sc": 26.2819956, + "FF": 87.6463, + "PCE": 27.3549 + } + }, + { + "x": 0.1, + "row": 4, + "reference": { + "V_oc": 1.177299, + "J_sc": 26.28199504, + "FF": 87.2819, + "PCE": 27.0066 + } + }, + { + "x": 0.2, + "row": 5, + "reference": { + "V_oc": 1.168613, + "J_sc": 26.28199408, + "FF": 87.0458, + "PCE": 26.7348 + } + }, + { + "x": 0.3, + "row": 6, + "reference": { + "V_oc": 1.16755, + "J_sc": 26.28199376, + "FF": 86.9876, + "PCE": 26.6926 + } + }, + { + "x": 0.4, + "row": 7, + "reference": { + "V_oc": 1.167495, + "J_sc": 26.28199374, + "FF": 86.9831, + "PCE": 26.69 + } + }, + { + "x": 0.5, + "row": 8, + "reference": { + "V_oc": 1.167494, + "J_sc": 26.28199374, + "FF": 86.9829, + "PCE": 26.6899 + } + }, + { + "x": 0.6, + "row": 9, + "reference": { + "V_oc": 1.167494, + "J_sc": 26.28199374, + "FF": 86.9829, + "PCE": 26.6899 + } + } + ] + } + } +} diff --git a/src/solarlab/reproducibility/data/__init__.py b/src/solarlab/reproducibility/data/__init__.py new file mode 100644 index 00000000..9dac01db --- /dev/null +++ b/src/solarlab/reproducibility/data/__init__.py @@ -0,0 +1 @@ +"""Packaged immutable reference study tables for reproducibility contracts.""" diff --git a/src/solarlab/reproducibility/scaps_beer_lambert.py b/src/solarlab/reproducibility/scaps_beer_lambert.py new file mode 100644 index 00000000..8a460e90 --- /dev/null +++ b/src/solarlab/reproducibility/scaps_beer_lambert.py @@ -0,0 +1,450 @@ +"""Read-only SCAPS Beer-Lambert reference catalog and parameter-point contract. + +Packages the 11-family SCAPS reference table extracted from +``reproducibility/ScapsParams.xlsx`` (93 workbook rows, retaining unmeasured +CBO rows as ``None``) plus the two SolarLab-only high-doping ``Nd_PVK`` +extrapolation points (``1e19`` and ``1e20 cm^-3`` with ``min_N_grid=90`` and +``None`` reference metrics). + +Historical parameter-sweep note: +- In ``historical_effective_lifetime`` mode (default), ``Nt_C_PVK`` and + ``Nt_V_PVK`` scale the combined absorber bulk defect inventory so that + ``1/tau_total`` reproduces the historical effective-lifetime sweep, while + ``Et_C_PVK`` and ``Et_V_PVK`` set the referenced effective trap depth; they + are NOT independent microscopic-species validation unless + ``bulk_defect_mode="species_only"`` is explicitly requested. +- Interface density sweeps (``Nt_HTL PVK``, ``Nt_PVK ETL``) retain the + historical areal ``cm^-2`` interpretation despite the workbook's ``cm^-3`` + column header; no synthetic thickness conversion is inferred. +""" + +from __future__ import annotations + +from copy import deepcopy +from importlib import resources +import json +import math +from typing import Any, Literal + +from solarlab.device.inputs import DeviceInput +from solarlab.physics.contacts import ContactMaterial, semiconductor_work_function +from solarlab.physics.statistics.thermal import thermal_voltage + +__all__ = [ + "EXTRA_SWEEP_POINTS", + "HIGH_DOPING_MIN_N_GRID", + "SCAPS_BEER_LAMBERT_RESOURCE", + "SCAPS_BEER_LAMBERT_STUDY_ID", + "STANDARD_JV_SWEEP_HINTS", + "SWEEPS", + "apply_reference_point", + "load_scaps_beer_lambert_catalog", + "reference_catalog", + "validate_reference_point", +] + +SCAPS_BEER_LAMBERT_STUDY_ID = "scaps_beer_lambert_v1" +SCAPS_BEER_LAMBERT_RESOURCE = "ScapsBeerLambertReferenceV1.json" +EXTRA_SWEEP_POINTS: dict[str, tuple[float, ...]] = { + "Nd_PVK": (1.0e19, 1.0e20), +} +STANDARD_JV_SWEEP_HINTS: dict[str, int | float] = { + "N_grid": 30, + "n_points": 40, + "v_rate": 5.0, + "V_max": 1.6, +} +HIGH_DOPING_MIN_N_GRID = 90 +BulkDefectSweepMode = Literal["historical_effective_lifetime", "species_only"] + +SWEEPS: dict[str, tuple[str, str, str, dict[str, str]]] = { + "CHI_ETL": ( + "ETL/PVK conduction-band offset", + "eV", + "etl_delta_ec_eV", + {}, + ), + "Nd_ETL": ( + "ETL donor doping", + "cm^-3", + "etl_doping_cm3", + {}, + ), + "Nd_PVK": ( + "PVK donor doping", + "cm^-3", + "absorber_doping_cm3", + {"absorber_doping_type": "donor"}, + ), + "Nt_C_PVK": ( + "PVK-CB effective bulk defect density", + "cm^-3", + "absorber_defect_density_cm3", + {"species_name": "Perovskite-CB"}, + ), + "Nt_V_PVK": ( + "PVK-VB effective bulk defect density", + "cm^-3", + "absorber_defect_density_cm3", + {"species_name": "Perovskite-VB"}, + ), + "Nt_HTL PVK": ( + "HTL/PVK interface defect density", + "cm^-2", + "interface_defect_N_t_cm2", + {"interface_defect_target": "htl/pvk"}, + ), + "Nt_PVK ETL": ( + "PVK/ETL interface defect density", + "cm^-2", + "interface_defect_N_t_cm2", + {"interface_defect_target": "pvk/etl"}, + ), + "Et_C_PVK": ( + "PVK-CB effective bulk defect depth", + "eV", + "absorber_defect_depth_eV", + { + "trap_depth_reference": "below_conduction_band", + "species_name": "Perovskite-CB", + }, + ), + "Et_V_PVK": ( + "PVK-VB effective bulk defect level", + "eV", + "absorber_defect_depth_eV", + { + "trap_depth_reference": "above_valence_band", + "species_name": "Perovskite-VB", + }, + ), + "Et_HTL PVK": ( + "HTL/PVK interface defect depth", + "eV", + "interface_defect_E_t_eV", + {"interface_defect_target": "htl/pvk"}, + ), + "Et_PVK ETL": ( + "PVK/ETL interface defect depth", + "eV", + "interface_defect_E_t_eV", + {"interface_defect_target": "pvk/etl"}, + ), +} + + +def load_scaps_beer_lambert_catalog() -> dict[str, Any]: + """Return a fresh copy of the 11-family SCAPS Beer-Lambert catalog.""" + + raw = ( + resources.files("solarlab.reproducibility.data") + .joinpath(SCAPS_BEER_LAMBERT_RESOURCE) + .read_text(encoding="utf-8") + ) + catalog: dict[str, Any] = json.loads(raw) + for sweep, values in EXTRA_SWEEP_POINTS.items(): + entry = catalog["sweeps"][sweep] + entry["workbook_max"] = max(float(point["x"]) for point in entry["points"]) + entry["points"].extend( + { + "x": float(val), + "row": None, + "origin": "solarlab_extension", + "reference": { + key: None for key in ("V_oc", "J_sc", "FF", "PCE") + }, + } + for val in values + ) + return catalog + + +def reference_catalog() -> dict[str, Any]: + """Alias matching the historical validation catalog entry point.""" + + return load_scaps_beer_lambert_catalog() + + +def validate_reference_point(sweep: str, value: float) -> dict[str, Any]: + """Validate ``(sweep, value)`` fail-closed and return point metadata.""" + + if not isinstance(sweep, str) or sweep not in SWEEPS: + raise ValueError(f"Unknown SCAPS reference sweep: {sweep!r}") + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(float(value)) + ): + raise ValueError("Reference point value must be a finite real number") + numeric = float(value) + catalog = load_scaps_beer_lambert_catalog() + entry = catalog["sweeps"][sweep] + points = entry["points"] + xs = [float(row["x"]) for row in points] + if numeric < min(xs) or numeric > max(xs): + raise ValueError( + f"Reference point {numeric!r} is outside {sweep!r} scan interval " + f"[{min(xs)}, {max(xs)}]" + ) + workbook_max = entry.get("workbook_max") + is_extension = workbook_max is not None and numeric > float(workbook_max) + min_n_grid = ( + HIGH_DOPING_MIN_N_GRID + if is_extension + else int(STANDARD_JV_SWEEP_HINTS["N_grid"]) + ) + title, unit, key, extra = SWEEPS[sweep] + jv_hints = dict(STANDARD_JV_SWEEP_HINTS) + jv_hints["N_grid"] = min_n_grid + return { + "reference_study": SCAPS_BEER_LAMBERT_STUDY_ID, + "sweep": sweep, + "value": numeric, + "unit": unit, + "title": title, + "handler_key": key, + "handler_extra": dict(extra), + "optical_model": "beer_lambert_spectral", + "scope": ( + "high_doping_extrapolation" if is_extension else "workbook_interval" + ), + "min_N_grid": min_n_grid, + "jv_sweep": jv_hints, + } + + +def _find_layer_by_role( + layers: list[dict[str, Any]], + role: str, +) -> dict[str, Any]: + matches = [ + layer + for layer in layers + if str(layer.get("role", "")).lower() == role.lower() + ] + if len(matches) != 1: + raise ValueError(f"Expected exactly one {role!r} layer, found {len(matches)}") + return matches[0] + + +def _find_interface_by_roles( + layers: list[dict[str, Any]], + interfaces: list[dict[str, Any]], + target: str, +) -> dict[str, Any]: + role_alias = { + "pvk": "absorber", + "perovskite": "absorber", + "absorber": "absorber", + "htl": "htl", + "etl": "etl", + } + parts = [role_alias.get(p.strip().lower(), p.strip().lower()) for p in target.split("/")] + if len(parts) != 2: + raise ValueError(f"Expected directed interface target LEFT/RIGHT, got {target!r}") + by_id = {str(layer["id"]): str(layer["role"]).lower() for layer in layers} + matches = [ + iface + for iface in interfaces + if [by_id.get(str(iface.get("left"))), by_id.get(str(iface.get("right")))] + == parts + ] + if len(matches) != 1: + raise ValueError( + f"Expected one directed interface matching {target!r}, found {len(matches)}" + ) + return matches[0] + + +def _recompute_doped_vbi(data: dict[str, Any]) -> float | None: + electrical = [ + layer + for layer in data["layers"] + if str(layer.get("role", "")).lower() != "substrate" + ] + if len(electrical) < 2: + return None + temp = float(data.get("settings", {}).get("T", 300.0)) + + def _wf(layer: dict[str, Any]) -> float | None: + p = layer.get("parameters", {}) + required = ("chi", "Eg", "Nc300", "Nv300") + if any(p.get(k) is None for k in required): + return None + mat = ContactMaterial( + temperature_K=temp, + electron_affinity_eV=float(p["chi"]), + band_gap_eV=float(p["Eg"]), + conduction_dos_m3=float(p["Nc300"]), + valence_dos_m3=float(p["Nv300"]), + donor_density_m3=float(p.get("N_D", 0.0) or 0.0), + acceptor_density_m3=float(p.get("N_A", 0.0) or 0.0), + ) + return semiconductor_work_function(mat) + + wf_left = _wf(electrical[0]) + wf_right = _wf(electrical[-1]) + if wf_left is None or wf_right is None: + return None + return float(wf_left - wf_right) + + +def apply_reference_point( + device: DeviceInput, + sweep: str, + value: float, + *, + sync_vbi: bool = True, + bulk_defect_mode: BulkDefectSweepMode = "historical_effective_lifetime", +) -> tuple[DeviceInput, dict[str, Any]]: + """Apply one SCAPS Beer-Lambert reference point to a ``DeviceInput``.""" + + if not isinstance(device, DeviceInput): + raise TypeError("device must be a DeviceInput") + if bulk_defect_mode not in ("historical_effective_lifetime", "species_only"): + raise ValueError( + "bulk_defect_mode must be 'historical_effective_lifetime' or 'species_only'" + ) + meta = validate_reference_point(sweep, value) + numeric = float(meta["value"]) + key = str(meta["handler_key"]) + extra: dict[str, str] = dict(meta["handler_extra"]) + + data = deepcopy(device.editing_data()) + # Editing canonical parameters clears original source-byte legacy_fields check + # only if the caller re-resolves without changing source_id; retain settings/layers. + data.pop("legacy_fields", None) + layers: list[dict[str, Any]] = data["layers"] + interfaces: list[dict[str, Any]] = data.setdefault("interfaces", []) + + if key == "etl_delta_ec_eV": + pvk = _find_layer_by_role(layers, "absorber") + etl = _find_layer_by_role(layers, "etl") + chi_pvk = float(pvk["parameters"]["chi"]) + etl.setdefault("parameters", {})["chi"] = chi_pvk - numeric + elif key == "etl_doping_cm3": + etl = _find_layer_by_role(layers, "etl") + params = etl.setdefault("parameters", {}) + params["N_D"] = numeric * 1.0e6 + params["N_A"] = 0.0 + elif key == "absorber_doping_cm3": + pvk = _find_layer_by_role(layers, "absorber") + params = pvk.setdefault("parameters", {}) + params["N_D"] = numeric * 1.0e6 + params["N_A"] = 0.0 + elif key == "absorber_defect_density_cm3": + pvk = _find_layer_by_role(layers, "absorber") + target_m3 = numeric * 1.0e6 + if target_m3 <= 0.0: + raise ValueError("absorber_defect_density_cm3 must be positive") + bulk_defects: list[dict[str, Any]] = pvk.get("bulk_defects", []) + if bulk_defects: + if bulk_defect_mode == "species_only": + species_name = extra["species_name"] + matched = [ + d for d in bulk_defects if d.get("name") == species_name + ] + if len(matched) != 1: + raise ValueError( + f"Expected one bulk defect named {species_name!r}" + ) + matched[0]["distribution"]["total_density_m3"] = target_m3 + else: + base_sum = sum( + float(d["distribution"]["total_density_m3"]) + for d in bulk_defects + ) + if base_sum <= 0.0: + raise ValueError("Baseline bulk defect density sum must be positive") + ratio = target_m3 / base_sum + for d in bulk_defects: + d["distribution"]["total_density_m3"] = ( + float(d["distribution"]["total_density_m3"]) * ratio + ) + else: + params = pvk.setdefault("parameters", {}) + ref_m3 = float(params.get("trap_N_t_bulk") or 1.0e22) + scale = ref_m3 / target_m3 + params["trap_N_t_bulk"] = target_m3 + if params.get("tau_n") is not None: + params["tau_n"] = float(params["tau_n"]) * scale + if params.get("tau_p") is not None: + params["tau_p"] = float(params["tau_p"]) * scale + elif key == "absorber_defect_depth_eV": + pvk = _find_layer_by_role(layers, "absorber") + ref_kind = extra["trap_depth_reference"] + bulk_defects = pvk.get("bulk_defects", []) + if bulk_defects: + targets = ( + [ + d + for d in bulk_defects + if d.get("name") == extra["species_name"] + ] + if bulk_defect_mode == "species_only" + else bulk_defects + ) + if not targets: + raise ValueError( + f"Expected bulk defect {extra['species_name']!r} in absorber" + ) + for d in targets: + d["energy_level"] = { + "reference": ref_kind, + "value_eV": numeric, + } + else: + params = pvk.setdefault("parameters", {}) + gap = float(params["Eg"]) + temp = float(data.get("settings", {}).get("T", 300.0)) + vt = float(thermal_voltage(temp)) + ni = float(params["ni"]) + delta = ( + gap / 2.0 - numeric + if ref_kind == "below_conduction_band" + else numeric - gap / 2.0 + ) + ratio = math.exp(delta / vt) + params["n1"] = ni * ratio + params["p1"] = ni / ratio + elif key == "interface_defect_N_t_cm2": + if numeric <= 0.0: + raise ValueError("interface_defect_N_t_cm2 must be positive") + iface = _find_interface_by_roles( + layers, interfaces, extra["interface_defect_target"] + ) + defect = iface.get("defect") + if not isinstance(defect, dict): + raise ValueError( + f"Interface target {extra['interface_defect_target']!r} has no " + "declared defect" + ) + old_m2 = float(defect["total_density_m2"]) + new_m2 = numeric * 1.0e4 + defect["total_density_m2"] = new_m2 + if old_m2 > 0.0: + srv_ratio = new_m2 / old_m2 + for v_key in ("v_n", "v_p"): + if iface.get(v_key) is not None: + iface[v_key] = float(iface[v_key]) * srv_ratio + elif key == "interface_defect_E_t_eV": + iface = _find_interface_by_roles( + layers, interfaces, extra["interface_defect_target"] + ) + defect = iface.get("defect") + if not isinstance(defect, dict): + raise ValueError( + f"Interface target {extra['interface_defect_target']!r} has no " + "declared defect" + ) + defect["trap_depth_eV"] = numeric + else: + raise ValueError(f"Unsupported sweep handler key: {key!r}") + + computed_vbi = _recompute_doped_vbi(data) + settings = data.setdefault("settings", {}) + if sync_vbi and computed_vbi is not None and "V_bi" in settings: + settings["V_bi"] = computed_vbi + meta["computed_V_bi"] = computed_vbi + meta["bulk_defect_mode"] = bulk_defect_mode + return DeviceInput.model_validate(data), meta diff --git a/tests/integration/test_spectral_beer_lambert_stress.py b/tests/integration/test_spectral_beer_lambert_stress.py new file mode 100644 index 00000000..a601d82d --- /dev/null +++ b/tests/integration/test_spectral_beer_lambert_stress.py @@ -0,0 +1,419 @@ +"""Integration stress tests for spectral Beer-Lambert on scaps_mirror_v2 (P08-04). + +Re-certifies the historical archive/wip-beer-lambert (658baa84) N=60 stress +case on the refactored solarlab 1D kernel: +- Exact spectral Beer-Lambert photon budget (~260.14 A/m^2 on 300..1000 nm AM1.5G) + with incoherent front glass substrate and mesh-invariant control-volume source. +- DC equilibrium, illuminated J-V operating points bracketing V_oc, and spatial + refinement (N = 30 -> 60 -> 120 -> 240). +- Conservative Backward-Euler transient illumination turn-on and 5 V/s forward + bias scan across absorber-front node 20 (where legacy density-variable Radau + drove p < 0 and collapsed step size), proving min(n) > 0, min(p) > 0 without + clipping and exact step-accounting conservation closure. +""" + +from __future__ import annotations + +from pathlib import Path +import time +from typing import Any, cast + +import numpy as np +import pytest + +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.resolve_device import resolve_device +from solarlab.config.scaps_input import import_scaps_device +from solarlab.device.compile_1d import CompiledDevice1D, compile_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import CapabilityError +from solarlab.experiments.transient import ( + TransientOptions, + TransientProtocol, + solve_transient, +) +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.physics.generation import sample_tabulated +from solarlab.physics.statistics.thermal import thermal_voltage +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + solve_equilibrium, + solve_steady_state, +) + +ROOT = Path(__file__).resolve().parents[2] +LEGACY = ROOT / "perovskite-sim" / "perovskite_sim" +DATA_DIR = LEGACY / "data" +CATALOG_PATHS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +def _am15g_resource_table(n_wavelengths: int = 200) -> ResourceTable: + raw = np.loadtxt(DATA_DIR / "am15g.csv", delimiter=",", comments="#") + wl_nm = np.linspace(300.0, 1000.0, n_wavelengths) + flux = sample_tabulated(raw[:, 0], raw[:, 1], wl_nm, name="am15g") + lines = ["wavelength_nm,spectral_flux_m-2_s-1_m-1\n"] + lines.extend(f"{repr(float(w))},{repr(float(f))}\n" for w, f in zip(wl_nm, flux)) + name = f"am15g_{n_wavelengths}" + return ResourceTable( + name, + "spectrum", + SourceDocument(f"{name}.csv", "".join(lines).encode("utf-8")), + ) + + +def _prepare_scaps_mirror_v2_new_core( + defaults: DefaultCatalog, + *, + n_wavelengths: int = 200, +) -> PreparedDevice: + """Import scaps_mirror_v2.yaml and bind its physical stack on the 1D kernel.""" + + scaps_src = SourceDocument( + "configs/scaps_mirror_v2.yaml", + (ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml").read_bytes(), + ) + nk_tables = tuple( + ResourceTable( + mat, + "nk", + SourceDocument(f"nk:{mat}.csv", (DATA_DIR / "nk" / f"{mat}.csv").read_bytes()), + ) + for mat in ("glass", "spiro_OMeTAD", "MAPbI3", "TiO2") + ) + am15g = _am15g_resource_table(n_wavelengths) + resources = ResourceLibrary((am15g, *nk_tables)) + + imported = import_scaps_device(scaps_src, id="scaps_mirror_v2", defaults=defaults) + data: dict[str, Any] = imported.editing_data() + data.pop("legacy_fields", None) + data["spectrum"] = am15g.name + + temp_k = 300.0 + vt = float(thermal_voltage(temp_k)) + data["settings"].update( + T=temp_k, + mode="full", + built_in_potential_mode="semiconductor_work_function", + dos_band_potentials=True, + flat_band_metal_contacts=False, + ion_steric_diffusion_only=False, + ion_steric_shared_site=False, + het_recomb_despike=0.0, + jv_solver_policy="general", + Phi=0.0, + ) + + scaps_fallbacks = dict(defaults.scaps) + for layer in data["layers"]: + layer["parameterization"] = "standard" + layer.pop("scaps_defect_metadata", None) + params = layer.setdefault("parameters", {}) + for key, fallback in scaps_fallbacks.items(): + params.setdefault(key, fallback) + if layer["role"] == "substrate": + # Optical-only glass front substrate retains incoherent=True. + assert params.get("incoherent") is True + params.update(ni=1.0, n1=1.0, p1=1.0) + continue + nc = float(params["Nc300"]) + nv = float(params["Nv300"]) + eg = float(params["Eg"]) + ni = float(np.sqrt(nc * nv) * np.exp(-eg / (2.0 * vt))) + params.update( + ni=ni, + n1=ni, + p1=ni, + tau_n=1.0e-3, + tau_p=1.0e-3, + P0=0.0, + P0_neg=0.0, + D_ion=0.0, + D_ion_neg=0.0, + ) + if layer.get("bulk_defects"): + # Bind both Perovskite-CB and Perovskite-VB as explicit neutral DEF-1 SRH. + layer["defect_schema_version"] = "solarlab-explicit-bulk-defects-v1" + layer["defect_model"] = "explicit_quasi_steady" + for defect in layer["bulk_defects"]: + defect["charge_transition"] = "neutral" + defect["neutral_reference"] = "all_occupancies" + defect["degeneracy"] = 1.0 + + # Both HTL/PVK and PVK/ETL interface defects from scaps_mirror_v2.yaml are + # already imported as InterfaceDefectInput (N_t=1e12 cm^-2, sigma=1e-19 cm^2, + # E_t=0.6 eV below CB, with preserved partner_metadata). + assert sum(1 for iface in data.get("interfaces", []) if iface.get("defect")) == 2 + + return resolve_device(DeviceInput.model_validate(data), defaults, resources) + + +@pytest.fixture(scope="module") +def defaults() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple( + SourceDocument(name, (LEGACY / name).read_bytes()) + for name in CATALOG_PATHS + ) + ) + + +@pytest.fixture(scope="module") +def scaps_prepared(defaults: DefaultCatalog) -> PreparedDevice: + return _prepare_scaps_mirror_v2_new_core(defaults, n_wavelengths=200) + + +@pytest.fixture(scope="module") +def scaps_device_n60(scaps_prepared: PreparedDevice) -> CompiledDevice1D: + # N=60 total electrical intervals (20 per layer -> 61 nodes; HTL/PVK shared + # absorber-front node is exact index 20, matching the 658baa84 witness). + return compile_device_1d( + scaps_prepared, + intervals_per_layer=(20, 20, 20), + optical_model="beer_lambert_spectral", + ) + + +def test_scaps_mirror_v2_n60_dc_jv_positivity_and_spatial_refinement( + scaps_prepared: PreparedDevice, + scaps_device_n60: CompiledDevice1D, +) -> None: + # Incoherent glass substrate fails closed on coherent TMM, while compiling + # cleanly on single-pass beer_lambert_spectral. + with pytest.raises(CapabilityError, match="incoherent"): + compile_device_1d( + scaps_prepared, intervals_per_layer=(20, 20, 20), optical_model="tmm" + ) + + assert scaps_device_n60.node_count == 61 + assert scaps_device_n60.geometry.interfaces[0].shared_node == 20 + assert scaps_device_n60.generation.method == "beer_lambert_spectral" + assert scaps_device_n60.generation_limit_A_m2 == pytest.approx(260.14, abs=0.15) + + options = SteadyOptions( + continuity_tolerance_A_m2=1.0e-6, + current_spread_tolerance_A_m2=1.0e-6, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + eq = solve_equilibrium(scaps_device_n60, options=options) + assert eq.converged + assert np.min(eq.state.electron_density_m3) > 0.0 + assert np.min(eq.state.hole_density_m3) > 0.0 + assert eq.state.hole_density_m3[20] > 0.0 + + # Short-circuit solve on deduplicated N=60 (exact node 20 shared HTL/PVK node). + sc_dedup = solve_steady_state( + scaps_device_n60, + voltage_V=0.0, + generation_scale=1.0, + options=options, + ) + assert sc_dedup.converged + assert all(gate.passed for gate in sc_dedup.physical_gates) + assert np.min(sc_dedup.state.electron_density_m3) > 0.0 + assert np.min(sc_dedup.state.hole_density_m3) > 0.0 + assert sc_dedup.state.hole_density_m3[20] > 0.0 + + # Full illuminated J-V sweep across V_oc (0.0 -> 1.19 V) on two-sided trace + # topology (59 nodes; HTL/PVK absorber-front right trace node is index 20), + # resolving the 1.54 eV HTL/PVK conduction-band offset through V_oc (~1.178 V). + scaps_trace_n60 = compile_device_1d( + scaps_prepared, + intervals_per_layer=(20, 20, 20), + optical_model="beer_lambert_spectral", + interface_topology="two_sided_trace", + ) + assert scaps_trace_n60.node_count == 59 + assert scaps_trace_n60.geometry.interfaces[0].right_node == 20 + assert scaps_trace_n60.generation_limit_A_m2 == pytest.approx( + scaps_device_n60.generation_limit_A_m2, rel=1.0e-13 + ) + + sc = solve_steady_state( + scaps_trace_n60, + voltage_V=0.0, + generation_scale=1.0, + options=options, + ) + assert sc.converged + assert all(gate.passed for gate in sc.physical_gates) + + voltages = (0.0, 0.2, 0.5, 0.8, 1.0, 1.10, 1.14, 1.16, 1.17, 1.18, 1.19) + currents: list[float] = [float(np.mean(sc.contact_current_density_A_m2))] + seed = sc + for v_bias in voltages[1:]: + pt = solve_steady_state( + scaps_trace_n60, + initial_state=seed.state, + voltage_V=v_bias, + generation_scale=1.0, + options=options, + ) + assert pt.converged + assert all(gate.passed for gate in pt.physical_gates) + assert np.min(pt.state.electron_density_m3) > 0.0 + assert np.min(pt.state.hole_density_m3) > 0.0 + assert pt.state.hole_density_m3[20] > 0.0 + currents.append(float(np.mean(pt.contact_current_density_A_m2))) + seed = pt + + # Photogenerated collection at V=0 has |J_sc| near ~258.95 A/m^2 (< 260.14 A/m^2 + # optical budget) and crosses zero cleanly between 1.17 V and 1.18 V (V_oc ~ 1.178 V). + assert abs(currents[0]) == pytest.approx(258.95, abs=0.25) + assert abs(currents[0]) <= scaps_trace_n60.generation_limit_A_m2 + assert currents[-3] < 0.0 < currents[-2] + + # Spatial refinement N = 30 -> 60 -> 120 -> 240: photon budget is mesh-exact + # and short-circuit current converges smoothly. + jsc_by_mesh: list[float] = [] + gen_limits: list[float] = [] + for n_layer in (10, 20, 40, 80): + dev_n = compile_device_1d( + scaps_prepared, + intervals_per_layer=(n_layer, n_layer, n_layer), + optical_model="beer_lambert_spectral", + ) + gen_limits.append(dev_n.generation_limit_A_m2) + sc_n = solve_steady_state( + dev_n, voltage_V=0.0, generation_scale=1.0, options=options + ) + assert np.min(sc_n.state.hole_density_m3) > 0.0 + jsc_by_mesh.append(abs(float(np.mean(sc_n.contact_current_density_A_m2)))) + + np.testing.assert_allclose(gen_limits, gen_limits[0], rtol=1.0e-13) + mesh_diffs = [ + abs(jsc_by_mesh[i + 1] - jsc_by_mesh[i]) for i in range(len(jsc_by_mesh) - 1) + ] + assert mesh_diffs[-1] < mesh_diffs[0] + assert mesh_diffs[-1] < 0.1 + + +def test_scaps_mirror_v2_n60_conservative_be_transient_positivity_and_closure( + scaps_device_n60: CompiledDevice1D, +) -> None: + started = time.perf_counter() + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-6, + current_spread_tolerance_A_m2=1.0e-6, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + dark_eq = solve_equilibrium(scaps_device_n60, options=steady_opts) + sc_eq = solve_steady_state( + scaps_device_n60, + voltage_V=0.0, + generation_scale=1.0, + options=steady_opts, + ) + + # Stage 1: Dark-to-1-sun step turn-on across geometric time steps (0 -> 1 sun + # over 1e-11 .. 1e-5 s), directly exercising the absorber-front node-20 regime + # where legacy 658baa84 density-variable Radau drove p < 0 and collapsed dt. + turn_on_times = np.concatenate(([0.0], np.geomspace(1.0e-11, 1.0e-5, 13))) + turn_on_protocol = TransientProtocol( + times_s=turn_on_times, + voltage_V=np.zeros_like(turn_on_times), + generation_scale=np.concatenate(([0.0], np.ones(13))), + ) + turn_on_opts = TransientOptions( + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=1.0e-6, + contact_log_tolerance=1.0e-11, + potential_step_V=0.1, + quasi_fermi_step=2.0, + newton_budget=SolveBudget( + max_iterations=80, + max_residual_evaluations=5000, + max_jacobian_evaluations=1000, + max_backtracks=30, + ), + max_steps=64, + wall_s=15.0, + predictor="generation_inventory", + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + turn_on_result = solve_transient( + scaps_device_n60, + dark_eq, + turn_on_protocol, + options=turn_on_opts, + initial_options=steady_opts, + method="backward_euler", + ) + + # Stage 2: Illuminated 5 V/s forward scan (0.0 -> 0.80 V over 16 steps) with + # 10% sinusoidal illumination modulation from accepted short-circuit state. + scan_steps = 16 + scan_voltages = np.linspace(0.0, 0.80, scan_steps + 1) + scan_times = scan_voltages / 5.0 + scan_gen = 1.0 + 0.1 * np.sin(np.pi * np.linspace(0.0, 1.0, scan_steps + 1)) + scan_gen[0] = 1.0 + scan_protocol = TransientProtocol( + times_s=scan_times, + voltage_V=scan_voltages, + generation_scale=scan_gen, + ) + scan_opts = TransientOptions( + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=1.0e-6, + contact_log_tolerance=1.0e-11, + potential_step_V=0.1, + quasi_fermi_step=2.0, + newton_budget=SolveBudget( + max_iterations=80, + max_residual_evaluations=5000, + max_jacobian_evaluations=1000, + max_backtracks=30, + ), + max_steps=64, + wall_s=15.0, + predictor="previous", + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + scan_result = solve_transient( + scaps_device_n60, + sc_eq, + scan_protocol, + options=scan_opts, + initial_options=steady_opts, + method="backward_euler", + ) + elapsed_s = time.perf_counter() - started + assert elapsed_s < 10.0 + + for res in (turn_on_result, scan_result): + assert res.completed + assert not res.failed_attempts + + # Strictly positive n and p across ALL nodes (specifically node 20) and ALL steps. + min_n = min(float(np.min(st.electron_density_m3)) for st in res.states) + min_p = min(float(np.min(st.hole_density_m3)) for st in res.states) + min_p_node20 = min(float(st.hole_density_m3[20]) for st in res.states) + assert min_n > 0.0 + assert min_p > 0.0 + assert min_p_node20 > 0.0 + + # Verify conservative Backward-Euler step accounting at every accepted step. + for attempt in res.attempts: + assert attempt.accepted + acc = attempt.accounting + assert isinstance(acc, dict) + assert float(cast(float, acc["poisson_normalized_max"])) <= 1.0e-11 + assert float(cast(float, acc["continuity_defect_bound_A_m2"])) <= 1.0e-6 + assert float( + np.max(np.abs(np.asarray(acc["maxwell_identity_error_A_m2"]))) + ) <= 1.0e-9 + assert abs(float(cast(float, acc["global_charge_balance_A_m2"]))) <= 1.0e-6 diff --git a/tests/unit/physics/test_beer_lambert_spectral.py b/tests/unit/physics/test_beer_lambert_spectral.py new file mode 100644 index 00000000..9484dfe8 --- /dev/null +++ b/tests/unit/physics/test_beer_lambert_spectral.py @@ -0,0 +1,673 @@ +"""Unit tests for spectral control-volume Beer-Lambert optics and SCAPS catalog.""" + +from __future__ import annotations + +from copy import deepcopy +import hashlib +from pathlib import Path + +import numpy as np +from numpy.typing import NDArray +import pytest + +from solarlab.config.device_import import import_standard_device +from solarlab.config.identity import ( + IdentityInputs, + ModelInputs, + input_identity, + physics_identity, +) +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.model_parameters import device_topology, layer_parameter_source +from solarlab.config.resolve_device import resolve_device +from solarlab.config.scaps_input import import_scaps_device +from solarlab.contracts.units import ELEMENTARY_CHARGE_C as Q +from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.mesh import ( + HALF_ENDPOINT_V1, + INTEGER_ENDPOINT_V1, + TWO_SIDED_TRACE_V1, + build_geometry, + multilayer_grid, +) +from solarlab.physics.generation import ( + SPECTRAL_BEER_LAMBERT_MODEL_ID, + OpticalLayerSpec, + OpticalStackBinding, + SpectralBeerLambertBinding, + SpectralPhotonFlux, + constant_index_optical_constants, + sample_nk_table, + sample_tabulated, + spectral_beer_lambert_absorption_coefficients, + wavelength_grid_m, +) +from solarlab.physics.generation import transfer_matrix as tm_module +from solarlab.physics.statistics.thermal import thermal_voltage +from solarlab.physics.interface_transport import remove_shared_interface_nodes +from solarlab.physics.registry import ( + CapabilityContext, + CapabilityRule, + EvidenceRef, + ModelDefinition, + ModelRef, + ModelRegistry, + Scope, +) +from solarlab.physics.selection import ModelChoice, select_models +from solarlab.physics.semantic_projection import SemanticProjection +from solarlab.reproducibility.scaps_beer_lambert import ( + HIGH_DOPING_MIN_N_GRID, + SCAPS_BEER_LAMBERT_STUDY_ID, + STANDARD_JV_SWEEP_HINTS, + SWEEPS, + apply_reference_point, + load_scaps_beer_lambert_catalog, + reference_catalog, + validate_reference_point, +) + +ROOT = Path(__file__).resolve().parents[3] +LEGACY = ROOT / "perovskite-sim" / "perovskite_sim" +DATA_DIR = LEGACY / "data" +CATALOG_PATHS = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + + +@pytest.fixture(scope="module") +def defaults() -> DefaultCatalog: + return read_legacy_default_catalog( + tuple( + SourceDocument(name, (LEGACY / name).read_bytes()) + for name in CATALOG_PATHS + ) + ) + + +def _am15g_spectrum(n_wavelengths: int = 200) -> SpectralPhotonFlux: + raw = np.loadtxt(DATA_DIR / "am15g.csv", delimiter=",", comments="#") + wl_nm = np.linspace(300.0, 1000.0, n_wavelengths) + flux = sample_tabulated(raw[:, 0], raw[:, 1], wl_nm, name="am15g") + return SpectralPhotonFlux(wl_nm, flux, f"am15g_{n_wavelengths}") + + +def _am15g_resource(n_wavelengths: int = 200) -> ResourceTable: + spec = _am15g_spectrum(n_wavelengths) + lines = ["wavelength_nm,spectral_flux_m-2_s-1_m-1\n"] + lines.extend( + f"{repr(float(w))},{repr(float(f))}\n" + for w, f in zip(spec.wavelengths_nm, spec.flux_m2_s_m) + ) + name = f"am15g_{n_wavelengths}" + return ResourceTable( + name, + "spectrum", + SourceDocument(f"{name}.csv", "".join(lines).encode("utf-8")), + ) + + +def _nk_tables(*materials: str) -> tuple[ResourceTable, ...]: + return tuple( + ResourceTable( + mat, + "nk", + SourceDocument(f"nk:{mat}.csv", (DATA_DIR / "nk" / f"{mat}.csv").read_bytes()), + ) + for mat in materials + ) + + +def _scaps_mirror_v2_optical_layers( + wl_nm: NDArray[np.float64], + *, + incoherent_glass: bool = True, +) -> tuple[OpticalLayerSpec, ...]: + specs = ( + ("glass", 1.0e-3, "glass", incoherent_glass, False), + ("SCAPS_HTL", 20.0e-9, "spiro_OMeTAD", False, True), + ("SCAPS_PVK", 800.0e-9, "MAPbI3", False, True), + ("SCAPS_ETL", 25.0e-9, "TiO2", False, True), + ) + out: list[OpticalLayerSpec] = [] + for layer_id, d_m, mat_name, incoh, elec in specs: + raw = np.loadtxt(DATA_DIR / "nk" / f"{mat_name}.csv", delimiter=",", skiprows=1) + n, k = sample_nk_table(raw[:, 0], raw[:, 1], raw[:, 2], wl_nm, material=mat_name) + out.append( + OpticalLayerSpec( + layer_id, + d_m, + n, + k, + incoherent=incoh, + electrical=elec, + ) + ) + return tuple(out) + + +@pytest.mark.parametrize("count", [5, 13, 31, 127]) +@pytest.mark.parametrize("geom_kind", [INTEGER_ENDPOINT_V1, HALF_ENDPOINT_V1]) +def test_analytic_slab_with_front_substrate_closes_photon_budget( + count: int, + geom_kind: str, +) -> None: + wl_nm = np.linspace(300.0, 1000.0, 200) + wl_m = wavelength_grid_m(wl_nm) + flux: NDArray[np.float64] = np.full(200, 2.0e27, dtype=np.float64) + spectrum = SpectralPhotonFlux(wl_nm, flux, "flat_2e27") + substrate_alpha, absorber_alpha = 2.0e3, 8.0e6 + substrate_d, absorber_d = 1.0e-3, 800.0e-9 + + n_sub, k_sub = constant_index_optical_constants( + wl_nm, absorption_coefficient_m1=substrate_alpha, refractive_index=1.5 + ) + n_abs, k_abs = constant_index_optical_constants( + wl_nm, absorption_coefficient_m1=absorber_alpha, refractive_index=2.5 + ) + binding = SpectralBeerLambertBinding( + layers=( + OpticalLayerSpec( + "glass", substrate_d, n_sub, k_sub, incoherent=True, electrical=False + ), + OpticalLayerSpec( + "absorber", absorber_d, n_abs, k_abs, incoherent=False, electrical=True + ), + ), + spectrum=spectrum, + ) + nodes = multilayer_grid([(absorber_d, count - 1)], alpha=[3.0]) + geometry = build_geometry(geom_kind, nodes, np.asarray([], dtype=float)) + profile = binding.generation_profile(geometry) + budget = binding.photon_budget() + + incident_expected = float(np.trapezoid(flux, x=wl_m)) + expected_electrical = ( + incident_expected + * float(np.exp(-substrate_alpha * substrate_d)) + * float(-np.expm1(-absorber_alpha * absorber_d)) + ) + expected_parasitic = incident_expected * float( + -np.expm1(-substrate_alpha * substrate_d) + ) + expected_transmitted = incident_expected * float( + np.exp(-(substrate_alpha * substrate_d + absorber_alpha * absorber_d)) + ) + + assert profile.method == "beer_lambert_spectral" + assert np.all(profile.source_m3_s >= 0.0) + assert np.max(np.abs(budget.spectral_closure_residual())) <= 1.0e-15 + assert budget.reflected_m2_s == 0.0 + assert budget.dropped_m2_s == 0.0 + assert profile.areal_generation_m2_s == pytest.approx( + expected_electrical, rel=1.0e-13 + ) + assert float(np.sum(profile.source_m3_s * geometry.cell_measures_m)) == pytest.approx( + expected_electrical, rel=1.0e-13 + ) + assert budget.parasitic_absorbed_m2_s == pytest.approx( + expected_parasitic, rel=1.0e-13 + ) + assert budget.transmitted_m2_s == pytest.approx(expected_transmitted, rel=1.0e-13) + total_accounted = ( + profile.areal_generation_m2_s + + budget.parasitic_absorbed_m2_s + + budget.transmitted_m2_s + ) + assert abs(total_accounted - budget.incident_m2_s) <= 1.0e-14 * budget.incident_m2_s + + +def test_scaps_mirror_v2_photon_budget_mesh_invariance_and_spectral_convergence() -> None: + spectrum_200 = _am15g_spectrum(200) + layers_incoh = _scaps_mirror_v2_optical_layers( + spectrum_200.wavelengths_nm, incoherent_glass=True + ) + layers_coh = _scaps_mirror_v2_optical_layers( + spectrum_200.wavelengths_nm, incoherent_glass=False + ) + bl_binding = SpectralBeerLambertBinding(layers_incoh, spectrum_200) + tmm_incoh = OpticalStackBinding(layers_incoh, spectrum_200) + tmm_coh = OpticalStackBinding(layers_coh, spectrum_200) + + # Construct via from_optical_stack must reproduce cell fluxes identically. + from_stack = SpectralBeerLambertBinding.from_optical_stack(tmm_incoh) + assert from_stack.sha256 != tmm_incoh.sha256 + + thicknesses = [20.0e-9, 800.0e-9, 25.0e-9] + interfaces: NDArray[np.float64] = np.cumsum(thicknesses, dtype=np.float64)[:-1] + currents_A_m2: list[float] = [] + for n_per_layer in (5, 10, 20, 40, 80): + base_nodes = multilayer_grid( + [(d, n_per_layer) for d in thicknesses], alpha=[3.0, 3.0, 3.0] + ) + for geom in ( + build_geometry(INTEGER_ENDPOINT_V1, base_nodes, interfaces), + build_geometry(HALF_ENDPOINT_V1, base_nodes, interfaces), + build_geometry( + TWO_SIDED_TRACE_V1, + remove_shared_interface_nodes(base_nodes, interfaces), + interfaces, + ), + ): + prof = bl_binding.generation_profile(geom) + currents_A_m2.append(Q * prof.areal_generation_m2_s) + np.testing.assert_array_equal( + prof.absorbed_m2_s, + from_stack.generation_profile(geom).absorbed_m2_s, + ) + + np.testing.assert_allclose(currents_A_m2, currents_A_m2[0], rtol=1.0e-13) + # Historical archive/wip-beer-lambert (658baa84) reference: ~260.14 A/m^2 (BL) + # vs ~235.06 A/m^2 (coherent-glass TMM, legacy SCAPS loader effective) and + # ~232.52 A/m^2 (front-incoherent-glass TMM, declared incoherent=True). + assert currents_A_m2[0] == pytest.approx(260.14, abs=0.15) + tmm_incoh_j = Q * tmm_incoh.photon_budget().electrical_absorbed_m2_s + tmm_coh_j = Q * tmm_coh.photon_budget().electrical_absorbed_m2_s + assert tmm_coh_j == pytest.approx(235.06, abs=0.25) + assert tmm_incoh_j == pytest.approx(232.52, abs=0.25) + assert currents_A_m2[0] > tmm_coh_j > tmm_incoh_j > 220.0 + + budget = bl_binding.photon_budget() + assert np.max(np.abs(budget.spectral_closure_residual())) <= 1.0e-15 + closed = ( + budget.electrical_absorbed_m2_s + + budget.parasitic_absorbed_m2_s + + budget.transmitted_m2_s + ) + assert abs(closed - budget.incident_m2_s) <= 1.0e-14 * budget.incident_m2_s + + # Independent spectral quadrature refinement (100 -> 200 -> 400 -> 800 -> 1600). + spectral_j: list[float] = [] + for n_wl in (100, 200, 400, 800, 1600): + spec_n = _am15g_spectrum(n_wl) + lay_n = _scaps_mirror_v2_optical_layers(spec_n.wavelengths_nm) + b_n = SpectralBeerLambertBinding(lay_n, spec_n).photon_budget() + spectral_j.append(Q * b_n.electrical_absorbed_m2_s) + diffs = [abs(spectral_j[i + 1] - spectral_j[i]) for i in range(len(spectral_j) - 1)] + assert diffs[1] < diffs[0] + assert diffs[2] < diffs[1] + assert diffs[3] < diffs[2] + assert diffs[3] < 0.05 + + +def test_spectral_beer_lambert_never_calls_tmm_and_validates_inputs( + monkeypatch: pytest.MonkeyPatch, +) -> None: + for fn_name in ( + "tmm_absorbed_photon_flux_per_cell", + "tmm_absorption_profile", + "tmm_cumulative_absorptance", + "tmm_reflectance", + "tmm_transmittance", + ): + monkeypatch.setattr( + tm_module, + fn_name, + lambda *_a, **_k: pytest.fail(f"TMM {fn_name} invoked by Beer-Lambert"), + ) + + spec = _am15g_spectrum(64) + layers = _scaps_mirror_v2_optical_layers(spec.wavelengths_nm) + binding = SpectralBeerLambertBinding(layers, spec) + thicknesses = [20.0e-9, 800.0e-9, 25.0e-9] + nodes = multilayer_grid([(d, 8) for d in thicknesses], alpha=[3.0, 3.0, 3.0]) + geom = build_geometry( + INTEGER_ENDPOINT_V1, nodes, np.cumsum(thicknesses, dtype=float)[:-1] + ) + prof = binding.generation_profile(geom) + diag = binding.absorption_profile(nodes) + assert prof.areal_generation_m2_s > 0.0 + assert diag.shape == (nodes.size, 64) + assert np.all(diag >= 0.0) + assert binding.sha256 and SPECTRAL_BEER_LAMBERT_MODEL_ID == ( + "beer_lambert_spectral_front_incidence_v1" + ) + + with pytest.raises(ValueError, match="electrical window"): + binding.absorbed_photon_flux_per_cell(np.array([-1.0e-9, 100.0e-9])) + with pytest.raises(ValueError, match="electrical window"): + binding.absorption_profile(np.array([0.0, 900.0e-9])) + with pytest.raises(ValueError, match="strictly increasing"): + spectral_beer_lambert_absorption_coefficients( + layers, np.array([500.0e-9, 400.0e-9]) + ) + + +def test_opt_in_compilers_preserve_default_parity_and_separate_identities( + defaults: DefaultCatalog, + monkeypatch: pytest.MonkeyPatch, +) -> None: + original = SourceDocument( + "fixture:nip_MAPbI3", + (ROOT / "perovskite-sim/tests/fixtures/configs/nip_MAPbI3.yaml").read_bytes(), + ) + am15g = _am15g_resource(60) + nk = _nk_tables("TiO2", "MAPbI3", "spiro_OMeTAD") + lib = ResourceLibrary((am15g, *nk)) + + data = import_standard_device( + original, id="opt_in_optics", defaults=defaults + ).editing_data() + data["spectrum"] = am15g.name + data["settings"].update( + mode="full", + T=300.0, + built_in_potential_mode="semiconductor_work_function", + dos_band_potentials=True, + ion_steric_diffusion_only=False, + ion_steric_shared_site=False, + Phi=2.5e21, + ) + optical_map = {"ETL": "TiO2", "absorber": "MAPbI3", "HTL": "spiro_OMeTAD"} + band_map = { + "ETL": (4.0, 3.2), + "absorber": (3.9, 1.6), + "HTL": (2.45, 3.0), + } + vt = float(thermal_voltage(300.0)) + for layer in data["layers"]: + role = layer["role"] + chi_eV, eg_eV = band_map[role] + ni = float(np.sqrt(2.2e24 * 1.8e24) * np.exp(-eg_eV / (2.0 * vt))) + p = layer.setdefault("parameters", {}) + p.update( + chi=chi_eV, + Eg=eg_eV, + Nc300=2.2e24, + Nv300=1.8e24, + ni=ni, + n1=ni, + p1=ni, + optical_material=optical_map[role], + n_optical=None, + alpha=1.0e7 if role == "absorber" else 1.0e5, + P0=0.0, + P0_neg=0.0, + D_ion=0.0, + D_ion_neg=0.0, + ) + prepared = resolve_device( + DeviceInput.model_validate(data), defaults, lib, sources=(original,) + ) + + default_dc = compile_device_1d(prepared, intervals_per_layer=8) + explicit_tmm = compile_device_1d( + prepared, intervals_per_layer=8, optical_model="tmm" + ) + explicit_sbl = compile_device_1d( + prepared, intervals_per_layer=8, optical_model="beer_lambert_spectral" + ) + explicit_bl = compile_device_1d( + prepared, intervals_per_layer=8, optical_model="beer_lambert" + ) + + # Default (optical_model=None) is bit-identical to historical TMM dispatch. + assert default_dc.identity == explicit_tmm.identity + np.testing.assert_array_equal( + default_dc.generation.source_m3_s, explicit_tmm.generation.source_m3_s + ) + # Three optical models produce three distinct cryptographic identities. + assert ( + len({explicit_tmm.identity, explicit_sbl.identity, explicit_bl.identity}) == 3 + ) + assert explicit_tmm.generation.method == "transfer_matrix" + assert explicit_sbl.generation.method == "beer_lambert_spectral" + assert explicit_bl.generation.method == "beer_lambert" + + with pytest.raises(ValueError, match="optical_model"): + compile_device_1d(prepared, intervals_per_layer=8, optical_model="TMM-typo") # type: ignore[arg-type] + + # Guard: compiling with beer_lambert_spectral never invokes transfer_matrix. + monkeypatch.setattr( + tm_module, + "tmm_absorbed_photon_flux_per_cell", + lambda *_a, **_k: pytest.fail("TMM called during beer_lambert_spectral"), + ) + recompiled_sbl = compile_device_1d( + prepared, intervals_per_layer=8, optical_model="beer_lambert_spectral" + ) + assert recompiled_sbl.identity == explicit_sbl.identity + monkeypatch.undo() + + # Single-domain and two-domain ionic compilers preserve default identity + # and distinguish all three optical models. + ion_data = deepcopy(data) + ion_data["layers"][1]["parameters"].update( + P0=1.0e24, D_ion=1.0e-16, P_lim=1.0e26, E_a_ion=0.4 + ) + ion_prepared = resolve_device( + DeviceInput.model_validate(ion_data), defaults, lib, sources=(original,) + ) + ion_default = compile_ionic_device_1d( + ion_prepared, + intervals_per_layer=6, + ion_domain_layer=ion_data["layers"][1]["id"], + ion_domain_endpoints=("blocking", "blocking"), + ) + ion_models = [ + compile_ionic_device_1d( + ion_prepared, + intervals_per_layer=6, + ion_domain_layer=ion_data["layers"][1]["id"], + ion_domain_endpoints=("blocking", "blocking"), + optical_model=m, # type: ignore[arg-type] + ) + for m in ("tmm", "beer_lambert_spectral", "beer_lambert") + ] + assert ion_default.electronic_component.identity == ( + ion_models[0].electronic_component.identity + ) + elec_manifest = ion_default.binding_manifest["electronic_component"] + assert isinstance(elec_manifest, dict) + assert "optical_model" not in elec_manifest + assert len({c.identity for c in ion_models}) == 3 + + multi_data = deepcopy(data) + for idx in (0, 2): + multi_data["layers"][idx]["parameters"].update( + P0=1.0e24, D_ion=1.0e-16, P_lim=1.0e26, E_a_ion=0.4 + ) + multi_prepared = resolve_device( + DeviceInput.model_validate(multi_data), defaults, lib, sources=(original,) + ) + domains = ( + (multi_data["layers"][0]["id"], ("blocking", "blocking")), + (multi_data["layers"][2]["id"], ("blocking", "blocking")), + ) + multi_default = compile_multiple_ionic_device_1d( + multi_prepared, intervals_per_layer=6, ion_domains=domains + ) + multi_sbl = compile_multiple_ionic_device_1d( + multi_prepared, + intervals_per_layer=6, + ion_domains=domains, + optical_model="beer_lambert_spectral", + ) + assert multi_default.identity != multi_sbl.identity + + # H_input and H_physics distinguish explicit optical model overrides while + # keeping un-overridden default selection untouched. + src_bl = SourceDocument( + "src/solarlab/physics/generation/beer_lambert.py", + (ROOT / "src/solarlab/physics/generation/beer_lambert.py").read_bytes(), + ) + src_sbl = SourceDocument( + "src/solarlab/physics/generation/beer_lambert_spectral.py", + ( + ROOT / "src/solarlab/physics/generation/beer_lambert_spectral.py" + ).read_bytes(), + ) + src_tmm = SourceDocument( + "src/solarlab/physics/generation/optical_binding.py", + (ROOT / "src/solarlab/physics/generation/optical_binding.py").read_bytes(), + ) + defs = [] + projs = [] + refs: dict[str, ModelRef] = {} + for key_name, label, src in ( + ("beer_lambert", "Scalar Beer-Lambert", src_bl), + ("beer_lambert_spectral", "Spectral Beer-Lambert", src_sbl), + ("tmm", "Transfer-Matrix Optics", src_tmm), + ): + ref = ModelRef(f"generation.{key_name}", 1) + refs[key_name] = ref + cap = CapabilityRule( + "source_data_only", + (1,), + ("dc", "transient"), + (EvidenceRef(src.id + "#binding", src.sha256, "source"),), + backends=("metadata_only",), + ) + defs.append( + ModelDefinition( + ref, + label, + "generation", + ("layer",), + "node", + ("alpha",), + (), + (), + cap, + parameter_schema="full_layer", + ) + ) + projs.append(SemanticProjection(ref, "all_values_v1", (src,))) + registry = ModelRegistry(tuple(defs)) + model_defaults = { + "layer": (ModelChoice("optics", refs["tmm"], parameter_schema="full_layer"),) + } + topo = device_topology(prepared) + param_sources = { + Scope("layer", (layer.id,)): layer_parameter_source(layer) + for layer in prepared.layers + if layer.id in topo.electrical_layer_ids + } + ctx = CapabilityContext( + 1, + "dc", + "metadata_only", + "maxwell_boltzmann", + temperature_K=prepared.values["settings"]["T"], + ) + + def _id_for(override_key: str | None) -> tuple[str, str]: + ov: dict[Scope, dict[str, tuple[ModelChoice, ...]]] = {} + if override_key is not None: + choice = ModelChoice( + "optics", refs[override_key], parameter_schema="full_layer" + ) + ov = { + Scope("layer", (lid,)): {"generation": (choice,)} + for lid in topo.electrical_layer_ids + } + sel = select_models(registry, topo, ctx, model_defaults, param_sources, ov) + active_refs = {inst.model for inst in sel.instances} + active_projs = tuple(p for p in projs if p.model in active_refs) + inp = IdentityInputs( + prepared, + sel, + registry, + ModelInputs.from_mappings(defaults=model_defaults, overrides=ov), + active_projs, + ) + return input_identity(inp).sha256, physics_identity(inp).sha256 + + h_default = _id_for(None) + h_by_model = {k: _id_for(k) for k in ("tmm", "beer_lambert_spectral", "beer_lambert")} + assert h_default[1] == h_by_model["tmm"][1] + assert len({pair[0] for pair in h_by_model.values()}) == 3 + assert len({pair[1] for pair in h_by_model.values()}) == 3 + + +def test_scaps_beer_lambert_catalog_provenance_and_sweep_application( + defaults: DefaultCatalog, +) -> None: + catalog = load_scaps_beer_lambert_catalog() + assert catalog == reference_catalog() + assert catalog["study"] == SCAPS_BEER_LAMBERT_STUDY_ID + assert len(catalog["sweeps"]) == 11 + points = [p for s in catalog["sweeps"].values() for p in s["points"]] + assert sum(p.get("origin") != "solarlab_extension" for p in points) == 93 + assert len(points) == 95 + workbook_path = ROOT / "perovskite-sim" / catalog["source"] + assert ( + catalog["source_sha256"] + == hashlib.sha256(workbook_path.read_bytes()).hexdigest() + ) + assert catalog["sweeps"]["CHI_ETL"]["points"][-1]["reference"]["V_oc"] is None + + scaps_src = SourceDocument( + "configs/scaps_mirror_v2.yaml", + (ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml").read_bytes(), + ) + base_input = import_scaps_device(scaps_src, id="scaps_mirror_v2", defaults=defaults) + nk_lib = ResourceLibrary(_nk_tables("glass", "spiro_OMeTAD", "MAPbI3", "TiO2")) + + # High-doping Nd_PVK extension points carry null references and min_N_grid=90. + for ext_val in (1.0e19, 1.0e20): + pt = next( + p for p in catalog["sweeps"]["Nd_PVK"]["points"] if p["x"] == ext_val + ) + assert pt["origin"] == "solarlab_extension" + assert pt["row"] is None + assert all(v is None for v in pt["reference"].values()) + edited, meta = apply_reference_point(base_input, "Nd_PVK", ext_val) + assert meta["scope"] == "high_doping_extrapolation" + assert meta["min_N_grid"] == HIGH_DOPING_MIN_N_GRID == 90 + assert meta["jv_sweep"]["N_grid"] == 90 + assert meta["optical_model"] == "beer_lambert_spectral" + resolved = resolve_device(edited, defaults, nk_lib) + absorber = next(lay for lay in resolved.layers if lay.role == "absorber") + assert dict(absorber.parameters)["N_D"] == pytest.approx(ext_val * 1.0e6) + + # Every one of the 11 sweep families applies cleanly and resolves via PreparedDevice. + for sweep_name in SWEEPS: + first_x = float(catalog["sweeps"][sweep_name]["points"][0]["x"]) + edited, meta = apply_reference_point(base_input, sweep_name, first_x) + assert meta["jv_sweep"] == STANDARD_JV_SWEEP_HINTS + assert meta["computed_V_bi"] is not None + resolved = resolve_device(edited, defaults, nk_lib) + assert isinstance(resolved, PreparedDevice) + + # Verify species_only vs historical_effective_lifetime on Nt_C_PVK. + eff_in, _ = apply_reference_point( + base_input, "Nt_C_PVK", 1.0e15, bulk_defect_mode="historical_effective_lifetime" + ) + sp_in, _ = apply_reference_point( + base_input, "Nt_C_PVK", 1.0e15, bulk_defect_mode="species_only" + ) + eff_res = resolve_device(eff_in, defaults, nk_lib) + sp_res = resolve_device(sp_in, defaults, nk_lib) + eff_pvk = dict(next(lay for lay in eff_res.layers if lay.role == "absorber").parameters) + sp_pvk = dict(next(lay for lay in sp_res.layers if lay.role == "absorber").parameters) + assert eff_pvk["trap_N_t_bulk"] == pytest.approx(1.0e21) + assert sp_pvk["trap_N_t_bulk"] == pytest.approx(1.0e21 + 1.0e18) + + # Fail-closed validation on typos, booleans, nonfinite values, and out-of-range x. + for bad_sweep, bad_val in ( + ("typo", 0.0), + ("CHI_ETL", 10.0), + ("Nd_PVK", 1.0e21), + ("CHI_ETL", float("nan")), + ("CHI_ETL", float("inf")), + ): + with pytest.raises(ValueError): + validate_reference_point(bad_sweep, bad_val) + with pytest.raises(ValueError): + validate_reference_point("CHI_ETL", True) # type: ignore[arg-type] From 741a4771e4e832502b5d679cd5e83c4c328d81ba Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Sun, 15 Nov 2026 14:01:14 +0800 Subject: [PATCH 26/46] M(research): migrate precision, CBO scan, and R1 short-window public-interface verification to solarlab_research (P07-01, P07-02) --- src/solarlab/reproducibility/PublicAPI.json | 133 +- src/solarlab_research/__init__.py | 25 +- src/solarlab_research/cbo_scan.py | 1231 +++++++++++++++++ src/solarlab_research/precision/__init__.py | 71 + src/solarlab_research/precision/codecs.py | 568 ++++++++ .../precision/double_double.py | 712 ++++++++++ .../precision/two_sided_interface.py | 650 +++++++++ src/solarlab_research/r1/__init__.py | 97 ++ src/solarlab_research/r1/contracts.py | 428 ++++++ src/solarlab_research/r1/controls.py | 478 +++++++ src/solarlab_research/r1/provenance.py | 347 +++++ src/solarlab_research/r1/short_window.py | 1083 +++++++++++++++ src/solarlab_research/scripts/__init__.py | 3 + src/solarlab_research/scripts/cbo_scan.py | 110 ++ .../scripts/r1_short_window.py | 122 ++ .../scripts/r1_verify_sources.py | 112 ++ .../test_cbo_scan_and_r1_short_window.py | 202 +++ .../research/test_precision_and_codecs.py | 475 +++++++ .../test_r1_contracts_and_provenance.py | 307 ++++ 19 files changed, 7151 insertions(+), 3 deletions(-) create mode 100644 src/solarlab_research/cbo_scan.py create mode 100644 src/solarlab_research/precision/__init__.py create mode 100644 src/solarlab_research/precision/codecs.py create mode 100644 src/solarlab_research/precision/double_double.py create mode 100644 src/solarlab_research/precision/two_sided_interface.py create mode 100644 src/solarlab_research/r1/__init__.py create mode 100644 src/solarlab_research/r1/contracts.py create mode 100644 src/solarlab_research/r1/controls.py create mode 100644 src/solarlab_research/r1/provenance.py create mode 100644 src/solarlab_research/r1/short_window.py create mode 100644 src/solarlab_research/scripts/__init__.py create mode 100644 src/solarlab_research/scripts/cbo_scan.py create mode 100644 src/solarlab_research/scripts/r1_short_window.py create mode 100644 src/solarlab_research/scripts/r1_verify_sources.py create mode 100644 tests/integration/research/test_cbo_scan_and_r1_short_window.py create mode 100644 tests/unit/research/test_precision_and_codecs.py create mode 100644 tests/unit/research/test_r1_contracts_and_provenance.py diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json index cb270340..b3b70187 100644 --- a/src/solarlab/reproducibility/PublicAPI.json +++ b/src/solarlab/reproducibility/PublicAPI.json @@ -105,10 +105,71 @@ "solarlab.config.yaml": [ "load_yaml_mapping" ], + "solarlab.contracts": [ + "AREA", + "AlgebraicTerm", + "AssemblyArithmetic", + "COULOMB", + "CellSource", + "ContractError", + "Contribution", + "ELEMENTARY_CHARGE_C", + "EquationSpec", + "FaceFlux", + "FieldProjection", + "FloatArithmetic", + "FloatArray", + "Geometry", + "ImmutableArrays", + "KELVIN", + "LENGTH", + "Layout", + "LinearCoordinates", + "ONE", + "PARTICLE", + "PENDING_G2R", + "PhysicalArray", + "Point", + "ResolvedAuthority", + "SECOND", + "StateAuthority", + "StateIncrement", + "StateView", + "Support", + "SurfaceCharge", + "TermSink", + "TerminalPort", + "Unit", + "VOLT", + "VOLUME", + "VariableSpec", + "Vector", + "frozen_array", + "integer_indices" + ], "solarlab.contracts.persistence": [ "PersistenceReader", "PersistencePort" ], + "solarlab.physics.statistics.fermi_dirac": [ + "FERMI_DIRAC_HALF_TABLE_ETA_MAX", + "FERMI_DIRAC_HALF_TABLE_ETA_MIN", + "FERMI_DIRAC_HALF_TABLE_STEP", + "fermi_dirac_half", + "fermi_dirac_half_log_derivative", + "fermi_dirac_half_table", + "inverse_fermi_dirac_half" + ], + "solarlab.solvers.nonlinear.newton": [ + "IterationRecord", + "LinearSolveError", + "NewtonResult", + "NewtonSettings", + "Termination", + "factorize", + "gate_from", + "solve_newton" + ], "solarlab.device": [], "solarlab.device.defaults": [ "DefaultCatalog" @@ -1087,7 +1148,77 @@ "solve_ionic_transient" ], "solarlab.solvers.nonlinear.problem": [ - "SolveBudget" + "CallableProblem", + "GateOutcome", + "Matrix", + "PhysicalGate", + "ResidualScaling", + "SolveBudget", + "SteadyProblem", + "StepControl", + "Vector", + "state_digest" + ], + "solarlab.solvers.nonlinear.newton": [ + "IterationRecord", + "LinearSolveError", + "NewtonResult", + "NewtonSettings", + "Termination", + "factorize", + "gate_from", + "solve_newton" + ], + "solarlab.contracts": [ + "AREA", + "AlgebraicTerm", + "AssemblyArithmetic", + "COULOMB", + "CellSource", + "ContractError", + "Contribution", + "ELEMENTARY_CHARGE_C", + "EquationSpec", + "FaceFlux", + "FieldProjection", + "FloatArithmetic", + "FloatArray", + "Geometry", + "ImmutableArrays", + "KELVIN", + "LENGTH", + "Layout", + "LinearCoordinates", + "ONE", + "PARTICLE", + "PENDING_G2R", + "PhysicalArray", + "Point", + "ResolvedAuthority", + "SECOND", + "StateAuthority", + "StateIncrement", + "StateView", + "Support", + "SurfaceCharge", + "TermSink", + "TerminalPort", + "Unit", + "VOLT", + "VOLUME", + "VariableSpec", + "Vector", + "frozen_array", + "integer_indices" + ], + "solarlab.physics.statistics.fermi_dirac": [ + "FERMI_DIRAC_HALF_TABLE_ETA_MAX", + "FERMI_DIRAC_HALF_TABLE_ETA_MIN", + "FERMI_DIRAC_HALF_TABLE_STEP", + "fermi_dirac_half", + "fermi_dirac_half_log_derivative", + "fermi_dirac_half_table", + "inverse_fermi_dirac_half" ], "solarlab.equations.ionic_small_signal": [ "IonicACSystem", diff --git a/src/solarlab_research/__init__.py b/src/solarlab_research/__init__.py index ecf545a5..ea63aadb 100644 --- a/src/solarlab_research/__init__.py +++ b/src/solarlab_research/__init__.py @@ -1,3 +1,24 @@ -"""Research extensions for the public SolarLab interfaces.""" +"""Research extensions for the public SolarLab interfaces. -__all__: tuple[str, ...] = () +Provides: +* ``solarlab_research.precision``: double-double arithmetic (``DD``, ``DDArray``, + ``CompensatedArithmetic``), compensated local two-sided interface carrier + kernels, and reference-increment / affine input-lift state codecs. +* ``solarlab_research.cbo_scan``: public 1D conduction/valence-band-offset (CBO) + scan orchestration pinned to pre-``P08`` models per ``D20``. +* ``solarlab_research.r1``: frozen V53 certificate limits, 13-channel operator + schema, IDA ``R1-L2`` exclusion, immutable ``ReleaseBundle`` provenance and + non-relabeling historical readers, controls ``A-D`` verification, and + conservative ``4/8/16`` short-window public-interface verification. +* ``solarlab_research.scripts``: module CLI entrypoints invoked via + ``python -m solarlab_research.scripts.``. +""" + +from solarlab_research import cbo_scan, precision, r1, scripts + +__all__ = ( + "cbo_scan", + "precision", + "r1", + "scripts", +) diff --git a/src/solarlab_research/cbo_scan.py b/src/solarlab_research/cbo_scan.py new file mode 100644 index 00000000..891c14b2 --- /dev/null +++ b/src/solarlab_research/cbo_scan.py @@ -0,0 +1,1231 @@ +"""Public 1D conduction/valence-band-offset (CBO) scan orchestration (P07-01). + +Orchestrates 1D heterojunction band-offset scans strictly over the public +``solarlab`` configuration, compilation, and steady-state DC interfaces: +``delta_ec_eV = chi_absorber - chi_transport`` (positive values are electron +extraction spikes at an absorber/ETL boundary). + +Per decision ``D20``, CBO scans pin pre-``P08`` model tokens by default so +prospective ``P08`` optical or transport corrections cannot silently alter +CBO onset benchmarks unless ``allow_prospective_p08_models=True`` is requested. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +import hashlib +import json +import math +from typing import Any, Literal + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.config.device_inputs import DeviceInput +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import CapabilityError, CompiledDevice1D, compile_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.dc_1d import State1D +from solarlab.experiments.jv.steady import SteadyJVMetrics, steady_jv_metrics +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.physics.registry import ModelRef +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + SteadyState1D, + SteadyStateError, + solve_steady_state, +) + +__all__ = [ + "ADAPTIVE_JV_METRICS", + "CBO_BOUNDARY_POLICIES", + "FIXED_CONTACTS", + "PRE_P08_CBO_MODEL_PINS", + "PROSPECTIVE_P08_MODEL_IDS", + "RECOMPUTED_BUILT_IN", + "CBOCriticalInterval", + "CBOGridConvergenceCertificate", + "CBOScanConfig", + "CBOScanPoint", + "CBOScanResult", + "CBOScanTermination", + "CBOShortCircuitSample", + "CBOVoltageGridConvergenceCertificate", + "CBOVoltageGridConvergencePolicy", + "CBOVoltageGridPointCertificate", + "InterfaceCBOScanError", + "certify_cbo_grid_convergence", + "certify_cbo_voltage_grid_convergence", + "default_cbo_prepared_device", + "enforce_pre_p08_cbo_pinning", + "prepare_cbo_point_device", + "run_cbo_scan", + "validate_cbo_boundary_policy", +] + +FIXED_CONTACTS = "fixed_contacts" +RECOMPUTED_BUILT_IN = "recomputed_built_in" +CBO_BOUNDARY_POLICIES = (FIXED_CONTACTS, RECOMPUTED_BUILT_IN) +ADAPTIVE_JV_METRICS = ("Jsc", "Voc", "FF", "PCE") + +PRE_P08_CBO_MODEL_PINS: tuple[ModelRef, ...] = ( + ModelRef("maxwell_boltzmann_statistics", 1), + ModelRef("dos_aware_scharfetter_gummel_1d", 1), + ModelRef("semiconductor_work_function_contacts", 1), + ModelRef("bulk_srh_radiative_auger_1d", 1), + ModelRef("monochromatic_beer_lambert_1d", 1), +) + +PROSPECTIVE_P08_MODEL_IDS: frozenset[str] = frozenset({ + "spectral_control_volume_beer_lambert", + "tmm_spectral_generation_p08", + "prospective_interface_p08", +}) + + +class InterfaceCBOScanError(RuntimeError): + """A CBO scan could not preserve a certified continuation path or model contract.""" + + +def validate_cbo_boundary_policy(policy: str) -> Literal["fixed_contacts", "recomputed_built_in"]: + """Validate and normalize the contact/built-in-potential boundary policy.""" + normalized = str(policy).strip().lower() + if normalized == FIXED_CONTACTS: + return "fixed_contacts" + if normalized == RECOMPUTED_BUILT_IN: + return "recomputed_built_in" + raise ValueError(f"boundary_policy must be one of {CBO_BOUNDARY_POLICIES}; got {policy!r}") + + +def enforce_pre_p08_cbo_pinning( + prepared: PreparedDevice, + *, + requested_models: Sequence[ModelRef] = (), + allow_prospective_p08_models: bool = False, +) -> tuple[ModelRef, ...]: + """Enforce D20 pre-P08 model pinning on CBO scans unless explicitly opted in.""" + if not isinstance(prepared, PreparedDevice): + raise TypeError("prepared must be a PreparedDevice") + models = tuple(requested_models) if requested_models else PRE_P08_CBO_MODEL_PINS + for item in models: + if not isinstance(item, ModelRef): + raise TypeError("requested_models must contain ModelRef instances") + if allow_prospective_p08_models: + return models + + for item in models: + if item.id in PROSPECTIVE_P08_MODEL_IDS or item.version >= 2: + raise InterfaceCBOScanError( + f"D20 model-pinning violation: prospective P08 model {item.id}@v{item.version} " + "is disallowed unless allow_prospective_p08_models=True" + ) + mapping = prepared.to_mapping() + declaration = mapping.get("declaration", {}) + if declaration.get("spectrum") is not None: + for layer in prepared.layers: + params = dict(layer.parameters) + if bool(params.get("incoherent", False)): + raise InterfaceCBOScanError( + f"D20 model-pinning violation: layer {layer.id!r} enables spectral incoherent " + "optics (P08-04) without allow_prospective_p08_models=True" + ) + return models + + +def default_cbo_prepared_device() -> PreparedDevice: + """Construct a self-contained public 3-layer HTL/absorber/ETL PreparedDevice.""" + catalog_doc: dict[str, Any] = { + "schema": "solarlab.default-catalog.v1", + "material": { + "eps_r": 25.0, + "mu_n": 0.0019340863535916802, + "mu_p": 0.0019340863535916802, + "D_ion": 0.0, + "P_lim": 1e28, + "P0": 0.0, + "ni": 363572901223.5858, + "tau_n": 1e-6, + "tau_p": 1e-6, + "n1": 363572901223.5858, + "p1": 363572901223.5858, + "B_rad": 1e-18, + "C_n": 1e-42, + "C_p": 1e-42, + "alpha": 2000000.0, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.9, + "Eg": 1.6, + "A_star_n": 1.2e6, + "A_star_p": 1.2e6, + "v_th": 100000.0, + "D_ion_neg": 0.0, + "P0_neg": 0.0, + "P_lim_neg": 1e28, + "Nc300": 1e25, + "Nv300": 1e25, + "carrier_statistics": "maxwell_boltzmann", + "dopant_ionization_model": "fully_ionized", + "donor_binding_energy_eV": None, + "acceptor_binding_energy_eV": None, + "donor_degeneracy": 2.0, + "acceptor_degeneracy": 4.0, + "band_gap_narrowing_model": "off", + "bgn_reference_energy_eV": 0.0, + "bgn_reference_density_m3": 1e24, + "bgn_log_shape": 0.5, + "bgn_conduction_band_fraction": 0.5, + "mu_T_gamma": -1.5, + "E_a_ion": 0.0, + "B_rad_T_gamma": 0.0, + "varshni_alpha": 0.0, + "varshni_beta": 0.0, + "trap_N_t_interface": None, + "trap_N_t_bulk": None, + "trap_decay_length": None, + "trap_profile_shape": "exponential", + "trap_edge": "both", + "optical_material": None, + "n_optical": None, + "incoherent": False, + "v_sat_n": 0.0, + "v_sat_p": 0.0, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "pf_gamma_n": 0.0, + "pf_gamma_p": 0.0, + "Eg_back": None, + "chi_back": None, + "grading_profile": "linear", + "grading_direction": "front_to_back", + "grading_bowing": 0.0, + "grading_char_length": None, + "grading_N_mult": 1, + "N_A_bulk": None, + "N_D_bulk": None, + "doping_profile_shape": None, + "doping_decay_length": None, + "doping_edge": "front", + }, + "device": { + "phi_left": 0.0, + "V_bi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "work_function_left_eV": None, + "work_function_right_eV": None, + "Phi": 2e21, + "T": 300.0, + "mode": "fast", + "interface_plane_projection": False, + "dos_band_potentials": True, + "te_physical_norm": False, + "ion_steric_diffusion_only": False, + "ion_steric_shared_site": False, + "flat_band_contacts": False, + "flat_band_metal_contacts": False, + "contact_phi_B_eV": 0.0, + "interface_two_sided": False, + "interface_shared_occupancy": False, + "interface_plane_closure": False, + "interface_plane_generation": False, + "het_recomb_despike": 0.0, + "band_grading": False, + "graded_optics": False, + "interface_tunneling": False, + "tunnel_mass_eff": 0.2, + "jv_solver_policy": "general", + "interface_charge_closure": "off", + "interface_charge_rebaseline_acknowledged": False, + }, + "scaps": { + "D_ion": 0.0, + "P_lim": 1e28, + "P0": 0.0, + "B_rad": 1e-18, + "C_n": 1e-42, + "C_p": 1e-42, + "alpha": 2000000.0, + "tau_n": 1e-6, + "tau_p": 1e-6, + }, + "interface": { + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0, + }, + "constants": { + "Q": 1.602176634e-19, + "K_B": 1.380649e-23, + "T": 300.0, + }, + "contacts": { + "S_n_left": None, + "S_p_left": None, + "S_n_right": None, + "S_p_right": None, + }, + "structural": { + "grain_boundary_layer_role": "absorber", + "tandem_light_direction": "top_first", + "junction_incoherent": False, + }, + "defect_model": "effective_lifetime", + "defect_schema_version": None, + "defect_degeneracy": 1.0, + "distribution_width_convention": "not_applicable", + } + device_doc: dict[str, Any] = { + "schema_version": "solarlab.device-preparation.v1", + "id": "research_cbo_pin", + "name": "Research 1D p-i-n heterojunction CBO baseline", + "source_format": "canonical", + "settings": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "T": 300.0, + "Phi": 2e21, + }, + "layers": [ + { + "id": "htl", + "name": "HTL", + "role": "HTL", + "thickness": 8e-8, + "parameters": { + "chi": 3.6, + "Eg": 1.8, + "Nc300": 2e25, + "Nv300": 3e25, + "eps_r": 3.0, + "N_D": 0.0, + "N_A": 1e24, + "ni": 18609772721.447, + "n1": 18609772721.447, + "p1": 18609772721.447, + "mu_n": 3.8681727071833605e-5, + "mu_p": 3.8681727071833605e-5, + "alpha": 0.0, + "A_star_n": 1.2e6, + "A_star_p": 1.2e6, + }, + }, + { + "id": "absorber", + "name": "absorber", + "role": "absorber", + "thickness": 3e-7, + "parameters": { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1e25, + "Nv300": 1e25, + "eps_r": 25.0, + "N_D": 0.0, + "N_A": 5e22, + "ni": 363572901223.5858, + "n1": 363572901223.5858, + "p1": 363572901223.5858, + "tau_n": 5e-9, + "tau_p": 5e-9, + "mu_n": 0.0019340863535916802, + "mu_p": 0.0019340863535916802, + "alpha": 2000000.0, + "A_star_n": 1.2e6, + "A_star_p": 1.2e6, + }, + }, + { + "id": "etl", + "name": "ETL", + "role": "ETL", + "thickness": 8e-8, + "parameters": { + "chi": 3.9, + "Eg": 2.0, + "Nc300": 4e25, + "Nv300": 2e25, + "eps_r": 9.0, + "N_D": 5e21, + "N_A": 0.0, + "ni": 449039324.31171566, + "n1": 449039324.31171566, + "p1": 449039324.31171566, + "mu_n": 1.0e-5, + "mu_p": 1.0e-5, + "alpha": 0.0, + "A_star_n": 1.2e6, + "A_star_p": 1.2e6, + }, + }, + ], + "electrical_grid": [ + {"layer": "htl", "interval_weight": 12.0, "alpha": 3.0}, + {"layer": "absorber", "interval_weight": 24.0, "alpha": 3.0}, + {"layer": "etl", "interval_weight": 12.0, "alpha": 3.0}, + ], + } + raw_bytes = json.dumps( + {"default_catalog": catalog_doc, "device": device_doc}, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + source = SourceDocument("solarlab_research:cbo_baseline_v1", raw_bytes) + catalog_with_evidence = {**catalog_doc, "evidence": [[source.id, source.sha256]]} + return resolve_device( + DeviceInput.model_validate(device_doc), + DefaultCatalog.from_mapping(catalog_with_evidence), + ResourceLibrary(), + sources=(source,), + ) + + +def prepare_cbo_point_device( + baseline: PreparedDevice, + delta_ec_eV: float, + *, + boundary_policy: str = RECOMPUTED_BUILT_IN, + transport_layer_id: str | None = None, + absorber_layer_id: str | None = None, +) -> PreparedDevice: + """Resolve a PreparedDevice at ``delta_ec_eV = chi_absorber - chi_transport``. + + Under ``recomputed_built_in``, the transport layer's ``chi`` is updated + uniformly so outer-contact work functions adjust ``V_bi``. + Under ``fixed_contacts``, if the swept transport layer touches an outer + electrode, its contact-side affinity is anchored to the baseline contact + affinity via linear grading (``grading_N_mult = 1``) so the absorber/transport + heterointerface step equals ``delta_ec_eV`` while both contact work + functions and ``V_bi`` remain strictly invariant. + """ + if not math.isfinite(delta_ec_eV): + raise ValueError("delta_ec_eV must be finite") + policy = validate_cbo_boundary_policy(boundary_policy) + electrical = [layer for layer in baseline.layers if layer.role != "substrate"] + if len(electrical) < 2: + raise ValueError("CBO scan requires at least two electrical layers") + + absorber = ( + next((layer for layer in electrical if layer.id == absorber_layer_id), None) + if absorber_layer_id is not None + else next((layer for layer in electrical if layer.role.lower() == "absorber"), None) + ) + if absorber is None: + raise ValueError("could not locate absorber layer in PreparedDevice") + transport = ( + next((layer for layer in electrical if layer.id == transport_layer_id), None) + if transport_layer_id is not None + else next((layer for layer in electrical if layer.role.lower() == "etl"), None) + ) + if transport is None: + raise ValueError("could not locate transport layer in PreparedDevice") + + chi_abs = float(dict(absorber.parameters)["chi"]) # type: ignore[arg-type] + chi_transport_base = float(dict(transport.parameters)["chi"]) # type: ignore[arg-type] + target_chi = chi_abs - float(delta_ec_eV) + if target_chi <= 0.0: + raise ValueError(f"delta_ec_eV={delta_ec_eV:g} gives non-positive transport chi={target_chi:g} eV") + + data = baseline.to_input().editing_data() + abs_idx = electrical.index(absorber) + tr_idx = electrical.index(transport) + layer_entry = next(item for item in data["layers"] if item["id"] == transport.id) + params = layer_entry.setdefault("parameters", {}) + + if policy == RECOMPUTED_BUILT_IN or (0 < tr_idx < len(electrical) - 1): + params["chi"] = target_chi + params.pop("chi_back", None) + else: + data.setdefault("settings", {})["band_grading"] = True + params["grading_N_mult"] = 1 + params["grading_profile"] = "linear" + params["grading_direction"] = "front_to_back" + if tr_idx == len(electrical) - 1 and abs_idx < tr_idx: + # Transport layer is on the right: front is absorber interface, back is right contact. + params["chi"] = target_chi + params["chi_back"] = chi_transport_base + elif tr_idx == 0 and tr_idx < abs_idx: + # Transport layer is on the left: front is left contact, back is absorber interface. + params["chi"] = chi_transport_base + params["chi_back"] = target_chi + else: + params["chi"] = target_chi + + return resolve_device( + DeviceInput.model_validate(data), + baseline.defaults, + baseline.resources, + sources=baseline.sources, + ) + + +@dataclass(frozen=True, slots=True) +class CBOVoltageGridConvergencePolicy: + """Acceptance thresholds for nested J-V voltage-grid convergence.""" + + minimum_voltage_grids: int = 2 + maximum_voc_change_V: float = 5.0e-3 + maximum_ff_change: float = 1.5e-2 + maximum_pce_change: float = 1.5e-2 + + def __post_init__(self) -> None: + if type(self.minimum_voltage_grids) is not int or self.minimum_voltage_grids < 2: + raise ValueError("minimum_voltage_grids must be an integer >= 2") + for name in ("maximum_voc_change_V", "maximum_ff_change", "maximum_pce_change"): + val = getattr(self, name) + if isinstance(val, bool) or not math.isfinite(float(val)) or float(val) <= 0.0: + raise ValueError(f"{name} must be finite and positive") + + +def _default_cbo_steady_options() -> SteadyOptions: + return SteadyOptions( + convergence_policy=POISSON_CONTACT_BALANCE_V1, + continuity_tolerance_A_m2=1.0e-6, + current_spread_tolerance_A_m2=1.0e-6, + ) + + +@dataclass(frozen=True, slots=True) +class CBOScanConfig: + """Configuration for a public 1D CBO scan.""" + + delta_ec_eV: tuple[float, ...] + reference_delta_ec_eV: float = 0.0 + boundary_policy: str = RECOMPUTED_BUILT_IN + interface_topology: Literal["deduplicated", "two_sided_trace"] = "deduplicated" + interface_transmission: float = 1.0 + intervals_per_layer: int | tuple[int, ...] = 12 + voltages_V: tuple[float, ...] | None = None + voltage_grids_V: tuple[tuple[float, ...], ...] | None = None + incident_power_W_m2: float = 1000.0 + generation_scale: float = 1.0 + relative_drop_fraction: float = 0.05 + minimum_delta_step_eV: float = 5.0e-3 + maximum_delta_step_eV: float = 0.2 + max_bridge_points: int = 64 + calculate_jv_metrics: bool = True + allow_prospective_p08_models: bool = False + requested_models: tuple[ModelRef, ...] = () + steady_options: SteadyOptions = field(default_factory=_default_cbo_steady_options) + voltage_grid_policy: CBOVoltageGridConvergencePolicy = field( + default_factory=CBOVoltageGridConvergencePolicy + ) + + def __post_init__(self) -> None: + validate_cbo_boundary_policy(self.boundary_policy) + if not self.delta_ec_eV or any(not math.isfinite(v) for v in self.delta_ec_eV): + raise ValueError("delta_ec_eV must be a non-empty sequence of finite floats") + if not math.isfinite(self.reference_delta_ec_eV): + raise ValueError("reference_delta_ec_eV must be finite") + if not 0.0 < self.relative_drop_fraction < 1.0: + raise ValueError("relative_drop_fraction must lie strictly in (0, 1)") + if self.minimum_delta_step_eV <= 0.0 or self.maximum_delta_step_eV < self.minimum_delta_step_eV: + raise ValueError("0 < minimum_delta_step_eV <= maximum_delta_step_eV is required") + if self.voltages_V is not None and self.voltage_grids_V is not None: + raise ValueError("specify either voltages_V or voltage_grids_V, not both") + + +@dataclass(frozen=True, slots=True) +class CBOShortCircuitSample: + """One certified short-circuit point along the CBO continuation path.""" + + delta_ec_eV: float + output_current_A_m2: float + requested: bool + face_current_spread_A_m2: float + applied_V_bi_V: float + compiled_identity: str + + +@dataclass(frozen=True, slots=True) +class CBOScanPoint: + """Certified operating results and J-V metrics at one CBO value.""" + + delta_ec_eV: float + requested: bool + applied_V_bi_V: float + compiled_identity: str + short_circuit_output_A_m2: float + face_current_spread_A_m2: float + voltage_V: NDArray[np.float64] + output_current_A_m2: NDArray[np.float64] + metrics: SteadyJVMetrics | None + certified: bool + + +@dataclass(frozen=True, slots=True) +class CBOCriticalInterval: + """Sample-bounded onset interval for a relative metric drop on the spike branch.""" + + metric: str + reference_delta_ec_eV: float + reference_value: float | None + relative_drop_fraction: float + threshold_value: float | None + lower_delta_ec_eV: float | None + upper_delta_ec_eV: float | None + resolved: bool + + +@dataclass(frozen=True, slots=True) +class CBOScanTermination: + """Bracket where continuation terminated along one CBO branch.""" + + direction: str + last_certified_delta_ec_eV: float + first_failed_delta_ec_eV: float + requested_delta_ec_eV: float + reason: str + + +@dataclass(frozen=True, slots=True) +class CBOVoltageGridPointCertificate: + """Nested voltage-grid convergence audit at a single CBO value.""" + + delta_ec_eV: float + voltage_point_counts: tuple[int, ...] + voc_values_V: tuple[float, ...] + ff_values: tuple[float, ...] + pce_values: tuple[float, ...] + final_voc_change_V: float | None + final_ff_change: float | None + final_pce_change: float | None + certified: bool + reasons: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class CBOVoltageGridConvergenceCertificate: + """Nested voltage-grid convergence certificate across all requested CBO points.""" + + voltage_point_counts: tuple[int, ...] + minimum_voltage_grids: int + maximum_voc_change_V: float + maximum_ff_change: float + maximum_pce_change: float + points: tuple[CBOVoltageGridPointCertificate, ...] + certified: bool + reasons: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class CBOGridConvergenceCertificate: + """Spatial mesh convergence certificate across multiple CBO scans.""" + + metric: str + grid_interval_counts: tuple[int, ...] + critical_intervals_eV: tuple[tuple[float, float], ...] + envelope_lower_eV: float | None + envelope_upper_eV: float | None + envelope_width_eV: float | None + maximum_envelope_width_eV: float + reference_values: tuple[float, ...] + reference_relative_spread: float | None + maximum_reference_relative_spread: float + certified: bool + reasons: tuple[str, ...] + + +@dataclass(frozen=True, slots=True) +class CBOScanResult: + """Complete result of a public 1D CBO scan.""" + + requested_delta_ec_eV: NDArray[np.float64] + points: tuple[CBOScanPoint, ...] + short_circuit_trace: tuple[CBOShortCircuitSample, ...] + critical_intervals: tuple[CBOCriticalInterval, ...] + terminations: tuple[CBOScanTermination, ...] + reference_delta_ec_eV: float + relative_drop_fraction: float + boundary_policy: str + interface_topology: str + interface_transmission: float + grid_node_count: int + grid_interval_count: int + bridge_point_count: int + pinned_models: tuple[ModelRef, ...] + voltage_grids_V: tuple[NDArray[np.float64], ...] + voltage_grid_policy: CBOVoltageGridConvergencePolicy + protocol_sha256: str + + @property + def sync_vbi(self) -> bool: + return self.boundary_policy == RECOMPUTED_BUILT_IN + + @property + def complete(self) -> bool: + req = [p for p in self.points if p.requested] + return bool( + not self.terminations + and len(req) == self.requested_delta_ec_eV.size + and all( + any(math.isclose(p.delta_ec_eV, float(t), rel_tol=0.0, abs_tol=1.0e-12) for p in req) + for t in self.requested_delta_ec_eV + ) + ) + + @property + def certified(self) -> bool: + return bool(self.points and all(p.certified for p in self.points)) + + +def _validate_nested_voltage_grids( + grids: Sequence[ArrayLike], +) -> tuple[NDArray[np.float64], ...]: + if not grids: + raise ValueError("at least one voltage grid is required") + resolved: list[NDArray[np.float64]] = [] + for raw in grids: + arr = np.array(raw, dtype=float, copy=True) + if arr.ndim != 1 or arr.size < 2 or not np.all(np.isfinite(arr)): + raise ValueError("each voltage grid must be a 1D finite array with at least 2 points") + if not np.all(np.diff(arr) > 0.0): + raise ValueError("each voltage grid must be strictly increasing") + if not (arr[0] <= 0.0 <= arr[-1]): + raise ValueError("each voltage grid must bracket 0 V") + arr.setflags(write=False) + resolved.append(arr) + for coarse, fine in zip(resolved, resolved[1:]): + if fine.size <= coarse.size: + raise ValueError("nested voltage grids must strictly increase in point count") + for v in coarse: + if not np.any(np.isclose(fine, v, rtol=0.0, atol=1.0e-12)): + raise ValueError(f"coarse voltage {v:g} V is missing from refined voltage grid") + return tuple(resolved) + + +def _critical_interval_for_metric( + samples: Sequence[tuple[float, float]], + *, + metric: str, + reference_delta_ec_eV: float, + relative_drop_fraction: float, +) -> CBOCriticalInterval: + ordered = sorted(samples, key=lambda item: item[0]) + ref_val = next( + (val for delta, val in ordered if math.isclose(delta, reference_delta_ec_eV, rel_tol=0.0, abs_tol=1.0e-9)), + None, + ) + if ref_val is None or not math.isfinite(ref_val) or ref_val <= 0.0: + return CBOCriticalInterval( + metric=metric, + reference_delta_ec_eV=reference_delta_ec_eV, + reference_value=ref_val, + relative_drop_fraction=relative_drop_fraction, + threshold_value=None, + lower_delta_ec_eV=None, + upper_delta_ec_eV=None, + resolved=False, + ) + threshold = ref_val * (1.0 - relative_drop_fraction) + positive_branch = [ + (delta, val) for delta, val in ordered if delta >= reference_delta_ec_eV - 1.0e-12 + ] + prev_delta: float | None = None + for delta, val in positive_branch: + if val <= threshold and prev_delta is not None: + return CBOCriticalInterval( + metric=metric, + reference_delta_ec_eV=reference_delta_ec_eV, + reference_value=ref_val, + relative_drop_fraction=relative_drop_fraction, + threshold_value=threshold, + lower_delta_ec_eV=prev_delta, + upper_delta_ec_eV=delta, + resolved=True, + ) + if val > threshold: + prev_delta = delta + return CBOCriticalInterval( + metric=metric, + reference_delta_ec_eV=reference_delta_ec_eV, + reference_value=ref_val, + relative_drop_fraction=relative_drop_fraction, + threshold_value=threshold, + lower_delta_ec_eV=prev_delta, + upper_delta_ec_eV=None, + resolved=False, + ) + + +def _seed_state_on_compiled( + target_compiled: CompiledDevice1D, + previous_steady: SteadyState1D, +) -> State1D | None: + """Project an accepted steady state onto a neighboring CBO compiled device.""" + u_prev = previous_steady.state.u + if u_prev.size != 3 * target_compiled.node_count: + return None + left_p, right_p = target_compiled.contact_potentials(previous_steady.voltage_V) + u_trial = np.array(u_prev, dtype=float, copy=True) + # Match exact Dirichlet boundary potentials for the new compiled device. + old_left, old_right = float(u_prev[0]), float(u_prev[target_compiled.node_count - 1]) + span = target_compiled.nodes_m[-1] - target_compiled.nodes_m[0] + s = (target_compiled.nodes_m - target_compiled.nodes_m[0]) / span + u_trial[: target_compiled.node_count] += (left_p - old_left) * (1.0 - s) + (right_p - old_right) * s + try: + state: State1D = target_compiled.state(u_trial, voltage_V=previous_steady.voltage_V) + except ValueError: + return None + return state + + +def _solve_jv_from_short_circuit( + compiled: CompiledDevice1D, + sc_steady: SteadyState1D, + voltages_V: NDArray[np.float64], + *, + generation_scale: float, + incident_power_W_m2: float, + options: SteadyOptions, +) -> tuple[NDArray[np.float64], SteadyJVMetrics]: + """Continue upward and downward from an already-certified V=0 state.""" + polarity = float(compiled.voltage_polarity) + solutions_by_idx: dict[int, SteadyState1D] = {} + + zero_matches = np.flatnonzero(np.isclose(voltages_V, 0.0, rtol=0.0, atol=1.0e-12)) + if zero_matches.size: + zero_idx = int(zero_matches[0]) + solutions_by_idx[zero_idx] = sc_steady + up_indices = list(range(zero_idx + 1, voltages_V.size)) + down_indices = list(range(zero_idx - 1, -1, -1)) + else: + pos = np.flatnonzero(voltages_V > 0.0) + up_indices = pos.tolist() + down_indices = np.flatnonzero(voltages_V < 0.0)[::-1].tolist() + + def _advance_bias(state_in: State1D, v_from: float, v_to: float) -> SteadyState1D: + dv = v_to - v_from + if abs(dv) <= 1.0e-15: + return solve_steady_state( + compiled, + initial_state=state_in, + voltage_V=v_to, + generation_scale=generation_scale, + options=options, + ) + try: + return solve_steady_state( + compiled, + initial_state=state_in, + voltage_V=v_to, + generation_scale=generation_scale, + options=options, + ) + except SteadyStateError: + if abs(dv) <= 1.0e-3: + raise + v_mid = 0.5 * (v_from + v_to) + mid_sol = _advance_bias(state_in, v_from, v_mid) + return _advance_bias(mid_sol.state, v_mid, v_to) + + def march(indices: list[int], anchor: SteadyState1D) -> None: + state = anchor.state + prev_v = anchor.voltage_V + for idx in indices: + target_v = float(voltages_V[idx]) + dv = target_v - prev_v + sub_count = max(1, int(math.ceil(abs(dv) / options.max_bias_step_V))) + cur_v = prev_v + for step_i in range(1, sub_count + 1): + v_step = prev_v + dv * (step_i / sub_count) + sol = _advance_bias(state, cur_v, v_step) + state = sol.state + cur_v = v_step + if step_i == sub_count: + solutions_by_idx[idx] = sol + prev_v = target_v + + march(up_indices, sc_steady) + march(down_indices, sc_steady) + + ordered = [solutions_by_idx[i] for i in range(voltages_V.size)] + currents = np.array([ -polarity * float(sol.current_density_A_m2[0]) for sol in ordered ], dtype=float) + currents.setflags(write=False) + metrics = steady_jv_metrics(voltages_V, currents, incident_power_W_m2=incident_power_W_m2) + return currents, metrics + + +def run_cbo_scan( + baseline: PreparedDevice, + config: CBOScanConfig, +) -> CBOScanResult: + """Run a certified 1D CBO scan with adaptive bridge continuation.""" + pinned = enforce_pre_p08_cbo_pinning( + baseline, + requested_models=config.requested_models, + allow_prospective_p08_models=config.allow_prospective_p08_models, + ) + policy = validate_cbo_boundary_policy(config.boundary_policy) + + if config.voltage_grids_V is not None: + v_grids = _validate_nested_voltage_grids(config.voltage_grids_V) + elif config.voltages_V is not None: + v_grids = _validate_nested_voltage_grids((config.voltages_V,)) + else: + v_grids = _validate_nested_voltage_grids((np.linspace(0.0, 1.125, 25),)) + finest_v = v_grids[-1] + + requested_arr = np.array(sorted(set(float(v) for v in config.delta_ec_eV)), dtype=float) + requested_arr.setflags(write=False) + ref_delta = float(config.reference_delta_ec_eV) + + all_targets = sorted(set([*requested_arr.tolist(), ref_delta])) + pos_targets = [d for d in all_targets if d > ref_delta + 1.0e-12] + neg_targets = sorted([d for d in all_targets if d < ref_delta - 1.0e-12], reverse=True) + + trace: list[CBOShortCircuitSample] = [] + sc_by_key: dict[float, tuple[CompiledDevice1D, SteadyState1D]] = {} + terminations: list[CBOScanTermination] = [] + bridge_count = 0 + + def compile_at(delta: float) -> CompiledDevice1D: + prep = prepare_cbo_point_device(baseline, delta, boundary_policy=policy) + return compile_device_1d( + prep, + intervals_per_layer=config.intervals_per_layer, + interface_topology=config.interface_topology, + interface_transmission=config.interface_transmission, + ) + + def solve_sc( + delta: float, + anchor: SteadyState1D | None, + *, + requested: bool, + ) -> tuple[CompiledDevice1D, SteadyState1D]: + compiled = compile_at(delta) + seed = None if anchor is None else _seed_state_on_compiled(compiled, anchor) + try: + sol = solve_steady_state( + compiled, + initial_state=seed, + voltage_V=0.0, + generation_scale=config.generation_scale, + options=config.steady_options, + ) + except SteadyStateError: + if seed is None: + raise + sol = solve_steady_state( + compiled, + initial_state=None, + voltage_V=0.0, + generation_scale=config.generation_scale, + options=config.steady_options, + ) + polarity = float(compiled.voltage_polarity) + all_curr = np.r_[ + sol.contact_current_density_A_m2[:1], + sol.current_density_A_m2, + sol.contact_current_density_A_m2[1:], + ] + trace.append( + CBOShortCircuitSample( + delta_ec_eV=delta, + output_current_A_m2=float(-polarity * sol.current_density_A_m2[0]), + requested=requested, + face_current_spread_A_m2=float(np.ptp(all_curr)), + applied_V_bi_V=float(compiled.built_in_potential_V), + compiled_identity=compiled.identity, + ) + ) + return compiled, sol + + ref_requested = bool(np.any(np.isclose(requested_arr, ref_delta, rtol=0.0, atol=1.0e-12))) + ref_compiled, ref_sc = solve_sc(ref_delta, None, requested=ref_requested) + sc_by_key[ref_delta] = (ref_compiled, ref_sc) + + def continue_branch(targets: list[float], direction: str) -> None: + nonlocal bridge_count + current_delta = ref_delta + current_sc = ref_sc + for target in targets: + while not math.isclose(current_delta, target, rel_tol=0.0, abs_tol=1.0e-12): + remaining = target - current_delta + step = math.copysign(min(abs(remaining), config.maximum_delta_step_eV), remaining) + candidate = target if abs(remaining) <= config.maximum_delta_step_eV + 1.0e-15 else current_delta + step + is_req = math.isclose(candidate, target, rel_tol=0.0, abs_tol=1.0e-12) and bool( + np.any(np.isclose(requested_arr, target, rtol=0.0, atol=1.0e-12)) + ) + while True: + try: + comp, sol = solve_sc(candidate, current_sc, requested=is_req) + if not is_req: + bridge_count += 1 + current_delta = candidate + current_sc = sol + if is_req: + sc_by_key[target] = (comp, sol) + break + except (SteadyStateError, CapabilityError, ValueError) as exc: + half = 0.5 * (candidate - current_delta) + if abs(half) < config.minimum_delta_step_eV or bridge_count >= config.max_bridge_points: + terminations.append( + CBOScanTermination( + direction=direction, + last_certified_delta_ec_eV=current_delta, + first_failed_delta_ec_eV=candidate, + requested_delta_ec_eV=target, + reason=str(exc), + ) + ) + return + candidate = current_delta + half + is_req = False + + continue_branch(pos_targets, "positive_spike") + continue_branch(neg_targets, "negative_cliff") + + points: list[CBOScanPoint] = [] + for delta in sorted(sc_by_key): + comp, sc_sol = sc_by_key[delta] + is_req = bool(np.any(np.isclose(requested_arr, delta, rtol=0.0, atol=1.0e-12))) + polarity = float(comp.voltage_polarity) + sc_out = float(-polarity * sc_sol.current_density_A_m2[0]) + all_curr = np.r_[ + sc_sol.contact_current_density_A_m2[:1], + sc_sol.current_density_A_m2, + sc_sol.contact_current_density_A_m2[1:], + ] + spread = float(np.ptp(all_curr)) + if config.calculate_jv_metrics: + j_out, metrics = _solve_jv_from_short_circuit( + comp, + sc_sol, + finest_v, + generation_scale=config.generation_scale, + incident_power_W_m2=config.incident_power_W_m2, + options=config.steady_options, + ) + v_arr = finest_v + else: + v_arr = np.array([0.0], dtype=float) + v_arr.setflags(write=False) + j_out = np.array([sc_out], dtype=float) + j_out.setflags(write=False) + metrics = None + points.append( + CBOScanPoint( + delta_ec_eV=delta, + requested=is_req, + applied_V_bi_V=float(comp.built_in_potential_V), + compiled_identity=comp.identity, + short_circuit_output_A_m2=sc_out, + face_current_spread_A_m2=spread, + voltage_V=v_arr, + output_current_A_m2=j_out, + metrics=metrics, + certified=bool(sc_sol.converged and spread <= config.steady_options.current_spread_tolerance_A_m2), + ) + ) + + intervals: list[CBOCriticalInterval] = [] + jsc_samples = [ + ( + p.delta_ec_eV, + p.short_circuit_output_A_m2 + if p.metrics is None or p.metrics.short_circuit_current_A_m2 is None + else p.metrics.short_circuit_current_A_m2, + ) + for p in points + ] + intervals.append( + _critical_interval_for_metric( + jsc_samples, + metric="Jsc", + reference_delta_ec_eV=ref_delta, + relative_drop_fraction=config.relative_drop_fraction, + ) + ) + if config.calculate_jv_metrics: + for metric_name, attr in ( + ("Voc", "open_circuit_voltage_V"), + ("FF", "fill_factor"), + ("PCE", "efficiency"), + ): + m_samples = [ + (p.delta_ec_eV, float(getattr(p.metrics, attr))) + for p in points + if p.metrics is not None and getattr(p.metrics, attr) is not None + ] + intervals.append( + _critical_interval_for_metric( + m_samples, + metric=metric_name, + reference_delta_ec_eV=ref_delta, + relative_drop_fraction=config.relative_drop_fraction, + ) + ) + + protocol_payload = { + "schema": "solarlab_research.cbo_scan_protocol.v1", + "baseline_sha256": baseline.content_sha256, + "boundary_policy": policy, + "interface_topology": config.interface_topology, + "interface_transmission": config.interface_transmission, + "reference_delta_ec_eV": ref_delta, + "relative_drop_fraction": config.relative_drop_fraction, + "pinned_models": [{"id": m.id, "version": m.version} for m in pinned], + } + protocol_sha = hashlib.sha256( + json.dumps(protocol_payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + return CBOScanResult( + requested_delta_ec_eV=requested_arr, + points=tuple(p for p in points if p.requested), + short_circuit_trace=tuple(trace), + critical_intervals=tuple(intervals), + terminations=tuple(terminations), + reference_delta_ec_eV=ref_delta, + relative_drop_fraction=config.relative_drop_fraction, + boundary_policy=policy, + interface_topology=config.interface_topology, + interface_transmission=config.interface_transmission, + grid_node_count=ref_compiled.node_count, + grid_interval_count=ref_compiled.node_count - 1, + bridge_point_count=bridge_count, + pinned_models=pinned, + voltage_grids_V=v_grids if config.calculate_jv_metrics else (), + voltage_grid_policy=config.voltage_grid_policy, + protocol_sha256=protocol_sha, + ) + + +def certify_cbo_voltage_grid_convergence( + result: CBOScanResult, + *, + incident_power_W_m2: float = 1000.0, +) -> CBOVoltageGridConvergenceCertificate: + """Certify nested voltage-grid convergence of Voc, FF, and PCE across CBO points.""" + policy = result.voltage_grid_policy + reasons: list[str] = [] + counts = tuple(int(g.size) for g in result.voltage_grids_V) + if len(result.voltage_grids_V) < policy.minimum_voltage_grids: + reasons.append( + f"requires at least {policy.minimum_voltage_grids} nested voltage grids; got {len(result.voltage_grids_V)}" + ) + + point_certs: list[CBOVoltageGridPointCertificate] = [] + finest = result.voltage_grids_V[-1] if result.voltage_grids_V else np.empty(0) + for pt in result.points: + pt_reasons: list[str] = [] + vocs: list[float] = [] + ffs: list[float] = [] + pces: list[float] = [] + for grid in result.voltage_grids_V: + mask = np.isin(np.round(finest, 12), np.round(grid, 12)) + sub_v = pt.voltage_V[mask] + sub_j = pt.output_current_A_m2[mask] + m = steady_jv_metrics(sub_v, sub_j, incident_power_W_m2=incident_power_W_m2) + if m.open_circuit_voltage_V is None or m.fill_factor is None or m.efficiency is None: + pt_reasons.append(f"grid {grid.size} failed to bracket Voc/FF/PCE ({m.limitation})") + else: + vocs.append(m.open_circuit_voltage_V) + ffs.append(m.fill_factor) + pces.append(m.efficiency) + + d_voc = abs(vocs[-1] - vocs[-2]) if len(vocs) >= 2 else None + d_ff = abs(ffs[-1] - ffs[-2]) if len(ffs) >= 2 else None + d_pce = abs(pces[-1] - pces[-2]) if len(pces) >= 2 else None + if d_voc is None or d_voc > policy.maximum_voc_change_V: + pt_reasons.append(f"Voc change {d_voc} exceeds {policy.maximum_voc_change_V}") + if d_ff is None or d_ff > policy.maximum_ff_change: + pt_reasons.append(f"FF change {d_ff} exceeds {policy.maximum_ff_change}") + if d_pce is None or d_pce > policy.maximum_pce_change: + pt_reasons.append(f"PCE change {d_pce} exceeds {policy.maximum_pce_change}") + + pt_ok = not pt_reasons and len(vocs) == len(result.voltage_grids_V) + if not pt_ok: + reasons.append(f"CBO {pt.delta_ec_eV:+.4f} eV failed voltage-grid convergence") + point_certs.append( + CBOVoltageGridPointCertificate( + delta_ec_eV=pt.delta_ec_eV, + voltage_point_counts=counts, + voc_values_V=tuple(vocs), + ff_values=tuple(ffs), + pce_values=tuple(pces), + final_voc_change_V=d_voc, + final_ff_change=d_ff, + final_pce_change=d_pce, + certified=pt_ok, + reasons=tuple(pt_reasons), + ) + ) + + return CBOVoltageGridConvergenceCertificate( + voltage_point_counts=counts, + minimum_voltage_grids=policy.minimum_voltage_grids, + maximum_voc_change_V=policy.maximum_voc_change_V, + maximum_ff_change=policy.maximum_ff_change, + maximum_pce_change=policy.maximum_pce_change, + points=tuple(point_certs), + certified=bool(point_certs and not reasons), + reasons=tuple(dict.fromkeys(reasons)), + ) + + +def certify_cbo_grid_convergence( + scans: Sequence[CBOScanResult], + *, + metric: str = "FF", + minimum_grids: int = 2, + maximum_envelope_width_eV: float = 0.15, + maximum_reference_relative_spread: float = 0.02, +) -> CBOGridConvergenceCertificate: + """Certify spatial grid convergence of critical CBO onset across meshes.""" + ordered = sorted(scans, key=lambda s: s.grid_interval_count) + reasons: list[str] = [] + if len(ordered) < minimum_grids: + reasons.append(f"requires at least {minimum_grids} spatial grids; got {len(ordered)}") + counts = tuple(s.grid_interval_count for s in ordered) + if len(set(counts)) != len(counts): + reasons.append("spatial grid interval counts must be unique") + if ordered and len({s.protocol_sha256 for s in ordered}) != 1: + reasons.append("spatial grid scans do not share identical physical protocol_sha256") + for s in ordered: + if not s.complete or not s.certified: + reasons.append(f"grid {s.grid_interval_count} is incomplete or uncertified") + + intervals: list[tuple[float, float]] = [] + ref_vals: list[float] = [] + for s in ordered: + ci = next((c for c in s.critical_intervals if c.metric == metric), None) + if ci is None or not ci.resolved or ci.lower_delta_ec_eV is None or ci.upper_delta_ec_eV is None: + reasons.append(f"grid {s.grid_interval_count} did not resolve {metric} critical interval") + else: + intervals.append((ci.lower_delta_ec_eV, ci.upper_delta_ec_eV)) + if ci is not None and ci.reference_value is not None: + ref_vals.append(ci.reference_value) + + env_lo = min(lo for lo, _ in intervals) if intervals else None + env_hi = max(hi for _, hi in intervals) if intervals else None + env_w = (env_hi - env_lo) if (env_lo is not None and env_hi is not None) else None + if env_w is None or env_w > maximum_envelope_width_eV: + reasons.append(f"critical-interval envelope width {env_w} exceeds {maximum_envelope_width_eV}") + + ref_spread: float | None = None + if ref_vals and min(ref_vals) > 0.0: + ref_spread = (max(ref_vals) - min(ref_vals)) / max(ref_vals) + if ref_spread > maximum_reference_relative_spread: + reasons.append(f"reference {metric} spread {ref_spread} exceeds {maximum_reference_relative_spread}") + else: + reasons.append(f"missing positive reference {metric} values") + + return CBOGridConvergenceCertificate( + metric=metric, + grid_interval_counts=counts, + critical_intervals_eV=tuple(intervals), + envelope_lower_eV=env_lo, + envelope_upper_eV=env_hi, + envelope_width_eV=env_w, + maximum_envelope_width_eV=maximum_envelope_width_eV, + reference_values=tuple(ref_vals), + reference_relative_spread=ref_spread, + maximum_reference_relative_spread=maximum_reference_relative_spread, + certified=not reasons, + reasons=tuple(dict.fromkeys(reasons)), + ) diff --git a/src/solarlab_research/precision/__init__.py b/src/solarlab_research/precision/__init__.py new file mode 100644 index 00000000..0d26d089 --- /dev/null +++ b/src/solarlab_research/precision/__init__.py @@ -0,0 +1,71 @@ +"""Public precision primitives, compensated constitutive kernels, and state codecs.""" + +from solarlab_research.precision.codecs import ( + INPUT_LIFT_CHECKPOINT_SCHEMA, + INPUT_LIFT_REPRESENTATION, + INPUT_LIFT_STATE_SCHEMA, + PAIR_REPRESENTATION, + AffineInputLiftCodec, + InputLiftCheckpointError, + PairStateAuthority, + ReferenceIncrementCoordinates, + ResearchCoordinateMap, + ResearchStateCodec, + decode_historical_r1_pair_state, +) +from solarlab_research.precision.double_double import ( + CompensatedArithmetic, + DD, + DDArray, + exp, + expm1, + log, + log1p, + sum, +) +from solarlab_research.precision.two_sided_interface import ( + SCHEMA, + SCOPE, + CompensatedCarrierBalance, + CompensatedCarrierTangent, + FrozenLocalCoefficients, + LocalCarrierEvaluation, + UnsupportedCompensatedInterfaceDomain, + default_fd_table, + evaluate_local_carrier_pair, + freeze_coefficients, + to_float_tangent, +) + +__all__ = [ + "AffineInputLiftCodec", + "CompensatedArithmetic", + "CompensatedCarrierBalance", + "CompensatedCarrierTangent", + "DD", + "DDArray", + "FrozenLocalCoefficients", + "INPUT_LIFT_CHECKPOINT_SCHEMA", + "INPUT_LIFT_REPRESENTATION", + "INPUT_LIFT_STATE_SCHEMA", + "InputLiftCheckpointError", + "LocalCarrierEvaluation", + "PAIR_REPRESENTATION", + "PairStateAuthority", + "ReferenceIncrementCoordinates", + "ResearchCoordinateMap", + "ResearchStateCodec", + "SCHEMA", + "SCOPE", + "UnsupportedCompensatedInterfaceDomain", + "decode_historical_r1_pair_state", + "default_fd_table", + "evaluate_local_carrier_pair", + "exp", + "expm1", + "freeze_coefficients", + "log", + "log1p", + "sum", + "to_float_tangent", +] diff --git a/src/solarlab_research/precision/codecs.py b/src/solarlab_research/precision/codecs.py new file mode 100644 index 00000000..8189e9d6 --- /dev/null +++ b/src/solarlab_research/precision/codecs.py @@ -0,0 +1,568 @@ +"""Precision state authorities, reference-increment coordinates, and pair codecs. + +Implements precision injection through ``solarlab.contracts`` state and +coordinate boundaries (``StateAuthority``, ``StateIncrement``, ``Point``, +``StateView``, ``FieldProjection``) without registering physics models. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +import hashlib +import json +import math +import re +from types import MappingProxyType +from typing import Any, Protocol + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import ( + VOLT, + ContractError, + FieldProjection, + Layout, + PhysicalArray, + Point, + StateAuthority, + StateIncrement, + StateView, + Vector, + frozen_array, + integer_indices, +) +from solarlab_research.precision.double_double import DD, DDArray, log1p + +__all__ = [ + "AffineInputLiftCodec", + "INPUT_LIFT_CHECKPOINT_SCHEMA", + "INPUT_LIFT_REPRESENTATION", + "INPUT_LIFT_STATE_SCHEMA", + "InputLiftCheckpointError", + "PAIR_REPRESENTATION", + "PairStateAuthority", + "ReferenceIncrementCoordinates", + "ResearchCoordinateMap", + "ResearchStateCodec", + "decode_historical_r1_pair_state", +] + +PAIR_REPRESENTATION = "float64-pair-v1" +INPUT_LIFT_REPRESENTATION = "affine-input-lift-dd-v1" +INPUT_LIFT_CHECKPOINT_SCHEMA = "SolarLabResearchInputLiftCheckpointV1" +INPUT_LIFT_STATE_SCHEMA = "SolarLabResearchInputLiftStateV1" +_COORDINATE_ROLE = "accepted_physical_state_imported_as_new_zero_coordinate_reference" +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + + +class InputLiftCheckpointError(ValueError): + """Raised when an input-lift checkpoint or pair state violates codec invariants.""" + + +class ResearchCoordinateMap(Protocol): + """Research-side coordinate map over a ``solarlab.contracts.Layout``.""" + + @property + def layout(self) -> Layout: ... + @property + def reference(self) -> str: ... + def point(self, y: ArrayLike, time: float = 0.0, inputs: ArrayLike = ()) -> Point: ... + def advance( + self, left: Point, dy: ArrayLike, time: float, inputs: ArrayLike = () + ) -> tuple[Point, StateIncrement]: ... + + +class ResearchStateCodec(Protocol): + """Research-side lossless state codec preserving compensated low words.""" + + def encode_point(self, point: Point) -> dict[str, Any]: ... + def decode_point(self, payload: Mapping[str, Any], *, layout: Layout) -> Point: ... + + +def _canonical_json(value: Any) -> str: + try: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + except (TypeError, ValueError) as exc: + raise InputLiftCheckpointError("payload is not finite canonical JSON") from exc + + +def _digest(value: Any) -> str: + return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest() + + +def _face_pairs(pairs: ArrayLike, size: int) -> NDArray[np.intp]: + idx = integer_indices(pairs) + if idx.ndim != 2 or idx.shape[1] != 2 or np.any(idx < 0) or np.any(idx >= size): + raise ContractError("face_outside_support") + return idx + + +@dataclass(frozen=True) +class PairStateAuthority: + """``StateAuthority`` retaining normalized ``DDArray`` fields and exact increments.""" + + layout_identity: str + values: Mapping[str, DDArray] + anchor_reference: str + bound_coordinate: Vector | None = None + identity: str = field(init=False) + + def __post_init__(self) -> None: + if not self.anchor_reference: + raise ContractError("empty_authority_reference") + owned: dict[str, DDArray] = {} + for name, item in self.values.items(): + if not isinstance(item, DDArray) or not item.is_finite(): + raise ContractError("pair_authority_requires_finite_dd_arrays") + owned[name] = item.immutable_copy() + object.__setattr__(self, "values", MappingProxyType(owned)) + if self.bound_coordinate is not None: + coord = frozen_array(self.bound_coordinate) + if coord.ndim != 1: + raise ContractError("invalid_coordinate_shape") + object.__setattr__(self, "bound_coordinate", coord) + sha = hashlib.sha256( + b"pair-state-authority-v1:" + + self.layout_identity.encode() + + b":" + + self.anchor_reference.encode() + ) + for name in sorted(owned): + sha.update(name.encode() + owned[name].identity_bytes()) + object.__setattr__(self, "identity", sha.hexdigest()) + + def field(self, name: str) -> PhysicalArray: + return self.values[name] + + def dd_field(self, name: str) -> DDArray: + return self.values[name] + + def delta_from(self, left: StateView) -> Mapping[str, PhysicalArray]: + if not isinstance(left.authority, PairStateAuthority): + raise ContractError("authority_rebase_required") + if left.authority.layout_identity != self.layout_identity: + raise ContractError("increment_layout_mismatch") + return { + name: val.difference(left.authority.dd_field(name)) + for name, val in self.values.items() + } + + def project(self, name: str) -> FieldProjection: + return self.values[name].project_to_float(authority_identity=self.identity) + + def validate_binding(self, time: float, y: Vector, inputs: Vector, reference: str) -> None: + if reference != self.anchor_reference: + raise ContractError("coordinate_reference_mismatch") + if self.bound_coordinate is not None and not np.array_equal(y, self.bound_coordinate): + raise ContractError("authority_coordinate_binding_mismatch") + + def validate_transition(self, left: Point, right: Point) -> None: + if not isinstance(left.state.authority, PairStateAuthority): + raise ContractError("authority_rebase_required") + if left.coordinate_reference != right.coordinate_reference: + raise ContractError("coordinate_reference_mismatch") + + def electrochemical_difference( + self, + density_id: str, + potential_id: str, + pairs: ArrayLike, + thermal_voltage: float, + potential_sign: int, + ) -> PhysicalArray | None: + if not math.isfinite(thermal_voltage) or thermal_voltage <= 0.0 or potential_sign not in {-1, 1}: + raise ContractError("invalid_activity_parameters") + density = self.values[density_id] + potential = self.values[potential_id] + if len(density.shape) != 1 or potential.shape != density.shape: + raise ContractError("activity_support_shape_mismatch") + idx = _face_pairs(pairs, density.shape[0]) + log_term = density.take(idx[:, 1]).log_ratio(density.take(idx[:, 0])).values + pot_diff = potential.take(idx[:, 1]).difference(potential.take(idx[:, 0])).values + total = log_term + (potential_sign * pot_diff) / DD(thermal_voltage) + return DDArray(total) + + def temporal_log_ratio( + self, left: StateView, variable_id: str, indices: ArrayLike | None + ) -> PhysicalArray | None: + if not isinstance(left.authority, PairStateAuthority): + return None + before = left.authority.dd_field(variable_id) + after = self.values[variable_id] + if indices is not None: + before = before.take(indices) + after = after.take(indices) + return after.log_ratio(before) + + def face_delta( + self, left: StateView, variable_id: str, pairs: ArrayLike + ) -> PhysicalArray | None: + if not isinstance(left.authority, PairStateAuthority): + return None + delta = self.values[variable_id].difference(left.authority.dd_field(variable_id)) + if len(delta.shape) != 1: + raise ContractError("face_outside_support") + idx = _face_pairs(pairs, delta.shape[0]) + return delta.take(idx[:, 1]).difference(delta.take(idx[:, 0])) + + def electrochemical_delta( + self, + left: StateView, + density_id: str, + potential_id: str, + pairs: ArrayLike, + thermal_voltage: float, + potential_sign: int, + ) -> PhysicalArray | None: + if not isinstance(left.authority, PairStateAuthority): + return None + specs = {spec.id: spec for spec in left.layout.variables} + if specs[potential_id].unit != VOLT: + raise ContractError("activity_potential_unit_mismatch") + before_n = left.authority.dd_field(density_id) + after_n = self.values[density_id] + if len(after_n.shape) != 1: + raise ContractError("face_outside_support") + idx = _face_pairs(pairs, after_n.shape[0]) + # Compute temporal log ratios first, then spatial difference across face pairs, + # avoiding O(1) endpoint cancellation on tiny sub-ULP increments. + temporal_n = after_n.log_ratio(before_n).values + log_change = temporal_n[idx[:, 1]] - temporal_n[idx[:, 0]] + pot_delta = self.values[potential_id].difference(left.authority.dd_field(potential_id)).values + pot_face = pot_delta[idx[:, 1]] - pot_delta[idx[:, 0]] + return DDArray(log_change + (potential_sign * pot_face) / DD(thermal_voltage)) + + +_AUTHORITY_CONFORMANCE: StateAuthority = PairStateAuthority( + layout_identity="check", + values={}, + anchor_reference="check", +) + + +@dataclass(frozen=True) +class ReferenceIncrementCoordinates: + """Affine/log-lifting coordinate map around an exact ``DDArray`` anchor state. + + Variables listed in ``multiplicative_variables`` lift coordinates ``y`` via + ``anchor * (1 + expm1(y)) = anchor * exp(y)`` so positive densities stay + strictly positive and tiny ``dy`` updates preserve sub-ULP changes in ``lo``. + All other variables lift affinely via ``anchor + DD(y)``. + """ + + layout: Layout + anchor_fields: Mapping[str, DDArray] + multiplicative_variables: frozenset[str] = frozenset() + reference: str = field(init=False) + + def __post_init__(self) -> None: + specs = {spec.id: spec for spec in self.layout.variables} + if set(self.anchor_fields) != set(specs): + raise ContractError("incomplete_anchor_fields") + owned: dict[str, DDArray] = {} + for name, spec in specs.items(): + arr = self.anchor_fields[name] + if not isinstance(arr, DDArray) or arr.shape != spec.shape or not arr.is_finite(): + raise ContractError("anchor_shape_or_finiteness_mismatch") + if name in self.multiplicative_variables and np.any(arr.values <= 0.0): + raise ContractError("multiplicative_anchor_must_be_positive") + owned[name] = arr.immutable_copy() + unknown_mult = set(self.multiplicative_variables) - set(specs) + if unknown_mult: + raise ContractError("unknown_multiplicative_variable") + object.__setattr__(self, "anchor_fields", MappingProxyType(owned)) + sha = hashlib.sha256(b"ref-inc-coords-v1:" + self.layout.identity.encode()) + for name in sorted(owned): + mode = b"log:" if name in self.multiplicative_variables else b"aff:" + sha.update(mode + name.encode() + owned[name].identity_bytes()) + object.__setattr__(self, "reference", f"pair-anchor:{sha.hexdigest()[:32]}") + + @classmethod + def from_float_anchor( + cls, + layout: Layout, + anchor: Mapping[str, ArrayLike], + *, + multiplicative_variables: Iterable_or_Set = (), + ) -> ReferenceIncrementCoordinates: + dd_map = {name: DDArray.from_parts(val) for name, val in anchor.items()} + return cls( + layout=layout, + anchor_fields=dd_map, + multiplicative_variables=frozenset(multiplicative_variables), + ) + + def _lift_fields(self, words: Vector) -> dict[str, DDArray]: + lifted: dict[str, DDArray] = {} + for spec in self.layout.variables: + coord = DD(words[self.layout.offsets[spec.id]].reshape(spec.shape)) + base = self.anchor_fields[spec.id].values + if spec.id in self.multiplicative_variables: + # base + base * expm1(coord) preserves tiny sub-ULP multiplicative updates in lo. + val = base + base * coord.expm1() + else: + val = base + coord + lifted[spec.id] = DDArray(val) + return lifted + + def point(self, y: ArrayLike, time: float = 0.0, inputs: ArrayLike = ()) -> Point: + words = frozen_array(y) + if words.shape != (self.layout.size,): + raise ContractError("coordinate_layout_mismatch") + fields = self._lift_fields(words) + authority = PairStateAuthority( + layout_identity=self.layout.identity, + values=fields, + anchor_reference=self.reference, + bound_coordinate=words, + ) + view = StateView(self.layout, authority=authority) + return Point(time, words, frozen_array(inputs), view, self.reference) + + def advance( + self, left: Point, dy: ArrayLike, time: float, inputs: ArrayLike = () + ) -> tuple[Point, StateIncrement]: + step = frozen_array(dy) + if step.shape != left.y.shape or left.coordinate_reference != self.reference: + raise ContractError("coordinate_reference_mismatch") + if not isinstance(left.state.authority, PairStateAuthority): + raise ContractError("authority_rebase_required") + # Accumulate coordinate update in DD if needed; solver coordinates remain binary64 vector + # relative to the anchor, while physical DDArray fields retain full (hi, lo) precision. + new_y_dd = DD(left.y) + DD(step) + new_y = frozen_array(new_y_dd.hi) + # Reconstruct right fields using exact DD coordinate sum so sub-ULP dy on nonzero left.y + # is never lost before lifting into physical fields. + right_fields: dict[str, DDArray] = {} + for spec in self.layout.variables: + sl = self.layout.offsets[spec.id] + coord_dd = new_y_dd[sl].reshape(spec.shape) + base = self.anchor_fields[spec.id].values + if spec.id in self.multiplicative_variables: + val = base + base * coord_dd.expm1() + else: + val = base + coord_dd + right_fields[spec.id] = DDArray(val) + authority = PairStateAuthority( + layout_identity=self.layout.identity, + values=right_fields, + anchor_reference=self.reference, + bound_coordinate=new_y, + ) + right_view = StateView(self.layout, authority=authority) + right = Point(time, new_y, frozen_array(inputs), right_view, self.reference) + increment = StateIncrement.from_points(left, right) + return right, increment + + def rebase(self, accepted: Point) -> tuple[ReferenceIncrementCoordinates, Point]: + """Import an accepted physical state as a fresh zero-coordinate reference.""" + if accepted.state.layout.identity != self.layout.identity: + raise ContractError("increment_layout_mismatch") + if not isinstance(accepted.state.authority, PairStateAuthority): + raise ContractError("authority_rebase_required") + new_anchor = { + spec.id: accepted.state.authority.dd_field(spec.id) + for spec in self.layout.variables + } + rebased_map = ReferenceIncrementCoordinates( + layout=self.layout, + anchor_fields=new_anchor, + multiplicative_variables=self.multiplicative_variables, + ) + zero_point = rebased_map.point( + np.zeros(self.layout.size, dtype=np.float64), + time=accepted.time, + inputs=accepted.inputs, + ) + return rebased_map, zero_point + + +Iterable_or_Set = Any + + +class AffineInputLiftCodec: + """Lossless JSON checkpoint codec for ``PairStateAuthority`` states and input lifts.""" + + def encode_point(self, point: Point) -> dict[str, Any]: + if not isinstance(point.state.authority, PairStateAuthority): + raise InputLiftCheckpointError("codec requires a PairStateAuthority state") + represented: dict[str, dict[str, Any]] = {} + high_word: dict[str, Any] = {} + for spec in point.state.layout.variables: + dd = point.state.authority.dd_field(spec.id).values + represented[spec.id] = dd.to_pair_dict() + high_word[spec.id] = dd.hi.tolist() if dd.ndim else float(dd.hi.item()) + snapshot = { + "schema": INPUT_LIFT_STATE_SCHEMA, + "operator_representation": INPUT_LIFT_REPRESENTATION, + "layout_identity": point.state.layout.identity, + "coordinate_reference": point.coordinate_reference, + "high_word_state": high_word, + "represented_fields": represented, + } + record: dict[str, Any] = { + "schema": INPUT_LIFT_CHECKPOINT_SCHEMA, + "operator_representation": INPUT_LIFT_REPRESENTATION, + "coordinate_role": _COORDINATE_ROLE, + "time_s": float(point.time), + "inputs": point.inputs.tolist(), + "source_coordinate": point.y.tolist(), + "prior_point_identity": point.identity, + "state_identity": _digest(represented), + "snapshot": snapshot, + } + record["sha256"] = _digest(record) + return json.loads(_canonical_json(record)) # type: ignore[no-any-return] + + def decode_point( + self, + payload: Mapping[str, Any], + *, + layout: Layout, + multiplicative_variables: Iterable_or_Set = (), + ) -> Point: + """Restore a checkpoint as a new zero-coordinate ``Point`` preserving all ``(hi, lo)`` words.""" + if ( + not isinstance(payload, Mapping) + or payload.get("schema") != INPUT_LIFT_CHECKPOINT_SCHEMA + or payload.get("operator_representation") != INPUT_LIFT_REPRESENTATION + or payload.get("coordinate_role") != _COORDINATE_ROLE + ): + raise InputLiftCheckpointError("checkpoint schema, representation, or role mismatch") + expected_sha = payload.get("sha256") + if not isinstance(expected_sha, str) or not _SHA256_RE.fullmatch(expected_sha): + raise InputLiftCheckpointError("checkpoint sha256 digest is missing or malformed") + unsigned = {k: v for k, v in payload.items() if k != "sha256"} + if _digest(unsigned) != expected_sha: + raise InputLiftCheckpointError("checkpoint content sha256 mismatch") + + snapshot = payload.get("snapshot") + if ( + not isinstance(snapshot, Mapping) + or snapshot.get("schema") != INPUT_LIFT_STATE_SCHEMA + or snapshot.get("layout_identity") != layout.identity + ): + raise InputLiftCheckpointError("checkpoint snapshot or layout identity mismatch") + + specs = {spec.id: spec for spec in layout.variables} + represented = snapshot.get("represented_fields") + high_word = snapshot.get("high_word_state") + if ( + not isinstance(represented, Mapping) + or not isinstance(high_word, Mapping) + or set(represented) != set(specs) + or set(high_word) != set(specs) + ): + raise InputLiftCheckpointError("checkpoint field coverage differs from layout") + if _digest(represented) != payload.get("state_identity"): + raise InputLiftCheckpointError("checkpoint state_identity mismatch") + + anchor: dict[str, DDArray] = {} + for name, spec in specs.items(): + try: + dd = DD.from_pair_dict(represented[name], expected_shape=spec.shape) + except (TypeError, ValueError, OverflowError) as exc: + raise InputLiftCheckpointError(f"invalid DD pair for {name}: {exc}") from exc + hi_check = frozen_array(high_word[name]) + if hi_check.shape != spec.shape or hi_check.tobytes() != dd.hi.tobytes(): + raise InputLiftCheckpointError(f"high_word_state disagrees with DD hi for {name}") + anchor[name] = DDArray(dd) + + coord_map = ReferenceIncrementCoordinates( + layout=layout, + anchor_fields=anchor, + multiplicative_variables=frozenset(multiplicative_variables), + ) + time_val = payload.get("time_s") + if isinstance(time_val, bool) or not isinstance(time_val, (int, float)) or not math.isfinite(time_val): + raise InputLiftCheckpointError("checkpoint time_s must be finite") + inputs_arr = frozen_array(payload.get("inputs", ())) + return coord_map.point( + np.zeros(layout.size, dtype=np.float64), + time=float(time_val), + inputs=inputs_arr, + ) + + def decode_with_map( + self, + payload: Mapping[str, Any], + *, + layout: Layout, + multiplicative_variables: Iterable_or_Set = (), + ) -> tuple[ReferenceIncrementCoordinates, Point]: + point = self.decode_point( + payload, layout=layout, multiplicative_variables=multiplicative_variables + ) + assert isinstance(point.state.authority, PairStateAuthority) + coord_map = ReferenceIncrementCoordinates( + layout=layout, + anchor_fields={ + spec.id: point.state.authority.dd_field(spec.id) for spec in layout.variables + }, + multiplicative_variables=frozenset(multiplicative_variables), + ) + return coord_map, point + + +def decode_historical_r1_pair_state(record: Mapping[str, Any]) -> dict[str, DD]: + """Decode a historical ``R1CommonStatePairV2`` record without relabeling it. + + Validates its recorded ``sha256``, ``seed_preparation_sha256``, normalized + 17 ``(hi, lo)`` fields, and ``high == snapshot`` invariants. + """ + if ( + not isinstance(record, Mapping) + or record.get("schema") != "R1CommonStatePairV2" + or record.get("representation") != PAIR_REPRESENTATION + ): + raise InputLiftCheckpointError("historical record must have schema R1CommonStatePairV2") + unsigned = {k: v for k, v in record.items() if k != "sha256"} + if _digest(unsigned) != record.get("sha256"): + raise InputLiftCheckpointError("historical R1CommonStatePairV2 sha256 mismatch") + seed = record.get("seed_preparation") + if not isinstance(seed, Mapping) or seed.get("schema") != "R1CommonStateV1": + raise InputLiftCheckpointError("historical pair record lacks R1CommonStateV1 seed") + seed_unsigned = {k: v for k, v in seed.items() if k != "sha256"} + if _digest(seed_unsigned) != seed.get("sha256") or record.get("seed_preparation_sha256") != seed.get("sha256"): + raise InputLiftCheckpointError("historical R1CommonStateV1 seed sha256 mismatch") + + state = record.get("state") + if not isinstance(state, Mapping): + raise InputLiftCheckpointError("historical pair state mapping is missing") + fine_names = ( + "phi_V", + "dqfn_V", + "dqfp_V", + "n_m3", + "p_m3", + "positive_m3", + "occupancy", + "sheet_charge_C_m2", + "trace_potential_V", + "trace_state_m3", + "storage", + "poisson_residual_C_m2", + "electron_current_A_m2", + "hole_current_A_m2", + "positive_flux_m2_s", + "positive_rate_m3_s", + "boundary_flux_m2_s", + ) + decoded: dict[str, DD] = {} + for name in fine_names: + hi_key = f"precision_{name}_hi" + lo_key = f"precision_{name}_lo" + if hi_key not in state or lo_key not in state: + raise InputLiftCheckpointError(f"missing precision pair words for {name}") + dd = DD.from_pair_dict({"hi": state[hi_key], "lo": state[lo_key]}) + if name in state: + snap_hi = frozen_array(state[name]) + if snap_hi.shape != dd.shape or not np.array_equal(snap_hi, dd.hi): + raise InputLiftCheckpointError(f"binary64 snapshot differs from high word for {name}") + decoded[name] = dd + # Verify cancellation-safe log1p availability on decoded density changes vs seed + seed_n = DD(seed["state"]["n_m3"]) + _ = log1p((decoded["n_m3"] - seed_n) / seed_n) + return decoded diff --git a/src/solarlab_research/precision/double_double.py b/src/solarlab_research/precision/double_double.py new file mode 100644 index 00000000..6aa727b4 --- /dev/null +++ b/src/solarlab_research/precision/double_double.py @@ -0,0 +1,712 @@ +"""Immutable double-double (DD) compensated arithmetic and public contract adapters. + +Retains ~106 bits of significand precision via normalized non-overlapping +IEEE-754 binary64 pairs ``(hi, lo)`` satisfying ``fl(hi + lo) == hi``. +Injects into ``solarlab.contracts`` exclusively through ``PhysicalArray`` and +``AssemblyArithmetic`` without registering physics models. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from functools import lru_cache +import operator +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import ( + AssemblyArithmetic, + ContractError, + FieldProjection, + FloatArray, + PhysicalArray, + Vector, + frozen_array, + integer_indices, +) + +__all__ = [ + "CompensatedArithmetic", + "DD", + "DDArray", + "exp", + "expm1", + "log", + "log1p", + "sum", +] + +_SPLIT_MAX = float(np.ldexp(1.0, 996)) +_SPLIT_SCALE_DOWN = float(np.ldexp(1.0, -28)) +_SPLIT_SCALE_UP = float(np.ldexp(1.0, 28)) +_SAFE_MAX = float(np.ldexp(1.0, 1020)) +_SPLITTER = float(np.ldexp(1.0, 27) + 1.0) +_SERIES_EPS = float(np.ldexp(1.0, -110)) + + +def _readonly_float64(value: ArrayLike) -> NDArray[np.float64]: + array = np.asarray(value, dtype=np.float64) + return np.frombuffer(array.tobytes(), dtype=np.float64).reshape(array.shape) + + +def _require_supported_input(value: object) -> NDArray[np.float64]: + if isinstance(value, DD): + raise TypeError("nested DD inputs are ambiguous; add or copy explicitly") + raw = np.asarray(value) + if raw.dtype.kind == "c" or raw.dtype == object: + raise TypeError("DD requires finite real binary64-compatible inputs") + array = np.asarray(raw, dtype=np.float64) + if not np.all(np.isfinite(array)): + raise ValueError("DD requires finite inputs") + if raw.dtype.kind in ("i", "u") and raw.size: + exact = [int(item) for item in raw.flat] + back = [int(item) for item in array.flat] + if exact != back: + raise TypeError("integer exceeds exact IEEE-754 binary64 precision") + if np.any(np.abs(array) > _SAFE_MAX): + raise OverflowError("DD input exceeds the safe compensated range") + return array + + +def _two_sum( + left: NDArray[np.float64], right: NDArray[np.float64] +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + with np.errstate(over="raise", invalid="raise", under="ignore"): + high = np.asarray(left + right, dtype=np.float64) + virtual = high - left + low = np.asarray((left - (high - virtual)) + (right - virtual), dtype=np.float64) + return high, low + + +def _quick_two_sum( + left: NDArray[np.float64], right: NDArray[np.float64] +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + with np.errstate(over="raise", invalid="raise", under="ignore"): + high = np.asarray(left + right, dtype=np.float64) + low = np.asarray(right - (high - left), dtype=np.float64) + return high, low + + +def _split(value: NDArray[np.float64]) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + large = np.abs(value) > _SPLIT_MAX + work = np.where(large, value * _SPLIT_SCALE_DOWN, value) + with np.errstate(over="raise", invalid="raise", under="ignore"): + temp = _SPLITTER * work + high = temp - (temp - work) + low = work - high + if np.any(large): + high = np.where(large, high * _SPLIT_SCALE_UP, high) + low = np.where(large, low * _SPLIT_SCALE_UP, low) + return np.asarray(high, dtype=np.float64), np.asarray(low, dtype=np.float64) + + +def _two_product( + left: NDArray[np.float64], right: NDArray[np.float64] +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + left_arr, right_arr = np.broadcast_arrays(left, right) + with np.errstate(over="raise", invalid="raise", under="ignore"): + product = np.asarray(left_arr * right_arr, dtype=np.float64) + if np.any((left_arr != 0.0) & (right_arr != 0.0) & (product == 0.0)): + raise ArithmeticError("DD product underflow") + lh, ll = _split(left_arr) + rh, rl = _split(right_arr) + with np.errstate(over="raise", invalid="raise", under="ignore"): + error = np.asarray( + ((lh * rh - product) + lh * rl + ll * rh) + ll * rl, + dtype=np.float64, + ) + return product, error + + +class DD: + """Immutable compensated double-double scalar or ndarray.""" + + __slots__ = ("_hi", "_lo") + __array_ufunc__ = None + + _hi: NDArray[np.float64] + _lo: NDArray[np.float64] + + def __init__(self, hi: object, lo: object | None = None) -> None: + high = _require_supported_input(hi) + low = np.zeros_like(high) if lo is None else _require_supported_input(lo) + high_b, low_b = np.broadcast_arrays(high, low) + norm_hi, norm_lo = _two_sum(high_b, low_b) + norm_hi, norm_lo = _quick_two_sum(norm_hi, norm_lo) + if not (np.all(np.isfinite(norm_hi)) and np.all(np.isfinite(norm_lo))): + raise ArithmeticError("DD normalization produced nonfinite words") + if np.any(np.abs(norm_hi) > _SAFE_MAX): + raise OverflowError("DD normalized value exceeds safe compensated range") + object.__setattr__(self, "_hi", _readonly_float64(norm_hi)) + object.__setattr__(self, "_lo", _readonly_float64(norm_lo)) + + def __setattr__(self, name: str, value: object) -> None: + raise AttributeError("DD instances are immutable") + + @classmethod + def from_normalized_parts( + cls, hi: NDArray[np.float64], lo: NDArray[np.float64] + ) -> DD: + """Wrap already validated, normalized finite parts without re-rounding.""" + instance = object.__new__(cls) + object.__setattr__(instance, "_hi", _readonly_float64(hi)) + object.__setattr__(instance, "_lo", _readonly_float64(lo)) + return instance + + @classmethod + def _normalized(cls, hi: NDArray[np.float64], lo: NDArray[np.float64]) -> DD: + norm_hi, norm_lo = _two_sum(hi, lo) + norm_hi, norm_lo = _quick_two_sum(norm_hi, norm_lo) + if not (np.all(np.isfinite(norm_hi)) and np.all(np.isfinite(norm_lo))): + raise ArithmeticError("DD operation produced nonfinite words") + if np.any(np.abs(norm_hi) > _SAFE_MAX): + raise OverflowError("DD operation exceeded safe compensated range") + return cls.from_normalized_parts(norm_hi, norm_lo) + + @property + def hi(self) -> NDArray[np.float64]: + return self._hi.view() + + @property + def lo(self) -> NDArray[np.float64]: + return self._lo.view() + + @property + def shape(self) -> tuple[int, ...]: + return tuple(self._hi.shape) + + @property + def ndim(self) -> int: + return int(self._hi.ndim) + + @property + def size(self) -> int: + return int(self._hi.size) + + def copy(self) -> DD: + return self + + def __deepcopy__(self, memo: object) -> DD: + return self + + def __len__(self) -> int: + return len(self._hi) + + def __getitem__(self, index: Any) -> DD: + return self.from_normalized_parts( + np.asarray(self._hi[index], dtype=np.float64), + np.asarray(self._lo[index], dtype=np.float64), + ) + + def reshape(self, *shape: Any) -> DD: + target = shape[0] if len(shape) == 1 and isinstance(shape[0], tuple) else shape + return self.from_normalized_parts(self._hi.reshape(target), self._lo.reshape(target)) + + def ravel(self) -> DD: + return self.from_normalized_parts(self._hi.ravel(), self._lo.ravel()) + + def to_float(self) -> float | NDArray[np.float64]: + if self._hi.ndim == 0: + return float(self._hi.item()) + return _readonly_float64(self._hi) + + def __float__(self) -> float: + if self._hi.size != 1: + raise TypeError("only scalar DD instances convert to Python float") + return float(self._hi.item()) + + def to_pair_dict(self) -> dict[str, Any]: + if self._hi.ndim == 0: + return {"hi": float(self._hi.item()), "lo": float(self._lo.item())} + return {"hi": self._hi.tolist(), "lo": self._lo.tolist()} + + @classmethod + def from_pair_dict(cls, pair: Mapping[str, Any], *, expected_shape: tuple[int, ...] | None = None) -> DD: + if set(pair) != {"hi", "lo"}: + raise ValueError("DD pair dictionary must contain exact keys {'hi', 'lo'}") + hi_arr = _require_supported_input(pair["hi"]) + lo_arr = _require_supported_input(pair["lo"]) + if hi_arr.shape != lo_arr.shape: + raise ValueError("DD pair high and low shapes disagree") + if expected_shape is not None and hi_arr.shape != expected_shape: + raise ValueError(f"DD pair shape {hi_arr.shape} differs from expected {expected_shape}") + normalized = cls(hi_arr, lo_arr) + if not (np.array_equal(normalized.hi, hi_arr) and np.array_equal(normalized.lo, lo_arr)): + raise ValueError("serialized DD pair words are not normalized") + return cls.from_normalized_parts(hi_arr, lo_arr) + + def __repr__(self) -> str: + return f"DD(hi={self._hi!r}, lo={self._lo!r})" + + def __bool__(self) -> bool: + if self._hi.size != 1: + raise ValueError("The truth value of a multi-element DD is ambiguous") + return bool(self._hi.item() != 0.0 or self._lo.item() != 0.0) + + def __neg__(self) -> DD: + return self.from_normalized_parts(-self._hi, -self._lo) + + def __pos__(self) -> DD: + return self + + def __abs__(self) -> DD: + negative = self._hi < 0.0 + return self.from_normalized_parts( + np.where(negative, -self._hi, self._hi), + np.where(negative, -self._lo, self._lo), + ) + + def __add__(self, other: object) -> DD: + rhs = _as_dd(other) + high, low = _two_sum(self._hi, rhs._hi) + tail, tail_error = _two_sum(self._lo, rhs._lo) + high, low = _two_sum(high, low + tail) + high, low = _two_sum(high, low + tail_error) + return self._normalized(high, low) + + __radd__ = __add__ + + def __sub__(self, other: object) -> DD: + return self + (-_as_dd(other)) + + def __rsub__(self, other: object) -> DD: + return _as_dd(other) + (-self) + + def __mul__(self, other: object) -> DD: + rhs = _as_dd(other) + high, low = _two_product(self._hi, rhs._hi) + with np.errstate(over="raise", invalid="raise", under="ignore"): + cross = self._hi * rhs._lo + self._lo * rhs._hi + low = low + cross + high, low = _two_sum(high, low) + high, low = _two_sum(high, low + self._lo * rhs._lo) + return self._normalized(high, low) + + __rmul__ = __mul__ + + def __truediv__(self, other: object) -> DD: + rhs = _as_dd(other) + if np.any(rhs._hi == 0.0): + raise ZeroDivisionError("DD division by zero") + with np.errstate(over="raise", invalid="raise", under="ignore"): + q1 = self._hi / rhs._hi + if np.any((self._hi != 0.0) & (q1 == 0.0)): + raise ArithmeticError("DD quotient underflow") + first = DD(q1) + remainder = self - rhs * first + q2 = remainder._hi / rhs._hi + second = DD(q2) + remainder = remainder - rhs * second + q3 = remainder._hi / rhs._hi + return (first + second) + DD(q3) + + def __rtruediv__(self, other: object) -> DD: + return _as_dd(other) / self + + def __eq__(self, other: object) -> Any: # type: ignore[override] + try: + rhs = _as_dd(other) + except (TypeError, ValueError, OverflowError): + return False + return (self._hi == rhs._hi) & (self._lo == rhs._lo) + + def __ne__(self, other: object) -> Any: # type: ignore[override] + eq = self.__eq__(other) + return ~eq if isinstance(eq, np.ndarray) else not eq + + def __lt__(self, other: object) -> NDArray[np.bool_]: + rhs = _as_dd(other) + return np.asarray( + (self._hi < rhs._hi) | ((self._hi == rhs._hi) & (self._lo < rhs._lo)), + dtype=np.bool_, + ) + + def __le__(self, other: object) -> NDArray[np.bool_]: + rhs = _as_dd(other) + return np.asarray((self < rhs) | ((self._hi == rhs._hi) & (self._lo == rhs._lo)), dtype=np.bool_) + + def __gt__(self, other: object) -> NDArray[np.bool_]: + return _as_dd(other) < self + + def __ge__(self, other: object) -> NDArray[np.bool_]: + return _as_dd(other) <= self + + def exp(self) -> DD: + return exp(self) + + def expm1(self) -> DD: + return expm1(self) + + def log(self) -> DD: + return log(self) + + def log1p(self) -> DD: + return log1p(self) + + def sum(self, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> DD: + return sum(self, axis=axis, keepdims=keepdims) + + +def _as_dd(value: object) -> DD: + if isinstance(value, DD): + return value + if type(value) in (float, int): + return _scalar_constant(value) + return DD(value) + + +@lru_cache(maxsize=128, typed=True) +def _scalar_constant(value: float | int) -> DD: + return DD(value) + + +_LN2 = DD(0.6931471805599453, 2.3190468138462996e-17) +_LN2_TAIL = 5.707708438416212e-34 +_SERIES_RECIPROCALS = tuple(DD(1) / n for n in range(1, 53)) +_LOCAL_EXPM1_MAX = float(np.ldexp(1.0, -10)) + + +def _scale_two(value: DD, exponent: NDArray[np.int64] | int) -> DD: + with np.errstate(over="raise", invalid="raise", under="ignore"): + hi = np.asarray(np.ldexp(value._hi, exponent), dtype=np.float64) + lo = np.asarray(np.ldexp(value._lo, exponent), dtype=np.float64) + if np.any((value._hi != 0.0) & (hi == 0.0)): + raise ArithmeticError("DD power-of-two scaling underflow") + return DD._normalized(hi, lo) + + +def _small_expm1(value: DD) -> DD: + result, term = value, value + for n in range(2, 13): + active = (np.abs(term._hi) > np.abs(result._hi) * _SERIES_EPS) & ( + np.abs(value._hi) > _SERIES_EPS + ) + if not np.any(active): + return result + next_term = (term[active] * value[active]) * _SERIES_RECIPROCALS[n - 1] + hi: NDArray[np.float64] = np.zeros(value.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(value.shape, dtype=np.float64) + hi[active], lo[active] = next_term._hi, next_term._lo + term = DD._normalized(hi, lo) + result = result + term + raise ArithmeticError("DD exponential Taylor series did not converge") + + +def _general_reduced_expm1(value: DD) -> tuple[DD, NDArray[np.int64]]: + m = np.rint(value._hi / _LN2._hi).astype(np.int64) + product_hi, product_lo = _two_product(_LN2._hi, m.astype(np.float64)) + residual = (value - DD(product_hi)) - DD(product_lo) + residual = residual - DD(_LN2._lo) * m + residual = residual - DD(_LN2_TAIL) * m + reduced = _scale_two(residual, -9) + small = _small_expm1(reduced) + for _ in range(9): + active = np.abs(small._hi) > _SERIES_EPS + hi: NDArray[np.float64] = np.zeros(small.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(small.shape, dtype=np.float64) + if np.any(active): + square = small[active] * small[active] + hi[active], lo[active] = square._hi, square._lo + small = _scale_two(small, 1) + DD._normalized(hi, lo) + return small, m + + +def _reduced_expm1(value: DD) -> tuple[DD, NDArray[np.int64]]: + local = np.abs(value._hi) <= _LOCAL_EXPM1_MAX + if np.all(local): + return _small_expm1(value), np.zeros(value.shape, dtype=np.int64) + if np.any(local): + hi: NDArray[np.float64] = np.empty(value.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.empty(value.shape, dtype=np.float64) + exponent: NDArray[np.int64] = np.zeros(value.shape, dtype=np.int64) + small = _small_expm1(value[local]) + other, exponent[~local] = _general_reduced_expm1(value[~local]) + hi[local], lo[local] = small._hi, small._lo + hi[~local], lo[~local] = other._hi, other._lo + return DD._normalized(hi, lo), exponent + return _general_reduced_expm1(value) + + +def exp(value: object) -> DD: + """Compensated exponential ``exp(x)``.""" + dd = _as_dd(value) + if np.any(np.abs(dd._hi) > 672.0): + raise ArithmeticError("DD exponential is outside the supported precision range") + reduced, exponent = _reduced_expm1(dd) + return _scale_two(1.0 + reduced, exponent) + + +def expm1(value: object) -> DD: + """Compensated ``exp(x) - 1`` without sub-ULP cancellation.""" + dd = _as_dd(value) + if np.any(np.abs(dd._hi) > 672.0): + raise ArithmeticError("DD exponential is outside the supported precision range") + reduced, exponent = _reduced_expm1(dd) + if not np.any(exponent): + return reduced + full = _scale_two(1.0 + reduced, exponent) - 1.0 + return DD._normalized( + np.where(exponent == 0, reduced._hi, full._hi), + np.where(exponent == 0, reduced._lo, full._lo), + ) + + +def _small_log1p(value: DD) -> DD: + z = value / (2.0 + value) + result, term = z, z + active = np.abs(z._hi) > _SERIES_EPS + hi: NDArray[np.float64] = np.zeros(z.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(z.shape, dtype=np.float64) + if np.any(active): + square = z[active] * z[active] + hi[active], lo[active] = square._hi, square._lo + z2 = DD._normalized(hi, lo) + for odd in range(3, 53, 2): + active = active & (np.abs(term._hi) > np.abs(result._hi) * _SERIES_EPS) + if not np.any(active): + return 2.0 * result + next_term = term[active] * z2[active] + hi = np.zeros(z.shape, dtype=np.float64) + lo = np.zeros(z.shape, dtype=np.float64) + hi[active], lo[active] = next_term._hi, next_term._lo + term = DD._normalized(hi, lo) + result = result + term * _SERIES_RECIPROCALS[odd - 1] + raise ArithmeticError("DD logarithm Taylor series did not converge") + + +def log(value: object) -> DD: + """Compensated natural logarithm with cancellation-safe branch near 1.""" + dd = _as_dd(value) + if np.any(dd._hi <= 0.0): + raise ValueError("DD logarithm requires a positive argument") + near = (dd > 0.75) & (dd < 1.25) + hi: NDArray[np.float64] = np.zeros(dd.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(dd.shape, dtype=np.float64) + if np.any(near): + local = _small_log1p(dd[near] - 1.0) + hi[near], lo[near] = local._hi, local._lo + if np.any(~near): + a = dd[~near] + guess = DD(np.log(a._hi)) + for _ in range(2): + guess = guess + (a * exp(-guess) - 1.0) + hi[~near], lo[~near] = guess._hi, guess._lo + return DD._normalized(hi, lo) + + +def log1p(value: object) -> DD: + """Compensated ``log(1 + x)``.""" + dd = _as_dd(value) + if np.any(dd <= -1.0): + raise ValueError("DD log1p requires x > -1") + near = (dd >= -0.25) & (dd <= 0.25) + hi: NDArray[np.float64] = np.zeros(dd.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(dd.shape, dtype=np.float64) + if np.any(near): + local = _small_log1p(dd[near]) + hi[near], lo[near] = local._hi, local._lo + if np.any(~near): + local = log(1.0 + dd[~near]) + hi[~near], lo[~near] = local._hi, local._lo + return DD._normalized(hi, lo) + + +def sum( + value: object, + axis: int | tuple[int, ...] | None = None, + keepdims: bool = False, +) -> DD: + """Compensated ordered reduction preserving both words.""" + dd = _as_dd(value) + if axis is None: + result = sum(dd.ravel(), axis=0) + return result.reshape((1,) * dd.ndim) if keepdims else result + raw_axes = (axis,) if isinstance(axis, int) else tuple(axis) + axes = tuple(operator.index(a) for a in raw_axes) + if any(a < -dd.ndim or a >= dd.ndim for a in axes): + raise ValueError("DD reduction axis is out of bounds") + norm_axes = tuple(a % dd.ndim for a in axes) + if len(set(norm_axes)) != len(norm_axes): + raise ValueError("DD reduction axes must be distinct") + result = dd + for current in sorted(norm_axes, reverse=True): + high = np.moveaxis(result._hi, current, 0) + low = np.moveaxis(result._lo, current, 0) + reduced = DD(np.zeros(high.shape[1:], dtype=np.float64)) + for idx in range(high.shape[0]): + reduced = reduced + DD.from_normalized_parts(high[idx], low[idx]) + result = reduced + if keepdims: + kept = tuple(1 if i in norm_axes else n for i, n in enumerate(dd.shape)) + result = result.reshape(kept) + return result + + +@dataclass(frozen=True) +class DDArray: + """Compensated ``PhysicalArray`` implementation backed by normalized ``DD``.""" + + values: DD + + def __post_init__(self) -> None: + if not isinstance(self.values, DD): + raise ContractError("dd_array_requires_dd_values") + + @classmethod + def from_parts(cls, hi: ArrayLike, lo: ArrayLike | None = None) -> DDArray: + return cls(DD(hi, lo)) + + @property + def shape(self) -> tuple[int, ...]: + return self.values.shape + + def immutable_copy(self) -> DDArray: + return DDArray(self.values) + + def difference(self, other: PhysicalArray) -> DDArray: + if not isinstance(other, DDArray) or other.shape != self.shape: + raise ContractError("precision_or_shape_mismatch") + return DDArray(self.values - other.values) + + def take(self, indices: ArrayLike) -> DDArray: + selected = integer_indices(indices) + if not self.shape or np.any(selected < 0) or np.any(selected >= self.shape[0]): + raise ContractError("index_outside_support") + return DDArray(self.values[selected]) + + def log_ratio(self, other: PhysicalArray) -> DDArray: + if not isinstance(other, DDArray) or other.shape != self.shape: + raise ContractError("precision_or_shape_mismatch") + if np.any(self.values <= 0.0) or np.any(other.values <= 0.0): + raise ContractError("log_ratio_requires_positive_fields") + relative = (self.values - other.values) / other.values + close = abs(relative) <= 0.25 + hi: NDArray[np.float64] = np.zeros(self.shape, dtype=np.float64) + lo: NDArray[np.float64] = np.zeros(self.shape, dtype=np.float64) + if np.any(close): + near = log1p(relative[close]) + hi[close], lo[close] = near.hi, near.lo + if np.any(~close): + far = log(self.values[~close] / other.values[~close]) + hi[~close], lo[~close] = far.hi, far.lo + return DDArray(DD.from_normalized_parts(hi, lo)) + + def is_finite(self) -> bool: + return bool(np.isfinite(self.values.hi).all() and np.isfinite(self.values.lo).all()) + + def identity_bytes(self) -> bytes: + return ( + b"float64-pair-v1:" + + repr(self.shape).encode() + + self.values.hi.tobytes() + + self.values.lo.tobytes() + ) + + def project_to_float(self, *, authority_identity: str) -> FieldProjection: + """Project to binary64 with explicit compensated truncation error bound.""" + hi = frozen_array(self.values.hi) + # Projecting DD(hi, lo) -> hi discards lo plus at most 0.5 ULP of DD tail. + bound = np.abs(self.values.lo) + 0.5 * np.spacing(np.abs(hi)) * (2.0**-52) + return FieldProjection( + value=FloatArray(hi), + authority_identity=authority_identity, + evaluator_identity="dd-high-word-projection-v1", + absolute_error_bound=FloatArray(bound), + ) + + +def _unwrap_dd(value: Any) -> DD: + if isinstance(value, DD): + return value + if isinstance(value, DDArray): + return value.values + if isinstance(value, FloatArray): + return DD(value.values) + try: + return DD(value) + except (TypeError, ValueError, OverflowError, ArithmeticError) as exc: + raise ContractError("invalid_compensated_operand") from exc + + +class CompensatedArithmetic: + """``AssemblyArithmetic`` implementation preserving ``DD`` representation.""" + + def array(self, value: ArrayLike | PhysicalArray) -> DD: + return _unwrap_dd(value) + + def zeros(self, shape: tuple[int, ...]) -> DD: + return DD(np.zeros(shape, dtype=np.float64)) + + def weighted(self, value: Any, weights: Vector) -> DD: + dd = _unwrap_dd(value) + w = frozen_array(weights) + if dd.shape != w.shape: + raise ContractError("arithmetic_shape_mismatch") + return dd * DD(w) + + def add(self, left: Any, right: Any) -> DD: + lhs, rhs = _unwrap_dd(left), _unwrap_dd(right) + if lhs.shape != rhs.shape: + raise ContractError("arithmetic_shape_mismatch") + return lhs + rhs + + def subtract(self, left: Any, right: Any) -> DD: + lhs, rhs = _unwrap_dd(left), _unwrap_dd(right) + if lhs.shape != rhs.shape: + raise ContractError("arithmetic_shape_mismatch") + return lhs - rhs + + def divide(self, left: Any, right: Any) -> DD: + lhs, rhs = _unwrap_dd(left), _unwrap_dd(right) + if lhs.shape != rhs.shape or np.any(rhs.hi == 0.0): + raise ContractError("arithmetic_shape_or_divisor") + return lhs / rhs + + def matmul(self, left: Any, right: Any) -> DD: + lhs, rhs = _unwrap_dd(left), _unwrap_dd(right) + if lhs.ndim != 2 or rhs.ndim not in {1, 2} or lhs.shape[1] != rhs.shape[0]: + raise ContractError("arithmetic_shape_mismatch") + if rhs.ndim == 1: + products = lhs * rhs.reshape((1, rhs.shape[0])) + return sum(products, axis=1) + cols = [sum(lhs * rhs[:, col].reshape((1, lhs.shape[1])), axis=1) for col in range(rhs.shape[1])] + hi = np.stack([col.hi for col in cols], axis=1) + lo = np.stack([col.lo for col in cols], axis=1) + return DD.from_normalized_parts(hi, lo) + + def concatenate(self, values: Iterable[Any], axis: int = 0) -> DD: + items = tuple(_unwrap_dd(v) for v in values) + if not items: + raise ContractError("empty_concatenation") + hi = np.concatenate([item.hi for item in items], axis=axis) + lo = np.concatenate([item.lo for item in items], axis=axis) + return DD.from_normalized_parts(hi, lo) + + def reshape(self, value: Any, shape: tuple[int, ...]) -> DD: + return _unwrap_dd(value).reshape(shape) + + def scatter_add(self, target: Any, indices: NDArray[np.intp], value: Any) -> DD: + acc = _unwrap_dd(target) + inc = _unwrap_dd(value) + idx = integer_indices(indices) + if idx.shape != inc.shape or acc.ndim != 1: + raise ContractError("arithmetic_shape_mismatch") + if np.any(idx < 0) or np.any(idx >= acc.shape[0]): + raise ContractError("index_outside_support") + hi = acc.hi.copy() + lo = acc.lo.copy() + for pos, k in enumerate(idx.tolist()): + updated = DD.from_normalized_parts(np.asarray(hi[k]), np.asarray(lo[k])) + inc[pos] + hi[k] = float(updated.hi.item()) + lo[k] = float(updated.lo.item()) + return DD.from_normalized_parts(hi, lo) + + def freeze(self, value: Any) -> DD: + return _unwrap_dd(value) + + +# Verify protocol structural conformance at import time for static type checkers. +_ARITHMETIC_CONFORMANCE: AssemblyArithmetic = CompensatedArithmetic() diff --git a/src/solarlab_research/precision/two_sided_interface.py b/src/solarlab_research/precision/two_sided_interface.py new file mode 100644 index 00000000..7d0b0ced --- /dev/null +++ b/src/solarlab_research/precision/two_sided_interface.py @@ -0,0 +1,650 @@ +"""Compensated evaluation of the local two-sided carrier constitutive law. + +Built strictly on ``solarlab_research.precision.double_double`` and the public +``solarlab.physics.statistics.fermi_dirac`` table, with zero imports from +``perovskite_sim``. Missing constitutive branches raise +``UnsupportedCompensatedInterfaceDomain`` rather than falling back to binary64. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from dataclasses import dataclass, field +from functools import lru_cache +import hashlib +import json +from types import MappingProxyType +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from solarlab.contracts import ELEMENTARY_CHARGE_C, frozen_array +from solarlab.physics.statistics.fermi_dirac import fermi_dirac_half_table +from solarlab_research.precision.double_double import DD + +__all__ = [ + "CompensatedCarrierBalance", + "CompensatedCarrierTangent", + "FrozenLocalCoefficients", + "LocalCarrierEvaluation", + "SCHEMA", + "SCOPE", + "UnsupportedCompensatedInterfaceDomain", + "default_fd_table", + "evaluate_local_carrier_pair", + "freeze_coefficients", + "to_float_tangent", +] + +SCHEMA = "TwoSidedInterfaceCompensatedV1" +SCOPE = "bounded_local_constitutive_evaluation_not_a_nonlinear_solve" +_ZERO = DD(0) +_ONE = DD(1) +_HALF = DD(0.5) +_SMALL_B = DD(1e-8) +_DERIVATIVE_SERIES_LIMIT = DD(1e-3) +_MAX_EXP_ARGUMENT = DD(672) +_RECIPROCAL = tuple(_ONE / order for order in range(1, 14)) +_RECIPROCAL_SQUARE = tuple(_ONE / (order * order) for order in range(1, 13)) +_B_DERIVATIVE_COEFFICIENTS = ( + _ONE / 6, + -_ONE / 180, + _ONE / 5040, + -_ONE / 151200, + _ONE / 4790016, +) + + +class UnsupportedCompensatedInterfaceDomain(ArithmeticError): + """Raised when an interface state lies outside the compensated constitutive domain.""" + + +def _freeze_value(value: Any) -> Any: + if isinstance(value, DD): + return value + if isinstance(value, Mapping): + return MappingProxyType({str(k): _freeze_value(v) for k, v in value.items()}) + if isinstance(value, np.ndarray): + return _freeze_value(value.tolist()) + if isinstance(value, (tuple, list)): + return tuple(_freeze_value(item) for item in value) + if isinstance(value, np.generic): + return value.item() + return value + + +@dataclass(frozen=True, slots=True) +class LocalCarrierEvaluation(Mapping[str, object]): + """Immutable compensated local carrier balance, tangent, and audit metadata.""" + + balance: Mapping[str, DD] + tangent: Mapping[str, DD] + metadata: Mapping[str, object] + schema: str = SCHEMA + scope: str = SCOPE + + def __post_init__(self) -> None: + object.__setattr__(self, "balance", _freeze_value(self.balance)) + object.__setattr__(self, "tangent", _freeze_value(self.tangent)) + object.__setattr__(self, "metadata", _freeze_value(self.metadata)) + + def __getitem__(self, key: str) -> object: + if key not in ("schema", "scope", "balance", "tangent", "metadata"): + raise KeyError(key) + return getattr(self, key) + + def __iter__(self) -> Iterator[str]: + return iter(("schema", "scope", "balance", "tangent", "metadata")) + + def __len__(self) -> int: + return 5 + + def __deepcopy__(self, memo: object) -> LocalCarrierEvaluation: + return self + + +@dataclass(frozen=True, slots=True) +class CompensatedCarrierBalance: + """Explicit binary64 projection of compensated local carrier balance arrays.""" + + state_m3: NDArray[np.float64] + bulk_flux_m2_s: NDArray[np.float64] + cross_flux_m2_s: NDArray[np.float64] + capture_flux_m2_s: NDArray[np.float64] + residual_m2_s: NDArray[np.float64] + jacobian_log_state_m2_s: NDArray[np.float64] + jacobian_trace_potential_m2_s_V: NDArray[np.float64] + jacobian_bulk_coordinates: NDArray[np.float64] + one_way_cross_scale_m2_s: NDArray[np.float64] + + +@dataclass(frozen=True, slots=True) +class CompensatedCarrierTangent: + """Explicit binary64 projection of compensated local carrier balance and tangents.""" + + balance: CompensatedCarrierBalance + bulk_flux_jacobian_log_state_m2_s: NDArray[np.float64] + bulk_flux_jacobian_trace_potential_m2_s_V: NDArray[np.float64] + bulk_flux_jacobian_bulk_coordinates: NDArray[np.float64] + capture_flux_jacobian_log_state_m2_s: NDArray[np.float64] + capture_flux_occupancy_derivative_m2_s: NDArray[np.float64] + residual_occupancy_derivative_m2_s: NDArray[np.float64] + + +@lru_cache(maxsize=1) +def default_fd_table() -> tuple[Mapping[str, tuple[float, ...]], str]: + """Return the immutable Fermi-Dirac order-1/2 table and its SHA-256 digest.""" + eta, _values, log_half = fermi_dirac_half_table() + payload: dict[str, tuple[float, ...]] = { + "eta": tuple(float(v) for v in eta), + "log_half": tuple(float(v) for v in log_half), + } + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + return MappingProxyType(payload), hashlib.sha256(encoded).hexdigest() + + +def _cat(*values: DD) -> DD: + return DD.from_normalized_parts( + np.concatenate([np.atleast_1d(v.hi) for v in values]), + np.concatenate([np.atleast_1d(v.lo) for v in values]), + ) + + +def _put(value: DD, index: Any, part: DD) -> DD: + high, low = value.hi.copy(), value.lo.copy() + high[index], low[index] = part.hi, part.lo + return DD.from_normalized_parts(high, low) + + +def _choose(mask: NDArray[np.bool_], first: DD, second: DD) -> DD: + return DD.from_normalized_parts( + np.where(mask, first.hi, second.hi), + np.where(mask, first.lo, second.lo), + ) + + +def _diagonal(values: DD) -> DD: + return DD.from_normalized_parts(np.diag(values.hi), np.diag(values.lo)) + + +def _require_dd(name: str, value: object, shape: tuple[int, ...]) -> DD: + if not isinstance(value, DD) or value.shape != shape: + raise TypeError(f"{name} must be DD with shape {shape!r}") + return value + + +def _frozen_vector(values: ArrayLike) -> NDArray[np.float64]: + arr = frozen_array(values) + if arr.ndim != 1: + raise ValueError("frozen interpolation nodes must be finite 1D vectors") + return arr + + +@dataclass(frozen=True, slots=True) +class FrozenLocalCoefficients: + """State-independent compensated coefficients for one two-sided interface.""" + + physics: Mapping[str, DD] + carrier_diffusion_over_distance: DD + density_of_states: DD + emission_densities: DD + cross_prefactors: DD + eta_nodes: DD + log_half_nodes: DD + inverse_log_slopes: DD + _log_half_search_bytes: bytes = field(repr=False) + fd_table_sha256: str + + @property + def log_half_search(self) -> NDArray[np.float64]: + return np.frombuffer(self._log_half_search_bytes, dtype=np.float64) + + def __deepcopy__(self, memo: object) -> FrozenLocalCoefficients: + return self + + +def freeze_coefficients( + geometry: Mapping[str, float], + physics: Mapping[str, float], + *, + fd_table: Mapping[str, ArrayLike] | None = None, + fd_table_sha256: str | None = None, + q_C: float = ELEMENTARY_CHARGE_C, +) -> FrozenLocalCoefficients: + """Bind exact binary64 geometry, physics, and Fermi-table coefficients.""" + if fd_table is None and fd_table_sha256 is None: + fd_table, observed = default_fd_table() + else: + if ( + not isinstance(fd_table, Mapping) + or set(fd_table) != {"eta", "log_half"} + or not isinstance(fd_table_sha256, str) + ): + raise ValueError("frozen Fermi table fields differ from the declared contract") + table_payload = {name: [float(x) for x in np.asarray(vals)] for name, vals in fd_table.items()} + encoded = json.dumps(table_payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + observed = hashlib.sha256(encoded).hexdigest() + if observed != fd_table_sha256: + raise ValueError("frozen Fermi table identity mismatch") + eta = _frozen_vector(fd_table["eta"]) + log_half = _frozen_vector(fd_table["log_half"]) + if ( + eta.size != log_half.size + or eta.size < 2 + or not np.all(np.diff(eta) > 0.0) + or not np.all(np.diff(log_half) > 0.0) + ): + raise ValueError("frozen Fermi nodes must be strictly increasing and paired") + values = {name: DD(val) for name, val in physics.items()} + if any(val.shape != () for val in values.values()): + raise ValueError("material coefficients must be scalar binary64 inputs") + vt, temperature = values["thermal_voltage_V"], values["temperature_K"] + charge = DD(q_C) + left, right = DD(geometry["left_distance_m"]), DD(geometry["right_distance_m"]) + if ( + not bool(vt > 0) + or not bool(temperature > 0) + or not bool(charge > 0) + or not bool(left > 0) + or not bool(right > 0) + or not bool((values["transmission"] >= 0) & (values["transmission"] <= 1)) + ): + raise ValueError("invalid frozen local material or geometry") + diffusion = _cat( + values["D_n_left_m2_s"], + values["D_p_left_m2_s"], + values["D_n_right_m2_s"], + values["D_p_right_m2_s"], + ) + dos = _cat( + values["N_C_left_m3"], + values["N_V_left_m3"], + values["N_C_right_m3"], + values["N_V_right_m3"], + ) + emission = _cat( + values["n1_left_m3"], + values["p1_left_m3"], + values["n1_right_m3"], + values["p1_right_m3"], + ) + richardson = _cat(values["richardson_n_A_m2_K2"], values["richardson_p_A_m2_K2"]) + velocity = _cat( + values["surface_recombination_velocity_n_m_s"], + values["surface_recombination_velocity_p_m_s"], + ) + if ( + np.any(diffusion < 0) + or np.any(dos <= 0) + or np.any(emission < 0) + or np.any(richardson < 0) + or np.any(velocity < 0) + ): + raise ValueError("invalid frozen local carrier coefficients") + eta_dd, log_dd = DD(eta), DD(log_half) + return FrozenLocalCoefficients( + MappingProxyType(values), + diffusion / _cat(left, left, right, right), + dos, + emission, + values["transmission"] * richardson * temperature * temperature / charge, + eta_dd, + log_dd, + (eta_dd[1:] - eta_dd[:-1]) / (log_dd[1:] - log_dd[:-1]), + log_half.tobytes(), + observed, + ) + + +def _bernoulli_values_and_derivatives(x: DD) -> tuple[DD, DD, DD, DD]: + magnitude = abs(x) + if np.any(magnitude > _MAX_EXP_ARGUMENT): + raise UnsupportedCompensatedInterfaceDomain("Bernoulli argument exceeds compensated domain") + b = DD(np.ones(x.shape, dtype=np.float64)) + derivative = DD(np.full(x.shape, -0.5, dtype=np.float64)) + quadratic = magnitude < _SMALL_B + if np.any(quadratic): + a = magnitude[quadratic] + b = _put(b, quadratic, _ONE - a * _HALF + a * a * _RECIPROCAL[11]) + derivative = _put(derivative, quadratic, -_HALF + a * _RECIPROCAL[5]) + moderate = (~quadratic) & (magnitude <= 50) + if np.any(moderate): + a = magnitude[moderate] + denominator = a.expm1() + b = _put(b, moderate, a / denominator) + stable = a < _DERIVATIVE_SERIES_LIMIT + db = DD(np.zeros(a.shape, dtype=np.float64)) + if np.any(stable): + z = a[stable] + z2 = z * z + c1, c3, c5, c7, c9 = _B_DERIVATIVE_COEFFICIENTS + db = _put( + db, + stable, + -_HALF + z * (c1 + z2 * (c3 + z2 * (c5 + z2 * (c7 + z2 * c9)))), + ) + if np.any(~stable): + z, den = a[~stable], denominator[~stable] + db = _put(db, ~stable, (den - z * (den + _ONE)) / (den * den)) + derivative = _put(derivative, moderate, db) + large = magnitude > 50 + if np.any(large): + a = magnitude[large] + decay = (-a).exp() + denominator = _ONE - decay + b = _put(b, large, a * decay / denominator) + derivative = _put( + derivative, + large, + decay * (_ONE - a - decay) / (denominator * denominator), + ) + backward = b + magnitude + backward_derivative = -_ONE - derivative + positive = x >= 0 + return ( + _choose(positive, b, backward), + _choose(positive, backward, b), + _choose(positive, derivative, backward_derivative), + _choose(positive, backward_derivative, derivative), + ) + + +def _inverse_half( + log_ratio: DD, coefficients: FrozenLocalCoefficients +) -> tuple[DD, DD, NDArray[np.int64]]: + if np.any(log_ratio > coefficients.log_half_nodes[-1]): + raise UnsupportedCompensatedInterfaceDomain( + "compensated local carrier law does not implement the Sommerfeld inverse branch" + ) + below = log_ratio <= coefficients.log_half_nodes[0] + eta = log_ratio.copy() + slope = DD(np.ones(log_ratio.shape, dtype=np.float64)) + intervals: NDArray[np.int64] = np.full(log_ratio.shape, -1, dtype=np.int64) + if np.any(~below): + target = log_ratio[~below] + index = np.searchsorted(coefficients.log_half_search, target.hi, side="right") - 1 + index = np.clip(index, 0, coefficients.log_half_search.size - 2) + lower = target < coefficients.log_half_nodes[index] + index = index - lower.astype(np.int64) + upper = (index < coefficients.log_half_search.size - 2) & ( + target >= coefficients.log_half_nodes[index + 1] + ) + index = index + upper.astype(np.int64) + if ( + np.any(index < 0) + or np.any(index >= coefficients.log_half_search.size - 1) + or np.any(target < coefficients.log_half_nodes[index]) + or np.any(target > coefficients.log_half_nodes[index + 1]) + ): + raise ArithmeticError("full-pair inverse-table interval selection failed") + derivative = coefficients.inverse_log_slopes[index] + eta = _put( + eta, + ~below, + coefficients.eta_nodes[index] + (target - coefficients.log_half_nodes[index]) * derivative, + ) + slope = _put(slope, ~below, derivative) + intervals[~below] = index + return eta, slope, intervals + + +def _series_power_mul(power: DD, activity: DD) -> DD: + """Multiply positive Fermi-series power ``a^k`` by ``a`` without subnormal DD underflow. + + When ``|a^k * a| < 1e-290`` (with ``0 < a < exp(-4)``), ``a^k / a <= 1e-96 << 2^-106``, + so higher series powers are strictly zero at 106-bit double-double precision. + """ + with np.errstate(under="ignore"): + approx = np.abs(power.hi) * np.abs(activity.hi) + active = approx >= 1.0e-290 + if bool(np.all(active)): + return power * activity + if not bool(np.any(active)): + return DD(np.zeros(power.shape, dtype=np.float64)) + safe_power = _choose(active, power, DD(np.zeros(power.shape, dtype=np.float64))) + return safe_power * activity + + +def _supplies( + state: DD, barriers: DD, coefficients: FrozenLocalCoefficients +) -> tuple[DD, DD, DD, dict[str, object]]: + ratio = state / coefficients.density_of_states + log_ratio = ratio.log() + eta, inverse_slope, intervals = _inverse_half(log_ratio, coefficients) + argument = eta - barriers / coefficients.physics["thermal_voltage_V"] + if np.any(argument >= -4): + raise UnsupportedCompensatedInterfaceDomain( + "compensated local carrier law only covers the frozen twelve-term Fermi-one branch" + ) + activity = argument.exp() + total = DD(np.zeros(state.shape, dtype=np.float64)) + derivative = DD(np.zeros(state.shape, dtype=np.float64)) + power = activity + for order in range(1, 13): + sign = 1 if order % 2 else -1 + total = total + sign * power * _RECIPROCAL_SQUARE[order - 1] + derivative = derivative + sign * power * _RECIPROCAL[order - 1] + if order != 12: + power = _series_power_mul(power, activity) + old_fermi_zero = activity.log1p() + tail_bound = _series_power_mul(power, activity) * _RECIPROCAL[12] / (_ONE - activity) + return ( + total, + derivative * inverse_slope, + -derivative / coefficients.physics["thermal_voltage_V"], + { + "inverse_half_arguments": eta, + "inverse_log_ratio": log_ratio, + "inverse_intervals": intervals, + "inverse_log_derivative": inverse_slope, + "supply_arguments": argument, + "polynomial_argument_derivative": derivative, + "old_complete_F0_argument_derivative": old_fermi_zero, + "computed_DD_old_F0_minus_polynomial_derivative": old_fermi_zero - derivative, + "analytic_old_F0_tail_bound": tail_bound, + }, + ) + + +def evaluate_local_carrier_pair( + *, + state_density: DD, + trace_potential: DD, + bulk_density: DD, + bulk_potential: DD, + occupancy: DD, + capture_multiplier: float | int, + coefficients: FrozenLocalCoefficients, +) -> LocalCarrierEvaluation: + """Evaluate four compensated local interface carrier rows and exact partials.""" + _require_dd("state_density", state_density, (4,)) + _require_dd("trace_potential", trace_potential, (2,)) + _require_dd("bulk_density", bulk_density, (4,)) + _require_dd("bulk_potential", bulk_potential, (2,)) + _require_dd("occupancy", occupancy, ()) + multiplier = DD(capture_multiplier) + if ( + np.any(state_density <= 0) + or np.any(bulk_density <= 0) + or not bool((occupancy >= 0) & (occupancy <= 1)) + or not bool((multiplier >= 0) & (multiplier <= 1)) + ): + raise ValueError("compensated local carriers require positive densities and physical occupancies") + if not isinstance(coefficients, FrozenLocalCoefficients): + raise TypeError("explicit FrozenLocalCoefficients are required") + + physics = coefficients.physics + vt = physics["thermal_voltage_V"] + xl = (trace_potential[0] - bulk_potential[0]) / vt + xr = (bulk_potential[1] - trace_potential[1]) / vt + b, bm, db, dbm = _bernoulli_values_and_derivatives(_cat(xl, xr)) + incoming = _cat(bm[0], b[0], b[1], bm[1]) + outgoing = _cat(b[0], bm[0], bm[1], b[1]) + k = coefficients.carrier_diffusion_over_distance + bulk_flux = k * (incoming * bulk_density - outgoing * state_density) + bulk_log_jacobian = _diagonal(-k * outgoing * state_density) + potential_derivative = (k / vt) * _cat( + -dbm[0] * bulk_density[0] - db[0] * state_density[0], + db[0] * bulk_density[1] + dbm[0] * state_density[1], + -db[1] * bulk_density[2] - dbm[1] * state_density[2], + dbm[1] * bulk_density[3] + db[1] * state_density[3], + ) + bulk_trace_jacobian = DD(np.zeros((4, 2), dtype=np.float64)) + bulk_trace_jacobian = _put(bulk_trace_jacobian, (slice(0, 2), 0), potential_derivative[:2]) + bulk_trace_jacobian = _put(bulk_trace_jacobian, (slice(2, 4), 1), potential_derivative[2:]) + bulk_coordinate_jacobian = DD(np.zeros((4, 6), dtype=np.float64)) + bulk_coordinate_jacobian = _put( + bulk_coordinate_jacobian, (slice(None), slice(0, 2)), -bulk_trace_jacobian + ) + bulk_coordinate_jacobian = _put( + bulk_coordinate_jacobian, + (slice(None), slice(2, 6)), + _diagonal(k * incoming * bulk_density), + ) + + jump = trace_potential[1] - trace_potential[0] + electron_step = physics["conduction_band_step_eV"] - jump + hole_step = physics["hole_transport_step_eV"] + jump + barriers = _cat( + electron_step if bool(electron_step > 0) else _ZERO, + hole_step if bool(hole_step > 0) else _ZERO, + -electron_step if bool(electron_step < 0) else _ZERO, + -hole_step if bool(hole_step < 0) else _ZERO, + ) + supplies, supply_log_derivative, supply_barrier_derivative, metadata = _supplies( + state_density, barriers, coefficients + ) + pn, pp = coefficients.cross_prefactors[0], coefficients.cross_prefactors[1] + xn = pn * (supplies[0] - supplies[2]) + xp = pp * (supplies[1] - supplies[3]) + cross_flux = _cat(-xn, -xp, xn, xp) + cross_pair_log = DD(np.zeros((2, 4), dtype=np.float64)) + cross_pair_log = _put(cross_pair_log, (0, 0), pn * supply_log_derivative[0]) + cross_pair_log = _put(cross_pair_log, (0, 2), -pn * supply_log_derivative[2]) + cross_pair_log = _put(cross_pair_log, (1, 1), pp * supply_log_derivative[1]) + cross_pair_log = _put(cross_pair_log, (1, 3), -pp * supply_log_derivative[3]) + + electron_jump_derivative = _ZERO + if bool(electron_step > 0): + electron_jump_derivative = -pn * supply_barrier_derivative[0] + elif bool(electron_step < 0): + electron_jump_derivative = -pn * supply_barrier_derivative[2] + hole_jump_derivative = _ZERO + if bool(hole_step > 0): + hole_jump_derivative = pp * supply_barrier_derivative[1] + elif bool(hole_step < 0): + hole_jump_derivative = pp * supply_barrier_derivative[3] + + cross_pair_trace = _cat( + -electron_jump_derivative, + electron_jump_derivative, + -hole_jump_derivative, + hole_jump_derivative, + ).reshape(2, 2) + cross_log_jacobian = _cat( + -cross_pair_log[0], + -cross_pair_log[1], + cross_pair_log[0], + cross_pair_log[1], + ).reshape(4, 4) + cross_trace_jacobian = _cat( + -cross_pair_trace[0], + -cross_pair_trace[1], + cross_pair_trace[0], + cross_pair_trace[1], + ).reshape(4, 2) + + vn = multiplier * physics["surface_recombination_velocity_n_m_s"] + vp = multiplier * physics["surface_recombination_velocity_p_m_s"] + velocity = _cat(vn, vp, vn, vp) + live_factor = _cat(_ONE - occupancy, occupancy, _ONE - occupancy, occupancy) + emission_factor = _ONE - live_factor + capture_flux = velocity * ( + state_density * live_factor - coefficients.emission_densities * emission_factor + ) + capture_log_jacobian = _diagonal(velocity * live_factor * state_density) + capture_occupancy_derivative = _cat(-vn, vp, -vn, vp) * ( + state_density + coefficients.emission_densities + ) + residual = bulk_flux + cross_flux - capture_flux + one_way_scale = _cat( + pn * _choose(supplies[0] >= supplies[2], supplies[0], supplies[2]), + pp * _choose(supplies[1] >= supplies[3], supplies[1], supplies[3]), + ) + + balance: dict[str, DD] = { + "state_m3": state_density, + "bulk_flux_m2_s": bulk_flux, + "cross_flux_m2_s": cross_flux, + "capture_flux_m2_s": capture_flux, + "residual_m2_s": residual, + "jacobian_log_state_m2_s": bulk_log_jacobian + cross_log_jacobian - capture_log_jacobian, + "jacobian_trace_potential_m2_s_V": bulk_trace_jacobian + cross_trace_jacobian, + "jacobian_bulk_coordinates": bulk_coordinate_jacobian, + "one_way_cross_scale_m2_s": one_way_scale, + } + tangent: dict[str, DD] = { + "bulk_flux_jacobian_log_state_m2_s": bulk_log_jacobian, + "bulk_flux_jacobian_trace_potential_m2_s_V": bulk_trace_jacobian, + "bulk_flux_jacobian_bulk_coordinates": bulk_coordinate_jacobian, + "capture_flux_jacobian_log_state_m2_s": capture_log_jacobian, + "capture_flux_occupancy_derivative_m2_s": capture_occupancy_derivative, + "residual_occupancy_derivative_m2_s": -capture_occupancy_derivative, + } + return LocalCarrierEvaluation( + balance=balance, + tangent=tangent, + metadata={ + **metadata, + "fd_table_sha256": coefficients.fd_table_sha256, + "bulk_bernoulli_arguments": _cat(xl, xr), + "band_steps": _cat(electron_step, hole_step), + "barriers": barriers, + "fermi_one_polynomial_degree": 12, + "supply_derivative_policy": "derivative_of_the_same_frozen_twelve_term_polynomial", + "inverse_derivative_policy": "selected_linear_interval_not_legacy_knot_average", + "zero_band_step_derivative_policy": "original_zero_derivative_at_exact_zero", + "small_B_derivative_policy": "derivative_of_original_quadratic_B_below_1e_minus_8", + "old_F0_difference_note": "computed_DD_difference_may_not_resolve_the_smaller_analytic_tail", + "constitutive_domain_complete": False, + "fallback_used": False, + }, + ) + + +def _dd_array_float(value: DD) -> NDArray[np.float64]: + out = value.to_float() + return np.asarray(out, dtype=np.float64) + + +def to_float_tangent(evaluation: LocalCarrierEvaluation) -> CompensatedCarrierTangent: + """Explicit binary64 projection boundary from a ``LocalCarrierEvaluation``.""" + if evaluation.schema != SCHEMA: + raise ValueError("unexpected compensated local carrier evaluation schema") + bal = evaluation.balance + tan = evaluation.tangent + balance = CompensatedCarrierBalance( + state_m3=_dd_array_float(bal["state_m3"]), + bulk_flux_m2_s=_dd_array_float(bal["bulk_flux_m2_s"]), + cross_flux_m2_s=_dd_array_float(bal["cross_flux_m2_s"]), + capture_flux_m2_s=_dd_array_float(bal["capture_flux_m2_s"]), + residual_m2_s=_dd_array_float(bal["residual_m2_s"]), + jacobian_log_state_m2_s=_dd_array_float(bal["jacobian_log_state_m2_s"]), + jacobian_trace_potential_m2_s_V=_dd_array_float(bal["jacobian_trace_potential_m2_s_V"]), + jacobian_bulk_coordinates=_dd_array_float(bal["jacobian_bulk_coordinates"]), + one_way_cross_scale_m2_s=_dd_array_float(bal["one_way_cross_scale_m2_s"]), + ) + return CompensatedCarrierTangent( + balance=balance, + bulk_flux_jacobian_log_state_m2_s=_dd_array_float(tan["bulk_flux_jacobian_log_state_m2_s"]), + bulk_flux_jacobian_trace_potential_m2_s_V=_dd_array_float( + tan["bulk_flux_jacobian_trace_potential_m2_s_V"] + ), + bulk_flux_jacobian_bulk_coordinates=_dd_array_float(tan["bulk_flux_jacobian_bulk_coordinates"]), + capture_flux_jacobian_log_state_m2_s=_dd_array_float(tan["capture_flux_jacobian_log_state_m2_s"]), + capture_flux_occupancy_derivative_m2_s=_dd_array_float( + tan["capture_flux_occupancy_derivative_m2_s"] + ), + residual_occupancy_derivative_m2_s=_dd_array_float(tan["residual_occupancy_derivative_m2_s"]), + ) diff --git a/src/solarlab_research/r1/__init__.py b/src/solarlab_research/r1/__init__.py new file mode 100644 index 00000000..e6d7796a --- /dev/null +++ b/src/solarlab_research/r1/__init__.py @@ -0,0 +1,97 @@ +"""R1 interface-trap + mobile-ion research package over public SolarLab interfaces.""" + +from solarlab_research.r1.contracts import ( + R1_CONSERVATIVE_SUBSTEPS, + R1_CONTROLS, + R1_FULL_WINDOW_EXPECTED_ROWS, + R1_OPERATOR_CHANNELS, + R1_RELATIVE_ENGINEERING_LIMITS, + R1_SOLVER_BUDGETS, + R1_STUDY_REQUEST_SCHEMA, + R1_V53_CERTIFICATE_LIMITS, + R1CertificateEvaluation, + R1QualificationAssessment, + R1StudyRequest, + assess_r1_qualification, + build_r1_study_request, + evaluate_v53_certificate, + expected_substep_rows, + load_r1_study_request, + observation_times_12_per_decade, + validate_operator_channel_packet, + verify_r1_study_request, +) +from solarlab_research.r1.controls import ( + R1ControlAudit, + R1ControlSuiteReport, + R1ZeroMinusAnchor, + default_r1_prepared_device, + prepare_r1_zero_minus_anchor, + verify_r1_controls_abcd, +) +from solarlab_research.r1.provenance import ( + HistoricalR1ArtifactSummary, + HistoricalR1WitnessAudit, + R1ReleaseSourceBinding, + load_verified_release_bundle, + read_historical_r1_artifact, + synthetic_research_release_bundle, + verify_historical_r1_failure_witness, + verify_r1_release_source, +) +from solarlab_research.r1.short_window import ( + R1CoupledStepResult, + R1ModeWindowRun, + R1ReplayReceipt, + R1ShortWindowPairingResult, + R1WitnessMinimalEvaluation, + evaluate_r1_witness_minimal_input, + evaluate_sub_ulp_storage_precision, + run_r1_short_window_pairing, + solve_coupled_r1_step, +) + +__all__ = [ + "HistoricalR1ArtifactSummary", + "HistoricalR1WitnessAudit", + "R1CertificateEvaluation", + "R1ControlAudit", + "R1ControlSuiteReport", + "R1CoupledStepResult", + "R1ModeWindowRun", + "R1QualificationAssessment", + "R1ReleaseSourceBinding", + "R1ReplayReceipt", + "R1ShortWindowPairingResult", + "R1StudyRequest", + "R1WitnessMinimalEvaluation", + "R1ZeroMinusAnchor", + "R1_CONSERVATIVE_SUBSTEPS", + "R1_CONTROLS", + "R1_FULL_WINDOW_EXPECTED_ROWS", + "R1_OPERATOR_CHANNELS", + "R1_RELATIVE_ENGINEERING_LIMITS", + "R1_SOLVER_BUDGETS", + "R1_STUDY_REQUEST_SCHEMA", + "R1_V53_CERTIFICATE_LIMITS", + "assess_r1_qualification", + "build_r1_study_request", + "default_r1_prepared_device", + "evaluate_r1_witness_minimal_input", + "evaluate_sub_ulp_storage_precision", + "evaluate_v53_certificate", + "expected_substep_rows", + "load_r1_study_request", + "load_verified_release_bundle", + "observation_times_12_per_decade", + "prepare_r1_zero_minus_anchor", + "read_historical_r1_artifact", + "run_r1_short_window_pairing", + "solve_coupled_r1_step", + "synthetic_research_release_bundle", + "validate_operator_channel_packet", + "verify_historical_r1_failure_witness", + "verify_r1_controls_abcd", + "verify_r1_release_source", + "verify_r1_study_request", +] diff --git a/src/solarlab_research/r1/contracts.py b/src/solarlab_research/r1/contracts.py new file mode 100644 index 00000000..e4b1f4ae --- /dev/null +++ b/src/solarlab_research/r1/contracts.py @@ -0,0 +1,428 @@ +"""Frozen R1 V53 certificate limits, 13-channel schema, study requests, and qualification rules. + +Implements the research-side R1 contracts for ``P07-01`` and ``P07-02``: +* Exact 16-item V53 certificate limits, solver budgets, and relative engineering limits. +* Exact 13-channel operator observation packet validator. +* Controls ``A-D`` definitions (``A:(0,0)``, ``B:(1,0)``, ``C:(0,1)``, ``D:(1,1)``). +* Conservative ``(4, 8, 16)`` substep row-count formula (``3727`` rows on the 100 s + 12-per-decade window; ``59`` rows on a 2-interval short window). +* Strict IDA ``R1-L2`` exclusion (``P07-02.4``): IDA or interpolated trajectories + can never grant ``R1-L2``, and short-window verification never claims ``R1-L2`` + (full 100 s) or ``R1-L3`` device qualification. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import hashlib +import json +import math +from types import MappingProxyType +from typing import Any + +import numpy as np +from numpy.typing import NDArray + +__all__ = [ + "R1_CONSERVATIVE_SUBSTEPS", + "R1_CONTROLS", + "R1_FULL_WINDOW_EXPECTED_ROWS", + "R1_OPERATOR_CHANNELS", + "R1_RELATIVE_ENGINEERING_LIMITS", + "R1_SOLVER_BUDGETS", + "R1_STUDY_REQUEST_SCHEMA", + "R1_V53_CERTIFICATE_LIMITS", + "R1CertificateEvaluation", + "R1QualificationAssessment", + "R1StudyRequest", + "assess_r1_qualification", + "build_r1_study_request", + "evaluate_v53_certificate", + "expected_substep_rows", + "load_r1_study_request", + "observation_times_12_per_decade", + "validate_operator_channel_packet", + "verify_r1_study_request", +] + +R1_STUDY_REQUEST_SCHEMA = "solarlab_research.r1_study_request.v1" + +R1_CONSERVATIVE_SUBSTEPS: tuple[int, int, int] = (4, 8, 16) +R1_FULL_WINDOW_EXPECTED_ROWS: int = 3727 + +R1_OPERATOR_CHANNELS: tuple[str, ...] = ( + "capture_flux", + "electron_current", + "electron_density", + "electron_rate", + "hole_current", + "hole_density", + "hole_rate", + "local_state", + "positive_ion_flux", + "positive_ion_rate", + "potential", + "sheet_charge", + "trace_potential", +) + +R1_V53_CERTIFICATE_LIMITS: Mapping[str, float] = MappingProxyType({ + "all_face_current_relative": 2.0e-6, + "analytic_jacobian_error": 3.0e-4, + "charge_balance_relative": 1.0e-10, + "current_decomposition_error": 1.0e-14, + "eliminated_operator_error": 1.0e-6, + "full_charge_balance_normalized": 1.0e-10, + "full_gauss_normalized": 1.0e-10, + "interface_current_relative": 2.0e-6, + "inventory_relative_drift": 1.0e-10, + "local_carrier_residual": 1.0e-7, + "local_gauss_residual": 1.0e-7, + "nonlinear_residual": 0.05, + "physical_current_spread_relative": 2.0e-6, + "refinement_current_change": 0.05, + "refinement_state_change": 0.02, + "trap_storage_normalized_error": 1.0, +}) + +R1_SOLVER_BUDGETS: Mapping[str, int] = MappingProxyType({ + "maximum_newton_iterations": 100, + "maximum_line_search_steps": 40, + "maximum_near_acceptance_nonmonotone_steps": 2, + "maximum_joint_corrector_iterations": 8, + "maximum_independent_poisson_iterations": 12, +}) + +R1_RELATIVE_ENGINEERING_LIMITS: Mapping[str, float] = MappingProxyType({ + "bytes_per_row_ratio": 3.0, + "elapsed_ratio": 5.0, + "peak_rss_ratio": 2.0, +}) + +R1_CONTROLS: Mapping[str, Mapping[str, int]] = MappingProxyType({ + "A": MappingProxyType({"nu_I": 0, "nu_t": 0}), + "B": MappingProxyType({"nu_I": 1, "nu_t": 0}), + "C": MappingProxyType({"nu_I": 0, "nu_t": 1}), + "D": MappingProxyType({"nu_I": 1, "nu_t": 1}), +}) + + +def _canonical_json_bytes(payload: Any) -> bytes: + return json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") + + +def observation_times_12_per_decade( + *, + first_time_s: float = 1.0e-9, + last_time_s: float = 1.0e2, + points_per_decade: int = 12, +) -> tuple[float, ...]: + """Build the canonical ``0.0`` + logarithmic 12-points-per-decade R1 observation grid.""" + if not (math.isfinite(first_time_s) and math.isfinite(last_time_s)) or first_time_s <= 0.0 or last_time_s <= first_time_s: + raise ValueError("0 < first_time_s < last_time_s is required") + if type(points_per_decade) is not int or points_per_decade < 1: + raise ValueError("points_per_decade must be a positive integer") + decades = math.log10(last_time_s / first_time_s) + intervals = int(round(decades * points_per_decade)) + if not math.isclose(decades * points_per_decade, intervals, rel_tol=0.0, abs_tol=1.0e-9): + raise ValueError("time span must be an exact rational multiple of 1/points_per_decade decades") + log_start = math.log10(first_time_s) + positive = [10.0 ** (log_start + k / points_per_decade) for k in range(intervals + 1)] + positive[0] = float(first_time_s) + positive[-1] = float(last_time_s) + return (0.0, *positive) + + +def expected_substep_rows( + times_s: Sequence[float], + substeps: Sequence[int] = R1_CONSERVATIVE_SUBSTEPS, +) -> int: + """Compute exact accepted row count ``sum(1 + s * K for s in substeps)`` without interpolation.""" + if len(times_s) < 2: + raise ValueError("times_s must contain 0.0 and at least one positive observation endpoint") + arr: NDArray[np.float64] = np.asarray(times_s, dtype=float) + if arr.ndim != 1 or not np.all(np.isfinite(arr)) or arr[0] != 0.0 or not np.all(np.diff(arr) > 0.0): + raise ValueError("times_s must start at 0.0 and strictly increase") + if not substeps or any(type(s) is not int or s < 1 for s in substeps): + raise ValueError("substeps must be a non-empty sequence of positive integers") + k_intervals = len(times_s) - 1 + return sum(1 + int(s) * k_intervals for s in substeps) + + +@dataclass(frozen=True, slots=True) +class R1CertificateEvaluation: + """Outcome of checking the 16 frozen V53 certificate limits.""" + + passed: bool + metrics: Mapping[str, float] + limits: Mapping[str, float] + failed_items: tuple[str, ...] + + +def evaluate_v53_certificate( + metrics: Mapping[str, float], + *, + limits: Mapping[str, float] = R1_V53_CERTIFICATE_LIMITS, +) -> R1CertificateEvaluation: + """Evaluate all 16 V53 certificate metrics against frozen limits.""" + missing = sorted(set(limits) - set(metrics)) + extra = sorted(set(metrics) - set(limits)) + if missing or extra: + raise ValueError( + f"certificate metrics must match the exact 16 V53 keys; missing={missing}, extra={extra}" + ) + checked: dict[str, float] = {} + failed: list[str] = [] + for key, limit in sorted(limits.items()): + raw = metrics[key] + if isinstance(raw, bool): + raise TypeError(f"metric {key!r} must be numeric, not bool") + val = float(raw) + checked[key] = val + if not math.isfinite(val) or val < 0.0 or val > float(limit): + failed.append(key) + return R1CertificateEvaluation( + passed=not failed, + metrics=MappingProxyType(checked), + limits=MappingProxyType(dict(limits)), + failed_items=tuple(failed), + ) + + +def validate_operator_channel_packet( + packet: Mapping[str, Any], + *, + expected_rows: int | None = None, +) -> dict[str, tuple[int, ...]]: + """Validate that an observation packet contains the exact 13 R1 operator channels.""" + keys = set(packet) + expected = set(R1_OPERATOR_CHANNELS) + if keys != expected: + missing = sorted(expected - keys) + extra = sorted(keys - expected) + raise ValueError(f"operator packet mismatch: missing={missing}, extra={extra}") + shapes: dict[str, tuple[int, ...]] = {} + first_dim: int | None = expected_rows + for name in R1_OPERATOR_CHANNELS: + arr: NDArray[np.float64] = np.asarray(packet[name], dtype=float) + if arr.ndim < 1 or arr.size == 0 or not np.all(np.isfinite(arr)): + raise ValueError(f"channel {name!r} must be a non-empty finite numeric array") + if first_dim is None: + first_dim = int(arr.shape[0]) + elif int(arr.shape[0]) != first_dim: + raise ValueError( + f"channel {name!r} row count {arr.shape[0]} differs from expected {first_dim}" + ) + shapes[name] = tuple(int(d) for d in arr.shape) + return shapes + + +@dataclass(frozen=True, slots=True) +class R1StudyRequest: + """Immutable, content-addressed R1 study request.""" + + study_id: str + control: str + times_s: tuple[float, ...] + substeps: tuple[int, int, int] + voltage_step_V: float + integrator: str + precision_modes: tuple[str, ...] + release_bundle_sha256: str + prepared_device_sha256: str + sha256: str + + def to_mapping(self) -> dict[str, Any]: + body = self._body() + return {**body, "sha256": self.sha256} + + def _body(self) -> dict[str, Any]: + return { + "schema": R1_STUDY_REQUEST_SCHEMA, + "study_id": self.study_id, + "control": self.control, + "control_switches": dict(R1_CONTROLS[self.control]), + "times_s": list(self.times_s), + "substeps": list(self.substeps), + "expected_rows_per_mode": expected_substep_rows(self.times_s, self.substeps), + "voltage_step_V": self.voltage_step_V, + "integrator": self.integrator, + "precision_modes": list(self.precision_modes), + "certificate_limits": dict(R1_V53_CERTIFICATE_LIMITS), + "operator_channels": list(R1_OPERATOR_CHANNELS), + "release_bundle_sha256": self.release_bundle_sha256, + "prepared_device_sha256": self.prepared_device_sha256, + } + + +def build_r1_study_request( + *, + study_id: str, + control: str = "D", + times_s: Sequence[float], + substeps: tuple[int, int, int] = R1_CONSERVATIVE_SUBSTEPS, + voltage_step_V: float = 5.0e-3, + integrator: str = "conservative_backward_euler", + precision_modes: Sequence[str] = ("baseline", "compensated"), + release_bundle_sha256: str, + prepared_device_sha256: str, +) -> R1StudyRequest: + """Build and hash a validated R1StudyRequest.""" + if not isinstance(study_id, str) or not study_id.strip(): + raise ValueError("study_id must be a non-empty string") + if control not in R1_CONTROLS: + raise ValueError(f"control must be one of {tuple(R1_CONTROLS)}; got {control!r}") + times = tuple(float(t) for t in times_s) + expected_substep_rows(times, substeps) + if tuple(substeps) != R1_CONSERVATIVE_SUBSTEPS: + raise ValueError(f"R1 conservative stepping requires substeps={R1_CONSERVATIVE_SUBSTEPS}") + if not math.isfinite(voltage_step_V) or voltage_step_V == 0.0: + raise ValueError("voltage_step_V must be finite and non-zero") + if integrator not in {"conservative_backward_euler", "ida"}: + raise ValueError("integrator must be 'conservative_backward_euler' or 'ida'") + modes = tuple(str(m) for m in precision_modes) + if not modes or any(m not in {"baseline", "compensated"} for m in modes): + raise ValueError("precision_modes must be drawn from ('baseline', 'compensated')") + for label, digest in ( + ("release_bundle_sha256", release_bundle_sha256), + ("prepared_device_sha256", prepared_device_sha256), + ): + if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): + raise ValueError(f"{label} must be a 64-character lowercase hex SHA-256") + provisional = R1StudyRequest( + study_id=study_id, + control=control, + times_s=times, + substeps=(int(substeps[0]), int(substeps[1]), int(substeps[2])), + voltage_step_V=float(voltage_step_V), + integrator=integrator, + precision_modes=modes, + release_bundle_sha256=release_bundle_sha256, + prepared_device_sha256=prepared_device_sha256, + sha256="0" * 64, + ) + digest = hashlib.sha256(_canonical_json_bytes(provisional._body())).hexdigest() + return R1StudyRequest( + study_id=provisional.study_id, + control=provisional.control, + times_s=provisional.times_s, + substeps=provisional.substeps, + voltage_step_V=provisional.voltage_step_V, + integrator=provisional.integrator, + precision_modes=provisional.precision_modes, + release_bundle_sha256=provisional.release_bundle_sha256, + prepared_device_sha256=provisional.prepared_device_sha256, + sha256=digest, + ) + + +def verify_r1_study_request(payload: Mapping[str, Any]) -> R1StudyRequest: + """Verify a serialized R1StudyRequest mapping against tampering.""" + if payload.get("schema") != R1_STUDY_REQUEST_SCHEMA: + raise ValueError(f"unexpected study request schema: {payload.get('schema')!r}") + substeps_raw = payload.get("substeps") + if not isinstance(substeps_raw, list) or len(substeps_raw) != 3: + raise ValueError("substeps must be a 3-element list") + rebuilt = build_r1_study_request( + study_id=str(payload["study_id"]), + control=str(payload["control"]), + times_s=payload["times_s"], + substeps=(int(substeps_raw[0]), int(substeps_raw[1]), int(substeps_raw[2])), + voltage_step_V=float(payload["voltage_step_V"]), + integrator=str(payload["integrator"]), + precision_modes=payload["precision_modes"], + release_bundle_sha256=str(payload["release_bundle_sha256"]), + prepared_device_sha256=str(payload["prepared_device_sha256"]), + ) + if rebuilt.sha256 != payload.get("sha256"): + raise ValueError("R1StudyRequest sha256 digest mismatch (tampered request)") + if payload.get("certificate_limits") != dict(R1_V53_CERTIFICATE_LIMITS): + raise ValueError("R1StudyRequest certificate_limits differ from frozen V53 limits") + if payload.get("operator_channels") != list(R1_OPERATOR_CHANNELS): + raise ValueError("R1StudyRequest operator_channels differ from frozen 13-channel contract") + return rebuilt + + +def load_r1_study_request(raw_json: str | bytes) -> R1StudyRequest: + """Parse and verify a JSON-encoded R1StudyRequest.""" + data = json.loads(raw_json) + if not isinstance(data, Mapping): + raise ValueError("R1StudyRequest JSON root must be an object") + return verify_r1_study_request(data) + + +@dataclass(frozen=True, slots=True) +class R1QualificationAssessment: + """Explicit qualification verdict separating short-window, IDA, L2, and L3.""" + + qualification_level: str + short_window_interface_verified: bool + r1_l2_certified: bool + r1_l3_device_qualified: bool + reasons: tuple[str, ...] + + +def assess_r1_qualification( + request: R1StudyRequest, + *, + baseline_certificate: R1CertificateEvaluation | None, + compensated_certificate: R1CertificateEvaluation | None, + baseline_rows: int, + compensated_rows: int, + interpolated_rows: bool = False, + release_verified: bool = False, +) -> R1QualificationAssessment: + """Assess R1 qualification without ever inflating short-window or IDA results to L2/L3.""" + reasons: list[str] = [] + if request.integrator != "conservative_backward_euler": + reasons.append( + "P07-02.4: integrator 'ida' is a method-specific comparison only and is strictly " + "ineligible for R1-L2 qualification" + ) + if interpolated_rows: + reasons.append("P07-02.4: interpolated trajectory rows cannot satisfy the 4/8/16 step contract") + if not release_verified: + reasons.append("release bundle provenance is not verified") + + expected_rows = expected_substep_rows(request.times_s, request.substeps) + if baseline_rows != expected_rows or compensated_rows != expected_rows: + reasons.append( + f"row count mismatch: expected {expected_rows}, got baseline={baseline_rows}, compensated={compensated_rows}" + ) + if baseline_certificate is None or not baseline_certificate.passed: + reasons.append("baseline V53 certificate did not pass") + if compensated_certificate is None or not compensated_certificate.passed: + reasons.append("compensated V53 certificate did not pass") + + is_full_100s = ( + expected_rows == R1_FULL_WINDOW_EXPECTED_ROWS + and math.isclose(request.times_s[-1], 100.0, rel_tol=0.0, abs_tol=1.0e-12) + and request.control == "D" + ) + if not reasons and not is_full_100s: + return R1QualificationAssessment( + qualification_level="short_window_interface_verification_only", + short_window_interface_verified=True, + r1_l2_certified=False, + r1_l3_device_qualified=False, + reasons=( + "short-window/control verification completed (P07-02); full 100s N256 R1-L2 " + "(P07-03) and R1-L3 budgets (P07-04) are not claimed", + ), + ) + if not reasons and is_full_100s: + return R1QualificationAssessment( + qualification_level="r1_l2_candidate_pending_l3_budgets", + short_window_interface_verified=True, + r1_l2_certified=True, + r1_l3_device_qualified=False, + reasons=("R1-L3 independent spatial/temporal/amplitude/AC budgets (P07-04) not supplied",), + ) + return R1QualificationAssessment( + qualification_level="unqualified", + short_window_interface_verified=False, + r1_l2_certified=False, + r1_l3_device_qualified=False, + reasons=tuple(reasons), + ) diff --git a/src/solarlab_research/r1/controls.py b/src/solarlab_research/r1/controls.py new file mode 100644 index 00000000..d96ec9c5 --- /dev/null +++ b/src/solarlab_research/r1/controls.py @@ -0,0 +1,478 @@ +"""R1 controls A-D (nu_I, nu_t) preparation, 0- replication, and channel suppression checks (P07-02.1). + +Verifies on the public ``solarlab`` interface that: +* A single dark equilibrium ``0-`` anchor state is prepared once and replicated + identically across controls ``A:(0,0)``, ``B:(1,0)``, ``C:(0,1)``, and ``D:(1,1)`` + without relabeling any historical ``R1CommonState`` certificate. +* When ``nu_I == 0`` (controls ``A`` and ``C``), positive-ion face flux and + cell storage rate are identically zero while ion background/inventory remain intact. +* When ``nu_t == 0`` (controls ``A`` and ``B``), dynamic interface trap occupancy + rate ``df_t / dt`` and sheet-charge variation ``sigma_if`` are identically zero. +* Under control ``D`` (``nu_I == 1, nu_t == 1``), both ionic and trap channels + actively respond while conserving total ion inventory and Maxwell current. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +from types import MappingProxyType +from typing import Any, Mapping + +import numpy as np + +from solarlab.config.device_inputs import DeviceInput +from solarlab.config.resolve_device import resolve_device +from solarlab.contracts import ELEMENTARY_CHARGE_C +from solarlab.device.compile_ionic_1d import CompiledIonicDevice1D, compile_ionic_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.equations.ionic_1d import IonicState1D +from solarlab.materials.resources import ResourceLibrary +from solarlab.materials.source import SourceDocument +from solarlab.solvers.nonlinear.ionic_1d import IonicSteadyOptions, solve_ionic_steady_state +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions + +from solarlab_research.r1.contracts import R1_CONTROLS + +__all__ = [ + "R1ControlAudit", + "R1ControlSuiteReport", + "R1ZeroMinusAnchor", + "default_r1_prepared_device", + "prepare_r1_zero_minus_anchor", + "verify_r1_controls_abcd", +] + +Q = ELEMENTARY_CHARGE_C + + +def default_r1_prepared_device( + *, + nu_I: int = 1, + ion_diffusivity_m2_s: float = 2.0e-15, + ion_reference_m3: float = 1.0e24, + ion_limit_m3: float = 1.0e27, +) -> PreparedDevice: + """Build a self-contained public 2-layer absorber/ETL heterojunction for R1 verification.""" + if nu_I not in (0, 1): + raise ValueError(f"nu_I must be 0 or 1; got {nu_I!r}") + if ion_diffusivity_m2_s <= 0.0 or not 0.0 < ion_reference_m3 < ion_limit_m3: + raise ValueError("positive unsaturated ion reference and positive base diffusivity required") + + effective_d_ion = float(ion_diffusivity_m2_s) if nu_I == 1 else 0.0 + catalog_doc: dict[str, Any] = { + "schema": "solarlab.default-catalog.v1", + "material": { + "eps_r": 24.0, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "D_ion": 0.0, + "P_lim": 1.0e27, + "P0": 0.0, + "ni": 363572901223.5858, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + "n1": 363572901223.5858, + "p1": 363572901223.5858, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "N_A": 0.0, + "N_D": 0.0, + "chi": 3.9, + "Eg": 1.6, + "A_star_n": 1.2e6, + "A_star_p": 1.2e6, + "v_th": 1.0e5, + "D_ion_neg": 0.0, + "P0_neg": 0.0, + "P_lim_neg": 1.0e27, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "carrier_statistics": "maxwell_boltzmann", + "dopant_ionization_model": "fully_ionized", + "donor_binding_energy_eV": None, + "acceptor_binding_energy_eV": None, + "donor_degeneracy": 2.0, + "acceptor_degeneracy": 4.0, + "band_gap_narrowing_model": "off", + "bgn_reference_energy_eV": 0.0, + "bgn_reference_density_m3": 1.0e24, + "bgn_log_shape": 0.5, + "bgn_conduction_band_fraction": 0.5, + "mu_T_gamma": -1.5, + "E_a_ion": 0.0, + "B_rad_T_gamma": 0.0, + "varshni_alpha": 0.0, + "varshni_beta": 0.0, + "trap_N_t_interface": None, + "trap_N_t_bulk": None, + "trap_decay_length": None, + "trap_profile_shape": "exponential", + "trap_edge": "both", + "optical_material": None, + "n_optical": None, + "incoherent": False, + "v_sat_n": 0.0, + "v_sat_p": 0.0, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "pf_gamma_n": 0.0, + "pf_gamma_p": 0.0, + "Eg_back": None, + "chi_back": None, + "grading_profile": "linear", + "grading_direction": "front_to_back", + "grading_bowing": 0.0, + "grading_char_length": None, + "grading_N_mult": 1, + "N_A_bulk": None, + "N_D_bulk": None, + "doping_profile_shape": None, + "doping_decay_length": None, + "doping_edge": "front", + }, + "device": { + "phi_left": 0.0, + "V_bi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "work_function_left_eV": None, + "work_function_right_eV": None, + "Phi": 2.0e21, + "T": 300.0, + "mode": "fast", + "interface_plane_projection": False, + "dos_band_potentials": True, + "te_physical_norm": False, + "ion_steric_diffusion_only": True, + "ion_steric_shared_site": False, + "flat_band_contacts": False, + "flat_band_metal_contacts": False, + "contact_phi_B_eV": 0.0, + "interface_two_sided": False, + "interface_shared_occupancy": False, + "interface_plane_closure": False, + "interface_plane_generation": False, + "het_recomb_despike": 0.0, + "band_grading": False, + "graded_optics": False, + "interface_tunneling": False, + "tunnel_mass_eff": 0.2, + "jv_solver_policy": "general", + "interface_charge_closure": "off", + "interface_charge_rebaseline_acknowledged": False, + }, + "scaps": { + "D_ion": 0.0, + "P_lim": 1.0e27, + "P0": 0.0, + "B_rad": 1.0e-18, + "C_n": 1.0e-42, + "C_p": 1.0e-42, + "alpha": 2.0e6, + "tau_n": 1.0e-6, + "tau_p": 1.0e-6, + }, + "interface": { + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0, + }, + "constants": { + "Q": 1.602176634e-19, + "K_B": 1.380649e-23, + "T": 300.0, + }, + "contacts": { + "S_n_left": None, + "S_p_left": None, + "S_n_right": None, + "S_p_right": None, + }, + "structural": { + "grain_boundary_layer_role": "absorber", + "tandem_light_direction": "top_first", + "junction_incoherent": False, + }, + "defect_model": "effective_lifetime", + "defect_schema_version": None, + "defect_degeneracy": 1.0, + "distribution_width_convention": "not_applicable", + } + device_doc: dict[str, Any] = { + "schema_version": "solarlab.device-preparation.v1", + "id": f"r1_heterojunction_nuI_{nu_I}", + "name": "R1 1D absorber/ETL heterojunction", + "source_format": "canonical", + "settings": { + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": True, + "ion_steric_diffusion_only": True, + "T": 300.0, + "Phi": 2.0e21, + }, + "layers": [ + { + "id": "absorber", + "name": "absorber", + "role": "absorber", + "thickness": 3.0e-7, + "parameters": { + "chi": 3.9, + "Eg": 1.6, + "Nc300": 1.0e25, + "Nv300": 1.0e25, + "eps_r": 24.0, + "N_D": 0.0, + "N_A": 1.0e22, + "ni": 363572901223.5858, + "n1": 363572901223.5858, + "p1": 363572901223.5858, + "mu_n": 2.0e-4, + "mu_p": 2.0e-4, + "alpha": 2.0e6, + "P0": ion_reference_m3, + "P_lim": ion_limit_m3, + "D_ion": effective_d_ion, + "E_a_ion": 0.0, + }, + }, + { + "id": "etl", + "name": "ETL", + "role": "ETL", + "thickness": 8.0e-8, + "parameters": { + "chi": 4.0, + "Eg": 2.0, + "Nc300": 4.0e25, + "Nv300": 2.0e25, + "eps_r": 9.0, + "N_D": 2.0e23, + "N_A": 0.0, + "ni": 449039324.31171566, + "n1": 449039324.31171566, + "p1": 449039324.31171566, + "mu_n": 5.0e-5, + "mu_p": 5.0e-5, + "alpha": 0.0, + "P0": 0.0, + "D_ion": 0.0, + }, + }, + ], + "electrical_grid": [ + {"layer": "absorber", "interval_weight": 12.0, "alpha": 2.5}, + {"layer": "etl", "interval_weight": 8.0, "alpha": 2.5}, + ], + } + raw_bytes = json.dumps( + {"default_catalog": catalog_doc, "device": device_doc}, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + source = SourceDocument(f"solarlab_research:r1_control_nuI_{nu_I}", raw_bytes) + catalog_with_evidence = {**catalog_doc, "evidence": [[source.id, source.sha256]]} + return resolve_device( + DeviceInput.model_validate(device_doc), + DefaultCatalog.from_mapping(catalog_with_evidence), + ResourceLibrary(), + sources=(source,), + ) + + +@dataclass(frozen=True, slots=True) +class R1ZeroMinusAnchor: + """Common dark equilibrium 0- anchor state shared across controls A-D.""" + + mobile_device: CompiledIonicDevice1D + immobile_device: CompiledIonicDevice1D + mobile_state: IonicState1D + immobile_state: IonicState1D + interface_node: int + equilibrium_trap_occupancy: float + trap_density_m2: float + capture_n_m_s: float + capture_p_m_s: float + n1_trap_m3: float + p1_trap_m3: float + + +def prepare_r1_zero_minus_anchor( + *, + intervals_per_layer: tuple[int, int] = (6, 4), + trap_density_m2: float = 2.0e15, + capture_n_m_s: float = 5.0e-14, + capture_p_m_s: float = 5.0e-14, + equilibrium_occupancy_target: float = 0.35, +) -> R1ZeroMinusAnchor: + """Solve the common dark 0- ionic steady state and replicate it onto immobile nu_I=0. + + Note: ``capture_n_m_s`` / ``capture_p_m_s`` are 3D SRH capture rate constants + ``sigma * v_th`` [m^3/s] such that ``N_t * c_n = 100 m/s`` at ``N_t = 2e15 m^-2``. + """ + prep_mobile = default_r1_prepared_device(nu_I=1) + prep_immobile = default_r1_prepared_device(nu_I=0) + + dev_mobile = compile_ionic_device_1d( + prep_mobile, + intervals_per_layer=intervals_per_layer, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + steady_opts = IonicSteadyOptions( + electronic=SteadyOptions( + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=1.0e-9, + current_spread_tolerance_A_m2=1.0e-9, + ), + inventory_relative_tolerance=1.0e-12, + ion_balance_tolerance_m2_s=1.0e6, + ion_flux_tolerance_m2_s=1.0e6, + ion_logit_step=1.0, + inventory_row_node=0, + budget=SolveBudget(100, 5000, 1000, 40), + wall_s=30.0, + ) + res_mobile = solve_ionic_steady_state( + dev_mobile, + voltage_V=0.0, + generation_scale=0.0, + options=steady_opts, + ) + if not res_mobile.accepted or res_mobile.state is None: + raise RuntimeError(f"R1 0- mobile steady state failed: {res_mobile.termination} ({res_mobile.error})") + + dev_immobile = compile_ionic_device_1d( + prep_immobile, + intervals_per_layer=intervals_per_layer, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + # Replicate the exact 0- physical state vector onto the nu_I=0 device (no re-solve drift). + immobile_state = dev_immobile.state(res_mobile.state.u, voltage_V=0.0) + + if_node = int(dev_mobile.ion_node_indices[-1]) + n0 = float(res_mobile.state.electronic_state.electron_density_m3[if_node]) + p0 = float(res_mobile.state.electronic_state.hole_density_m3[if_node]) + if not 0.0 < equilibrium_occupancy_target < 1.0: + raise ValueError("equilibrium_occupancy_target must lie strictly in (0, 1)") + f_t0 = float(equilibrium_occupancy_target) + # Place the interface trap level near the dark equilibrium Fermi level at if_node + # with exact SRH detailed balance (n1_t * p1_t == n0 * p0 and rn_0 == rp_0 == 0). + n1_t = n0 * (1.0 - f_t0) / f_t0 + p1_t = p0 * f_t0 / (1.0 - f_t0) + + return R1ZeroMinusAnchor( + mobile_device=dev_mobile, + immobile_device=dev_immobile, + mobile_state=res_mobile.state, + immobile_state=immobile_state, + interface_node=if_node, + equilibrium_trap_occupancy=f_t0, + trap_density_m2=trap_density_m2, + capture_n_m_s=capture_n_m_s, + capture_p_m_s=capture_p_m_s, + n1_trap_m3=n1_t, + p1_trap_m3=p1_t, + ) + + +@dataclass(frozen=True, slots=True) +class R1ControlAudit: + """Single-control verification evidence for 0- replication and suppressed channels.""" + + control: str + nu_I: int + nu_t: int + zero_minus_replicated: bool + max_ion_flux_m2_s: float + max_ion_rate_m2_s: float + ion_inventory_relative_drift: float + trap_occupancy_rate_s: float + sheet_charge_C_m2: float + passed: bool + + +@dataclass(frozen=True, slots=True) +class R1ControlSuiteReport: + """Combined verification report across controls A, B, C, and D.""" + + passed: bool + zero_minus_potential_sha256: str + zero_minus_ion_density_sha256: str + controls: Mapping[str, R1ControlAudit] + + +def verify_r1_controls_abcd( + *, + intervals_per_layer: tuple[int, int] = (6, 4), + dt_s: float = 1.0e-4, + voltage_step_V: float = 5.0e-3, +) -> R1ControlSuiteReport: + """Run one coupled Backward-Euler step under controls A, B, C, and D from a common 0- anchor.""" + from solarlab_research.r1.short_window import solve_coupled_r1_step + + anchor = prepare_r1_zero_minus_anchor(intervals_per_layer=intervals_per_layer) + ref_phi = anchor.mobile_state.electronic_state.potential_V + ref_ion = anchor.mobile_state.positive_ion_density_m3 + import hashlib + + phi_sha = hashlib.sha256(np.ascontiguousarray(ref_phi, dtype=" 0.0 and max_ion_rate > 0.0) + trap_ok = (trap_rate == 0.0 and sheet_q == 0.0) if nu_t == 0 else (trap_rate > 0.0 and abs(sheet_q) > 0.0) + ok = bool(replicated and step_res.accepted and ion_ok and trap_ok and inv_drift <= 1.0e-12) + audits[ctrl] = R1ControlAudit( + control=ctrl, + nu_I=nu_i, + nu_t=nu_t, + zero_minus_replicated=replicated, + max_ion_flux_m2_s=max_ion_flux, + max_ion_rate_m2_s=max_ion_rate, + ion_inventory_relative_drift=inv_drift, + trap_occupancy_rate_s=trap_rate, + sheet_charge_C_m2=sheet_q, + passed=ok, + ) + + all_passed = all(a.passed for a in audits.values()) + return R1ControlSuiteReport( + passed=all_passed, + zero_minus_potential_sha256=phi_sha, + zero_minus_ion_density_sha256=ion_sha, + controls=MappingProxyType(audits), + ) diff --git a/src/solarlab_research/r1/provenance.py b/src/solarlab_research/r1/provenance.py new file mode 100644 index 00000000..05e64739 --- /dev/null +++ b/src/solarlab_research/r1/provenance.py @@ -0,0 +1,347 @@ +"""Release-source provenance validator and non-relabeling historical R1 readers (P07-01/P03-05). + +* Binds new ``solarlab_research`` runs to immutable ``ReleaseBundle`` build-commit + and file-digest identities without inferring from mutable working trees. +* Reads historical R1 artifacts (``R1CommonStateV1``, ``R1CommonStatePairV2``, + ``SolarLabR1FailureFixtureV1``) strictly against their original recorded source + commits and digests without relabeling them to current sources or clearing + historical failure verdicts (e.g., V53 step 309). +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +from types import MappingProxyType +from typing import Any, Mapping + +import numpy as np +from numpy.typing import NDArray + +from solarlab.config.identity import BuildSource +from solarlab.materials.source import SourceDocument +from solarlab.reproducibility.release import ( + ReleaseBundle, + ReleaseFile, + read_release_bundle, + verify_release_installation, +) + +from solarlab_research.precision.codecs import decode_historical_r1_pair_state +from solarlab_research.r1.contracts import R1_OPERATOR_CHANNELS, R1_V53_CERTIFICATE_LIMITS + +__all__ = [ + "HistoricalR1ArtifactSummary", + "HistoricalR1WitnessAudit", + "R1ReleaseSourceBinding", + "load_verified_release_bundle", + "read_historical_r1_artifact", + "synthetic_research_release_bundle", + "verify_historical_r1_failure_witness", + "verify_r1_release_source", +] + + +@dataclass(frozen=True, slots=True) +class R1ReleaseSourceBinding: + """Verified binding of a research run to an immutable ReleaseBundle.""" + + build_source_commit: str + profile: str + bundle_sha256: str + build_source: BuildSource + job_provenance_envelope: Mapping[str, Any] + scientific_qualification: bool + + +def verify_r1_release_source( + bundle: ReleaseBundle, + *, + expected_bundle_sha256: str, + inputs: dict[str, Any], + operator: str = "solarlab_research", + installation_root: Path | None = None, + module_origins: tuple[tuple[str, str], ...] | None = None, + required_modules: tuple[str, ...] = ("solarlab", "solarlab_research"), +) -> R1ReleaseSourceBinding: + """Verify a ReleaseBundle digest and issue a source-attested provenance envelope.""" + if not isinstance(bundle, ReleaseBundle): + raise TypeError("bundle must be a ReleaseBundle") + if bundle.sha256 != expected_bundle_sha256: + raise ValueError( + f"ReleaseBundle sha256 {bundle.sha256} differs from expected {expected_bundle_sha256}" + ) + exported = bundle.export() + if exported.get("scientific_qualification") is not False: + raise ValueError("ReleaseBundle provenance must keep scientific_qualification=False") + + if installation_root is not None: + if module_origins is None: + raise ValueError("module_origins is required when verifying an installation_root") + verify_release_installation( + bundle, + installation_root, + expected_sha256=expected_bundle_sha256, + module_origins=module_origins, + required_modules=required_modules, + ) + elif bundle.can_execute: + raise ValueError("ReleaseBundle cannot self-authorize execution") + + provenance = bundle.job_provenance(inputs, operator=operator) + return R1ReleaseSourceBinding( + build_source_commit=bundle.build_source_commit, + profile=bundle.profile, + bundle_sha256=bundle.sha256, + build_source=bundle.implementation(), + job_provenance_envelope=MappingProxyType(provenance.envelope()), + scientific_qualification=False, + ) + + +def load_verified_release_bundle( + bundle_dir: Path, + *, + expected_bundle_sha256: str, +) -> ReleaseBundle: + """Load and cryptographically verify a materialized ReleaseBundle directory.""" + manifest_path = bundle_dir / "ReleaseBundle.json" + manifest = SourceDocument("ReleaseBundle.json", manifest_path.read_bytes()) + return read_release_bundle(manifest, bundle_dir, expected_sha256=expected_bundle_sha256) + + +def synthetic_research_release_bundle( + *, + build_source_commit: str = "19c19776ff0b13beb791683697035594718ff317", +) -> ReleaseBundle: + """Construct a minimal self-contained target-profile ReleaseBundle for standalone/CLI checks.""" + files = ( + ReleaseFile("src/solarlab/__init__.py", "site/solarlab/__init__.py", "package", b"\"\"\"solarlab.\"\"\"\n"), + ReleaseFile("src/solarlab/py.typed", "site/solarlab/py.typed", "package", b""), + ReleaseFile( + "src/solarlab_research/__init__.py", + "site/solarlab_research/__init__.py", + "package", + b"\"\"\"solarlab_research.\"\"\"\n", + ), + ReleaseFile("src/solarlab_research/py.typed", "site/solarlab_research/py.typed", "package", b""), + ReleaseFile( + "src/solarlab_server/__init__.py", + "site/solarlab_server/__init__.py", + "package", + b"\"\"\"solarlab_server.\"\"\"\n", + ), + ReleaseFile("src/solarlab_server/py.typed", "site/solarlab_server/py.typed", "package", b""), + ReleaseFile( + "src/solarlab/config/identity.py", + "site/solarlab/config/identity.py", + "validator", + b"\"\"\"validator.\"\"\"\n", + ), + ReleaseFile( + "src/solarlab/reproducibility/PublicAPI.json", + "site/solarlab/reproducibility/PublicAPI.json", + "contract", + b"{}\n", + ), + ReleaseFile("resources/am15g.csv", "share/resources/am15g.csv", "resource", b"wl,flux\n500,1.0\n"), + ReleaseFile("uv.lock", "share/uv.lock", "dependency_lock", b"version = 1\n"), + ReleaseFile("pyproject.toml", "share/pyproject.toml", "build_configuration", b"[project]\nname = 'solarlab'\n"), + ReleaseFile( + "generated/configuration-schema.json", + "share/generated/configuration-schema.json", + "generated_schema", + b"{\"schema\":\"v1\"}\n", + ), + ) + return ReleaseBundle(build_source_commit=build_source_commit, profile="target", files=files) + + +@dataclass(frozen=True, slots=True) +class HistoricalR1ArtifactSummary: + """Read-only summary of a historical R1 artifact verified against its original source.""" + + schema: str + artifact_sha256: str + original_source_id: str | None + original_source_sha256: str | None + relabelled: bool + metadata: Mapping[str, Any] + + +def read_historical_r1_artifact(source: Path | bytes | str) -> HistoricalR1ArtifactSummary: + """Read a historical R1 state/witness artifact without relabeling its source identity.""" + if isinstance(source, Path): + raw_bytes = source.read_bytes() + elif isinstance(source, bytes): + raw_bytes = source + elif isinstance(source, str): + raw_bytes = source.encode("utf-8") + else: + raise TypeError("source must be Path, bytes, or str") + + artifact_sha = hashlib.sha256(raw_bytes).hexdigest() + payload = json.loads(raw_bytes.decode("utf-8")) + if not isinstance(payload, dict): + raise ValueError("historical R1 artifact root must be a JSON object") + + schema = str(payload.get("schema", "")) + if schema == "R1CommonStatePairV2": + decoded = decode_historical_r1_pair_state(payload) + seed = payload["seed_preparation"] + src_info = payload.get("source", {}) + return HistoricalR1ArtifactSummary( + schema=schema, + artifact_sha256=artifact_sha, + original_source_id=src_info.get("source_commit") or str(src_info.get("run_class", "legacy")), + original_source_sha256=str(src_info.get("sha256", payload["sha256"])), + relabelled=False, + metadata=MappingProxyType({ + "representation": payload["representation"], + "record_sha256": payload["sha256"], + "seed_preparation_sha256": payload["seed_preparation_sha256"], + "dc_state_sha256": seed["dc_state"]["state_sha256"], + "decoded_field_count": len(decoded), + }), + ) + + if schema == "R1CommonStateV1": + unsigned = {k: v for k, v in payload.items() if k != "sha256"} + canonical = json.dumps(unsigned, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") + computed_sha = hashlib.sha256(canonical).hexdigest() + recorded_sha = str(payload["sha256"]) + if computed_sha != recorded_sha: + raise ValueError( + f"R1CommonStateV1 sha256 mismatch: expected {recorded_sha}, got {computed_sha}" + ) + src_info = payload.get("source", {}) + dc_state = payload.get("dc_state", {}) + arr: NDArray[np.float64] = np.asarray(dc_state.get("potential_V", ()), dtype=float) + return HistoricalR1ArtifactSummary( + schema=schema, + artifact_sha256=artifact_sha, + original_source_id=src_info.get("source_commit") or str(src_info.get("run_class", "legacy")), + original_source_sha256=str(src_info.get("sha256", recorded_sha)), + relabelled=False, + metadata=MappingProxyType({ + "record_sha256": recorded_sha, + "dc_state_sha256": dc_state.get("state_sha256"), + "intervals": int(payload["intervals"]), + "temperature_K": float(payload["history"]["temperature_K"]), + "node_count": int(arr.size), + }), + ) + + if schema == "SolarLabR1FailureFixtureV1": + audit = verify_historical_r1_failure_witness(raw_bytes) + return HistoricalR1ArtifactSummary( + schema=schema, + artifact_sha256=artifact_sha, + original_source_id=audit.source_commit, + original_source_sha256=audit.source_content_sha256, + relabelled=False, + metadata=MappingProxyType({ + "source_commit": audit.source_commit, + "case_names": audit.case_names, + "step309_status": audit.step309_original_status, + "step309_nonlinear_residual": audit.step309_nonlinear_residual, + }), + ) + + raise ValueError(f"unsupported historical R1 artifact schema: {schema!r}") + + +@dataclass(frozen=True, slots=True) +class HistoricalR1WitnessAudit: + """Verified historical V53 witness record preserving original failure status.""" + + fixture_sha256: str + source_commit: str + source_content_sha256: str + source_fixture_yaml: str + case_names: tuple[str, ...] + step183_accepted_status: str + step183_failed_status: str + step309_original_status: str + step309_failure_type: str + step309_nonlinear_residual: float + step309_dt_s: float + step309_voltage_V: float + relabelled: bool + + +def verify_historical_r1_failure_witness( + source: Path | bytes | str, +) -> HistoricalR1WitnessAudit: + """Verify ``R1FailureWitnessV1.json`` against its original V53 commit and failure status.""" + raw = source.read_bytes() if isinstance(source, Path) else ( + source if isinstance(source, bytes) else source.encode("utf-8") + ) + fixture_sha = hashlib.sha256(raw).hexdigest() + payload = json.loads(raw.decode("utf-8")) + if payload.get("schema") != "SolarLabR1FailureFixtureV1": + raise ValueError(f"expected SolarLabR1FailureFixtureV1, got {payload.get('schema')!r}") + + commit = str(payload["source_commit"]) + content_sha = str(payload["source_content_sha256"]) + if len(commit) != 40 or len(content_sha) != 64: + raise ValueError("witness lacks valid original source_commit / source_content_sha256") + + req_info = payload.get("request", {}) + limits = req_info.get("certificate_limits", payload.get("certificate_limits", {})) + if limits != dict(R1_V53_CERTIFICATE_LIMITS): + raise ValueError("witness certificate_limits differ from frozen V53 limits") + channels = tuple(payload.get("operator_channels", ())) + if channels != R1_OPERATOR_CHANNELS: + raise ValueError("witness operator_channels differ from frozen 13-channel contract") + + cases = payload.get("cases", {}) + required_cases = ("step183_accepted", "step183_failed", "step309_failed") + if not all(name in cases for name in required_cases): + raise ValueError(f"witness missing required cases {required_cases}") + + c183_ok = cases["step183_accepted"] + c183_fail = cases["step183_failed"] + c309 = cases["step309_failed"] + orig_fail = c309.get("original_failure") + if not isinstance(orig_fail, dict): + raise ValueError("step309_failed must retain its original_failure record") + + fail_type = str(orig_fail.get("type", "")) + msg = str(orig_fail.get("message", "")) + if fail_type != "InterfaceDefectTransientError": + raise ValueError(f"unexpected step309 failure type: {fail_type!r}") + # Extract historical nonlinear residual (0.0532305 > 0.05) and preserve failed status. + residual_val: float | None = None + if "nonlinear_residual" in c309: + residual_val = float(c309["nonlinear_residual"]) + elif "residual" in msg: + tokens = msg.replace(",", " ").replace(";", " ").split() + for idx, tok in enumerate(tokens[:-1]): + if tok == "residual": + try: + residual_val = float(tokens[idx + 1]) + break + except ValueError: + continue + if residual_val is None or residual_val <= R1_V53_CERTIFICATE_LIMITS["nonlinear_residual"]: + raise ValueError("historical step309 witness residual cannot be relabeled as passing") + + saved_309 = c309.get("saved_witness", c309) + return HistoricalR1WitnessAudit( + fixture_sha256=fixture_sha, + source_commit=commit, + source_content_sha256=content_sha, + source_fixture_yaml=str(payload["source_fixture_yaml"]), + case_names=tuple(sorted(cases)), + step183_accepted_status="accepted" if c183_ok.get("original_failure") is None else "failed", + step183_failed_status="failed" if c183_fail.get("original_failure") is not None else "accepted", + step309_original_status="failed", + step309_failure_type=fail_type, + step309_nonlinear_residual=residual_val, + step309_dt_s=float(saved_309["dt_s"]), + step309_voltage_V=float(saved_309["voltage_V"]), + relabelled=False, + ) diff --git a/src/solarlab_research/r1/short_window.py b/src/solarlab_research/r1/short_window.py new file mode 100644 index 00000000..c4951c46 --- /dev/null +++ b/src/solarlab_research/r1/short_window.py @@ -0,0 +1,1083 @@ +"""Conservative 4/8/16 short-window coupled R1 driver, 183/309 witness harness, and replay receipt (P07-02). + +Executes coupled 1D two-sided interface + blocking finite-site positive-ion + +dynamic interface-trap Backward-Euler steps over public ``solarlab`` interfaces +and ``solarlab_research.precision`` (``DD``, ``ReferenceIncrementCoordinates``, +``AffineInputLiftCodec``, ``freeze_coefficients``, ``evaluate_local_carrier_pair``): +* Conservative ``(4, 8, 16)`` substep pairing in ``baseline`` (``float64``) and + ``compensated`` (``float64-pair-v1`` ``DD``) modes without trajectory interpolation. +* Full 16-item V53 certificate evaluation, 13-channel operator observation packet, + sub-ULP compensated precision check, and deterministic ``R1ReplayReceipt``. +* Minimal ``183/309`` public-interface witness evaluation preserving historical + step ``309`` failed status without relabeling. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import math +from pathlib import Path +from types import MappingProxyType +from typing import Literal + +import numpy as np +from numpy.typing import NDArray +from scipy.sparse import csc_matrix, lil_matrix +from scipy.special import expit + +from solarlab.config.yaml import load_yaml_mapping +from solarlab.contracts import ELEMENTARY_CHARGE_C, EquationSpec, Layout, ONE, Support, VariableSpec +from solarlab.device.compile_ionic_1d import CompiledIonicDevice1D +from solarlab.equations.ionic_1d import Ionic1DProblem, IonicState1D +from solarlab.reproducibility.release import ReleaseBundle +from solarlab.solvers.nonlinear.newton import NewtonSettings, solve_newton +from solarlab.solvers.nonlinear.problem import ( + CallableProblem, + ResidualScaling, + SolveBudget, + StepControl, + state_digest, +) +from solarlab.solvers.nonlinear.production import ( + POISSON_CONTACT_BALANCE_V1, + production_convergence_norm, + production_coordinates, + production_residual_scaling, +) +from solarlab.solvers.time.ionic_backward_euler import ( + IonicBackwardEuler1DStep, + step_accounting, +) + +from solarlab_research.precision.codecs import ( + AffineInputLiftCodec, + ReferenceIncrementCoordinates, +) +from solarlab_research.precision.double_double import DD, expm1 as dd_expm1 +from solarlab_research.precision.two_sided_interface import ( + FrozenLocalCoefficients, + evaluate_local_carrier_pair, + freeze_coefficients, + to_float_tangent, +) +from solarlab_research.r1.contracts import ( + R1_CONSERVATIVE_SUBSTEPS, + R1_CONTROLS, + R1_V53_CERTIFICATE_LIMITS, + R1CertificateEvaluation, + R1QualificationAssessment, + R1StudyRequest, + assess_r1_qualification, + build_r1_study_request, + evaluate_v53_certificate, + expected_substep_rows, + validate_operator_channel_packet, +) +from solarlab_research.r1.controls import R1ZeroMinusAnchor, prepare_r1_zero_minus_anchor +from solarlab_research.r1.provenance import ( + HistoricalR1WitnessAudit, + verify_historical_r1_failure_witness, + verify_r1_release_source, +) + +__all__ = [ + "R1CoupledStepResult", + "R1ModeWindowRun", + "R1ReplayReceipt", + "R1ShortWindowPairingResult", + "R1WitnessMinimalEvaluation", + "evaluate_r1_witness_minimal_input", + "evaluate_sub_ulp_storage_precision", + "run_r1_short_window_pairing", + "solve_coupled_r1_step", +] + +Q = ELEMENTARY_CHARGE_C + + +def _logit_from_occupancy(f: float) -> float: + if not 0.0 < f < 1.0: + raise ValueError(f"trap occupancy must lie strictly in (0, 1); got {f}") + return math.log(f) - math.log1p(-f) + + +def _compensated_logistic_diff(old_logit: float, new_logit: float) -> DD: + """Evaluate ``expit(new_logit) - expit(old_logit)`` in DD without cancellation.""" + delta = DD(new_logit) - DD(old_logit) + old_f = float(expit(old_logit)) + new_f = float(expit(new_logit)) + if float(delta) >= 0.0: + neg_expm1 = -(dd_expm1(-delta)) + return DD(new_f) * DD(float(expit(-old_logit))) * neg_expm1 + return DD(old_f) * DD(float(expit(-new_logit))) * dd_expm1(delta) + + +@dataclass(frozen=True, slots=True) +class R1CoupledStepResult: + """Single accepted coupled 1D electronic + confined-ion + dynamic-trap BE step.""" + + accepted: bool + ionic_state: IonicState1D + trap_occupancy: float + trap_logit: float + sheet_charge_C_m2: float + capture_flux_m2_s: float + electron_current_A_m2: NDArray[np.float64] + hole_current_A_m2: NDArray[np.float64] + total_current_A_m2: NDArray[np.float64] + electron_rate_m2_s: NDArray[np.float64] + hole_rate_m2_s: NDArray[np.float64] + ion_flux_m2_s: NDArray[np.float64] + ion_rate_m2_s: NDArray[np.float64] + trace_potential_V: float + scaled_nonlinear_residual: float + newton_iterations: int + analytic_jacobian_error: float + local_carrier_residual: float + eliminated_operator_error: float + local_gauss_residual: float + full_gauss_normalized: float + full_charge_balance_normalized: float + charge_balance_relative: float + current_decomposition_error: float + trap_storage_normalized_error: float + state_sha256: str + + +def _build_frozen_coefficients( + device: CompiledIonicDevice1D, + anchor: R1ZeroMinusAnchor, +) -> FrozenLocalCoefficients: + elec_comp = device.electronic_component + if_node = anchor.interface_node + l_idx, r_idx = if_node - 1, if_node + 1 + dx_l = float(device.nodes_m[if_node] - device.nodes_m[l_idx]) + dx_r = float(device.nodes_m[r_idx] - device.nodes_m[if_node]) + vt = elec_comp.thermal_voltage_V + bands = elec_comp.parameters.band_structure + return freeze_coefficients( + { + "left_distance_m": dx_l, + "right_distance_m": dx_r, + }, + { + "temperature_K": float(elec_comp.parameters.temperature_K), + "thermal_voltage_V": float(vt), + "transmission": 1.0, + "D_n_left_m2_s": float(elec_comp.electron_diffusivity_faces_m2_s[if_node - 1]), + "D_p_left_m2_s": float(elec_comp.hole_diffusivity_faces_m2_s[if_node - 1]), + "D_n_right_m2_s": float(elec_comp.electron_diffusivity_faces_m2_s[if_node]), + "D_p_right_m2_s": float(elec_comp.hole_diffusivity_faces_m2_s[if_node]), + "N_C_left_m3": float(elec_comp.parameters.conduction_dos_m3[l_idx]), + "N_V_left_m3": float(elec_comp.parameters.valence_dos_m3[l_idx]), + "N_C_right_m3": float(elec_comp.parameters.conduction_dos_m3[r_idx]), + "N_V_right_m3": float(elec_comp.parameters.valence_dos_m3[r_idx]), + "n1_left_m3": float(anchor.n1_trap_m3), + "p1_left_m3": float(anchor.p1_trap_m3), + "n1_right_m3": float(anchor.n1_trap_m3), + "p1_right_m3": float(anchor.p1_trap_m3), + "richardson_n_A_m2_K2": 1.2e6, + "richardson_p_A_m2_K2": 1.2e6, + "surface_recombination_velocity_n_m_s": float(anchor.trap_density_m2 * anchor.capture_n_m_s), + "surface_recombination_velocity_p_m_s": float(anchor.trap_density_m2 * anchor.capture_p_m_s), + "conduction_band_step_eV": float( + bands.physical_electron_affinity_eV[l_idx] + - bands.physical_electron_affinity_eV[r_idx] + ), + "hole_transport_step_eV": float( + (bands.physical_electron_affinity_eV[r_idx] + bands.physical_band_gap_eV[r_idx]) + - (bands.physical_electron_affinity_eV[l_idx] + bands.physical_band_gap_eV[l_idx]) + ), + }, + ) + + +def solve_coupled_r1_step( + *, + device: CompiledIonicDevice1D, + previous_ionic: IonicState1D, + previous_trap_occupancy: float, + anchor: R1ZeroMinusAnchor, + voltage_V: float, + dt_s: float, + nu_t: int = 1, + mode: Literal["baseline", "compensated"] = "compensated", + generation_scale: float = 0.0, + light_turn_on: bool = False, + frozen_coefficients: FrozenLocalCoefficients | None = None, + verify_codec: bool = True, + audit_operators: bool = True, +) -> R1CoupledStepResult: + """Solve one conservative Backward-Euler step of the coupled R1 1D system.""" + if nu_t not in (0, 1): + raise ValueError("nu_t must be 0 or 1") + if mode not in ("baseline", "compensated"): + raise ValueError("mode must be 'baseline' or 'compensated'") + + n_nodes = device.node_count + state_n = device.state_size + if_node = anchor.interface_node + vt = device.electronic_component.thermal_voltage_V + old_logit = _logit_from_occupancy(previous_trap_occupancy) + f0 = anchor.equilibrium_trap_occupancy + nt = anchor.trap_density_m2 + cn = anchor.capture_n_m_s + cp = anchor.capture_p_m_s + n1_t = anchor.n1_trap_m3 + p1_t = anchor.p1_trap_m3 + + endpoint = Ionic1DProblem(device, voltage_V=voltage_V, generation_scale=generation_scale) + base_step = IonicBackwardEuler1DStep(endpoint, previous_ionic, dt_s) + predictor = "generation_inventory" if (light_turn_on and generation_scale > 0.0) else "previous" + y0 = base_step.initial_coordinates(predictor, voltage_lift=True) + + # Coordinate codec & authority in compensated mode + if verify_codec: + coupled_layout = Layout( + supports=(Support("coupled_1d", "cell", (state_n + 1,)),), + variables=(VariableSpec("z", "r1_coupled_1d", "coupled_1d", (state_n + 1,), ONE),), + equations=(EquationSpec("r", "r1_coupled_1d", "coupled_1d", (state_n + 1,), ONE, derivative_support=("z",)),), + ) + ref_coords = ReferenceIncrementCoordinates.from_float_anchor( + coupled_layout, + {"z": np.r_[y0, old_logit]}, + ) + codec = AffineInputLiftCodec() + _ = codec.encode_point(ref_coords.point(np.zeros(state_n + 1, dtype=float))) + + def trap_terms( + n_if: float, + p_if: float, + logit_f: float, + ) -> tuple[float, float, float, float, float]: + if nu_t == 0: + return previous_trap_occupancy, 0.0, 0.0, 0.0, 0.0 + f_val = float(expit(logit_f)) + rn_cap = nt * cn * (n_if * (1.0 - f_val) - n1_t * f_val) + rp_cap = nt * cp * (p_if * f_val - p1_t * (1.0 - f_val)) + sigma = -Q * nt * (f_val - f0) + if mode == "compensated": + df = float(_compensated_logistic_diff(old_logit, logit_f)) + else: + df = f_val - previous_trap_occupancy + storage_rate = nt * df / dt_s + trap_res = storage_rate - (rn_cap - rp_cap) + return f_val, rn_cap, rp_cap, sigma, trap_res + + def residual(z: NDArray[np.float64]) -> NDArray[np.float64]: + y = z[:state_n] + logit_f = float(z[state_n]) + res: NDArray[np.float64] = np.empty(state_n + 1, dtype=float) + try: + res[:state_n] = base_step.residual(y) + _, n_arr, p_arr, _ = device.fields_by_species(y, voltage_V=voltage_V) + except (ValueError, FloatingPointError): + return np.full(state_n + 1, np.nan) + n_if = float(n_arr[if_node]) + p_if = float(p_arr[if_node]) + if nu_t == 0: + res[state_n] = logit_f - old_logit + return res + _, rn_cap, rp_cap, sigma, trap_res = trap_terms(n_if, p_if, logit_f) + res[if_node] += sigma + res[n_nodes + if_node] -= rn_cap + res[2 * n_nodes + if_node] -= rp_cap + res[state_n] = trap_res + return res + + def jacobian(z: NDArray[np.float64]) -> csc_matrix: + y = z[:state_n] + logit_f = float(z[state_n]) + j_base = base_step.jacobian(y) + mat = lil_matrix((state_n + 1, state_n + 1), dtype=float) + mat[:state_n, :state_n] = j_base + if nu_t == 0: + mat[state_n, state_n] = 1.0 + return mat.tocsc() + + _, n_arr, p_arr, _ = device.fields_by_species(y, voltage_V=voltage_V) + n_if = float(n_arr[if_node]) + p_if = float(p_arr[if_node]) + f_val = float(expit(logit_f)) + df_dl = float(expit(logit_f) * expit(-logit_f)) + + dn_dphi = n_if / vt + dn_dzn = n_if + dp_dphi = -p_if / vt + dp_dzp = -p_if + + drn_dn = nt * cn * (1.0 - f_val) + drn_df = -nt * cn * (n_if + n1_t) + drp_dp = nt * cp * f_val + drp_df = nt * cp * (p_if + p1_t) + + # Gauss row at if_node: +sigma where sigma = -Q * nt * (f - f0) + mat[if_node, state_n] += -Q * nt * df_dl + + # Electron row at n_nodes + if_node: -rn_cap + e_row = n_nodes + if_node + mat[e_row, if_node] -= drn_dn * dn_dphi + mat[e_row, n_nodes + if_node] -= drn_dn * dn_dzn + mat[e_row, state_n] -= drn_df * df_dl + + # Hole row at 2*n_nodes + if_node: -rp_cap + h_row = 2 * n_nodes + if_node + mat[h_row, if_node] -= drp_dp * dp_dphi + mat[h_row, 2 * n_nodes + if_node] -= drp_dp * dp_dzp + mat[h_row, state_n] -= drp_df * df_dl + + # Trap row at state_n: nt*(f - f_old)/dt - (rn_cap - rp_cap) + mat[state_n, if_node] += -drn_dn * dn_dphi + drp_dp * dp_dphi + mat[state_n, n_nodes + if_node] += -drn_dn * dn_dzn + mat[state_n, 2 * n_nodes + if_node] += drp_dp * dp_dzp + mat[state_n, state_n] += (nt / dt_s - drn_df + drp_df) * df_dl + return mat.tocsc() + + elec_comp = device.electronic_component + continuity_tol_A_m2 = 5.0e-8 + ion_tol_m2_s = max(1.0e8, 5.0e-7 / Q) + trap_tol_A_m2 = 5.0e-8 + + base_weights = production_residual_scaling( + elec_comp, + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=continuity_tol_A_m2, + contact_log_tolerance=1.0e-11, + ).row_weights + ion_weights = np.full(device.ion_node_count, device.ion_node_count / ion_tol_m2_s) + trap_weight = 1.0 if nu_t == 0 else Q / trap_tol_A_m2 + weights = np.r_[base_weights, ion_weights, trap_weight] + + elec_norm = production_convergence_norm( + elec_comp, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + assert elec_norm is not None + + def coupled_convergence_norm(scaled: NDArray[np.float64]) -> float: + if scaled.shape != (state_n + 1,) or not np.all(np.isfinite(scaled)): + return math.inf + return max( + elec_norm(scaled[: 3 * n_nodes]), + float(np.sum(np.abs(scaled[3 * n_nodes : state_n]))) / device.ion_node_count, + abs(float(scaled[state_n])), + ) + + steps = np.r_[ + production_coordinates(elec_comp, potential_step_V=0.1, quasi_fermi_step=2.0).max_step, + np.full(device.ion_node_count, 1.0), + 2.0, + ] + settings = NewtonSettings( + ResidualScaling(weights), + 4.5e-2, + StepControl(steps), + SolveBudget(100, 5000, 1000, 40), + (), + False, + ) + z_init = np.r_[y0, old_logit] + newton_res = solve_newton( + CallableProblem(residual, jacobian), + z_init, + settings, + convergence_norm=coupled_convergence_norm, + ) + z_sol = newton_res.state + y_sol = z_sol[:state_n] + logit_sol = float(z_sol[state_n]) + f_sol = previous_trap_occupancy if nu_t == 0 else float(expit(logit_sol)) + new_ionic = device.state(y_sol, voltage_V=voltage_V) + + # Directional FD Jacobian check at accepted solution + if audit_operators: + rng = np.random.default_rng(183309) + direction = rng.uniform(-0.02, 0.02, state_n + 1) + direction[:n_nodes] *= vt + if nu_t == 0: + direction[state_n] = 0.0 + j_mat = jacobian(z_sol) + h_fd = 1.0e-6 + fd_vec = (residual(z_sol + h_fd * direction) - residual(z_sol - h_fd * direction)) / (2.0 * h_fd) + scale_vec = np.abs(j_mat) @ np.abs(direction) + jac_err = float( + np.max(np.abs(j_mat @ direction - fd_vec) / np.maximum(scale_vec, 1.0e-16)) + ) + else: + jac_err = 0.0 + + # Full interval accounting + modified Gauss/Maxwell displacement with sheet charge + info = step_accounting(base_step, y_sol) + carrier_particles = np.asarray(info["carrier_particle_fluxes_m2_s"], dtype=float) + carrier_rates = np.asarray(info["carrier_inventory_rate_m2_s"], dtype=float) + ion_rate = np.asarray(info["ion_inventory_rate_m2_s"], dtype=float) + ion_domain_flux = np.asarray(info["ion_domain_fluxes_m2_s"], dtype=float) + ion_particles = np.asarray(info["ion_particle_fluxes_m2_s"], dtype=float) + + n_if = float(new_ionic.electronic_state.electron_density_m3[if_node]) + p_if = float(new_ionic.electronic_state.hole_density_m3[if_node]) + _, rn_cap, rp_cap, sigma_new, trap_res_val = trap_terms(n_if, p_if, logit_sol) + sigma_old = 0.0 if nu_t == 0 else -Q * nt * (previous_trap_occupancy - f0) + dsigma_dt = 0.0 if nu_t == 0 else ( + float(-DD(Q * nt) * _compensated_logistic_diff(old_logit, logit_sol) / DD(dt_s)) + if mode == "compensated" + else (sigma_new - sigma_old) / dt_s + ) + + charge_rate = np.array(info["charge_inventory_rate_A_m2"], dtype=float, copy=True) + charge_rate[if_node] += dsigma_dt + + poisson = elec_comp.poisson + phi_delta = new_ionic.electronic_state.potential_V - previous_ionic.electronic_state.potential_V + interior_delta_d = -poisson.face_capacitance_F_m2 * np.diff(phi_delta) + interval_d = np.r_[ + interior_delta_d[0] - dt_s * charge_rate[0], + interior_delta_d, + interior_delta_d[-1] + dt_s * charge_rate[-1], + ] + disp_curr = interval_d / dt_s + e_curr = -Q * carrier_particles[0] + h_curr = Q * carrier_particles[1] + cond_curr = e_curr + h_curr + Q * ion_particles + tot_curr = cond_curr + disp_curr + + decomp_err = float(np.max(np.abs(tot_curr - (cond_curr + disp_curr)))) + stable_gauss_rate = (interval_d[:-1] - interval_d[1:]) / dt_s + charge_rate + curr_scale = max(1.0e-6, float(np.max(np.abs(tot_curr))), float(np.max(np.abs(charge_rate)))) + charge_bal_rel = float(np.max(np.abs(stable_gauss_rate - (tot_curr[:-1] - tot_curr[1:]))) / curr_scale) + + final_res = residual(z_sol) + gauss_weights = base_weights[:n_nodes] * 1.0e-11 + full_gauss_norm = float(np.max(np.abs(final_res[:n_nodes] * gauss_weights))) + local_gauss_res = float(abs(final_res[if_node] * gauss_weights[if_node])) + + e_rows = final_res[n_nodes : 2 * n_nodes].copy() + h_rows = final_res[2 * n_nodes : 3 * n_nodes].copy() + e_rows[[0, -1]] = 0.0 + h_rows[[0, -1]] = 0.0 + ion_rows = final_res[3 * n_nodes : state_n] + full_charge_norm = float( + (Q * (np.sum(np.abs(e_rows)) + np.sum(np.abs(h_rows)) + np.sum(np.abs(ion_rows)))) / curr_scale + ) + trap_norm_err = 0.0 if nu_t == 0 else abs(Q * trap_res_val) / curr_scale + + # Two-sided compensated local carrier pair evaluation & Schur-elimination check + phi_arr = new_ionic.electronic_state.potential_V + psi_trace = float(phi_arr[if_node]) + if audit_operators: + l_idx, r_idx = if_node - 1, if_node + 1 + n_arr = new_ionic.electronic_state.electron_density_m3 + p_arr = new_ionic.electronic_state.hole_density_m3 + frozen_c = ( + frozen_coefficients + if frozen_coefficients is not None + else _build_frozen_coefficients(device, anchor) + ) + + # Solve 4x4 local two-sided trace densities in DD (linear density predictor + damped log-Newton) + trace_pot_dd = DD(np.array([psi_trace, psi_trace], dtype=float)) + bulk_pot_dd = DD(np.array([float(phi_arr[l_idx]), float(phi_arr[r_idx])], dtype=float)) + bulk_dens_arr = np.array( + [ + float(n_arr[l_idx]), + float(p_arr[l_idx]), + float(n_arr[r_idx]), + float(p_arr[r_idx]), + ], + dtype=float, + ) + bulk_dens_dd = DD(bulk_dens_arr) + occ_dd = DD(f_sol) + dens_vec = np.maximum(bulk_dens_arr.copy(), 1.0e-30) + + # First step in density space solves the affine Boltzmann part directly without log-step overflow. + for it in range(6): + ev = evaluate_local_carrier_pair( + state_density=DD(dens_vec), + trace_potential=trace_pot_dd, + bulk_density=bulk_dens_dd, + bulk_potential=bulk_pot_dd, + occupancy=occ_dd, + capture_multiplier=nu_t, + coefficients=frozen_c, + ) + flt = to_float_tangent(ev) + if it == 0: + jac_dens = flt.balance.jacobian_log_state_m2_s / dens_vec[np.newaxis, :] + dn: NDArray[np.float64] = -np.linalg.solve(jac_dens, flt.balance.residual_m2_s) + dens_vec = np.maximum(1.0e-60, dens_vec + dn) + if float(np.max(np.abs(dn) / dens_vec)) < 1.0e-14: + break + else: + du: NDArray[np.float64] = -np.linalg.solve( + flt.balance.jacobian_log_state_m2_s, + flt.balance.residual_m2_s, + ) + du_clipped = np.clip(du, -4.0, 4.0) + dens_vec = np.maximum(1.0e-60, dens_vec * np.exp(du_clipped)) + if float(np.max(np.abs(du))) < 1.0e-14: + break + + u_vec = np.log(dens_vec) + ev_final = evaluate_local_carrier_pair( + state_density=DD(dens_vec), + trace_potential=trace_pot_dd, + bulk_density=bulk_dens_dd, + bulk_potential=bulk_pot_dd, + occupancy=occ_dd, + capture_multiplier=nu_t, + coefficients=frozen_c, + ) + flt_final = to_float_tangent(ev_final) + flux_scale = max( + 1.0, + float(np.max(np.abs(flt_final.balance.bulk_flux_m2_s))), + float(np.max(np.abs(flt_final.balance.one_way_cross_scale_m2_s))), + ) + local_carrier_res = float(np.max(np.abs(flt_final.balance.residual_m2_s))) / flux_scale + + # Schur-eliminated operator check wrt bulk coordinate col 2 (log n_left) + du_dlogn_l: NDArray[np.float64] = -np.linalg.solve( + flt_final.balance.jacobian_log_state_m2_s, + flt_final.balance.jacobian_bulk_coordinates[:, 2], + ) + dflux_dlogn_schur = float( + flt_final.bulk_flux_jacobian_bulk_coordinates[0, 2] + + flt_final.bulk_flux_jacobian_log_state_m2_s[0, :] @ du_dlogn_l + ) + eps_log = 1.0e-6 + pert_bulk_arr = bulk_dens_arr.copy() + pert_bulk_arr[0] *= math.exp(eps_log) + pert_bulk_dd = DD(pert_bulk_arr) + u_pert = u_vec + du_dlogn_l * eps_log + for _ in range(2): + ev_p = evaluate_local_carrier_pair( + state_density=DD(np.exp(u_pert)), + trace_potential=trace_pot_dd, + bulk_density=pert_bulk_dd, + bulk_potential=bulk_pot_dd, + occupancy=occ_dd, + capture_multiplier=nu_t, + coefficients=frozen_c, + ) + flt_p = to_float_tangent(ev_p) + step_u: NDArray[np.float64] = -np.linalg.solve( + flt_p.balance.jacobian_log_state_m2_s, + flt_p.balance.residual_m2_s, + ) + u_pert = u_pert + step_u + if float(np.max(np.abs(step_u))) < 1.0e-13: + break + ev_pert = evaluate_local_carrier_pair( + state_density=DD(np.exp(u_pert)), + trace_potential=trace_pot_dd, + bulk_density=pert_bulk_dd, + bulk_potential=bulk_pot_dd, + occupancy=occ_dd, + capture_multiplier=nu_t, + coefficients=frozen_c, + ) + flt_pert = to_float_tangent(ev_pert) + dflux_dlogn_fd = ( + float(flt_pert.balance.bulk_flux_m2_s[0]) - float(flt_final.balance.bulk_flux_m2_s[0]) + ) / eps_log + elim_err = abs(dflux_dlogn_schur - dflux_dlogn_fd) / max(abs(dflux_dlogn_fd), 1.0e-12) + else: + local_carrier_res = 0.0 + elim_err = 0.0 + + return R1CoupledStepResult( + accepted=bool(newton_res.accepted), + ionic_state=new_ionic, + trap_occupancy=f_sol, + trap_logit=logit_sol, + sheet_charge_C_m2=sigma_new, + capture_flux_m2_s=rn_cap - rp_cap, + electron_current_A_m2=e_curr, + hole_current_A_m2=h_curr, + total_current_A_m2=tot_curr, + electron_rate_m2_s=carrier_rates[0], + hole_rate_m2_s=carrier_rates[1], + ion_flux_m2_s=ion_domain_flux, + ion_rate_m2_s=ion_rate, + trace_potential_V=psi_trace, + scaled_nonlinear_residual=float(newton_res.scaled_residual), + newton_iterations=int(newton_res.iteration_count), + analytic_jacobian_error=jac_err, + local_carrier_residual=local_carrier_res, + eliminated_operator_error=elim_err, + local_gauss_residual=local_gauss_res, + full_gauss_normalized=full_gauss_norm, + full_charge_balance_normalized=full_charge_norm, + charge_balance_relative=charge_bal_rel, + current_decomposition_error=decomp_err, + trap_storage_normalized_error=trap_norm_err, + state_sha256=state_digest(z_sol), + ) + + +@dataclass(frozen=True, slots=True) +class R1ModeWindowRun: + """Single precision-mode conservative (4, 8, 16) short-window run and certificate.""" + + mode: str + accepted_rows: int + substep_row_counts: Mapping[int, int] + certificate: R1CertificateEvaluation + operator_channels: Mapping[str, NDArray[np.float64]] + channel_shapes: Mapping[str, tuple[int, ...]] + final_state_sha256: str + + +@dataclass(frozen=True, slots=True) +class R1ReplayReceipt: + """Deterministic replay receipt bound to the verified ReleaseBundle and study request.""" + + request_sha256: str + release_bundle_sha256: str + build_source_commit: str + baseline_final_state_sha256: str + compensated_final_state_sha256: str + replay_compensated_state_sha256: str + deterministic_match: bool + qualification_level: str + r1_l2_certified: bool + r1_l3_device_qualified: bool + + +@dataclass(frozen=True, slots=True) +class R1ShortWindowPairingResult: + """Combined baseline-vs-compensated conservative 4/8/16 short-window verification.""" + + request: R1StudyRequest + baseline: R1ModeWindowRun + compensated: R1ModeWindowRun + qualification: R1QualificationAssessment + replay_receipt: R1ReplayReceipt + sub_ulp_precision_ratio: float + + +def evaluate_sub_ulp_storage_precision( + *, + old_logit: float = 0.4, + delta_logit: float = 1.0e-15, + dt_s: float = 1.0e-9, + trap_density_m2: float = 2.0e15, +) -> dict[str, float]: + """Compare baseline float64 subtraction vs DD compensated logistic storage at sub-ULP steps.""" + from decimal import Decimal, localcontext + + new_logit = old_logit + delta_logit + with localcontext() as ctx: + ctx.prec = 90 + d_old = Decimal.from_float(old_logit) + d_new = Decimal.from_float(new_logit) + f_old_exact = Decimal(1) / (Decimal(1) + (-d_old).exp()) + f_new_exact = Decimal(1) / (Decimal(1) + (-d_new).exp()) + exact_rate = float( + Decimal.from_float(trap_density_m2) * (f_new_exact - f_old_exact) / Decimal.from_float(dt_s) + ) + + baseline_df = float(expit(new_logit)) - float(expit(old_logit)) + baseline_rate = trap_density_m2 * baseline_df / dt_s + + comp_df = float(_compensated_logistic_diff(old_logit, new_logit)) + comp_rate = trap_density_m2 * comp_df / dt_s + + base_err = abs(baseline_rate - exact_rate) / max(abs(exact_rate), 1.0e-30) + comp_err = abs(comp_rate - exact_rate) / max(abs(exact_rate), 1.0e-30) + return { + "exact_rate_m2_s": exact_rate, + "baseline_rate_m2_s": baseline_rate, + "compensated_rate_m2_s": comp_rate, + "baseline_relative_error": base_err, + "compensated_relative_error": comp_err, + "error_reduction_ratio": base_err / max(comp_err, 1.0e-20), + } + + +def _execute_mode_window( + *, + anchor: R1ZeroMinusAnchor, + control: str, + times_s: tuple[float, ...], + substeps: tuple[int, int, int], + voltage_step_V: float, + mode: Literal["baseline", "compensated"], + audit_observation_boundaries: bool = True, +) -> R1ModeWindowRun: + switches = R1_CONTROLS[control] + nu_i, nu_t = int(switches["nu_I"]), int(switches["nu_t"]) + dev = anchor.mobile_device if nu_i == 1 else anchor.immobile_device + init_ionic = anchor.mobile_state if nu_i == 1 else anchor.immobile_state + init_f = anchor.equilibrium_trap_occupancy + inv0 = anchor.mobile_state.domain_inventory_m2 + frozen_c = _build_frozen_coefficients(dev, anchor) + + n_nodes = dev.node_count + m_nodes = dev.ion_node_count + row_counts: dict[int, int] = {} + obs_states_by_s: dict[int, list[NDArray[np.float64]]] = {} + obs_curr_by_s: dict[int, list[float]] = {} + + ch_capture: list[float] = [] + ch_ecurr: list[NDArray[np.float64]] = [] + ch_edens: list[NDArray[np.float64]] = [] + ch_erate: list[NDArray[np.float64]] = [] + ch_hcurr: list[NDArray[np.float64]] = [] + ch_hdens: list[NDArray[np.float64]] = [] + ch_hrate: list[NDArray[np.float64]] = [] + ch_local: list[float] = [] + ch_iflux: list[NDArray[np.float64]] = [] + ch_irate: list[NDArray[np.float64]] = [] + ch_pot: list[NDArray[np.float64]] = [] + ch_sheet: list[float] = [] + ch_trace: list[float] = [] + + max_face_spread_rel = 0.0 + max_jac_err = 0.0 + max_charge_bal_rel = 0.0 + max_decomp_err = 0.0 + max_elim_err = 0.0 + max_full_charge = 0.0 + max_full_gauss = 0.0 + max_if_curr_rel = 0.0 + max_inv_drift = 0.0 + max_local_carrier = 0.0 + max_local_gauss = 0.0 + max_nl_res = 0.0 + max_trap_err = 0.0 + last_sha = "" + + def append_initial_row() -> None: + ch_capture.append(0.0) + ch_ecurr.append(np.zeros(n_nodes + 1, dtype=float)) + ch_edens.append(np.array(init_ionic.electronic_state.electron_density_m3, copy=True)) + ch_erate.append(np.zeros(n_nodes, dtype=float)) + ch_hcurr.append(np.zeros(n_nodes + 1, dtype=float)) + ch_hdens.append(np.array(init_ionic.electronic_state.hole_density_m3, copy=True)) + ch_hrate.append(np.zeros(n_nodes, dtype=float)) + ch_local.append(init_f) + ch_iflux.append(np.zeros(m_nodes - 1, dtype=float)) + ch_irate.append(np.zeros(m_nodes, dtype=float)) + ch_pot.append(np.array(init_ionic.electronic_state.potential_V, copy=True)) + ch_sheet.append(0.0) + ch_trace.append(float(init_ionic.electronic_state.potential_V[anchor.interface_node])) + + for s in substeps: + cur_ionic = init_ionic + cur_f = init_f + append_initial_row() + rows_this_s = 1 + s_states: list[NDArray[np.float64]] = [] + s_currs: list[float] = [] + for t0, t1 in zip(times_s[:-1], times_s[1:]): + dt_sub = (t1 - t0) / s + for sub_i in range(s): + step_r = solve_coupled_r1_step( + device=dev, + previous_ionic=cur_ionic, + previous_trap_occupancy=cur_f, + anchor=anchor, + voltage_V=voltage_step_V, + dt_s=dt_sub, + nu_t=nu_t, + mode=mode, + generation_scale=1.0, + light_turn_on=(sub_i == 0 and t0 == times_s[0]), + frozen_coefficients=frozen_c, + verify_codec=(sub_i == 0 and t0 == times_s[0] and audit_observation_boundaries), + audit_operators=(audit_observation_boundaries and sub_i == s - 1), + ) + if not step_r.accepted: + raise RuntimeError(f"coupled R1 step failed at s={s}, sub={sub_i}, mode={mode}") + cur_ionic = step_r.ionic_state + cur_f = step_r.trap_occupancy + rows_this_s += 1 + last_sha = step_r.state_sha256 + + ch_capture.append(step_r.capture_flux_m2_s) + ch_ecurr.append(step_r.electron_current_A_m2) + ch_edens.append(cur_ionic.electronic_state.electron_density_m3) + ch_erate.append(step_r.electron_rate_m2_s) + ch_hcurr.append(step_r.hole_current_A_m2) + ch_hdens.append(cur_ionic.electronic_state.hole_density_m3) + ch_hrate.append(step_r.hole_rate_m2_s) + ch_local.append(cur_f) + ch_iflux.append(step_r.ion_flux_m2_s) + ch_irate.append(step_r.ion_rate_m2_s) + ch_pot.append(cur_ionic.electronic_state.potential_V) + ch_sheet.append(step_r.sheet_charge_C_m2) + ch_trace.append(step_r.trace_potential_V) + + c_scale = max(1.0e-6, float(np.max(np.abs(step_r.total_current_A_m2)))) + spread_rel = float(np.ptp(step_r.total_current_A_m2)) / c_scale + if_jump_rel = abs( + float(step_r.total_current_A_m2[anchor.interface_node]) + - float(step_r.total_current_A_m2[anchor.interface_node + 1]) + ) / c_scale + inv_drift = abs(cur_ionic.domain_inventory_m2 - inv0) / inv0 + + max_face_spread_rel = max(max_face_spread_rel, spread_rel) + max_if_curr_rel = max(max_if_curr_rel, if_jump_rel) + max_jac_err = max(max_jac_err, step_r.analytic_jacobian_error) + max_charge_bal_rel = max(max_charge_bal_rel, step_r.charge_balance_relative) + max_decomp_err = max(max_decomp_err, step_r.current_decomposition_error) + max_elim_err = max(max_elim_err, step_r.eliminated_operator_error) + max_full_charge = max(max_full_charge, step_r.full_charge_balance_normalized) + max_full_gauss = max(max_full_gauss, step_r.full_gauss_normalized) + max_inv_drift = max(max_inv_drift, inv_drift) + max_local_carrier = max(max_local_carrier, step_r.local_carrier_residual) + max_local_gauss = max(max_local_gauss, step_r.local_gauss_residual) + max_nl_res = max(max_nl_res, step_r.scaled_nonlinear_residual) + max_trap_err = max(max_trap_err, step_r.trap_storage_normalized_error) + + if sub_i == s - 1: + s_states.append(np.r_[cur_ionic.electronic_state.potential_V, cur_f]) + s_currs.append(float(step_r.total_current_A_m2[0])) + + row_counts[s] = rows_this_s + obs_states_by_s[s] = s_states + obs_curr_by_s[s] = s_currs + + s_mid, s_fine = substeps[-2], substeps[-1] + ref_state_chg = max( + float(np.max(np.abs(a - b)) / max(1.0, float(np.max(np.abs(b))))) + for a, b in zip(obs_states_by_s[s_mid], obs_states_by_s[s_fine]) + ) + curr_window_scale = max(1.0, *(abs(v) for v in obs_curr_by_s[s_fine])) + ref_curr_chg = max( + abs(a - b) / curr_window_scale + for a, b in zip(obs_curr_by_s[s_mid], obs_curr_by_s[s_fine]) + ) + + cert_metrics = { + "all_face_current_relative": max_face_spread_rel, + "analytic_jacobian_error": max_jac_err, + "charge_balance_relative": max_charge_bal_rel, + "current_decomposition_error": max_decomp_err, + "eliminated_operator_error": max_elim_err, + "full_charge_balance_normalized": max_full_charge, + "full_gauss_normalized": max_full_gauss, + "interface_current_relative": max_if_curr_rel, + "inventory_relative_drift": max_inv_drift, + "local_carrier_residual": max_local_carrier, + "local_gauss_residual": max_local_gauss, + "nonlinear_residual": max_nl_res, + "physical_current_spread_relative": max_face_spread_rel, + "refinement_current_change": ref_curr_chg, + "refinement_state_change": ref_state_chg, + "trap_storage_normalized_error": max_trap_err, + } + cert = evaluate_v53_certificate(cert_metrics, limits=R1_V53_CERTIFICATE_LIMITS) + + packet: dict[str, NDArray[np.float64]] = { + "capture_flux": np.asarray(ch_capture, dtype=float), + "electron_current": np.asarray(ch_ecurr, dtype=float), + "electron_density": np.asarray(ch_edens, dtype=float), + "electron_rate": np.asarray(ch_erate, dtype=float), + "hole_current": np.asarray(ch_hcurr, dtype=float), + "hole_density": np.asarray(ch_hdens, dtype=float), + "hole_rate": np.asarray(ch_hrate, dtype=float), + "local_state": np.asarray(ch_local, dtype=float), + "positive_ion_flux": np.asarray(ch_iflux, dtype=float), + "positive_ion_rate": np.asarray(ch_irate, dtype=float), + "potential": np.asarray(ch_pot, dtype=float), + "sheet_charge": np.asarray(ch_sheet, dtype=float), + "trace_potential": np.asarray(ch_trace, dtype=float), + } + total_rows = sum(row_counts.values()) + shapes = validate_operator_channel_packet(packet, expected_rows=total_rows) + + return R1ModeWindowRun( + mode=mode, + accepted_rows=total_rows, + substep_row_counts=MappingProxyType(row_counts), + certificate=cert, + operator_channels=MappingProxyType(packet), + channel_shapes=MappingProxyType(shapes), + final_state_sha256=last_sha, + ) + + +def run_r1_short_window_pairing( + *, + bundle: ReleaseBundle, + study_id: str = "p07_02_short_window_d", + control: str = "D", + times_s: Sequence[float] = (0.0, 1.0e-7, 1.0e-6), + substeps: tuple[int, int, int] = R1_CONSERVATIVE_SUBSTEPS, + voltage_step_V: float = 5.0e-3, + intervals_per_layer: tuple[int, int] = (6, 4), +) -> R1ShortWindowPairingResult: + """Run conservative 4/8/16 baseline-vs-compensated short-window verification and replay.""" + anchor = prepare_r1_zero_minus_anchor(intervals_per_layer=intervals_per_layer) + request = build_r1_study_request( + study_id=study_id, + control=control, + times_s=times_s, + substeps=substeps, + voltage_step_V=voltage_step_V, + integrator="conservative_backward_euler", + precision_modes=("baseline", "compensated"), + release_bundle_sha256=bundle.sha256, + prepared_device_sha256=anchor.mobile_device.original_prepared_sha256, + ) + rel_binding = verify_r1_release_source( + bundle, + expected_bundle_sha256=bundle.sha256, + inputs=request.to_mapping(), + operator="solarlab_research", + ) + + t_tuple = tuple(float(t) for t in times_s) + expected_rows = expected_substep_rows(t_tuple, substeps) + + base_run = _execute_mode_window( + anchor=anchor, + control=control, + times_s=t_tuple, + substeps=substeps, + voltage_step_V=voltage_step_V, + mode="baseline", + ) + comp_run = _execute_mode_window( + anchor=anchor, + control=control, + times_s=t_tuple, + substeps=substeps, + voltage_step_V=voltage_step_V, + mode="compensated", + ) + # Independent replay of compensated mode to issue deterministic R1ReplayReceipt + replay_run = _execute_mode_window( + anchor=anchor, + control=control, + times_s=t_tuple, + substeps=substeps, + voltage_step_V=voltage_step_V, + mode="compensated", + audit_observation_boundaries=False, + ) + if base_run.accepted_rows != expected_rows or comp_run.accepted_rows != expected_rows: + raise RuntimeError("short-window row count violated expected conservative 4/8/16 formula") + + qual = assess_r1_qualification( + request, + baseline_certificate=base_run.certificate, + compensated_certificate=comp_run.certificate, + baseline_rows=base_run.accepted_rows, + compensated_rows=comp_run.accepted_rows, + interpolated_rows=False, + release_verified=(not rel_binding.scientific_qualification), + ) + sub_ulp = evaluate_sub_ulp_storage_precision() + + receipt = R1ReplayReceipt( + request_sha256=request.sha256, + release_bundle_sha256=rel_binding.bundle_sha256, + build_source_commit=rel_binding.build_source_commit, + baseline_final_state_sha256=base_run.final_state_sha256, + compensated_final_state_sha256=comp_run.final_state_sha256, + replay_compensated_state_sha256=replay_run.final_state_sha256, + deterministic_match=(comp_run.final_state_sha256 == replay_run.final_state_sha256), + qualification_level=qual.qualification_level, + r1_l2_certified=qual.r1_l2_certified, + r1_l3_device_qualified=qual.r1_l3_device_qualified, + ) + return R1ShortWindowPairingResult( + request=request, + baseline=base_run, + compensated=comp_run, + qualification=qual, + replay_receipt=receipt, + sub_ulp_precision_ratio=sub_ulp["error_reduction_ratio"], + ) + + +@dataclass(frozen=True, slots=True) +class R1WitnessMinimalEvaluation: + """Public-interface evaluation of step 183 and step 309 minimal inputs (P07-02.2).""" + + witness_audit: HistoricalR1WitnessAudit + parsed_fixture_layer_count: int + step183_dt_s: float + step309_dt_s: float + public_step183_accepted: bool + public_step309_accepted: bool + public_step183_jacobian_error: float + public_step309_jacobian_error: float + public_step309_nonlinear_residual: float + historical_step309_status: str + relabelled: bool + + +def evaluate_r1_witness_minimal_input( + witness_source: Path | bytes | str, + *, + intervals_per_layer: tuple[int, int] = (6, 4), +) -> R1WitnessMinimalEvaluation: + """Re-evaluate 183/309 minimal witness step parameters on the new public interface. + + Per ``P07-02.2``, the historical V53 step 309 record remains ``failed`` and + unrelabelled, while the new public-interface step solver is verified against + independent Jacobian and nonlinear residual gates rather than forced to fail. + """ + audit = verify_historical_r1_failure_witness(witness_source) + raw = witness_source.read_bytes() if isinstance(witness_source, Path) else ( + witness_source if isinstance(witness_source, bytes) else witness_source.encode("utf-8") + ) + import json + + payload = json.loads(raw.decode("utf-8")) + yaml_mapping = load_yaml_mapping(audit.source_fixture_yaml.encode("utf-8")) + layers_list = yaml_mapping.get("layers", []) + layer_count = len(layers_list) if isinstance(layers_list, list) else 0 + + c183_ok = payload["cases"]["step183_accepted"] + saved_183 = c183_ok.get("saved_row", c183_ok) + dt_183 = float(saved_183["dt_s"]) + v_183 = float( + saved_183.get( + "voltage_V", + payload.get("request", {}).get("case", {}).get("amplitude_V", audit.step309_voltage_V), + ) + ) + dt_309 = audit.step309_dt_s + v_309 = audit.step309_voltage_V + + anchor = prepare_r1_zero_minus_anchor(intervals_per_layer=intervals_per_layer) + res_183 = solve_coupled_r1_step( + device=anchor.mobile_device, + previous_ionic=anchor.mobile_state, + previous_trap_occupancy=anchor.equilibrium_trap_occupancy, + anchor=anchor, + voltage_V=v_183, + dt_s=dt_183, + nu_t=1, + mode="compensated", + ) + res_309 = solve_coupled_r1_step( + device=anchor.mobile_device, + previous_ionic=anchor.mobile_state, + previous_trap_occupancy=anchor.equilibrium_trap_occupancy, + anchor=anchor, + voltage_V=v_309, + dt_s=dt_309, + nu_t=1, + mode="compensated", + ) + return R1WitnessMinimalEvaluation( + witness_audit=audit, + parsed_fixture_layer_count=layer_count, + step183_dt_s=dt_183, + step309_dt_s=dt_309, + public_step183_accepted=res_183.accepted, + public_step309_accepted=res_309.accepted, + public_step183_jacobian_error=res_183.analytic_jacobian_error, + public_step309_jacobian_error=res_309.analytic_jacobian_error, + public_step309_nonlinear_residual=res_309.scaled_nonlinear_residual, + historical_step309_status=audit.step309_original_status, + relabelled=False, + ) diff --git a/src/solarlab_research/scripts/__init__.py b/src/solarlab_research/scripts/__init__.py new file mode 100644 index 00000000..fb496148 --- /dev/null +++ b/src/solarlab_research/scripts/__init__.py @@ -0,0 +1,3 @@ +"""Module CLI entrypoints for ``python -m solarlab_research.scripts.``.""" + +__all__: tuple[str, ...] = () diff --git a/src/solarlab_research/scripts/cbo_scan.py b/src/solarlab_research/scripts/cbo_scan.py new file mode 100644 index 00000000..c16dae09 --- /dev/null +++ b/src/solarlab_research/scripts/cbo_scan.py @@ -0,0 +1,110 @@ +"""CLI entrypoint for public 1D CBO scans (`python -m solarlab_research.scripts.cbo_scan`).""" + +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import json +import sys +from typing import Any + +from solarlab_research.cbo_scan import ( + CBO_BOUNDARY_POLICIES, + CBOScanConfig, + RECOMPUTED_BUILT_IN, + default_cbo_prepared_device, + run_cbo_scan, +) + +__all__ = ["build_parser", "main"] + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m solarlab_research.scripts.cbo_scan", + description="Run a public 1D conduction/valence-band-offset (CBO) scan.", + ) + parser.add_argument( + "--delta-ec", + type=float, + nargs="+", + default=[-0.1, 0.0, 0.1, 0.2], + help="Requested delta_ec_eV = chi_absorber - chi_transport points (eV).", + ) + parser.add_argument( + "--boundary-policy", + choices=CBO_BOUNDARY_POLICIES, + default=RECOMPUTED_BUILT_IN, + help="Contact boundary policy across the band-offset sweep.", + ) + parser.add_argument( + "--intervals", + type=int, + nargs="+", + default=[6, 12, 6], + help="Intervals per layer for the 3-layer HTL/absorber/ETL stack.", + ) + parser.add_argument( + "--voltage-points", + type=int, + default=13, + help="Number of bias points between 0 V and V_upper.", + ) + parser.add_argument( + "--v-upper", + type=float, + default=1.125, + help="Upper bias voltage (V) for dark/illuminated JV scan.", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + intervals = tuple(int(n) for n in args.intervals) + device = default_cbo_prepared_device() + voltages = tuple( + args.v_upper * idx / max(int(args.voltage_points) - 1, 1) + for idx in range(int(args.voltage_points)) + ) + config = CBOScanConfig( + delta_ec_eV=tuple(float(v) for v in args.delta_ec), + intervals_per_layer=intervals, + voltages_V=voltages, + boundary_policy=args.boundary_policy, + ) + result = run_cbo_scan(device, config) + payload: dict[str, Any] = { + "schema": "solarlab_research.cbo_scan_cli.v1", + "boundary_policy": result.boundary_policy, + "pinned_models": [f"{ref.id}@{ref.version}" for ref in result.pinned_models], + "complete": result.complete, + "termination_count": len(result.terminations), + "points": [ + { + "delta_ec_eV": pt.delta_ec_eV, + "applied_V_bi_V": pt.applied_V_bi_V, + "Jsc": None if pt.metrics is None else pt.metrics.short_circuit_current_A_m2, + "Voc": None if pt.metrics is None else pt.metrics.open_circuit_voltage_V, + "FF": None if pt.metrics is None else pt.metrics.fill_factor, + "PCE": None if pt.metrics is None else pt.metrics.efficiency, + } + for pt in result.points + if pt.requested + ], + "critical_intervals": [ + { + "metric": ci.metric, + "lower_delta_ec_eV": ci.lower_delta_ec_eV, + "upper_delta_ec_eV": ci.upper_delta_ec_eV, + "resolved": ci.resolved, + } + for ci in result.critical_intervals + ], + } + sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/solarlab_research/scripts/r1_short_window.py b/src/solarlab_research/scripts/r1_short_window.py new file mode 100644 index 00000000..f6c85df7 --- /dev/null +++ b/src/solarlab_research/scripts/r1_short_window.py @@ -0,0 +1,122 @@ +"""CLI entrypoint for R1 short-window verification (`python -m solarlab_research.scripts.r1_short_window`).""" + +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import json +from pathlib import Path +import sys +from typing import Any + +from solarlab_research.r1.contracts import R1_CONTROLS +from solarlab_research.r1.controls import verify_r1_controls_abcd +from solarlab_research.r1.provenance import ( + load_verified_release_bundle, + synthetic_research_release_bundle, +) +from solarlab_research.r1.short_window import ( + evaluate_r1_witness_minimal_input, + run_r1_short_window_pairing, +) + +__all__ = ["build_parser", "main"] + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m solarlab_research.scripts.r1_short_window", + description=( + "Run conservative 4/8/16 short-window baseline-vs-compensated R1 public-interface " + "verification without claiming R1-L2 (100 s) or R1-L3 device qualification." + ), + ) + parser.add_argument( + "--control", + choices=tuple(R1_CONTROLS), + default="D", + help="R1 control identifier A:(0,0), B:(1,0), C:(0,1), or D:(1,1).", + ) + parser.add_argument( + "--intervals", + type=int, + nargs=2, + default=[4, 3], + help="Intervals per layer for the 2-layer absorber/ETL R1 stack.", + ) + parser.add_argument( + "--bundle-dir", + type=Path, + default=None, + help="Optional materialized ReleaseBundle directory.", + ) + parser.add_argument( + "--expected-bundle-sha256", + type=str, + default=None, + help="Expected SHA-256 hex digest when --bundle-dir is supplied.", + ) + parser.add_argument( + "--check-controls", + action="store_true", + help="Also run and verify controls A-D 0- anchor replication and suppression.", + ) + parser.add_argument( + "--witness", + type=Path, + default=None, + help="Optional path to R1FailureWitnessV1.json for minimal 183/309 public check.", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + if args.bundle_dir is not None: + if not args.expected_bundle_sha256: + raise ValueError("--expected-bundle-sha256 is required with --bundle-dir") + bundle = load_verified_release_bundle( + args.bundle_dir, + expected_bundle_sha256=args.expected_bundle_sha256, + ) + else: + bundle = synthetic_research_release_bundle() + + intervals = (int(args.intervals[0]), int(args.intervals[1])) + pairing = run_r1_short_window_pairing( + bundle=bundle, + control=str(args.control), + intervals_per_layer=intervals, + ) + payload: dict[str, Any] = { + "schema": "solarlab_research.r1_short_window_cli.v1", + "control": pairing.request.control, + "baseline_passed": pairing.baseline.certificate.passed, + "compensated_passed": pairing.compensated.certificate.passed, + "baseline_rows": pairing.baseline.accepted_rows, + "compensated_rows": pairing.compensated.accepted_rows, + "sub_ulp_precision_ratio": pairing.sub_ulp_precision_ratio, + "deterministic_replay_match": pairing.replay_receipt.deterministic_match, + "request_sha256": pairing.replay_receipt.request_sha256, + "release_bundle_sha256": pairing.replay_receipt.release_bundle_sha256, + "qualification_level": pairing.qualification.qualification_level, + "r1_l2_certified": pairing.qualification.r1_l2_certified, + "r1_l3_device_qualified": pairing.qualification.r1_l3_device_qualified, + } + if args.check_controls: + suite = verify_r1_controls_abcd(intervals_per_layer=intervals) + payload["controls_abcd_passed"] = suite.passed + if args.witness is not None: + witness_eval = evaluate_r1_witness_minimal_input(args.witness, intervals_per_layer=intervals) + payload["witness_minimal_evaluation"] = { + "public_step183_accepted": witness_eval.public_step183_accepted, + "public_step309_accepted": witness_eval.public_step309_accepted, + "historical_step309_status": witness_eval.historical_step309_status, + "relabelled": witness_eval.relabelled, + } + sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/solarlab_research/scripts/r1_verify_sources.py b/src/solarlab_research/scripts/r1_verify_sources.py new file mode 100644 index 00000000..f893e819 --- /dev/null +++ b/src/solarlab_research/scripts/r1_verify_sources.py @@ -0,0 +1,112 @@ +"""CLI entrypoint for R1 source & historical artifact verification (`python -m solarlab_research.scripts.r1_verify_sources`).""" + +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import json +from pathlib import Path +import sys +from typing import Any + +from solarlab_research.r1.provenance import ( + load_verified_release_bundle, + read_historical_r1_artifact, + verify_historical_r1_failure_witness, + verify_r1_release_source, +) + +__all__ = ["build_parser", "main"] + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m solarlab_research.scripts.r1_verify_sources", + description=( + "Verify historical R1 artifacts against their original recorded sources " + "without relabeling, and/or verify an immutable ReleaseBundle directory." + ), + ) + parser.add_argument( + "--historical", + type=Path, + action="append", + default=[], + help="Path to a historical R1 JSON artifact (R1CommonStateV1/V2 or R1FailureWitnessV1).", + ) + parser.add_argument( + "--witness", + type=Path, + default=None, + help="Path to R1FailureWitnessV1.json for explicit witness audit.", + ) + parser.add_argument( + "--bundle-dir", + type=Path, + default=None, + help="Optional materialized ReleaseBundle directory.", + ) + parser.add_argument( + "--expected-bundle-sha256", + type=str, + default=None, + help="Expected SHA-256 hex digest of the ReleaseBundle manifest.", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + historical_records: list[dict[str, Any]] = [] + for path in args.historical: + summary = read_historical_r1_artifact(path) + historical_records.append({ + "path": str(path), + "schema": summary.schema, + "artifact_sha256": summary.artifact_sha256, + "original_source_id": summary.original_source_id, + "original_source_sha256": summary.original_source_sha256, + "relabelled": summary.relabelled, + }) + + payload: dict[str, Any] = { + "schema": "solarlab_research.r1_verify_sources_cli.v1", + "historical_artifacts": historical_records, + } + + if args.witness is not None: + audit = verify_historical_r1_failure_witness(args.witness) + payload["witness_audit"] = { + "fixture_sha256": audit.fixture_sha256, + "source_commit": audit.source_commit, + "step183_accepted_status": audit.step183_accepted_status, + "step183_failed_status": audit.step183_failed_status, + "step309_original_status": audit.step309_original_status, + "relabelled": audit.relabelled, + } + + if args.bundle_dir is not None: + if not args.expected_bundle_sha256: + raise ValueError("--expected-bundle-sha256 is required with --bundle-dir") + bundle = load_verified_release_bundle( + args.bundle_dir, + expected_bundle_sha256=args.expected_bundle_sha256, + ) + binding = verify_r1_release_source( + bundle, + expected_bundle_sha256=args.expected_bundle_sha256, + inputs={"cli": "r1_verify_sources"}, + ) + payload["release_bundle"] = { + "build_source_commit": binding.build_source_commit, + "profile": binding.profile, + "bundle_sha256": binding.bundle_sha256, + "scientific_qualification": binding.scientific_qualification, + } + + sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/integration/research/test_cbo_scan_and_r1_short_window.py b/tests/integration/research/test_cbo_scan_and_r1_short_window.py new file mode 100644 index 00000000..4a37a08f --- /dev/null +++ b/tests/integration/research/test_cbo_scan_and_r1_short_window.py @@ -0,0 +1,202 @@ +"""Integration tests for ``solarlab_research.cbo_scan`` and ``solarlab_research.r1`` (P07-01, P07-02). + +Covers: +* Public 1D CBO scan orchestration with ``recomputed_built_in`` and ``fixed_contacts`` + boundary policies, adaptive midpoint bridge continuation, onset critical intervals, + nested voltage-grid convergence certification, spatial mesh convergence certification, + and ``D20`` pre-``P08`` model-pinning enforcement. +* R1 controls ``A-D`` preparation from a common dark ``0-`` equilibrium anchor with + exact replication and exact zero-flux / zero-rate suppression of disabled channels. +* Minimal ``183/309`` public-interface witness evaluation preserving historical V53 + step ``309`` ``failed`` status without relabeling. +* Conservative ``4/8/16`` baseline-vs-compensated short-window coupled pairing with + all 16 V53 certificate gates, 13 operator channels, sub-ULP storage precision check, + and deterministic ``R1ReplayReceipt`` (``r1_l2_certified=False``, + ``r1_l3_device_qualified=False``). +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest + +from solarlab.physics.registry import ModelRef + +from solarlab_research.cbo_scan import ( + CBOScanConfig, + CBOVoltageGridConvergencePolicy, + FIXED_CONTACTS, + InterfaceCBOScanError, + RECOMPUTED_BUILT_IN, + certify_cbo_grid_convergence, + certify_cbo_voltage_grid_convergence, + default_cbo_prepared_device, + enforce_pre_p08_cbo_pinning, + run_cbo_scan, +) +from solarlab_research.r1 import ( + R1_OPERATOR_CHANNELS, + R1_V53_CERTIFICATE_LIMITS, + evaluate_r1_witness_minimal_input, + run_r1_short_window_pairing, + synthetic_research_release_bundle, + verify_r1_controls_abcd, +) + +REPO_ROOT = Path(__file__).resolve().parents[3] +HIST_WITNESS = REPO_ROOT / "tests" / "fixtures" / "refactor" / "R1FailureWitnessV1.json" + + +def test_cbo_scan_boundary_policies_adaptive_bridge_and_d20_pinning() -> None: + baseline = default_cbo_prepared_device() + + # D20 pre-P08 model pinning rejects prospective P08 models unless explicitly opted in + p08_ref = ModelRef("spectral_control_volume_beer_lambert", 1) + with pytest.raises(InterfaceCBOScanError, match="D20 model-pinning violation"): + enforce_pre_p08_cbo_pinning(baseline, requested_models=(p08_ref,)) + opted_in = enforce_pre_p08_cbo_pinning( + baseline, requested_models=(p08_ref,), allow_prospective_p08_models=True + ) + assert opted_in == (p08_ref,) + + coarse_v = tuple(np.linspace(0.0, 1.125, 17).tolist()) + fine_v = tuple(np.linspace(0.0, 1.125, 33).tolist()) + + # 1. recomputed_built_in with nested voltage grids + adaptive midpoint bridges + cfg_recomputed = CBOScanConfig( + delta_ec_eV=(-0.10, 0.0, 0.15, 0.25), + boundary_policy=RECOMPUTED_BUILT_IN, + intervals_per_layer=(4, 8, 4), + voltage_grids_V=(coarse_v, fine_v), + maximum_delta_step_eV=0.06, + relative_drop_fraction=0.02, + voltage_grid_policy=CBOVoltageGridConvergencePolicy( + minimum_voltage_grids=2, + maximum_voc_change_V=2.0e-2, + maximum_ff_change=3.0e-2, + maximum_pce_change=3.0e-2, + ), + ) + res_recomputed = run_cbo_scan(baseline, cfg_recomputed) + assert res_recomputed.complete is True + assert res_recomputed.certified is True + assert res_recomputed.sync_vbi is True + assert res_recomputed.bridge_point_count >= 2 + + req_pts_recomp = [pt for pt in res_recomputed.points if pt.requested] + assert len(req_pts_recomp) == 4 + # Under recomputed_built_in, shifting ETL chi changes applied V_bi linearly + vbi_vals_recomp = [pt.applied_V_bi_V for pt in req_pts_recomp] + assert max(vbi_vals_recomp) - min(vbi_vals_recomp) > 0.30 + + vgrid_cert = certify_cbo_voltage_grid_convergence(res_recomputed) + assert vgrid_cert.certified is True, f"voltage grid convergence failed: {vgrid_cert.reasons}" + assert vgrid_cert.voltage_point_counts == (17, 33) + + # 2. fixed_contacts keeps applied_V_bi_V and grid_node_count strictly invariant + cfg_fixed = CBOScanConfig( + delta_ec_eV=(-0.10, 0.0, 0.15), + boundary_policy=FIXED_CONTACTS, + intervals_per_layer=(4, 8, 4), + voltages_V=coarse_v, + calculate_jv_metrics=False, + ) + res_fixed = run_cbo_scan(baseline, cfg_fixed) + assert res_fixed.complete is True + assert res_fixed.sync_vbi is False + vbi_fixed = [pt.applied_V_bi_V for pt in res_fixed.points] + assert np.allclose(vbi_fixed, vbi_fixed[0], rtol=0.0, atol=1.0e-12) + assert res_fixed.grid_node_count == res_recomputed.grid_node_count + + # 3. Spatial mesh convergence across two meshes sharing identical protocol_sha256 + cfg_mesh_fine = CBOScanConfig( + delta_ec_eV=(-0.10, 0.0, 0.15, 0.25), + boundary_policy=RECOMPUTED_BUILT_IN, + intervals_per_layer=(6, 12, 6), + voltage_grids_V=(coarse_v, fine_v), + maximum_delta_step_eV=0.06, + relative_drop_fraction=0.02, + voltage_grid_policy=cfg_recomputed.voltage_grid_policy, + ) + res_mesh_fine = run_cbo_scan(baseline, cfg_mesh_fine) + assert res_mesh_fine.protocol_sha256 == res_recomputed.protocol_sha256 + + ff_ci = next(c for c in res_recomputed.critical_intervals if c.metric == "FF") + assert ff_ci.resolved is True + mesh_cert = certify_cbo_grid_convergence( + (res_recomputed, res_mesh_fine), + metric="FF", + maximum_envelope_width_eV=0.20, + maximum_reference_relative_spread=0.05, + ) + assert mesh_cert.certified is True, f"spatial mesh convergence failed: {mesh_cert.reasons}" + assert mesh_cert.grid_interval_counts == (16, 24) + + +def test_r1_controls_abcd_witness_and_short_window_pairing() -> None: + # 1. Controls A-D from a common replicated 0- anchor + suite = verify_r1_controls_abcd(intervals_per_layer=(4, 3)) + assert suite.passed is True + assert set(suite.controls) == {"A", "B", "C", "D"} + for code in ("A", "B", "C", "D"): + audit = suite.controls[code] + assert audit.passed is True + assert audit.zero_minus_replicated is True + assert audit.ion_inventory_relative_drift <= 1.0e-12 + + assert suite.controls["A"].max_ion_flux_m2_s == 0.0 + assert suite.controls["A"].max_ion_rate_m2_s == 0.0 + assert suite.controls["A"].trap_occupancy_rate_s == 0.0 + assert suite.controls["A"].sheet_charge_C_m2 == 0.0 + + assert suite.controls["B"].max_ion_flux_m2_s > 0.0 + assert suite.controls["B"].trap_occupancy_rate_s == 0.0 + assert suite.controls["B"].sheet_charge_C_m2 == 0.0 + + assert suite.controls["C"].max_ion_flux_m2_s == 0.0 + assert suite.controls["C"].trap_occupancy_rate_s > 0.0 + assert abs(suite.controls["C"].sheet_charge_C_m2) > 0.0 + + assert suite.controls["D"].max_ion_flux_m2_s > 0.0 + assert suite.controls["D"].trap_occupancy_rate_s > 0.0 + assert abs(suite.controls["D"].sheet_charge_C_m2) > 0.0 + + # 2. Minimal 183/309 public-interface witness evaluation (non-relabeling) + witness_eval = evaluate_r1_witness_minimal_input(HIST_WITNESS, intervals_per_layer=(4, 3)) + assert witness_eval.parsed_fixture_layer_count >= 2 + assert witness_eval.public_step183_accepted is True + assert witness_eval.public_step309_accepted is True + assert witness_eval.public_step183_jacobian_error < R1_V53_CERTIFICATE_LIMITS["analytic_jacobian_error"] + assert witness_eval.public_step309_jacobian_error < R1_V53_CERTIFICATE_LIMITS["analytic_jacobian_error"] + assert witness_eval.public_step309_nonlinear_residual <= R1_V53_CERTIFICATE_LIMITS["nonlinear_residual"] + # Historical V53 step 309 remains failed and unrelabelled + assert witness_eval.historical_step309_status == "failed" + assert witness_eval.relabelled is False + + # 3. Conservative 4/8/16 baseline-vs-compensated short-window pairing + replay receipt + bundle = synthetic_research_release_bundle() + pairing = run_r1_short_window_pairing( + bundle=bundle, + control="D", + times_s=(0.0, 1.0e-7, 1.0e-6), + intervals_per_layer=(4, 3), + ) + assert pairing.baseline.accepted_rows == 59 + assert pairing.compensated.accepted_rows == 59 + assert dict(pairing.baseline.substep_row_counts) == {4: 9, 8: 17, 16: 33} + assert dict(pairing.compensated.substep_row_counts) == {4: 9, 8: 17, 16: 33} + assert pairing.baseline.certificate.passed is True, pairing.baseline.certificate.failed_items + assert pairing.compensated.certificate.passed is True, pairing.compensated.certificate.failed_items + assert set(pairing.compensated.operator_channels) == set(R1_OPERATOR_CHANNELS) + assert pairing.sub_ulp_precision_ratio > 1.0e6 + + receipt = pairing.replay_receipt + assert receipt.deterministic_match is True + assert receipt.compensated_final_state_sha256 == receipt.replay_compensated_state_sha256 + assert receipt.qualification_level == "short_window_interface_verification_only" + assert receipt.r1_l2_certified is False + assert receipt.r1_l3_device_qualified is False + assert pairing.qualification.r1_l2_certified is False + assert pairing.qualification.r1_l3_device_qualified is False diff --git a/tests/unit/research/test_precision_and_codecs.py b/tests/unit/research/test_precision_and_codecs.py new file mode 100644 index 00000000..0a445681 --- /dev/null +++ b/tests/unit/research/test_precision_and_codecs.py @@ -0,0 +1,475 @@ +"""Unit tests for ``solarlab_research.precision`` (P07-01). + +Covers: +* ``DD`` exact TwoSum/TwoProduct, immutability, normalized ``(hi, lo)`` roundtrip, + and ``exp``/``expm1``/``log``/``log1p``/``sum`` to ``<= 1e-30`` relative error + against 90-digit ``decimal.Decimal`` across sub-ULP and moderate inputs. +* ``DDArray`` and ``CompensatedArithmetic`` conformance with ``solarlab.contracts`` + (``PhysicalArray``, ``AssemblyArithmetic``, ``FieldProjection``, ``log_ratio``). +* ``freeze_coefficients``, ``evaluate_local_carrier_pair``, and ``to_float_tangent``: + Fermi-table SHA-256 tamper rejection, exact compensated Jacobians vs high-precision + central differences in ``DD``, and ``UnsupportedCompensatedInterfaceDomain`` + without binary64 fallback. +* ``PairStateAuthority``, ``ReferenceIncrementCoordinates``, ``AffineInputLiftCodec``, + and ``decode_historical_r1_pair_state`` (plus tamper rejection). +* Boundary & registry hygiene: zero ``PhysicsModel`` registrations in + ``solarlab.physics.registry`` from ``solarlab_research``, zero imports from + ``perovskite_sim`` / ``solarlab_server`` / ``backend``, and zero private ``_`` + imports/attributes from ``solarlab``. +""" + +from __future__ import annotations + +import ast +from decimal import Decimal, localcontext +import json +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +from solarlab.contracts import ( + AssemblyArithmetic, + ContractError, + EquationSpec, + Layout, + ONE, + PARTICLE, + PhysicalArray, + StateAuthority, + Support, + VOLT, + VOLUME, + VariableSpec, +) +from solarlab_research.precision import ( + AffineInputLiftCodec, + CompensatedArithmetic, + DD, + DDArray, + InputLiftCheckpointError, + PairStateAuthority, + ReferenceIncrementCoordinates, + UnsupportedCompensatedInterfaceDomain, + decode_historical_r1_pair_state, + default_fd_table, + evaluate_local_carrier_pair, + exp, + expm1, + freeze_coefficients, + log, + log1p, + sum as dd_sum, + to_float_tangent, +) + +REPO_ROOT = Path(__file__).resolve().parents[3] +RESEARCH_SRC = REPO_ROOT / "src" / "solarlab_research" +HISTORICAL_PAIR_FIXTURE = ( + REPO_ROOT / "tests" / "refactor" / "fixtures" / "r1_pair_common_state_preparation.json" +) + + +def _dd_to_decimal(val: DD) -> Decimal: + assert val.ndim == 0 + return Decimal(float(val.hi.item())) + Decimal(float(val.lo.item())) + + +def _rel_err_decimal(val: DD, ref: Decimal) -> float: + got = _dd_to_decimal(val) + if ref == 0: + return float(abs(got)) + return float(abs(got - ref) / abs(ref)) + + +def test_dd_exact_arithmetic_immutability_and_transcendentals() -> None: + sub_ulp = 2.0**-60 + added = DD(1.0) + DD(sub_ulp) + recovered = added - DD(1.0) + assert float(recovered) == sub_ulp + assert float(added.hi) == 1.0 + assert float(added.lo) == sub_ulp + + with pytest.raises(AttributeError): + added.hi = np.asarray(2.0) # type: ignore[misc] + with pytest.raises((ValueError, TypeError)): + added.hi[...] = 2.0 + + pair = added.to_pair_dict() + rebuilt = DD.from_pair_dict(pair, expected_shape=()) + assert rebuilt == added + with pytest.raises(ValueError, match="not normalized"): + DD.from_pair_dict({"hi": 1.0, "lo": 0.25}) + + with localcontext() as ctx: + ctx.prec = 90 + for x_val in (-1.25, -1.0e-18, 1.0e-18, 0.375, 3.5): + x_dd = DD(x_val) + x_dec = Decimal(x_val) + + ref_exp = x_dec.exp() + assert _rel_err_decimal(exp(x_dd), ref_exp) <= 1.0e-30 + + ref_expm1 = x_dec.exp() - Decimal(1) + assert _rel_err_decimal(expm1(x_dd), ref_expm1) <= 1.0e-30 + + for y_val in (0.125, 0.999999999999, 1.000000000001, 7.5): + y_dd = DD(y_val) + y_dec = Decimal(y_val) + assert _rel_err_decimal(log(y_dd), y_dec.ln()) <= 1.0e-30 + + for z_val in (-0.2, -1.0e-18, 1.0e-18, 0.2): + z_dd = DD(z_val) + z_dec = Decimal(z_val) + assert _rel_err_decimal(log1p(z_dd), (Decimal(1) + z_dec).ln()) <= 1.0e-30 + + terms = DD(np.array([1.0, 2.0**-60, -1.0, 2.0**-60], dtype=np.float64)) + total = dd_sum(terms) + assert float(total) == pytest.approx(2.0**-59, rel=0.0, abs=1.0e-32) + + +def _accepts_physical_array(arr: PhysicalArray) -> PhysicalArray: + return arr + + +def _accepts_arithmetic(arith: AssemblyArithmetic) -> AssemblyArithmetic: + return arith + + +def _accepts_authority(auth: StateAuthority) -> StateAuthority: + return auth + + +def test_dd_array_and_compensated_arithmetic_contracts() -> None: + base = DDArray.from_parts([1.0e22, 2.0e22, 4.0e22]) + perturbed = DDArray(base.values + base.values * DD([1.0e-18, -2.0e-18, 0.5])) + assert _accepts_physical_array(base) is base + + ratio = perturbed.log_ratio(base) + assert float(ratio.values[0]) == pytest.approx(1.0e-18, rel=1.0e-12) + assert float(ratio.values[1]) == pytest.approx(-2.0e-18, rel=1.0e-12) + assert float(ratio.values[2]) == pytest.approx(np.log(1.5), rel=1.0e-15) + + proj = perturbed.project_to_float(authority_identity="auth-1") + assert proj.authority_identity == "auth-1" + assert proj.evaluator_identity == "dd-high-word-projection-v1" + assert proj.absolute_error_bound is not None + assert np.all(np.asarray(proj.absolute_error_bound.values) >= np.abs(perturbed.values.lo)) + + arith = CompensatedArithmetic() + assert _accepts_arithmetic(arith) is arith + mat = np.array([[1.0, 1.0], [2.0, -1.0]], dtype=np.float64) + vec = DD(np.array([1.0, -1.0], dtype=np.float64), np.array([2.0**-60, 0.0], dtype=np.float64)) + prod = arith.matmul(mat, vec) + assert float(prod[0]) == pytest.approx(2.0**-60, rel=0.0, abs=1.0e-32) + assert float(prod[1]) == pytest.approx(3.0, rel=1.0e-15) + + scattered = arith.scatter_add(arith.zeros((3,)), np.array([1, 1], dtype=np.intp), DD([1.0, 2.0**-60])) + assert float(scattered[1] - DD(1.0)) == pytest.approx(2.0**-60, rel=0.0, abs=1.0e-32) + + +def _sample_frozen_coefficients() -> Any: + geometry = {"left_distance_m": 2.5e-8, "right_distance_m": 2.0e-8} + physics = { + "thermal_voltage_V": 0.02585199102456544, + "temperature_K": 300.0, + "transmission": 1.0, + "D_n_left_m2_s": 5.0e-6, + "D_p_left_m2_s": 5.0e-6, + "D_n_right_m2_s": 1.5e-6, + "D_p_right_m2_s": 1.5e-6, + "N_C_left_m3": 2.0e25, + "N_V_left_m3": 2.0e25, + "N_C_right_m3": 4.0e25, + "N_V_right_m3": 3.0e25, + "n1_left_m3": 1.0e17, + "p1_left_m3": 2.0e17, + "n1_right_m3": 1.0e17, + "p1_right_m3": 2.0e17, + "richardson_n_A_m2_K2": 1.2e6, + "richardson_p_A_m2_K2": 1.2e6, + "surface_recombination_velocity_n_m_s": 80.0, + "surface_recombination_velocity_p_m_s": 90.0, + "conduction_band_step_eV": 0.08, + "hole_transport_step_eV": 0.25, + } + return geometry, physics, freeze_coefficients(geometry, physics) + + +def test_two_sided_interface_fd_tamper_jacobians_and_domain_guards() -> None: + geometry, physics, coeffs = _sample_frozen_coefficients() + table, sha = default_fd_table() + assert coeffs.fd_table_sha256 == sha + + with pytest.raises(ValueError, match="identity mismatch"): + freeze_coefficients(geometry, physics, fd_table=table, fd_table_sha256="0" * 64) + + state_d = DD(np.array([1.2e19, 2.5e18, 3.0e20, 1.5e16], dtype=np.float64)) + trace_v = DD(np.array([0.12, 0.14], dtype=np.float64)) + bulk_d = DD(np.array([1.4e19, 2.2e18, 3.3e20, 1.2e16], dtype=np.float64)) + bulk_v = DD(np.array([0.11, 0.155], dtype=np.float64)) + occ = DD(0.37) + + ev = evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + projected = to_float_tangent(ev) + assert projected.balance.jacobian_log_state_m2_s.shape == (4, 4) + assert projected.balance.jacobian_trace_potential_m2_s_V.shape == (4, 2) + assert projected.balance.jacobian_bulk_coordinates.shape == (4, 6) + assert ev.metadata["fallback_used"] is False + + eps = DD(1.0e-10) + # 4x4 log-state Jacobian check via central difference in DD + jac_log = projected.balance.jacobian_log_state_m2_s + for col in range(4): + hi_p, lo_p = state_d.hi.copy(), state_d.lo.copy() + hi_m, lo_m = state_d.hi.copy(), state_d.lo.copy() + up = state_d[col] * exp(eps) + dn = state_d[col] * exp(-eps) + hi_p[col], lo_p[col] = up.hi, up.lo + hi_m[col], lo_m[col] = dn.hi, dn.lo + ev_p = evaluate_local_carrier_pair( + state_density=DD.from_normalized_parts(hi_p, lo_p), + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + ev_m = evaluate_local_carrier_pair( + state_density=DD.from_normalized_parts(hi_m, lo_m), + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + fd_col = ((ev_p.balance["residual_m2_s"] - ev_m.balance["residual_m2_s"]) / (DD(2.0) * eps)).to_float() + assert np.allclose(jac_log[:, col], np.asarray(fd_col), rtol=1.0e-9, atol=1.0e-9) + + # 4x2 trace-potential Jacobian check + jac_tr = projected.balance.jacobian_trace_potential_m2_s_V + for col in range(2): + hi_p, lo_p = trace_v.hi.copy(), trace_v.lo.copy() + hi_m, lo_m = trace_v.hi.copy(), trace_v.lo.copy() + up = trace_v[col] + eps + dn = trace_v[col] - eps + hi_p[col], lo_p[col] = up.hi, up.lo + hi_m[col], lo_m[col] = dn.hi, dn.lo + ev_p = evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=DD.from_normalized_parts(hi_p, lo_p), + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + ev_m = evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=DD.from_normalized_parts(hi_m, lo_m), + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + fd_col = ((ev_p.balance["residual_m2_s"] - ev_m.balance["residual_m2_s"]) / (DD(2.0) * eps)).to_float() + assert np.allclose(jac_tr[:, col], np.asarray(fd_col), rtol=1.0e-9, atol=1.0e-9) + + # Occupancy derivative check + ev_occ_p = evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ + eps, + capture_multiplier=1.0, + coefficients=coeffs, + ) + ev_occ_m = evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ - eps, + capture_multiplier=1.0, + coefficients=coeffs, + ) + fd_occ = ( + (ev_occ_p.balance["capture_flux_m2_s"] - ev_occ_m.balance["capture_flux_m2_s"]) / (DD(2.0) * eps) + ).to_float() + assert np.allclose(projected.capture_flux_occupancy_derivative_m2_s, np.asarray(fd_occ), rtol=1.0e-9, atol=1.0e-9) + + # Domain guards raise UnsupportedCompensatedInterfaceDomain without silent fallback + degenerate_state = DD(np.array([1.5e25, 2.5e18, 3.0e20, 1.5e16], dtype=np.float64)) + with pytest.raises(UnsupportedCompensatedInterfaceDomain): + evaluate_local_carrier_pair( + state_density=degenerate_state, + trace_potential=trace_v, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + + extreme_trace = DD(np.array([50.0, 0.14], dtype=np.float64)) + with pytest.raises(UnsupportedCompensatedInterfaceDomain): + evaluate_local_carrier_pair( + state_density=state_d, + trace_potential=extreme_trace, + bulk_density=bulk_d, + bulk_potential=bulk_v, + occupancy=occ, + capture_multiplier=1.0, + coefficients=coeffs, + ) + + +def test_state_authority_reference_coordinates_and_codecs() -> None: + support = Support("nodes", "cell", (2,)) + iface = Support("iface", "global", (1,)) + layout = Layout( + supports=(support, iface), + variables=( + VariableSpec("phi", "electrostatics", "nodes", (2,), VOLT), + VariableSpec("n", "transport", "nodes", (2,), PARTICLE / VOLUME), + VariableSpec("f_t", "interface", "iface", (1,), ONE), + ), + equations=( + EquationSpec("eq_phi", "electrostatics", "nodes", (2,), ONE), + EquationSpec("eq_n", "transport", "nodes", (2,), ONE), + EquationSpec("eq_f", "interface", "iface", (1,), ONE), + ), + ) + coords = ReferenceIncrementCoordinates.from_float_anchor( + layout, + { + "phi": np.array([0.1, 0.2], dtype=np.float64), + "n": np.array([1.0e21, 2.0e21], dtype=np.float64), + "f_t": np.array([0.4], dtype=np.float64), + }, + multiplicative_variables=("n",), + ) + p0 = coords.point(np.zeros(layout.size, dtype=np.float64), time=0.0, inputs=[0.005]) + assert p0.state.authority is not None + assert _accepts_authority(p0.state.authority) is p0.state.authority + assert isinstance(p0.state.authority, PairStateAuthority) + + dy = np.array([1.0e-18, -2.0e-18, 3.0e-18, -1.0e-18, 5.0e-18], dtype=np.float64) + p1, inc = coords.advance(p0, dy, time=1.0e-9, inputs=[0.005]) + # layout sorts variables alphabetically: ('f_t', 'n', 'phi') -> offsets: f_t=[0:1], n=[1:3], phi=[3:5] + f_delta = inc.field("f_t") + n_delta = inc.field("n") + phi_delta = inc.field("phi") + assert isinstance(f_delta, DDArray) and isinstance(n_delta, DDArray) and isinstance(phi_delta, DDArray) + assert float(f_delta.values[0]) == pytest.approx(1.0e-18, rel=1.0e-12) + assert float(phi_delta.values[0]) == pytest.approx(-1.0e-18, rel=1.0e-12) + assert float(phi_delta.values[1]) == pytest.approx(5.0e-18, rel=1.0e-12) + + ec_delta = inc.electrochemical_delta( + p0, + p1, + "n", + "phi", + np.array([[0, 1]], dtype=np.intp), + 0.02585, + potential_sign=-1, + arithmetic=CompensatedArithmetic(), + ) + # dy on 'n' is [-2e-18, 3e-18], dy on 'phi' is [-1e-18, 5e-18] + expected_ec = (3.0e-18 - (-2.0e-18)) + (-1.0) * (5.0e-18 - (-1.0e-18)) / 0.02585 + assert isinstance(ec_delta, DD) + assert float(ec_delta[0]) == pytest.approx(expected_ec, rel=1.0e-11) + + rebased_map, p_rebased = coords.rebase(p1) + assert np.all(p_rebased.y == 0.0) + assert isinstance(p_rebased.state.authority, PairStateAuthority) + assert isinstance(p1.state.authority, PairStateAuthority) + assert np.all(p_rebased.state.authority.dd_field("phi").values == p1.state.authority.dd_field("phi").values) + + codec = AffineInputLiftCodec() + encoded = codec.encode_point(p1) + decoded_map, p_decoded = codec.decode_with_map( + encoded, layout=layout, multiplicative_variables=("n",) + ) + assert decoded_map.layout.identity == layout.identity + assert isinstance(p_decoded.state.authority, PairStateAuthority) + assert np.all(p_decoded.state.authority.dd_field("n").values == p1.state.authority.dd_field("n").values) + + tampered = json.loads(json.dumps(encoded)) + tampered["snapshot"]["represented_fields"]["phi"]["lo"][0] = 0.0 + with pytest.raises(InputLiftCheckpointError): + codec.decode_point(tampered, layout=layout) + + +def test_decode_historical_r1_pair_state_and_tamper_rejection() -> None: + record = json.loads(HISTORICAL_PAIR_FIXTURE.read_text(encoding="utf-8")) + decoded = decode_historical_r1_pair_state(record) + assert len(decoded) == 17 + assert "phi_V" in decoded and "n_m3" in decoded and "occupancy" in decoded + assert isinstance(decoded["phi_V"], DD) + + tampered = json.loads(json.dumps(record)) + tampered["state"]["precision_phi_V_lo"][0] += 1.0e-25 + with pytest.raises(InputLiftCheckpointError): + decode_historical_r1_pair_state(tampered) + + with pytest.raises(ContractError): + PairStateAuthority(layout_identity="x", values={}, anchor_reference="") + + +def test_research_boundary_and_registry_hygiene() -> None: + public_api = json.loads( + (REPO_ROOT / "src" / "solarlab" / "reproducibility" / "PublicAPI.json").read_text( + encoding="utf-8" + ) + ) + allowed_public_imports = set(public_api["public_imports"]) + forbidden_roots = {"perovskite_sim", "solarlab_server", "backend"} + + py_files = sorted(RESEARCH_SRC.rglob("*.py")) + assert py_files, "expected solarlab_research python modules" + + for path in py_files: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + root = alias.name.split(".")[0] + assert root not in forbidden_roots, f"{path} imports forbidden {alias.name}" + if root == "solarlab": + assert alias.name in allowed_public_imports, ( + f"{path} imports {alias.name} missing from PublicAPI.json" + ) + elif isinstance(node, ast.ImportFrom) and node.module: + root = node.module.split(".")[0] + assert root not in forbidden_roots, f"{path} imports forbidden {node.module}" + if root == "solarlab": + for alias in node.names: + assert not alias.name.startswith("_"), ( + f"{path} imports private symbol {node.module}.{alias.name}" + ) + fq = f"{node.module}.{alias.name}" + assert ( + node.module in allowed_public_imports or fq in allowed_public_imports + ), f"{path} import {fq} not declared in PublicAPI.json" + # Precision injection must NOT register PhysicsModel / ModelDefinition. + if path.is_relative_to(RESEARCH_SRC / "precision"): + assert alias.name not in {"ModelDefinition", "ModelRegistry"}, ( + f"{path} must not register physics models ({alias.name})" + ) + elif isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name): + if node.value.id == "solarlab": + assert not node.attr.startswith("_"), f"{path} accesses private solarlab.{node.attr}" diff --git a/tests/unit/research/test_r1_contracts_and_provenance.py b/tests/unit/research/test_r1_contracts_and_provenance.py new file mode 100644 index 00000000..70b41be1 --- /dev/null +++ b/tests/unit/research/test_r1_contracts_and_provenance.py @@ -0,0 +1,307 @@ +"""Unit tests for ``solarlab_research.r1`` contracts/provenance and CLI scripts (P07-01, P07-02). + +Covers: +* Frozen 16-item V53 certificate limits, solver budgets, relative engineering limits, + controls ``A-D``, and 13-channel operator schema validator. +* 12-per-decade observation grid and conservative ``(4, 8, 16)`` substep row counts + (``3727`` on full 100 s window; ``59`` on 2-interval short window). +* ``R1StudyRequest`` hashing/tamper rejection and strict IDA ``R1-L2`` exclusion (``P07-02.4``) + plus short-window non-qualification. +* Immutable ``ReleaseBundle`` provenance verification (``scientific_qualification=False``) + and materialized bundle directory roundtrip. +* Non-relabeling historical readers for ``R1CommonStateV1``, ``R1CommonStatePairV2``, + and ``R1FailureWitnessV1.json`` (preserving ``step309_failed`` status). +* Module CLI entrypoints under ``solarlab_research.scripts``. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest + +from solarlab.reproducibility.release import write_release_bundle + +from solarlab_research.r1 import ( + R1_CONSERVATIVE_SUBSTEPS, + R1_CONTROLS, + R1_FULL_WINDOW_EXPECTED_ROWS, + R1_OPERATOR_CHANNELS, + R1_RELATIVE_ENGINEERING_LIMITS, + R1_SOLVER_BUDGETS, + R1_V53_CERTIFICATE_LIMITS, + assess_r1_qualification, + build_r1_study_request, + evaluate_v53_certificate, + expected_substep_rows, + load_r1_study_request, + load_verified_release_bundle, + observation_times_12_per_decade, + read_historical_r1_artifact, + synthetic_research_release_bundle, + validate_operator_channel_packet, + verify_historical_r1_failure_witness, + verify_r1_release_source, + verify_r1_study_request, +) +from solarlab_research.scripts import ( + cbo_scan as cbo_scan_cli, + r1_short_window as r1_short_window_cli, + r1_verify_sources as r1_verify_sources_cli, +) + +REPO_ROOT = Path(__file__).resolve().parents[3] +HIST_COMMON_V1 = REPO_ROOT / "tests" / "refactor" / "fixtures" / "r1_common_state_preparation.json" +HIST_PAIR_V2 = ( + REPO_ROOT / "tests" / "refactor" / "fixtures" / "r1_pair_common_state_preparation.json" +) +HIST_WITNESS = REPO_ROOT / "tests" / "fixtures" / "refactor" / "R1FailureWitnessV1.json" + + +def test_frozen_v53_limits_channels_and_observation_row_counts() -> None: + assert len(R1_V53_CERTIFICATE_LIMITS) == 16 + assert R1_V53_CERTIFICATE_LIMITS["nonlinear_residual"] == 0.05 + assert R1_V53_CERTIFICATE_LIMITS["analytic_jacobian_error"] == 3.0e-4 + assert len(R1_OPERATOR_CHANNELS) == 13 + assert set(R1_CONTROLS) == {"A", "B", "C", "D"} + assert R1_CONTROLS["A"] == {"nu_I": 0, "nu_t": 0} + assert R1_CONTROLS["D"] == {"nu_I": 1, "nu_t": 1} + assert R1_SOLVER_BUDGETS["maximum_newton_iterations"] == 100 + assert R1_RELATIVE_ENGINEERING_LIMITS["elapsed_ratio"] == 5.0 + + full_times = observation_times_12_per_decade() + assert full_times[0] == 0.0 + assert full_times[1] == 1.0e-9 + assert full_times[-1] == 100.0 + assert len(full_times) == 134 # 0.0 + 133 log points across 11 decades + assert expected_substep_rows(full_times, R1_CONSERVATIVE_SUBSTEPS) == R1_FULL_WINDOW_EXPECTED_ROWS + + short_times = (0.0, 1.0e-9, 1.0e-8) + assert expected_substep_rows(short_times, R1_CONSERVATIVE_SUBSTEPS) == 59 + + passing_metrics = {key: lim * 0.5 for key, lim in R1_V53_CERTIFICATE_LIMITS.items()} + cert = evaluate_v53_certificate(passing_metrics) + assert cert.passed is True + assert cert.failed_items == () + + failing_metrics = {**passing_metrics, "nonlinear_residual": 0.0532305} + cert_fail = evaluate_v53_certificate(failing_metrics) + assert cert_fail.passed is False + assert cert_fail.failed_items == ("nonlinear_residual",) + + valid_packet: dict[str, object] = {ch: np.zeros((59, 2), dtype=float) for ch in R1_OPERATOR_CHANNELS} + shapes = validate_operator_channel_packet(valid_packet, expected_rows=59) + assert len(shapes) == 13 + assert all(sh == (59, 2) for sh in shapes.values()) + + with pytest.raises(ValueError, match="operator packet mismatch"): + validate_operator_channel_packet({k: v for k, v in valid_packet.items() if k != "sheet_charge"}) + with pytest.raises(ValueError, match="row count"): + validate_operator_channel_packet(valid_packet, expected_rows=60) + + +def test_study_request_and_ida_r1_l2_exclusion() -> None: + bundle = synthetic_research_release_bundle() + prep_sha = "a" * 64 + short_req = build_r1_study_request( + study_id="short_test", + control="D", + times_s=(0.0, 1.0e-9, 1.0e-8), + release_bundle_sha256=bundle.sha256, + prepared_device_sha256=prep_sha, + ) + raw = json.dumps(short_req.to_mapping()) + reloaded = load_r1_study_request(raw) + assert reloaded == short_req + + tampered = short_req.to_mapping() + tampered["voltage_step_V"] = 0.01 + with pytest.raises(ValueError, match="digest mismatch"): + verify_r1_study_request(tampered) + + passing_cert = evaluate_v53_certificate({k: v * 0.1 for k, v in R1_V53_CERTIFICATE_LIMITS.items()}) + + # Short-window run passes interface verification ONLY; never claims R1-L2 or R1-L3 + short_qual = assess_r1_qualification( + short_req, + baseline_certificate=passing_cert, + compensated_certificate=passing_cert, + baseline_rows=59, + compensated_rows=59, + interpolated_rows=False, + release_verified=True, + ) + assert short_qual.qualification_level == "short_window_interface_verification_only" + assert short_qual.short_window_interface_verified is True + assert short_qual.r1_l2_certified is False + assert short_qual.r1_l3_device_qualified is False + + # P07-02.4: IDA integrator on full 100 s window is strictly excluded from R1-L2 + full_times = observation_times_12_per_decade() + ida_req = build_r1_study_request( + study_id="ida_comparison", + control="D", + times_s=full_times, + integrator="ida", + release_bundle_sha256=bundle.sha256, + prepared_device_sha256=prep_sha, + ) + ida_qual = assess_r1_qualification( + ida_req, + baseline_certificate=passing_cert, + compensated_certificate=passing_cert, + baseline_rows=R1_FULL_WINDOW_EXPECTED_ROWS, + compensated_rows=R1_FULL_WINDOW_EXPECTED_ROWS, + interpolated_rows=False, + release_verified=True, + ) + assert ida_qual.qualification_level == "unqualified" + assert ida_qual.r1_l2_certified is False + assert ida_qual.r1_l3_device_qualified is False + assert any("P07-02.4" in reason for reason in ida_qual.reasons) + + # Interpolated rows are also rejected even for conservative_backward_euler + be_full_req = build_r1_study_request( + study_id="be_full", + control="D", + times_s=full_times, + integrator="conservative_backward_euler", + release_bundle_sha256=bundle.sha256, + prepared_device_sha256=prep_sha, + ) + interp_qual = assess_r1_qualification( + be_full_req, + baseline_certificate=passing_cert, + compensated_certificate=passing_cert, + baseline_rows=R1_FULL_WINDOW_EXPECTED_ROWS, + compensated_rows=R1_FULL_WINDOW_EXPECTED_ROWS, + interpolated_rows=True, + release_verified=True, + ) + assert interp_qual.r1_l2_certified is False + assert any("interpolated" in reason for reason in interp_qual.reasons) + + +def test_release_bundle_provenance_and_non_relabeling_historical_readers(tmp_path: Path) -> None: + bundle = synthetic_research_release_bundle( + build_source_commit="19c19776ff0b13beb791683697035594718ff317" + ) + bundle_dir = tmp_path / "release_bundle" + write_release_bundle(bundle, bundle_dir) + + loaded = load_verified_release_bundle(bundle_dir, expected_bundle_sha256=bundle.sha256) + binding = verify_r1_release_source( + loaded, + expected_bundle_sha256=bundle.sha256, + inputs={"study": "provenance_test"}, + ) + assert binding.build_source_commit == "19c19776ff0b13beb791683697035594718ff317" + assert binding.scientific_qualification is False + assert ( + binding.job_provenance_envelope["record"]["git_commit"] + == "19c19776ff0b13beb791683697035594718ff317" + ) + assert "scientific_qualification" not in binding.job_provenance_envelope + assert "scientific_qualification" not in binding.job_provenance_envelope["record"] + + with pytest.raises(ValueError, match="differs from expected"): + verify_r1_release_source(loaded, expected_bundle_sha256="f" * 64, inputs={}) + + # Non-relabeling historical readers + s_v1 = read_historical_r1_artifact(HIST_COMMON_V1) + assert s_v1.schema == "R1CommonStateV1" + assert s_v1.relabelled is False + assert s_v1.metadata["intervals"] == 4 + assert s_v1.metadata["node_count"] == 4 + + s_v2 = read_historical_r1_artifact(HIST_PAIR_V2) + assert s_v2.schema == "R1CommonStatePairV2" + assert s_v2.relabelled is False + assert s_v2.metadata["decoded_field_count"] == 17 + expected_seed_sha = json.loads(HIST_PAIR_V2.read_text(encoding="utf-8"))["seed_preparation"]["sha256"] + assert s_v2.metadata["seed_preparation_sha256"] == expected_seed_sha + + witness_audit = verify_historical_r1_failure_witness(HIST_WITNESS) + assert witness_audit.relabelled is False + assert witness_audit.step183_accepted_status == "accepted" + assert witness_audit.step183_failed_status == "failed" + assert witness_audit.step309_original_status == "failed" + assert witness_audit.step309_failure_type == "InterfaceDefectTransientError" + assert witness_audit.step309_nonlinear_residual == pytest.approx(0.0532305) + assert witness_audit.step309_dt_s == pytest.approx(0.00011393063141266287) + + # Attempt to relabel historical step309 residual as passing (<= 0.05) must fail + tampered_witness = json.loads(HIST_WITNESS.read_text(encoding="utf-8")) + tampered_witness["cases"]["step309_failed"]["nonlinear_residual"] = 0.01 + with pytest.raises(ValueError, match="cannot be relabeled as passing"): + verify_historical_r1_failure_witness(json.dumps(tampered_witness)) + + +def test_module_cli_scripts(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + # 1. r1_verify_sources CLI + bundle = synthetic_research_release_bundle() + bundle_dir = tmp_path / "cli_bundle" + write_release_bundle(bundle, bundle_dir) + + rc = r1_verify_sources_cli.main([ + "--historical", + str(HIST_COMMON_V1), + "--historical", + str(HIST_PAIR_V2), + "--witness", + str(HIST_WITNESS), + "--bundle-dir", + str(bundle_dir), + "--expected-bundle-sha256", + bundle.sha256, + ]) + assert rc == 0 + out_sources = json.loads(capsys.readouterr().out) + assert out_sources["schema"] == "solarlab_research.r1_verify_sources_cli.v1" + assert len(out_sources["historical_artifacts"]) == 2 + assert out_sources["witness_audit"]["step309_original_status"] == "failed" + assert out_sources["witness_audit"]["relabelled"] is False + assert out_sources["release_bundle"]["scientific_qualification"] is False + + # 2. cbo_scan CLI (coarse 2-point sweep for fast unit execution) + rc_cbo = cbo_scan_cli.main([ + "--delta-ec", + "0.0", + "0.1", + "--intervals", + "4", + "6", + "4", + "--voltage-points", + "7", + ]) + assert rc_cbo == 0 + out_cbo = json.loads(capsys.readouterr().out) + assert out_cbo["schema"] == "solarlab_research.cbo_scan_cli.v1" + assert out_cbo["complete"] is True + assert len(out_cbo["points"]) == 2 + + # 3. r1_short_window CLI + rc_r1 = r1_short_window_cli.main([ + "--control", + "D", + "--intervals", + "3", + "2", + "--bundle-dir", + str(bundle_dir), + "--expected-bundle-sha256", + bundle.sha256, + ]) + assert rc_r1 == 0 + out_r1 = json.loads(capsys.readouterr().out) + assert out_r1["schema"] == "solarlab_research.r1_short_window_cli.v1" + assert out_r1["baseline_passed"] is True + assert out_r1["compensated_passed"] is True + assert out_r1["baseline_rows"] == 59 + assert out_r1["compensated_rows"] == 59 + assert out_r1["deterministic_replay_match"] is True + assert out_r1["r1_l2_certified"] is False + assert out_r1["r1_l3_device_qualified"] is False From f2c11c1e48e11e88bfb6cb4cdf0cafc5d2b29858 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Mon, 16 Nov 2026 11:58:10 +0800 Subject: [PATCH 27/46] P(device,physics): wire opt-in P08 v2 models, PublicAPI exports, and G8 closeout (P08-05) --- docs/PhysicsCorrectionsScopeV1.md | 39 +- src/solarlab/device/compile_1d.py | 300 +++- src/solarlab/device/compile_2d.py | 108 +- src/solarlab/device/compile_ionic_1d.py | 39 +- src/solarlab/device/compile_ionic_2d.py | 39 +- .../device/compile_multiple_ionic_1d.py | 15 + .../equations/assembly/classical_1d.py | 1 + .../equations/assembly/two_dimensional.py | 34 +- src/solarlab/equations/dc_1d.py | 252 ++- src/solarlab/equations/dc_2d.py | 350 ++++- src/solarlab/equations/field_transport_2d.py | 20 +- src/solarlab/equations/ionic_1d.py | 11 +- src/solarlab/equations/ionic_2d.py | 114 +- .../physics/interface_transport/__init__.py | 32 +- .../physics/interface_transport/thermionic.py | 13 + .../physics/interface_transport/two_sided.py | 250 ++- src/solarlab/physics/presets.py | 438 +++++- src/solarlab/reproducibility/PublicAPI.json | 1381 ++++++++++++++++- .../test_p08_05_compiler_wiring.py | 828 ++++++++++ 19 files changed, 4038 insertions(+), 226 deletions(-) create mode 100644 tests/integration/test_p08_05_compiler_wiring.py diff --git a/docs/PhysicsCorrectionsScopeV1.md b/docs/PhysicsCorrectionsScopeV1.md index 5acfc02c..da14fe66 100644 --- a/docs/PhysicsCorrectionsScopeV1.md +++ b/docs/PhysicsCorrectionsScopeV1.md @@ -1,7 +1,7 @@ # Prospective Physics Corrections Scope (V1) -**Task ID:** `P08-01` (Wave 3 Lead-In — Prospective Physics Questions, Falsification Citations & Executable Counterexamples) -**Baseline Branch / Commit:** `devel` @ `0b03de5028e2124e743483671de890278dd038de` +**Task ID:** `P08-01` (Wave 3 Lead-In — Prospective Physics Questions, Falsification Citations & Executable Counterexamples) +**Baseline Branch / Commit:** `devel` @ `0b03de5028e2124e743483671de890278dd038de` **Executable Witness Suite:** `tests/refactor/test_p08_counterexamples.py` --- @@ -199,3 +199,38 @@ All prospective **physical** corrections (`P`-class) are quarantined into Stage - Core `solarlab` produces typed immutable results and reproducible `RunStore` bundles; ad-hoc plotting scripts remain outside `src/solarlab/`. 4. **`RS` (`R1`) Research Lane Pinning (`V2` `D20`):** - `R1` execution and long-window `G2-R` / `RS-G7` qualification remain pinned to pre-`P08` model versions so prospective `P08` physics updates cannot invalidate or confound historical `R1` long-window evidence. + +--- + +## 7. `P08-05` — Unified Opt-In Compiler Wiring, `v1 -> v2` Version Mapping & Gate `G8` Closeout + +### 7.1 Explicit `v1 -> v2` Model & Compiler Mapping (`P08_MODEL_VERSION_MAPPINGS`) + +`src/solarlab/physics/presets.py` (`P08_MODEL_VERSION_MAPPINGS`, `P08CompilerOptions`, `build_p08_model_registry`, `build_p08_preset`) and `src/solarlab/device/compile_1d.py` (`p08_identity_inputs`) bind every Stage `P08` physics correction to an explicit model-version upgrade (`v1 -> v2`) while keeping all five compilers (`compile_device_1d`, `compile_ionic_device_1d`, `compile_multiple_ionic_device_1d`, `compile_device_2d`, `compile_ionic_device_2d`) **0-ULP / 0-byte manifest-digest invariant** under default `v1`: + +| Item | Family | Pre-`P08` Default (`v1` `ModelRef` & Token) | Prospective Opt-In (`v2` `ModelRef` & Compiler Keyword) | Semantic Delta | +| --- | --- | --- | --- | --- | +| `P08-02a` | `electrostatics_face_permittivity` | `electrostatics.face_permittivity@v1` (`nodal_harmonic_dielectric_v1`) | `electrostatics.face_permittivity@v2` (`dielectric_rule="layer_series_capacitance_v2"`) | Replaces unweighted nodal harmonic face permittivity and shared-node right-layer bleed with exact sub-face material-extent series capacitance $C_f = \varepsilon_0 / (d_L/\varepsilon_L + d_R/\varepsilon_R)$ and 2D cell-parallel lateral permittivity. | +| `P08-02b` | `control_volume_geometry` | `mesh.endpoint_control_volume@v1` (`legacy_mol_integer_endpoint_v1` in 1D; `legacy_twod_half_endpoint_v1` in 2D) | `mesh.endpoint_control_volume@v2` (`geometry_name="physical_half_endpoint_v2"` in 1D; `stack_geometry="physical_half_endpoint_v2"` in 2D) | Binds contact half-cells ($w_0 = dx_0/2, w_{N-1} = dx_{N-1}/2$, $\sum_i w_i = L$) simultaneously across storage, mobile ions, optical generation, Poisson contact displacement, and terminal ports. | +| `P08-02c` | `band_step_differencing` | `transport.band_step_differencing@v1` (`legacy_summed_potential_v1`) | `transport.band_step_differencing@v2` (`band_step_mode="hole_separate_increment_v1"`) | Forms $(\Delta\phi + \Delta\chi_t) + \Delta E_{g,t}$ per face before summation in 1D/2D SG transport so $\sim 5.5\text{ eV}$ valence-band offsets do not quantize sub-mV electrostatic steps in binary64. | +| `P08-03` | `interface_thermionic` | `interface_transport.thermionic_emission@v1` (`legacy_unnormalized_thermionic_v1`) | `prospective_interface_p08@v2` / `prospective_interface_p08_compact_support@v2` (`thermionic_mode="reciprocal_physical_thermionic_v2"`, `combination_mode="harmonic_series" \| "compact_support"`) | Separates unfolded physical band-edge barriers ($\chi_{\text{phys}}, E_{g,\text{phys}}$), per-side DOS activities ($c_L/N_L, c_R/N_R$), reciprocal $\tilde{A}^* = \min(A^*_L, A^*_R)$, transmission $\mathcal{T}$, and cancellation-free `expm1` electrochemical drive across both `deduplicated` and `two_sided_trace` (`statistics="maxwell_boltzmann"`) 1D/2D heterointerfaces. | +| `P08-04` | `optical_generation` | `monochromatic_beer_lambert_1d@v1` (`"beer_lambert"` / coherent `"tmm"` per device declaration) | `spectral_control_volume_beer_lambert@v2` (`optical_model="beer_lambert_spectral"`) | Integrates wavelength-resolved $\alpha_\ell(\lambda) = 4\pi k_\ell(\lambda)/\lambda$ over exact physical control-volume optical depths with closed front-substrate + electrical + transmitted photon budget (`rtol <= 1e-12`). | + +### 7.2 Identity Separation, Certificate Non-Reuse & Historical Disable Tracking + +1. **Zero Drift on Default `v1`:** Calling any of the five compilers with default arguments (or `P08CompilerOptions()`) appends zero new manifest keys and preserves bit-for-bit identical `compiled.identity` SHA-256 digests, numerical residuals, and sparse Jacobians relative to the Wave 2 `N`-baseline (`refactor/wave2-n-baseline` @ `582f019ef5743d43546219590a5ae094ca300594`). +2. **Deterministic `compiled.identity` & `H_physics` Invalidation on `v2`:** Activating any `P08` `v2` selector deterministically mutates both: + - `compiled.identity` (and `interface_model.identity_sha256` / `CompiledIonicDevice{1D,2D}.identity`), preventing `solve_transient`, `solve_impedance`, `solve_ionic_transient`, and `solve_ionic_impedance` from reusing a `v1` steady-state operating point or certificate on a `v2`-compiled device (`ValueError`); and + - `physics_identity(p08_identity_inputs(prepared, implementation, options=...)).sha256` (`H_physics`), while `build_p08_preset(P08CompilerOptions(), sources)` records all five `v2` `ModelRef`s in `historical_disables` so explicit `select_preset(..., overrides=...)` surfaces exact `reenabled_historical_mechanisms` provenance. + +### 7.3 Gate `G8` Closeout Disposition Matrix + +| `G8` Verification Requirement | Disposition | Executable Evidence / Enforcement | +| --- | --- | --- | +| One-commit-per-physics-fix isolation (`P08-01`..`P08-05`) | **Satisfied** | Separate isolated commits on `wave3/ws1-p08-05-compiler-wiring`: `P08-01` (`dab6e1c`), `P08-02a` (`8b00294`), `P08-02b` (`6ace4d0`), `P08-02c` (`521a9fb`), `P08-03` (`b9bec98`), `P08-04` (`958d0cc`), and `P08-05` compiler/registry closeout. | +| Default `v1` 0-byte manifest & numerical parity with `582f019e` | **Satisfied** | `tests/integration/test_p08_05_compiler_wiring.py` pins exact `582f019e` SHA-256 hex digests across 1D (`deduplicated` & `two_sided_trace`), single/dual ionic 1D, 2D, and ionic 2D compilers. | +| End-to-end `v2` 1D/2D DC, BE transient conservation, 0-ULP `Assembled` parity & spatial refinement | **Satisfied** | `test_p08_02_refinement_and_parity.py`, `test_p08_03_heterojunction_detailed_balance.py`, `test_spectral_beer_lambert_stress.py`, and `test_p08_05_compiler_wiring.py`. | +| Preservation of historical `v1` verdicts & failed criteria (`AGENTS.md`) | **Enforced** | `scaps_mirror_v2` `6.024958093130e-3 eV` `legacy_manual_v_bi_contact_offset` remains `inconsistent` (`CONTACT_THERMODYNAMIC_TOLERANCE_EV = 5.0e-3` unrelaxed); historical `Final121` (`4.010735e-4 > 1/3000 A/m^2`), `CND2 V4` strict-scope (`not_passed`), and `R1 V53` step-309 (`failed`) remain unoverwritten. | +| Permanent refusal of falsified closures (`interface_shared_occupancy`, bulk-node Gaussian $E_t$) | **Enforced** | `compile_device_1d`, `compile_device_2d`, and `compile_ionic_device_2d` raise `CapabilityError` pre-solve (`test_p08_counterexamples.py`, `test_p08_03_thermionic_and_contacts.py`, `test_p08_05_compiler_wiring.py`). | +| Decoupled `RS` (`R1`) lane pre-`P08` baseline pinning (`V2` `D20`) | **Enforced** | `RS` remains pinned to `refactor/wave2-n-baseline` @ `582f019ef5743d43546219590a5ae094ca300594`; `solarlab_research.cbo_scan.enforce_pre_p08_cbo_pinning` rejects all `P08_V2_MODEL_REFS` (`InterfaceCBOScanError`) unless `allow_prospective_p08_models=True`. | +| Deferred out-of-`P08` scope (`F14` kinks, dynamic $T(x,t)$ PDE, external `.gen` file loader) | **Demarcated (not counted as `passed`)** | Explicitly documented in §5.2 & §6; non-smooth AC switching manifolds fail closed via `CapabilityError`. | diff --git a/src/solarlab/device/compile_1d.py b/src/solarlab/device/compile_1d.py index dc5f29ee..578c2504 100644 --- a/src/solarlab/device/compile_1d.py +++ b/src/solarlab/device/compile_1d.py @@ -22,10 +22,13 @@ import numpy as np +from solarlab.config.identity import BuildSource, IdentityInputs, ModelInputs +from solarlab.config.model_parameters import device_topology, layer_parameter_source from solarlab.contracts.units import ELEMENTARY_CHARGE_C from solarlab.device.resolved import PreparedDevice, PreparedLayer from solarlab.device.neutral_defects import LITERAL_ABOVE_VB_DOS_REFERENCE_V1, bind_neutral_defects from solarlab.device.optical_generation import bind_optical_generation_1d +from solarlab.discretization.face_average import DIELECTRIC_RULES from solarlab.equations.dc_1d import ( CapabilityError, CompiledDevice1D, @@ -46,7 +49,11 @@ from solarlab.equations.field_transport_1d import FieldTransport1D, bind_field_transport_1d from solarlab.physics.generation.profile import GenerationProfile from solarlab.mesh import ( + GEOMETRY_NAMES, + HALF_ENDPOINT_V1, INTEGER_ENDPOINT_V1, + PHYSICAL_BOUNDARY_TWO_SIDED_V1, + PHYSICAL_HALF_ENDPOINT_V2, RIGHT_LAYER_WINS, TWO_SIDED_TRACE_V1, build_geometry, @@ -87,13 +94,25 @@ from solarlab.physics.generation.spectrum import SpectralPhotonFlux, sample_nk_table from solarlab.physics.interface_transport import ( EquilibriumReferencedSheetCharge, + LEGACY_UNNORMALIZED_THERMIONIC_V1, TE_BARRIER_THRESHOLD_EV, + THERMIONIC_MODEL_VERSIONS, + ThermionicCombinationMode, + ThermionicModelVersion, TwoSidedBulkState, TwoSidedInterfacePhysics, remove_shared_interface_nodes, resolve_layer_richardson, solve_two_sided_interface_qss, ) +from solarlab.physics.presets import ( + P08_MODEL_VERSION_MAPPINGS, + P08_SOURCE_PATHS, + P08CompilerOptions, + build_p08_model_registry, + build_p08_preset, + select_preset, +) from solarlab.physics.recombination.interface import ( InterfaceDefectSpec, build_plane_closure_params, @@ -103,10 +122,23 @@ BulkRecombinationCoefficients, BulkRecombinationReaction, ) +from solarlab.physics.registry import CapabilityContext, Scope +from solarlab.physics.semantic_projection import SemanticProjection from solarlab.physics.transport import legacy_face_diffusivity +from solarlab.physics.transport.electrochemical_flux import ( + BAND_STEP_MODES, + LEGACY_SUMMED_POTENTIAL_V1, +) from solarlab.physics.transport.field_mobility_tangents import FieldMobilityCapabilityError -__all__ = ["CapabilityError", "CompiledDevice1D", "compile_device_1d", "unsupported"] +__all__ = [ + "CapabilityError", + "CompiledDevice1D", + "bind_spectral_beer_lambert_1d", + "compile_device_1d", + "p08_identity_inputs", + "unsupported", +] Q = ELEMENTARY_CHARGE_C InterfaceTopologyName = Literal["deduplicated", "two_sided_trace"] @@ -270,6 +302,8 @@ def _solve_dark_uncharged_two_sided_equilibrium( additional_recombination: LocalRecombinationModel | None, field_transport: FieldTransport1D | None, provisional_specs: Sequence[tuple[int, int, int, int, TraceElectrostatics, TwoSidedInterfacePhysics, float]], + thermionic_mode: ThermionicModelVersion = LEGACY_UNNORMALIZED_THERMIONIC_V1, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, ) -> np.ndarray: """Certify dark (V=0, G=0) charge-off two_sided_trace steady state for equilibrium_referenced.""" uncharged_specs = tuple( @@ -290,6 +324,7 @@ def _solve_dark_uncharged_two_sided_equilibrium( topology="two_sided_trace", identity_sha256="0" * 64, two_sided=uncharged_specs, + thermionic_mode=thermionic_mode, ) prov_dev = CompiledDevice1D( device_id, @@ -312,6 +347,7 @@ def _solve_dark_uncharged_two_sided_equilibrium( capabilities=("ion_free", "classical_1d_dc", "heterointerface_1d"), field_transport=field_transport, interface_model=prov_model, + band_step_mode=band_step_mode, ) try: return solve_equilibrium( @@ -355,6 +391,9 @@ def _bind_interfaces_1d( te_regularization_mode: TERegularizationName, interface_transmission: float, equilibrium_occupancies: Sequence[float] | None, + thermionic_mode: ThermionicModelVersion = LEGACY_UNNORMALIZED_THERMIONIC_V1, + combination_mode: ThermionicCombinationMode | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, ) -> CompiledInterfaceModel1D | None: iface_count = len(layers) - 1 charge_closure = str(settings["interface_charge_closure"]) @@ -407,6 +446,7 @@ def _bind_interfaces_1d( face = idx - 1 left_p = dict(layers[k].parameters) + right_p = dict(layers[k + 1].parameters) a_star_n = resolve_layer_richardson( float(cast(float, left_p["A_star_n"])), float(cast(float, left_p["Nc300"])), @@ -425,21 +465,56 @@ def _bind_interfaces_1d( (bands.physical_electron_affinity_eV[face] + bands.physical_band_gap_eV[face]) - (bands.physical_electron_affinity_eV[face + 1] + bands.physical_band_gap_eV[face + 1]) ) - cap_e = a_star_n > 0.0 and abs(delta_ec) > TE_BARRIER_THRESHOLD_EV - cap_h = a_star_p > 0.0 and abs(delta_ev) > TE_BARRIER_THRESHOLD_EV - if cap_e or cap_h: - te_specs.append( - DeduplicatedThermionicFaceSpec( - interface_index=k, - face=face, - delta_Ec_eV=delta_ec, - delta_Ev_eV=delta_ev, - a_star_n_A_m2_K2=a_star_n, - a_star_p_A_m2_K2=a_star_p, - cap_electron=cap_e, - cap_hole=cap_h, + if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1: + cap_e = a_star_n > 0.0 and abs(delta_ec) > TE_BARRIER_THRESHOLD_EV + cap_h = a_star_p > 0.0 and abs(delta_ev) > TE_BARRIER_THRESHOLD_EV + if cap_e or cap_h: + te_specs.append( + DeduplicatedThermionicFaceSpec( + interface_index=k, + face=face, + delta_Ec_eV=delta_ec, + delta_Ev_eV=delta_ev, + a_star_n_A_m2_K2=a_star_n, + a_star_p_A_m2_K2=a_star_p, + cap_electron=cap_e, + cap_hole=cap_h, + ) ) + else: + a_star_n_r = resolve_layer_richardson( + float(cast(float, right_p["A_star_n"])), + float(cast(float, right_p["Nc300"])), + temp, + ) + a_star_p_r = resolve_layer_richardson( + float(cast(float, right_p["A_star_p"])), + float(cast(float, right_p["Nv300"])), + temp, ) + cap_e = min(a_star_n, a_star_n_r) > 0.0 + cap_h = min(a_star_p, a_star_p_r) > 0.0 + if cap_e or cap_h: + te_specs.append( + DeduplicatedThermionicFaceSpec( + interface_index=k, + face=face, + delta_Ec_eV=delta_ec, + delta_Ev_eV=delta_ev, + a_star_n_A_m2_K2=a_star_n, + a_star_p_A_m2_K2=a_star_p, + cap_electron=cap_e, + cap_hole=cap_h, + a_star_n_right_A_m2_K2=a_star_n_r, + a_star_p_right_A_m2_K2=a_star_p_r, + dos_n_left_m3=float(binding.conduction_dos_m3[face]), + dos_n_right_m3=float(binding.conduction_dos_m3[face + 1]), + dos_p_left_m3=float(binding.valence_dos_m3[face]), + dos_p_right_m3=float(binding.valence_dos_m3[face + 1]), + hole_band_offset_eV=-delta_ev, + transmission=interface_transmission, + ) + ) defect = entry.get("defect") raw_vn = entry.get("v_n") @@ -547,7 +622,7 @@ def _bind_interfaces_1d( if not bare_specs and not defect_specs and not te_specs: return None - manifest = { + manifest: dict[str, Any] = { "schema": "compiled_interface_model_1d_v1", "topology": "deduplicated", "plane_projection": plane_proj, @@ -597,6 +672,30 @@ def _bind_interfaces_1d( for s in te_specs ], } + resolved_comb = ( + None + if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 + else ("harmonic_series" if combination_mode is None else combination_mode) + ) + if thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1: + manifest["thermionic_mode"] = thermionic_mode + manifest["combination_mode"] = resolved_comb + manifest["interface_transmission"] = interface_transmission + manifest["thermionic_faces_v2"] = [ + [ + s.interface_index, + s.face, + s.a_star_n_right_A_m2_K2, + s.a_star_p_right_A_m2_K2, + s.dos_n_left_m3, + s.dos_n_right_m3, + s.dos_p_left_m3, + s.dos_p_right_m3, + s.hole_band_offset_eV, + s.transmission, + ] + for s in te_specs + ] iface_sha = hashlib.sha256( json.dumps(manifest, separators=(",", ":"), allow_nan=False).encode() ).hexdigest() @@ -611,6 +710,8 @@ def _bind_interfaces_1d( plane_generation=plane_gen, te_softness=te_softness, te_regularization_mode=te_regularization_mode, + thermionic_mode=thermionic_mode, + combination_mode=resolved_comb, ) # Two-sided trace topology @@ -739,6 +840,24 @@ def _bind_interfaces_1d( n1_right_m3=n1_r, p1_left_m3=p1_l, p1_right_m3=p1_r, + thermionic_mode=thermionic_mode, + carrier_statistics=( + "fermi_dirac" + if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 + else "maxwell_boltzmann" + ), + a_star_n_left_A_m2_K2=( + None if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 else a_n_l + ), + a_star_n_right_A_m2_K2=( + None if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 else a_n_r + ), + a_star_p_left_A_m2_K2=( + None if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 else a_p_l + ), + a_star_p_right_A_m2_K2=( + None if thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 else a_p_r + ), ) provisional_specs.append((k, face, l_node, r_node, trace_elec, phys, trap_density_m2)) @@ -774,6 +893,8 @@ def _bind_interfaces_1d( additional_recombination=additional_recombination, field_transport=field_transport, provisional_specs=provisional_specs, + thermionic_mode=thermionic_mode, + band_step_mode=band_step_mode, ) count_nodes = geometry.node_count phi_eq = u_dark[:count_nodes] @@ -859,12 +980,24 @@ def _bind_interfaces_1d( ] ) - manifest_ts = { + manifest_ts: dict[str, Any] = { "schema": "compiled_interface_model_1d_v1", "topology": "two_sided_trace", "charge_closure": charge_closure, "two_sided": manifest_two_sided, } + if thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1: + manifest_ts["thermionic_mode"] = thermionic_mode + manifest_ts["carrier_statistics"] = "maxwell_boltzmann" + manifest_ts["two_sided_richardson_sides"] = [ + [ + s.physics.a_star_n_left_A_m2_K2, + s.physics.a_star_n_right_A_m2_K2, + s.physics.a_star_p_left_A_m2_K2, + s.physics.a_star_p_right_A_m2_K2, + ] + for s in two_sided_specs + ] iface_sha = hashlib.sha256( json.dumps(manifest_ts, separators=(",", ":"), allow_nan=False).encode() ).hexdigest() @@ -872,6 +1005,7 @@ def _bind_interfaces_1d( topology="two_sided_trace", identity_sha256=iface_sha, two_sided=tuple(two_sided_specs), + thermionic_mode=thermionic_mode, ) @@ -907,7 +1041,7 @@ def _layer_input(layer: PreparedLayer) -> LayerParameterInput: ) -def _bind_spectral_beer_lambert_1d( +def bind_spectral_beer_lambert_1d( prepared: PreparedDevice, control_volumes: ControlVolumes, ) -> GenerationProfile: @@ -1051,6 +1185,11 @@ def compile_device_1d( interface_transmission: float = 1.0, equilibrium_occupancies: Sequence[float] | None = None, optical_model: OpticalModelName | None = None, + dielectric_rule: str | None = None, + geometry_name: str | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + thermionic_mode: ThermionicModelVersion | None = None, + combination_mode: ThermionicCombinationMode | None = None, ) -> CompiledDevice1D: """Cold compile genuine resolved configuration; no legacy/test execution. @@ -1072,6 +1211,29 @@ def compile_device_1d( "optical_model must be 'beer_lambert', 'beer_lambert_spectral', " "'tmm', or None" ) + if dielectric_rule is not None and dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown dielectric_rule {dielectric_rule!r}") + if geometry_name is not None and geometry_name not in GEOMETRY_NAMES: + raise ValueError(f"unknown geometry_name {geometry_name!r}") + if band_step_mode not in BAND_STEP_MODES: + raise ValueError(f"unknown band_step_mode {band_step_mode!r}") + resolved_thermionic: ThermionicModelVersion = ( + LEGACY_UNNORMALIZED_THERMIONIC_V1 if thermionic_mode is None else thermionic_mode + ) + if resolved_thermionic not in THERMIONIC_MODEL_VERSIONS: + raise ValueError(f"unknown thermionic_mode {thermionic_mode!r}") + if combination_mode is not None and combination_mode not in ( + "harmonic_series", + "compact_support", + "legacy_logistic", + "hard", + ): + raise ValueError(f"unknown combination_mode {combination_mode!r}") + if combination_mode is not None and resolved_thermionic == LEGACY_UNNORMALIZED_THERMIONIC_V1: + raise ValueError( + "combination_mode requires thermionic_mode='reciprocal_physical_thermionic_v2' " + "or 'scaps_effective_velocity_thermionic_v1'" + ) if te_regularization_mode not in ("legacy_logistic", "compact_support"): raise ValueError("te_regularization_mode must be 'legacy_logistic' or 'compact_support'") if isinstance(te_softness, bool) or not math.isfinite(float(te_softness)) or float(te_softness) < 0.0: @@ -1094,6 +1256,17 @@ def compile_device_1d( ) if resolved_topology == "two_sided_trace" and len(layers) < 2: raise CapabilityError("unsupported_classical_1d_dc: two_sided_trace requires at least two electrical layers") + if geometry_name is not None: + if resolved_topology == "deduplicated" and geometry_name in ( + TWO_SIDED_TRACE_V1, + PHYSICAL_BOUNDARY_TWO_SIDED_V1, + ): + raise ValueError("deduplicated topology requires a shared-node geometry") + if resolved_topology == "two_sided_trace" and geometry_name in ( + INTEGER_ENDPOINT_V1, + HALF_ENDPOINT_V1, + ): + raise ValueError("two_sided_trace topology requires a two-sided split geometry") grid = {entry["layer"]: entry for entry in data["electrical_grid"]} if isinstance(intervals_per_layer, bool): @@ -1119,10 +1292,12 @@ def compile_device_1d( base_nodes = multilayer_grid(list(zip(thicknesses, counts)), alpha=alphas) if resolved_topology == "two_sided_trace": nodes = remove_shared_interface_nodes(base_nodes, interface_positions) - geometry = build_geometry(TWO_SIDED_TRACE_V1, nodes, interface_positions) + geom_token = TWO_SIDED_TRACE_V1 if geometry_name is None else geometry_name + geometry = build_geometry(geom_token, nodes, interface_positions) else: nodes = base_nodes - geometry = build_geometry(INTEGER_ENDPOINT_V1, nodes, interface_positions) + geom_token = INTEGER_ENDPOINT_V1 if geometry_name is None else geometry_name + geometry = build_geometry(geom_token, nodes, interface_positions) masks = layer_node_masks(nodes, thicknesses, RIGHT_LAYER_WINS) binding = compile_layer_parameters( nodes, [_layer_input(layer) for layer in layers], @@ -1156,7 +1331,16 @@ def paint(name: str) -> np.ndarray: if np.any(configured <= 0.0) or not np.all(np.isfinite(configured)) or np.max(np.abs(np.log(configured) - log_product)) > 1.0e-10: raise CapabilityError("inconsistent_intrinsic_product: configured ni and physical Nc/Nv/Eg do not share one Maxwell-Boltzmann equilibrium") eps_r_node = paint("eps_r") - poisson = PoissonOperator1D.for_geometry(geometry, eps_r_node) + if dielectric_rule is None and geometry.name != PHYSICAL_HALF_ENDPOINT_V2: + poisson = PoissonOperator1D.for_geometry(geometry, eps_r_node) + else: + layer_eps_r = [float(cast(float, dict(layer.parameters)["eps_r"])) for layer in layers] + poisson = PoissonOperator1D.for_geometry( + geometry, + eps_r_node, + dielectric_rule=dielectric_rule, + layer_eps_r=layer_eps_r, + ) coefficients = BulkRecombinationCoefficients( nodes.size, configured, paint("tau_n"), paint("tau_p"), binding.srh_n1_m3, binding.srh_p1_m3, binding.radiative_coefficient_m3_s, @@ -1177,7 +1361,7 @@ def paint(name: str) -> np.ndarray: elif optical_model == "beer_lambert": generation = BeerLambertBinding(nodes, paint("alpha"), settings["Phi"]).generation_profile(geometry) elif optical_model == "beer_lambert_spectral": - generation = _bind_spectral_beer_lambert_1d(prepared, geometry) + generation = bind_spectral_beer_lambert_1d(prepared, geometry) elif optical_model == "tmm": generation = bind_optical_generation_1d(prepared, geometry).profile elif data["declaration"].get("spectrum") is not None: @@ -1246,6 +1430,9 @@ def contact_material(node: int) -> ContactMaterial: te_regularization_mode=te_regularization_mode, interface_transmission=float(interface_transmission), equilibrium_occupancies=equilibrium_occupancies, + thermionic_mode=resolved_thermionic, + combination_mode=combination_mode, + band_step_mode=band_step_mode, ) extra_id = None if additional_recombination is None else additional_recombination.model_id @@ -1262,6 +1449,18 @@ def contact_material(node: int) -> ContactMaterial: identity_parts += (field_transport.identity_sha256,) if interface_model is not None: identity_parts += (interface_model.identity_sha256,) + if dielectric_rule is not None: + identity_parts += (("dielectric_rule", poisson.dielectric_rule),) + if band_step_mode != LEGACY_SUMMED_POTENTIAL_V1: + identity_parts += (("band_step_mode", band_step_mode),) + if resolved_thermionic != LEGACY_UNNORMALIZED_THERMIONIC_V1 or combination_mode is not None: + identity_parts += ( + ( + "thermionic_mode", + resolved_thermionic, + "harmonic_series" if combination_mode is None else combination_mode, + ), + ) identity = hashlib.sha256(json.dumps( identity_parts, separators=(",", ":"), allow_nan=False, @@ -1283,4 +1482,63 @@ def contact_material(node: int) -> ContactMaterial: capabilities=capabilities, field_transport=field_transport, interface_model=interface_model, + band_step_mode=band_step_mode, + ) + + +def p08_identity_inputs( + prepared: PreparedDevice, + implementation: BuildSource, + *, + options: P08CompilerOptions | None = None, + problem: str = "dc", +) -> IdentityInputs: + """Bind a PreparedDevice and P08 model selection into source-bound IdentityInputs. + + Every P08 V2 option deterministically updates the selected ``ModelRef`` + version (``1 -> 2``) and its immutable source evidence, ensuring ``H_physics`` + (``physics_identity(inputs).sha256``) changes whenever any V2 model is active. + """ + if type(prepared) is not PreparedDevice: + raise ValueError("an actual explicit PreparedDevice is required") + resolved_options = P08CompilerOptions() if options is None else options + by_id = {doc.id: doc for doc in implementation.files} + missing = [path for path in P08_SOURCE_PATHS if path not in by_id] + if missing: + raise ValueError("BuildSource is missing P08 source files: " + ", ".join(missing)) + sources = {path: by_id[path] for path in P08_SOURCE_PATHS} + registry = build_p08_model_registry(sources) + preset = build_p08_preset(resolved_options, sources) + topology = device_topology(prepared) + param_sources = { + Scope("layer", (layer.id,)): layer_parameter_source(layer) + for layer in prepared.layers + if layer.id in topology.electrical_layer_ids + } + context = CapabilityContext( + 1, + problem, + "solarlab_assembled", + "maxwell_boltzmann", + temperature_K=prepared.to_mapping()["settings"]["T"], + ) + selected = select_preset(preset, registry, topology, context, param_sources) + projections = tuple( + SemanticProjection( + ref, + "all_values_v1", + ( + sources[ + mapping.v1_source_path if ref == mapping.v1_model else mapping.v2_source_path + ], + ), + ) + for mapping, ref in zip(P08_MODEL_VERSION_MAPPINGS, resolved_options.active_model_refs()) + ) + return IdentityInputs( + prepared, + selected.selection, + registry, + ModelInputs.from_mappings(defaults=dict(preset.defaults), overrides={}), + projections, ) diff --git a/src/solarlab/device/compile_2d.py b/src/solarlab/device/compile_2d.py index f0de6954..e8234cb0 100644 --- a/src/solarlab/device/compile_2d.py +++ b/src/solarlab/device/compile_2d.py @@ -10,11 +10,12 @@ import hashlib import json +from typing import Literal import numpy as np from solarlab.config.resolve_device import resolve_device -from solarlab.device.compile_1d import compile_device_1d +from solarlab.device.compile_1d import bind_spectral_beer_lambert_1d, compile_device_1d from solarlab.device.grain_2d import bind_grain_regions_2d, grain_declarations from solarlab.device.inputs import DeviceInput from solarlab.device.resolved import PreparedDevice @@ -32,8 +33,25 @@ ) from solarlab.mesh.geometry_2d import RectangularGeometry2D from solarlab.physics.generation.beer_lambert import BeerLambertBinding +from solarlab.physics.interface_transport import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + ThermionicCombinationMode, + ThermionicModelVersion, +) +from solarlab.physics.transport.electrochemical_flux import ( + BAND_STEP_MODES, + LEGACY_SUMMED_POTENTIAL_V1, +) from solarlab.units import normalize_quantity +__all__ = [ + "CLASSICAL_2D_CONTACTS_V1", + "CLASSICAL_2D_DC_V1", + "CLASSICAL_2D_PERIODIC_CONTACTS_V1", + "CLASSICAL_2D_PERIODIC_DC_V1", + "compile_device_2d", +] + CLASSICAL_2D_DC_V1 = "classical_mb_fixed_reservoir_neumann_2d_dc_v1" CLASSICAL_2D_CONTACTS_V1 = "classical_mb_carrier_exchange_neumann_2d_dc_v1" CLASSICAL_2D_PERIODIC_DC_V1 = "classical_mb_fixed_reservoir_periodic_2d_dc_v1" @@ -47,6 +65,11 @@ def compile_device_2d( *, dielectric_rule: str | None = None, stack_geometry: str = HALF_ENDPOINT_V1, + geometry_name: str | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + thermionic_mode: ThermionicModelVersion | None = None, + combination_mode: ThermionicCombinationMode | None = None, + optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, ) -> CompiledDevice2D: """Compile without a nonlinear solve or inferred geometric defaults. @@ -58,10 +81,26 @@ def compile_device_2d( """ if not isinstance(prepared, PreparedDevice) or not isinstance(spatial, JV2DInput): raise TypeError("compile_device_2d requires PreparedDevice and typed JV2DInput geometry") - if stack_geometry not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2}: - raise ValueError(f"unsupported 2D stack_geometry {stack_geometry!r}") + if geometry_name is not None: + if geometry_name not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2}: + raise ValueError(f"unsupported 2D geometry_name {geometry_name!r}") + if stack_geometry != HALF_ENDPOINT_V1 and stack_geometry != geometry_name: + raise ValueError("stack_geometry and geometry_name disagree") + effective_stack_geometry = geometry_name + else: + effective_stack_geometry = stack_geometry + if effective_stack_geometry not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2}: + raise ValueError(f"unsupported 2D stack_geometry {effective_stack_geometry!r}") + if band_step_mode not in BAND_STEP_MODES: + raise ValueError(f"unknown 2D band_step_mode {band_step_mode!r}") + if optical_model is not None and optical_model not in ( + "beer_lambert", + "beer_lambert_spectral", + "tmm", + ): + raise ValueError(f"unknown 2D optical_model {optical_model!r}") resolved_dielectric = ( - (LAYER_SERIES_CAPACITANCE_V2 if stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 else NODAL_HARMONIC_DIELECTRIC_V1) + (LAYER_SERIES_CAPACITANCE_V2 if effective_stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 else NODAL_HARMONIC_DIELECTRIC_V1) if dielectric_rule is None else dielectric_rule ) @@ -78,15 +117,22 @@ def compile_device_2d( raise ValueError("Ny_per_layer must be at least two intervals") data = prepared.to_mapping() spectral = data["declaration"].get("spectrum") is not None + scalar_override = optical_model == "beer_lambert" if data["declaration"].get("fixed_generation") is not None: raise CapabilityError("unsupported_classical_2d_dc: spectral/fixed optical generation is not bound") + if optical_model in ("beer_lambert_spectral", "tmm") and not spectral: + raise CapabilityError(f"unsupported_classical_2d_dc: optical_model={optical_model!r} requires an explicit spectrum") if data["settings"]["band_grading"]: raise CapabilityError("unsupported_classical_2d_dc: graded bands are outside this first slice") - for layer in prepared.layers: + for idx_layer, layer in enumerate(prepared.layers): p = dict(layer.parameters) - if p["incoherent"]: + if p["incoherent"] and not (optical_model == "beer_lambert_spectral" and idx_layer == 0): raise CapabilityError("unsupported_classical_2d_dc: layers." + layer.id + ".incoherent optics is not bound") - if layer.role == "substrate" or (not spectral and (layer.optical is not None or p["n_optical"] is not None)): + if layer.role == "substrate" or ( + not spectral + and not scalar_override + and (layer.optical is not None or p["n_optical"] is not None) + ): raise CapabilityError("unsupported_classical_2d_dc: optical-only/index layers are not bound") if any(p[name] != 0.0 for name in ("pf_gamma_n", "pf_gamma_p")): raise CapabilityError("unsupported_classical_2d_dc: field-dependent carrier mobility is not bound") @@ -101,14 +147,37 @@ def compile_device_2d( "source_prepared_sha256": prepared.content_sha256, "coefficient_prepared_sha256": column_prepared.content_sha256, "removed_declaration": "grain_boundaries", "used_as_2d_result": False}, sort_keys=True).encode() - column = compile_device_1d(column_prepared, intervals_per_layer=(spatial.Ny_per_layer,) * len(prepared.layers)) + has_column_p08 = ( + geometry_name is not None + or band_step_mode != LEGACY_SUMMED_POTENTIAL_V1 + or (thermionic_mode is not None and thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1) + or combination_mode is not None + or optical_model is not None + ) + if has_column_p08: + column = compile_device_1d( + column_prepared, + intervals_per_layer=(spatial.Ny_per_layer,) * len(prepared.layers), + dielectric_rule=dielectric_rule, + geometry_name=( + PHYSICAL_HALF_ENDPOINT_V2 + if effective_stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 + else None + ), + band_step_mode=band_step_mode, + thermionic_mode=thermionic_mode, + combination_mode=combination_mode, + optical_model=optical_model, + ) + else: + column = compile_device_1d(column_prepared, intervals_per_layer=(spatial.Ny_per_layer,) * len(prepared.layers)) if column.recombination.explicit_defects is not None: raise CapabilityError("unsupported_classical_2d_dc: explicit defect populations are not bound") length = normalize_quantity(spatial.lateral_length, "m") interface_positions = [plane.position_m for plane in column.geometry.interfaces] y_geometry = ( physical_half_endpoint_geometry(column.nodes_m, interface_positions) - if stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 + if effective_stack_geometry == PHYSICAL_HALF_ENDPOINT_V2 else half_endpoint_geometry(column.nodes_m, interface_positions) ) geometry = RectangularGeometry2D( @@ -118,9 +187,16 @@ def compile_device_2d( for layer, mask in zip(prepared.layers, column.parameters.layer_masks): values = dict(layer.parameters) alpha[mask], eps[mask] = values["alpha"], values["eps_r"] - optical = bind_optical_generation_2d(prepared, geometry) if spectral else None - generation = (BeerLambertBinding(column.nodes_m, alpha, data["settings"]["Phi"]).generation_profile(y_geometry) - if optical is None else optical.optical_y.profile) + if optical_model == "beer_lambert_spectral": + optical = None + generation = bind_spectral_beer_lambert_1d(prepared, y_geometry) + elif optical_model == "beer_lambert": + optical = None + generation = BeerLambertBinding(column.nodes_m, alpha, data["settings"]["Phi"]).generation_profile(y_geometry) + else: + optical = bind_optical_generation_2d(prepared, geometry) if (spectral or optical_model == "tmm") else None + generation = (BeerLambertBinding(column.nodes_m, alpha, data["settings"]["Phi"]).generation_profile(y_geometry) + if optical is None else optical.optical_y.profile) grains = bind_grain_regions_2d(prepared, spatial, geometry) faceD = [] for carrier in ("electron", "hole"): @@ -151,9 +227,13 @@ def compile_device_2d( identity = hashlib.sha256(json.dumps((identity, optical.identity_sha256), separators=(",", ":")).encode()).hexdigest() if transport is not None: identity = hashlib.sha256(json.dumps((identity, transport.identity_sha256), separators=(",", ":")).encode()).hexdigest() - if stack_geometry != HALF_ENDPOINT_V1: + if effective_stack_geometry != HALF_ENDPOINT_V1: + identity = hashlib.sha256( + json.dumps((identity, "stack_geometry", effective_stack_geometry), separators=(",", ":")).encode() + ).hexdigest() + if optical_model is not None: identity = hashlib.sha256( - json.dumps((identity, "stack_geometry", stack_geometry), separators=(",", ":")).encode() + json.dumps((identity, "optical_model", optical_model), separators=(",", ":")).encode() ).hexdigest() layer_permittivity_y: tuple[float, ...] | None = None if resolved_dielectric != NODAL_HARMONIC_DIELECTRIC_V1: diff --git a/src/solarlab/device/compile_ionic_1d.py b/src/solarlab/device/compile_ionic_1d.py index 3cc59db3..3682dde5 100644 --- a/src/solarlab/device/compile_ionic_1d.py +++ b/src/solarlab/device/compile_ionic_1d.py @@ -21,12 +21,22 @@ from solarlab.device.resolved import PreparedDevice from solarlab.equations.dc_1d import CapabilityError, TERegularizationName from solarlab.equations.ionic_1d import CompiledIonicDevice1D -from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry import ( + PHYSICAL_HALF_ENDPOINT_V2, + half_endpoint_geometry, + physical_half_endpoint_geometry, +) from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature +from solarlab.physics.interface_transport import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + ThermionicCombinationMode, + ThermionicModelVersion, +) from solarlab.physics.ions import ( DIFFUSION_ONLY_STERIC_V1, HISTORICAL_OCCUPANCY_CLIP, HISTORICAL_STERIC_FLOOR, WHOLE_FLUX_STERIC_V1, ) +from solarlab.physics.transport.electrochemical_flux import LEGACY_SUMMED_POTENTIAL_V1 __all__ = ["CompiledIonicDevice1D", "compile_ionic_device_1d", "ION_INPUTS"] ION_INPUTS = ("P0", "P0_neg", "D_ion", "D_ion_neg", "P_lim", "P_lim_neg", "E_a_ion") @@ -39,6 +49,11 @@ def compile_ionic_device_1d( te_softness: float = 0.02, te_regularization_mode: TERegularizationName = "legacy_logistic", optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, + dielectric_rule: str | None = None, + geometry_name: str | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + thermionic_mode: ThermionicModelVersion | None = None, + combination_mode: ThermionicCombinationMode | None = None, ) -> CompiledIonicDevice1D: """Compile independent or shared finite-site ions in one blocking layer. @@ -126,6 +141,11 @@ def compile_ionic_device_1d( te_softness=te_softness, te_regularization_mode=te_regularization_mode, optical_model=optical_model, + dielectric_rule=dielectric_rule, + geometry_name=geometry_name, + band_step_mode=band_step_mode, + thermionic_mode=thermionic_mode, + combination_mode=combination_mode, ) domain_index = layers.index(domain_layer) left = 0 if domain_index == 0 else component.geometry.interfaces[domain_index - 1].shared_node @@ -133,7 +153,11 @@ def compile_ionic_device_1d( if left is None or right is None: raise CapabilityError("first_ionic_1d: domain endpoints require actual shared electrostatic nodes") indices: np.ndarray = np.arange(left, right + 1, dtype=np.intp) - ion_geometry = half_endpoint_geometry(component.nodes_m[indices]) + ion_geometry = ( + physical_half_endpoint_geometry(component.nodes_m[indices]) + if component.geometry.name == PHYSICAL_HALF_ENDPOINT_V2 + else half_endpoint_geometry(component.nodes_m[indices]) + ) count = ion_geometry.node_count scaled_diffusion = ion_diffusivity_at_temperature(diffusion, component.parameters.temperature_K, activation) if not math.isfinite(scaled_diffusion) or scaled_diffusion < 0.0: @@ -205,6 +229,17 @@ def compile_ionic_device_1d( ion_species=["positive", "negative"], ion_species_count=2) if optical_model is not None: manifest["electronic_component"]["optical_model"] = optical_model + if dielectric_rule is not None: + manifest["electronic_component"]["dielectric_rule"] = component.poisson.dielectric_rule + if band_step_mode != LEGACY_SUMMED_POTENTIAL_V1: + manifest["electronic_component"]["band_step_mode"] = band_step_mode + if thermionic_mode is not None and thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1: + manifest["electronic_component"]["thermionic_mode"] = thermionic_mode + manifest["electronic_component"]["combination_mode"] = ( + "harmonic_series" if combination_mode is None else combination_mode + ) + elif combination_mode is not None: + manifest["electronic_component"]["combination_mode"] = combination_mode encoded = json.dumps(manifest, sort_keys=True, separators=(",", ":"), allow_nan=False) identity = hashlib.sha256(encoded.encode()).hexdigest() return CompiledIonicDevice1D( diff --git a/src/solarlab/device/compile_ionic_2d.py b/src/solarlab/device/compile_ionic_2d.py index fe5a1304..7d619ae1 100644 --- a/src/solarlab/device/compile_ionic_2d.py +++ b/src/solarlab/device/compile_ionic_2d.py @@ -12,7 +12,7 @@ import hashlib import json import math -from typing import Any, cast +from typing import Any, Literal, cast import numpy as np from numpy.typing import NDArray @@ -27,11 +27,21 @@ CompiledIonicDevice2D, RadiativeReabsorptionSpec2D, TwoSidedInterfaceSRHCoupling2D, ) from solarlab.experiments.two_dimensional.inputs import JV2DInput -from solarlab.mesh.geometry import half_endpoint_geometry +from solarlab.mesh.geometry import ( + HALF_ENDPOINT_V1, + PHYSICAL_HALF_ENDPOINT_V2, + half_endpoint_geometry, + physical_half_endpoint_geometry, +) from solarlab.mesh.geometry_2d import RectangularGeometry2D from solarlab.mesh.grid import LEFT_LAYER_WINS, node_owner from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature +from solarlab.physics.interface_transport import ( + ThermionicCombinationMode, + ThermionicModelVersion, +) from solarlab.physics.ions import DIFFUSION_ONLY_STERIC_V1, WHOLE_FLUX_STERIC_V1 +from solarlab.physics.transport.electrochemical_flux import LEGACY_SUMMED_POTENTIAL_V1 __all__ = [ "CompiledIonicDevice2D", @@ -267,6 +277,13 @@ def compile_ionic_device_2d( ion_domain_layer: str | None = None, ion_domain_endpoints: tuple[str, str] | None = None, enable_radiative_reabsorption: bool | None = None, + dielectric_rule: str | None = None, + stack_geometry: str = HALF_ENDPOINT_V1, + geometry_name: str | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + thermionic_mode: ThermionicModelVersion | None = None, + combination_mode: ThermionicCombinationMode | None = None, + optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, ) -> CompiledIonicDevice2D: """Compile a 2D single-positive-ion device with four-side blocking boundaries.""" if not isinstance(prepared, PreparedDevice) or not isinstance(spatial, JV2DInput): @@ -380,7 +397,17 @@ def compile_ionic_device_2d( lateral_bc=spatial.lateral_bc, microstructure=spatial.microstructure, ) - electronic_2d = compile_device_2d(component_prepared, geometry_spatial) + electronic_2d = compile_device_2d( + component_prepared, + geometry_spatial, + dielectric_rule=dielectric_rule, + stack_geometry=stack_geometry, + geometry_name=geometry_name, + band_step_mode=band_step_mode, + thermionic_mode=thermionic_mode, + combination_mode=combination_mode, + optical_model=optical_model, + ) if any(ch.kind != "fixed_reservoir" for ch in electronic_2d.column.channels): raise CapabilityError( "selective_robin_ionic_2d_unsupported: 2D mobile-ion requires ohmic fixed-reservoir contacts" @@ -400,7 +427,11 @@ def compile_ionic_device_2d( if left is None or right is None: raise CapabilityError("ionic_2d: domain endpoints require shared electrostatic stack nodes") row_indices: NDArray[np.intp] = np.arange(left, right + 1, dtype=np.intp) - ion_y_geometry = half_endpoint_geometry(electronic_2d.column.nodes_m[row_indices]) + ion_y_geometry = ( + physical_half_endpoint_geometry(electronic_2d.column.nodes_m[row_indices]) + if electronic_2d.column.geometry.name == PHYSICAL_HALF_ENDPOINT_V2 + else half_endpoint_geometry(electronic_2d.column.nodes_m[row_indices]) + ) ion_geometry = RectangularGeometry2D(electronic_2d.geometry.x_m, ion_y_geometry, lateral_bc="neumann") ion_count = ion_geometry.node_count ion_face_count = ion_geometry.face_spacing_m.size diff --git a/src/solarlab/device/compile_multiple_ionic_1d.py b/src/solarlab/device/compile_multiple_ionic_1d.py index 4dc9c61c..98e3a754 100644 --- a/src/solarlab/device/compile_multiple_ionic_1d.py +++ b/src/solarlab/device/compile_multiple_ionic_1d.py @@ -15,6 +15,11 @@ from solarlab.equations.dc_1d import CapabilityError, TERegularizationName from solarlab.equations.ionic_1d import CompiledIonicDevice1D from solarlab.equations.multiple_ionic_1d import CompiledMultipleIonicDevice1D +from solarlab.physics.interface_transport import ( + ThermionicCombinationMode, + ThermionicModelVersion, +) +from solarlab.physics.transport.electrochemical_flux import LEGACY_SUMMED_POTENTIAL_V1 __all__ = ["CompiledMultipleIonicDevice1D", "compile_multiple_ionic_device_1d"] @@ -25,6 +30,11 @@ def compile_multiple_ionic_device_1d( te_softness: float = 0.02, te_regularization_mode: TERegularizationName = "legacy_logistic", optical_model: Literal["beer_lambert", "beer_lambert_spectral", "tmm"] | None = None, + dielectric_rule: str | None = None, + geometry_name: str | None = None, + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1, + thermionic_mode: ThermionicModelVersion | None = None, + combination_mode: ThermionicCombinationMode | None = None, ) -> CompiledMultipleIonicDevice1D: """Exactly two layer-wide blocking domains separated by inactive material. @@ -83,6 +93,11 @@ def compile_multiple_ionic_device_1d( te_softness=te_softness, te_regularization_mode=te_regularization_mode, optical_model=optical_model, + dielectric_rule=dielectric_rule, + geometry_name=geometry_name, + band_step_mode=band_step_mode, + thermionic_mode=thermionic_mode, + combination_mode=combination_mode, ) if components: if component.electronic_component.identity != components[0].electronic_component.identity: diff --git a/src/solarlab/equations/assembly/classical_1d.py b/src/solarlab/equations/assembly/classical_1d.py index 9e4c459f..dc9d36cf 100644 --- a/src/solarlab/equations/assembly/classical_1d.py +++ b/src/solarlab/equations/assembly/classical_1d.py @@ -334,6 +334,7 @@ def fluxes(self, state: EvaluationState) -> CarrierFaceFluxes: device.parameters.band_structure, electron_electrochemical_step=np.diff(state.block(ELECTRON)), hole_electrochemical_step=-np.diff(state.block(HOLE)), + band_step_mode=device.band_step_mode, ) def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: diff --git a/src/solarlab/equations/assembly/two_dimensional.py b/src/solarlab/equations/assembly/two_dimensional.py index aaa043a4..57dd136e 100644 --- a/src/solarlab/equations/assembly/two_dimensional.py +++ b/src/solarlab/equations/assembly/two_dimensional.py @@ -40,7 +40,11 @@ FaceValue, FieldValues, LocalValue, OperatingInputs, Term, TermValue, ) from solarlab.equations.assembly.weighted import MEASURE -from solarlab.equations.dc_2d import CompiledDevice2D +from solarlab.equations.dc_2d import ( + CompiledDevice2D, + evaluate_2d_carrier_face_fluxes, + has_prospective_2d_transport, +) from solarlab.physics.contacts.boundary_flux import boundary_particle_flux from solarlab.physics.contacts.exchange import CarrierExchangeChannel from solarlab.physics.recombination.bulk import RecombinationRate @@ -204,6 +208,10 @@ def fluxes(self, state: EvaluationState) -> CarrierFaceFluxes: d = self.device phi = state.field("potential_V") n, p = _density(state, ELECTRON), _density(state, HOLE) + if has_prospective_2d_transport(d): + return evaluate_2d_carrier_face_fluxes( + d, phi, n, p, state.block(ELECTRON), state.block(HOLE), derivatives=False + ).fluxes left, right = d.geometry.contract_geometry.pairs.T potentials = d.band_structure.transport_potentials(phi) electron_step = state.block(ELECTRON)[right] - state.block(ELECTRON)[left] @@ -228,6 +236,30 @@ def fluxes(self, state: EvaluationState) -> CarrierFaceFluxes: def evaluate(self, state: EvaluationState, *, derivatives: bool) -> Mapping[str, TermValue]: d = self.device + if has_prospective_2d_transport(d): + ev = evaluate_2d_carrier_face_fluxes( + d, + state.field("potential_V"), + _density(state, ELECTRON), + _density(state, HOLE), + state.block(ELECTRON), + state.block(HOLE), + derivatives=derivatives, + ) + if not derivatives: + return {ELECTRON: FaceValue(ev.fluxes.electron.flux), HOLE: FaceValue(ev.fluxes.hole.flux)} + return { + ELECTRON: FaceValue( + ev.fluxes.electron.flux, + {POTENTIAL: ev.e_phi_left, ELECTRON: ev.e_z_left}, + {POTENTIAL: ev.e_phi_right, ELECTRON: ev.e_z_right}, + ), + HOLE: FaceValue( + ev.fluxes.hole.flux, + {POTENTIAL: ev.h_phi_left, HOLE: ev.h_z_left}, + {POTENTIAL: ev.h_phi_right, HOLE: ev.h_z_right}, + ), + } fluxes = self.fluxes(state) if not derivatives: return {ELECTRON: FaceValue(fluxes.electron.flux), HOLE: FaceValue(fluxes.hole.flux)} diff --git a/src/solarlab/equations/dc_1d.py b/src/solarlab/equations/dc_1d.py index 2e62d5aa..886da2d9 100644 --- a/src/solarlab/equations/dc_1d.py +++ b/src/solarlab/equations/dc_1d.py @@ -50,9 +50,15 @@ from solarlab.physics.generation.profile import GenerationProfile from solarlab.physics.interface_transport import ( EquilibriumReferencedSheetCharge, + LEGACY_UNNORMALIZED_THERMIONIC_V1, + THERMIONIC_MODEL_VERSIONS, + ThermionicCombinationMode, + ThermionicModelVersion, TwoSidedBulkState, TwoSidedInterfacePhysics, cap_particle_flux_thermionic, + combine_sg_and_reciprocal_thermionic_flux, + reciprocal_thermionic_flux_m2_s, solve_charged_two_sided_interface_qss, solve_two_sided_interface_qss, ) @@ -67,8 +73,10 @@ ) from solarlab.physics.recombination.reaction import BulkRecombinationReaction from solarlab.physics.transport.electrochemical_flux import ( + BAND_STEP_MODES, CarrierFaceFlux, CarrierFaceFluxes, + LEGACY_SUMMED_POTENTIAL_V1, carrier_particle_fluxes, ) @@ -176,6 +184,14 @@ class DeduplicatedThermionicFaceSpec: a_star_p_A_m2_K2: float cap_electron: bool cap_hole: bool + a_star_n_right_A_m2_K2: float | None = None + a_star_p_right_A_m2_K2: float | None = None + dos_n_left_m3: float | None = None + dos_n_right_m3: float | None = None + dos_p_left_m3: float | None = None + dos_p_right_m3: float | None = None + hole_band_offset_eV: float | None = None + transmission: float = 1.0 @dataclass(frozen=True) @@ -284,6 +300,19 @@ class CompiledInterfaceModel1D: plane_generation: bool = False te_softness: float = 0.02 te_regularization_mode: TERegularizationName = "legacy_logistic" + thermionic_mode: ThermionicModelVersion = LEGACY_UNNORMALIZED_THERMIONIC_V1 + combination_mode: ThermionicCombinationMode | None = None + + def __post_init__(self) -> None: + if self.thermionic_mode not in THERMIONIC_MODEL_VERSIONS: + raise ValueError(f"unknown thermionic_mode {self.thermionic_mode!r}") + if self.combination_mode is not None and self.combination_mode not in ( + "harmonic_series", + "compact_support", + "legacy_logistic", + "hard", + ): + raise ValueError(f"unknown combination_mode {self.combination_mode!r}") @property def has_carrier_port(self) -> bool: @@ -316,6 +345,8 @@ def evaluate_state( zn = u[count:2 * count] zp = u[2 * count:] + ec_n_steps = np.diff(zn) + ec_p_steps = -np.diff(zp) base = carrier_particle_fluxes( device.nodes_m, phi, @@ -325,15 +356,20 @@ def evaluate_state( hole_diffusivity, thermal, device.parameters.band_structure, - electron_electrochemical_step=np.diff(zn), - hole_electrochemical_step=-np.diff(zp), + electron_electrochemical_step=ec_n_steps, + hole_electrochemical_step=ec_p_steps, + band_step_mode=device.band_step_mode, ) e_flux = np.array(base.electron.flux, dtype=float, copy=True) e_ld = np.array(base.electron.left_density_derivative, dtype=float, copy=True) e_rd = np.array(base.electron.right_density_derivative, dtype=float, copy=True) + e_lpot = np.array(base.electron.left_potential_derivative, dtype=float, copy=True) + e_rpot = np.array(base.electron.right_potential_derivative, dtype=float, copy=True) h_flux = np.array(base.hole.flux, dtype=float, copy=True) h_ld = np.array(base.hole.left_density_derivative, dtype=float, copy=True) h_rd = np.array(base.hole.right_density_derivative, dtype=float, copy=True) + h_lpot = np.array(base.hole.left_potential_derivative, dtype=float, copy=True) + h_rpot = np.array(base.hole.right_potential_derivative, dtype=float, copy=True) face_count = count - 1 interior_count = count - 2 @@ -394,70 +430,164 @@ def evaluate_state( occupancies: Vector = np.full(iface_count, np.nan, dtype=float) if self.topology == "deduplicated": + comb_mode: ThermionicCombinationMode = ( + "harmonic_series" if self.combination_mode is None else self.combination_mode + ) for tf in self.thermionic_faces: f = tf.face - if tf.cap_electron: - cap_e = cap_particle_flux_thermionic( - float(e_flux[f]), - n_left_m3=float(n[f]), - n_right_m3=float(n[f + 1]), - delta_barrier_eV=tf.delta_Ec_eV, - temperature_K=temp, - a_star_A_m2_K2=tf.a_star_n_A_m2_K2, - te_softness=self.te_softness, - regularization_mode=self.te_regularization_mode, - ) - e_flux[f] = cap_e.flux_m2_s - e_ld[f] = cap_e.d_flux_d_sg_flux * e_ld[f] + cap_e.d_flux_d_n_left_m_s - e_rd[f] = cap_e.d_flux_d_sg_flux * e_rd[f] + cap_e.d_flux_d_n_right_m_s - if derivatives: - e_left_phi[f] = ( - cap_e.d_flux_d_sg_flux * e_left_phi[f] - + cap_e.d_flux_d_n_left_m_s * float(n[f]) / thermal - ) - e_right_phi[f] = ( - cap_e.d_flux_d_sg_flux * e_right_phi[f] - + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) / thermal + if self.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1: + if tf.cap_electron: + cap_e = cap_particle_flux_thermionic( + float(e_flux[f]), + n_left_m3=float(n[f]), + n_right_m3=float(n[f + 1]), + delta_barrier_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_n_A_m2_K2, + te_softness=self.te_softness, + regularization_mode=self.te_regularization_mode, ) - e_left_zn[f] = ( - cap_e.d_flux_d_sg_flux * e_left_zn[f] - + cap_e.d_flux_d_n_left_m_s * float(n[f]) + e_flux[f] = cap_e.flux_m2_s + e_ld[f] = cap_e.d_flux_d_sg_flux * e_ld[f] + cap_e.d_flux_d_n_left_m_s + e_rd[f] = cap_e.d_flux_d_sg_flux * e_rd[f] + cap_e.d_flux_d_n_right_m_s + if derivatives: + e_left_phi[f] = ( + cap_e.d_flux_d_sg_flux * e_left_phi[f] + + cap_e.d_flux_d_n_left_m_s * float(n[f]) / thermal + ) + e_right_phi[f] = ( + cap_e.d_flux_d_sg_flux * e_right_phi[f] + + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) / thermal + ) + e_left_zn[f] = ( + cap_e.d_flux_d_sg_flux * e_left_zn[f] + + cap_e.d_flux_d_n_left_m_s * float(n[f]) + ) + e_right_zn[f] = ( + cap_e.d_flux_d_sg_flux * e_right_zn[f] + + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) + ) + if tf.cap_hole: + cap_h = cap_particle_flux_thermionic( + float(h_flux[f]), + n_left_m3=float(p[f]), + n_right_m3=float(p[f + 1]), + delta_barrier_eV=tf.delta_Ev_eV, + temperature_K=temp, + a_star_A_m2_K2=tf.a_star_p_A_m2_K2, + te_softness=self.te_softness, + regularization_mode=self.te_regularization_mode, ) - e_right_zn[f] = ( - cap_e.d_flux_d_sg_flux * e_right_zn[f] - + cap_e.d_flux_d_n_right_m_s * float(n[f + 1]) + h_flux[f] = cap_h.flux_m2_s + h_ld[f] = cap_h.d_flux_d_sg_flux * h_ld[f] + cap_h.d_flux_d_n_left_m_s + h_rd[f] = cap_h.d_flux_d_sg_flux * h_rd[f] + cap_h.d_flux_d_n_right_m_s + if derivatives: + h_left_phi[f] = ( + cap_h.d_flux_d_sg_flux * h_left_phi[f] + - cap_h.d_flux_d_n_left_m_s * float(p[f]) / thermal + ) + h_right_phi[f] = ( + cap_h.d_flux_d_sg_flux * h_right_phi[f] + - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) / thermal + ) + h_left_zp[f] = ( + cap_h.d_flux_d_sg_flux * h_left_zp[f] + - cap_h.d_flux_d_n_left_m_s * float(p[f]) + ) + h_right_zp[f] = ( + cap_h.d_flux_d_sg_flux * h_right_zp[f] + - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) + ) + else: + if tf.cap_electron: + te_e = reciprocal_thermionic_flux_m2_s( + float(n[f]), + float(n[f + 1]), + carrier="electron", + phi_left_V=float(phi[f]), + phi_right_V=float(phi[f + 1]), + band_offset_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_left_A_m2_K2=tf.a_star_n_A_m2_K2, + a_star_right_A_m2_K2=tf.a_star_n_right_A_m2_K2, + dos_left_m3=tf.dos_n_left_m3, + dos_right_m3=tf.dos_n_right_m3, + transmission=tf.transmission, + statistics="maxwell_boltzmann", + model_version=self.thermionic_mode, + thermal_voltage_V=thermal, + electrochemical_step=float(ec_n_steps[f]), ) - if tf.cap_hole: - cap_h = cap_particle_flux_thermionic( - float(h_flux[f]), - n_left_m3=float(p[f]), - n_right_m3=float(p[f + 1]), - delta_barrier_eV=tf.delta_Ev_eV, - temperature_K=temp, - a_star_A_m2_K2=tf.a_star_p_A_m2_K2, - te_softness=self.te_softness, - regularization_mode=self.te_regularization_mode, - ) - h_flux[f] = cap_h.flux_m2_s - h_ld[f] = cap_h.d_flux_d_sg_flux * h_ld[f] + cap_h.d_flux_d_n_left_m_s - h_rd[f] = cap_h.d_flux_d_sg_flux * h_rd[f] + cap_h.d_flux_d_n_right_m_s - if derivatives: - h_left_phi[f] = ( - cap_h.d_flux_d_sg_flux * h_left_phi[f] - - cap_h.d_flux_d_n_left_m_s * float(p[f]) / thermal + comb_e = combine_sg_and_reciprocal_thermionic_flux( + float(e_flux[f]), + d_sg_d_phi_left_m2_s_V=float(e_lpot[f]), + d_sg_d_phi_right_m2_s_V=float(e_rpot[f]), + d_sg_d_c_left_m_s=float(e_ld[f]), + d_sg_d_c_right_m_s=float(e_rd[f]), + c_left_m3=float(n[f]), + c_right_m3=float(n[f + 1]), + thermionic=te_e, + combination_mode=comb_mode, + te_softness=self.te_softness, ) - h_right_phi[f] = ( - cap_h.d_flux_d_sg_flux * h_right_phi[f] - - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) / thermal + e_flux[f] = comb_e.flux_m2_s + e_ld[f] = comb_e.d_flux_d_c_left_m_s + e_rd[f] = comb_e.d_flux_d_c_right_m_s + e_lpot[f] = comb_e.d_flux_d_phi_left_m2_s_V + e_rpot[f] = comb_e.d_flux_d_phi_right_m2_s_V + if derivatives: + te_qf_phi_l = (te_e.right_barrier_weight / thermal) * te_e.flux_m2_s + te_qf_phi_r = (te_e.left_barrier_weight / thermal) * te_e.flux_m2_s + e_left_phi[f] = comb_e.sg_weight * e_left_phi[f] + comb_e.te_weight * te_qf_phi_l + e_right_phi[f] = comb_e.sg_weight * e_right_phi[f] + comb_e.te_weight * te_qf_phi_r + e_left_zn[f] = comb_e.d_flux_d_log_c_left_m2_s + e_right_zn[f] = comb_e.d_flux_d_log_c_right_m2_s + if tf.cap_hole: + h_offset = ( + -tf.delta_Ev_eV if tf.hole_band_offset_eV is None else tf.hole_band_offset_eV ) - h_left_zp[f] = ( - cap_h.d_flux_d_sg_flux * h_left_zp[f] - - cap_h.d_flux_d_n_left_m_s * float(p[f]) + te_h = reciprocal_thermionic_flux_m2_s( + float(p[f]), + float(p[f + 1]), + carrier="hole", + phi_left_V=float(phi[f]), + phi_right_V=float(phi[f + 1]), + band_offset_eV=h_offset, + temperature_K=temp, + a_star_left_A_m2_K2=tf.a_star_p_A_m2_K2, + a_star_right_A_m2_K2=tf.a_star_p_right_A_m2_K2, + dos_left_m3=tf.dos_p_left_m3, + dos_right_m3=tf.dos_p_right_m3, + transmission=tf.transmission, + statistics="maxwell_boltzmann", + model_version=self.thermionic_mode, + thermal_voltage_V=thermal, + electrochemical_step=float(ec_p_steps[f]), ) - h_right_zp[f] = ( - cap_h.d_flux_d_sg_flux * h_right_zp[f] - - cap_h.d_flux_d_n_right_m_s * float(p[f + 1]) + comb_h = combine_sg_and_reciprocal_thermionic_flux( + float(h_flux[f]), + d_sg_d_phi_left_m2_s_V=float(h_lpot[f]), + d_sg_d_phi_right_m2_s_V=float(h_rpot[f]), + d_sg_d_c_left_m_s=float(h_ld[f]), + d_sg_d_c_right_m_s=float(h_rd[f]), + c_left_m3=float(p[f]), + c_right_m3=float(p[f + 1]), + thermionic=te_h, + combination_mode=comb_mode, + te_softness=self.te_softness, ) + h_flux[f] = comb_h.flux_m2_s + h_ld[f] = comb_h.d_flux_d_c_left_m_s + h_rd[f] = comb_h.d_flux_d_c_right_m_s + h_lpot[f] = comb_h.d_flux_d_phi_left_m2_s_V + h_rpot[f] = comb_h.d_flux_d_phi_right_m2_s_V + if derivatives: + te_qf_phi_l = -(te_h.right_barrier_weight / thermal) * te_h.flux_m2_s + te_qf_phi_r = -(te_h.left_barrier_weight / thermal) * te_h.flux_m2_s + h_left_phi[f] = comb_h.sg_weight * h_left_phi[f] + comb_h.te_weight * te_qf_phi_l + h_right_phi[f] = comb_h.sg_weight * h_right_phi[f] + comb_h.te_weight * te_qf_phi_r + h_left_zp[f] = -comb_h.d_flux_d_log_c_left_m2_s + h_right_zp[f] = -comb_h.d_flux_d_log_c_right_m2_s for bare in self.bare_srh: idx = bare.node @@ -708,12 +838,16 @@ def evaluate_state( flux=e_flux, left_density_derivative=e_ld, right_density_derivative=e_rd, + left_potential_derivative=e_lpot, + right_potential_derivative=e_rpot, ), hole=replace( base.hole, flux=h_flux, left_density_derivative=h_ld, right_density_derivative=h_rd, + left_potential_derivative=h_lpot, + right_potential_derivative=h_rpot, ), ) return InterfaceEvaluation1D( @@ -783,10 +917,13 @@ class CompiledDevice1D: ) field_transport: FieldTransport1D | None = None interface_model: CompiledInterfaceModel1D | None = None + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1 _carrier_layout: Layout = field(init=False, repr=False) _carrier_geometry: Geometry = field(init=False, repr=False) def __post_init__(self) -> None: + if self.band_step_mode not in BAND_STEP_MODES: + raise ValueError(f"unknown band_step_mode {self.band_step_mode!r}") for name in ( "electron_diffusivity_faces_m2_s", "hole_diffusivity_faces_m2_s", @@ -1016,6 +1153,7 @@ def fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: device.parameters.band_structure, electron_electrochemical_step=np.diff(values[count:2 * count]), hole_electrochemical_step=-np.diff(values[2 * count:]), + band_step_mode=device.band_step_mode, ) def recombination_rate(self, n: Vector, p: Vector, *, derivatives: bool = True) -> RecombinationRate: diff --git a/src/solarlab/equations/dc_2d.py b/src/solarlab/equations/dc_2d.py index 24c281b4..8141adf6 100644 --- a/src/solarlab/equations/dc_2d.py +++ b/src/solarlab/equations/dc_2d.py @@ -9,7 +9,7 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace import math from typing import Protocol, TypeAlias @@ -33,12 +33,24 @@ from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger from solarlab.physics.electrostatics.poisson import rectangular_2d_face_capacitances from solarlab.physics.generation.profile import GenerationProfile +from solarlab.physics.interface_transport import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + ThermionicCombinationMode, + combine_sg_and_reciprocal_thermionic_flux, + reciprocal_thermionic_flux_m2_s, +) from solarlab.physics.recombination.bulk import RecombinationRate from solarlab.physics.recombination.reaction import ( BulkRecombinationCoefficients, BulkRecombinationEvaluation, BulkRecombinationReaction, ) from solarlab.physics.statistics.band_potentials import BandStructure -from solarlab.physics.transport.electrochemical_flux import CarrierFaceFlux, CarrierFaceFluxes, stable_sg_particle_flux +from solarlab.physics.transport.electrochemical_flux import ( + CarrierFaceFlux, + CarrierFaceFluxes, + LEGACY_SUMMED_POTENTIAL_V1, + carrier_transport_potential_steps, + stable_sg_particle_flux, +) Vector: TypeAlias = NDArray[np.float64] Q = ELEMENTARY_CHARGE_C @@ -258,6 +270,277 @@ def charge_ledger(self, n: Vector, p: Vector) -> ChargeLedger: )) +@dataclass(frozen=True) +class FaceTransportEvaluation2D: + """2D face particle fluxes and optional quasi-Fermi tangents for P08 V2 channels.""" + + fluxes: CarrierFaceFluxes + e_phi_left: Vector + e_phi_right: Vector + e_z_left: Vector + e_z_right: Vector + h_phi_left: Vector + h_phi_right: Vector + h_z_left: Vector + h_z_right: Vector + + +def has_prospective_2d_transport(device: CompiledDevice2D) -> bool: + """True when 2D transport opts into P08-02c band steps or P08-03 reciprocal TE.""" + model = device.column.interface_model + return ( + device.column.band_step_mode != LEGACY_SUMMED_POTENTIAL_V1 + or ( + model is not None + and model.topology == "deduplicated" + and model.thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1 + and bool(model.thermionic_faces) + ) + ) + + +def evaluate_2d_carrier_face_fluxes( + device: CompiledDevice2D, + phi: Vector, + n: Vector, + p: Vector, + z_n: Vector, + z_p: Vector, + *, + derivatives: bool = False, +) -> FaceTransportEvaluation2D: + """Evaluate 2D SG/CT + optional P08-02c/P08-03 reciprocal TE with exact QF tangents.""" + left, right = device.geometry.contract_geometry.pairs.T + thermal = device.thermal_voltage_V + temp = device.column.parameters.temperature_K + dpsi_n, dpsi_p = carrier_transport_potential_steps( + phi, + device.band_structure, + band_step_mode=device.column.band_step_mode, + left_nodes=left, + right_nodes=right, + ) + ec_n = z_n[right] - z_n[left] + ec_p = -(z_p[right] - z_p[left]) + if device.field_transport is not None: + potentials = device.band_structure.transport_potentials(phi) + base = device.field_transport.fluxes( + phi, + n, + p, + potentials[0], + potentials[1], + electron_electrochemical_step=ec_n, + hole_electrochemical_step=ec_p, + electron_potential_step_V=dpsi_n, + hole_potential_step_V=dpsi_p, + ) + else: + pair_fluxes = [] + for density, dpsi, diffusivity, sign, drive in ( + (n, dpsi_n, device.electron_diffusivity_faces_m2_s, 1.0, ec_n), + (p, dpsi_p, device.hole_diffusivity_faces_m2_s, -1.0, ec_p), + ): + step = -sign * dpsi / thermal + coefficient = diffusivity / device.geometry.face_spacing_m + evaluated = stable_sg_particle_flux( + density[left], density[right], step, coefficient, electrochemical_step=drive + ) + per_volt = -sign / thermal * evaluated.energy_step_derivative + pair_fluxes.append( + CarrierFaceFlux( + evaluated.flux, + evaluated.left_density_derivative, + evaluated.right_density_derivative, + -per_volt, + per_volt, + step, + coefficient, + ) + ) + base = CarrierFaceFluxes(pair_fluxes[0], pair_fluxes[1]) + + e_flux = np.array(base.electron.flux, dtype=float, copy=True) + e_ld = np.array(base.electron.left_density_derivative, dtype=float, copy=True) + e_rd = np.array(base.electron.right_density_derivative, dtype=float, copy=True) + e_lpot = np.array(base.electron.left_potential_derivative, dtype=float, copy=True) + e_rpot = np.array(base.electron.right_potential_derivative, dtype=float, copy=True) + h_flux = np.array(base.hole.flux, dtype=float, copy=True) + h_ld = np.array(base.hole.left_density_derivative, dtype=float, copy=True) + h_rd = np.array(base.hole.right_density_derivative, dtype=float, copy=True) + h_lpot = np.array(base.hole.left_potential_derivative, dtype=float, copy=True) + h_rpot = np.array(base.hole.right_potential_derivative, dtype=float, copy=True) + + if derivatives: + e_phi_l, e_phi_r = quasi_fermi_potential_tangents(base.electron, ec_n, 1.0, thermal) + h_phi_l, h_phi_r = quasi_fermi_potential_tangents(base.hole, ec_p, -1.0, thermal) + e_phi_l = np.array(e_phi_l, dtype=float, copy=True) + e_phi_r = np.array(e_phi_r, dtype=float, copy=True) + h_phi_l = np.array(h_phi_l, dtype=float, copy=True) + h_phi_r = np.array(h_phi_r, dtype=float, copy=True) + if device.field_transport is not None: + tr_eval = device.field_transport.evaluate(phi) + h_space = device.geometry.face_spacing_m + e_chain = ( + (e_flux / tr_eval.electron_diffusivity_m2_s) + * tr_eval.electron_d_diffusivity_d_field + / h_space + ) + h_chain = ( + (h_flux / tr_eval.hole_diffusivity_m2_s) + * tr_eval.hole_d_diffusivity_d_field + / h_space + ) + e_phi_l = e_phi_l + e_chain + e_phi_r = e_phi_r - e_chain + h_phi_l = h_phi_l + h_chain + h_phi_r = h_phi_r - h_chain + e_z_l = np.array(e_ld * n[left], dtype=float, copy=True) + e_z_r = np.array(e_rd * n[right], dtype=float, copy=True) + h_z_l = np.array(-h_ld * p[left], dtype=float, copy=True) + h_z_r = np.array(-h_rd * p[right], dtype=float, copy=True) + else: + e_phi_l = e_phi_r = e_z_l = e_z_r = np.empty(0) + h_phi_l = h_phi_r = h_z_l = h_z_r = np.empty(0) + + model = device.column.interface_model + if ( + model is not None + and model.topology == "deduplicated" + and model.thermionic_mode != LEGACY_UNNORMALIZED_THERMIONIC_V1 + ): + comb_mode: ThermionicCombinationMode = ( + "harmonic_series" if model.combination_mode is None else model.combination_mode + ) + x_offset = device.geometry.x_face_count + nx = device.geometry.nx + for tf in model.thermionic_faces: + base_idx = x_offset + tf.face * nx + for col in range(nx): + f = base_idx + col + a = int(left[f]) + b = int(right[f]) + if tf.cap_electron: + te_e = reciprocal_thermionic_flux_m2_s( + float(n[a]), + float(n[b]), + carrier="electron", + phi_left_V=float(phi[a]), + phi_right_V=float(phi[b]), + band_offset_eV=tf.delta_Ec_eV, + temperature_K=temp, + a_star_left_A_m2_K2=tf.a_star_n_A_m2_K2, + a_star_right_A_m2_K2=tf.a_star_n_right_A_m2_K2, + dos_left_m3=tf.dos_n_left_m3, + dos_right_m3=tf.dos_n_right_m3, + transmission=tf.transmission, + statistics="maxwell_boltzmann", + model_version=model.thermionic_mode, + thermal_voltage_V=thermal, + electrochemical_step=float(ec_n[f]), + ) + comb_e = combine_sg_and_reciprocal_thermionic_flux( + float(e_flux[f]), + d_sg_d_phi_left_m2_s_V=float(e_lpot[f]), + d_sg_d_phi_right_m2_s_V=float(e_rpot[f]), + d_sg_d_c_left_m_s=float(e_ld[f]), + d_sg_d_c_right_m_s=float(e_rd[f]), + c_left_m3=float(n[a]), + c_right_m3=float(n[b]), + thermionic=te_e, + combination_mode=comb_mode, + te_softness=model.te_softness, + ) + e_flux[f] = comb_e.flux_m2_s + e_ld[f] = comb_e.d_flux_d_c_left_m_s + e_rd[f] = comb_e.d_flux_d_c_right_m_s + e_lpot[f] = comb_e.d_flux_d_phi_left_m2_s_V + e_rpot[f] = comb_e.d_flux_d_phi_right_m2_s_V + if derivatives: + te_qf_l = (te_e.right_barrier_weight / thermal) * te_e.flux_m2_s + te_qf_r = (te_e.left_barrier_weight / thermal) * te_e.flux_m2_s + e_phi_l[f] = comb_e.sg_weight * e_phi_l[f] + comb_e.te_weight * te_qf_l + e_phi_r[f] = comb_e.sg_weight * e_phi_r[f] + comb_e.te_weight * te_qf_r + e_z_l[f] = comb_e.d_flux_d_log_c_left_m2_s + e_z_r[f] = comb_e.d_flux_d_log_c_right_m2_s + if tf.cap_hole: + h_offset = ( + -tf.delta_Ev_eV if tf.hole_band_offset_eV is None else tf.hole_band_offset_eV + ) + te_h = reciprocal_thermionic_flux_m2_s( + float(p[a]), + float(p[b]), + carrier="hole", + phi_left_V=float(phi[a]), + phi_right_V=float(phi[b]), + band_offset_eV=h_offset, + temperature_K=temp, + a_star_left_A_m2_K2=tf.a_star_p_A_m2_K2, + a_star_right_A_m2_K2=tf.a_star_p_right_A_m2_K2, + dos_left_m3=tf.dos_p_left_m3, + dos_right_m3=tf.dos_p_right_m3, + transmission=tf.transmission, + statistics="maxwell_boltzmann", + model_version=model.thermionic_mode, + thermal_voltage_V=thermal, + electrochemical_step=float(ec_p[f]), + ) + comb_h = combine_sg_and_reciprocal_thermionic_flux( + float(h_flux[f]), + d_sg_d_phi_left_m2_s_V=float(h_lpot[f]), + d_sg_d_phi_right_m2_s_V=float(h_rpot[f]), + d_sg_d_c_left_m_s=float(h_ld[f]), + d_sg_d_c_right_m_s=float(h_rd[f]), + c_left_m3=float(p[a]), + c_right_m3=float(p[b]), + thermionic=te_h, + combination_mode=comb_mode, + te_softness=model.te_softness, + ) + h_flux[f] = comb_h.flux_m2_s + h_ld[f] = comb_h.d_flux_d_c_left_m_s + h_rd[f] = comb_h.d_flux_d_c_right_m_s + h_lpot[f] = comb_h.d_flux_d_phi_left_m2_s_V + h_rpot[f] = comb_h.d_flux_d_phi_right_m2_s_V + if derivatives: + te_qf_l = -(te_h.right_barrier_weight / thermal) * te_h.flux_m2_s + te_qf_r = -(te_h.left_barrier_weight / thermal) * te_h.flux_m2_s + h_phi_l[f] = comb_h.sg_weight * h_phi_l[f] + comb_h.te_weight * te_qf_l + h_phi_r[f] = comb_h.sg_weight * h_phi_r[f] + comb_h.te_weight * te_qf_r + h_z_l[f] = -comb_h.d_flux_d_log_c_left_m2_s + h_z_r[f] = -comb_h.d_flux_d_log_c_right_m2_s + + replaced = CarrierFaceFluxes( + electron=replace( + base.electron, + flux=e_flux, + left_density_derivative=e_ld, + right_density_derivative=e_rd, + left_potential_derivative=e_lpot, + right_potential_derivative=e_rpot, + ), + hole=replace( + base.hole, + flux=h_flux, + left_density_derivative=h_ld, + right_density_derivative=h_rd, + left_potential_derivative=h_lpot, + right_potential_derivative=h_rpot, + ), + ) + return FaceTransportEvaluation2D( + fluxes=replaced, + e_phi_left=e_phi_l, + e_phi_right=e_phi_r, + e_z_left=e_z_l, + e_z_right=e_z_r, + h_phi_left=h_phi_l, + h_phi_right=h_phi_r, + h_z_left=h_z_l, + h_z_right=h_z_r, + ) + + @dataclass(frozen=True) class DC2DProblem: device: CompiledDevice2D @@ -273,6 +556,16 @@ def fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: d = self.device values = np.asarray(u, dtype=float) phi, n, p = d.fields(values, voltage_V=self.voltage_V) + if has_prospective_2d_transport(d): + return evaluate_2d_carrier_face_fluxes( + d, + phi, + n, + p, + values[d.node_count:2 * d.node_count], + values[2 * d.node_count:], + derivatives=False, + ).fluxes left, right = d.geometry.contract_geometry.pairs.T potentials = d.band_structure.transport_potentials(phi) if d.field_transport is not None: @@ -362,7 +655,7 @@ def jacobian(self, u: ArrayLike) -> csc_matrix: """Full analytic Newton Jacobian, including both spatial directions.""" d, count = self.device, self.device.node_count values = np.asarray(u, dtype=float) - _, n, p = d.fields(values, voltage_V=self.voltage_V) + phi, n, p = d.fields(values, voltage_V=self.voltage_V) thermal = d.thermal_voltage_V geometry = d.geometry.contract_geometry left, right = geometry.pairs.T @@ -376,27 +669,48 @@ def jacobian(self, u: ArrayLike) -> csc_matrix: matrix[node, node] -= Q * area * (n[node] + p[node]) / thermal matrix[node, count + node] = -Q * area * n[node] matrix[node, 2 * count + node] = -Q * area * p[node] - fluxes = self.fluxes(values) + prospective_eval = ( + evaluate_2d_carrier_face_fluxes( + d, + phi, + n, + p, + values[count:2 * count], + values[2 * count:], + derivatives=True, + ) + if has_prospective_2d_transport(d) + else None + ) + fluxes = self.fluxes(values) if prospective_eval is None else prospective_eval.fluxes rate = self.recombination_rate(n, p) assert rate.d_rate_dn is not None and rate.d_rate_dp is not None source_n = -np.asarray(rate.d_rate_dn) * n source_p = np.asarray(rate.d_rate_dp) * p source_phi = (source_n + source_p) / thermal for offset, sign, density, flux in ((count, 1.0, n, fluxes.electron), (2 * count, -1.0, p, fluxes.hole)): - drive = sign * (values[offset + right] - values[offset + left]) - # Reuse the accepted cancellation-safe quasi-Fermi chain, without altering its source. - phi_left, phi_right = quasi_fermi_potential_tangents(flux, drive, sign, thermal) - if d.field_transport is not None: - evaluated_transport = d.field_transport.evaluate(values[:count]) - diffusivity = (evaluated_transport.electron_diffusivity_m2_s if offset == count - else evaluated_transport.hole_diffusivity_m2_s) - diffusivity_slope = (evaluated_transport.electron_d_diffusivity_d_field if offset == count - else evaluated_transport.hole_d_diffusivity_d_field) - field_chain = (flux.flux / diffusivity) * diffusivity_slope / d.geometry.face_spacing_m - phi_left = phi_left + field_chain - phi_right = phi_right - field_chain - z_left = sign * flux.left_density_derivative * density[left] - z_right = sign * flux.right_density_derivative * density[right] + if prospective_eval is not None: + if offset == count: + phi_left, phi_right = prospective_eval.e_phi_left, prospective_eval.e_phi_right + z_left, z_right = prospective_eval.e_z_left, prospective_eval.e_z_right + else: + phi_left, phi_right = prospective_eval.h_phi_left, prospective_eval.h_phi_right + z_left, z_right = prospective_eval.h_z_left, prospective_eval.h_z_right + else: + drive = sign * (values[offset + right] - values[offset + left]) + # Reuse the accepted cancellation-safe quasi-Fermi chain, without altering its source. + phi_left, phi_right = quasi_fermi_potential_tangents(flux, drive, sign, thermal) + if d.field_transport is not None: + evaluated_transport = d.field_transport.evaluate(values[:count]) + diffusivity = (evaluated_transport.electron_diffusivity_m2_s if offset == count + else evaluated_transport.hole_diffusivity_m2_s) + diffusivity_slope = (evaluated_transport.electron_d_diffusivity_d_field if offset == count + else evaluated_transport.hole_d_diffusivity_d_field) + field_chain = (flux.flux / diffusivity) * diffusivity_slope / d.geometry.face_spacing_m + phi_left = phi_left + field_chain + phi_right = phi_right - field_chain + z_left = sign * flux.left_density_derivative * density[left] + z_right = sign * flux.right_density_derivative * density[right] for face, (a, b) in enumerate(geometry.pairs): for orientation, node in ((-1.0, a), (1.0, b)): weight = orientation * geometry.face_measures[face] diff --git a/src/solarlab/equations/field_transport_2d.py b/src/solarlab/equations/field_transport_2d.py index a24adb6d..2e7320c5 100644 --- a/src/solarlab/equations/field_transport_2d.py +++ b/src/solarlab/equations/field_transport_2d.py @@ -116,22 +116,28 @@ def evaluate(self, phi_V: ArrayLike) -> FieldTransportEvaluation2D: def fluxes(self, phi_V: ArrayLike, electron_density_m3: ArrayLike, hole_density_m3: ArrayLike, electron_transport_potential_V: ArrayLike, hole_transport_potential_V: ArrayLike, *, electron_electrochemical_step: ArrayLike | None = None, - hole_electrochemical_step: ArrayLike | None = None) -> CarrierFaceFluxes: + hole_electrochemical_step: ArrayLike | None = None, + electron_potential_step_V: ArrayLike | None = None, + hole_potential_step_V: ArrayLike | None = None) -> CarrierFaceFluxes: """Reuse SG density/energy derivatives and add dF/dk*dD/dphi/h.""" evaluation = self.evaluate(phi_V) left, right = self.geometry.contract_geometry.pairs.T h = self.geometry.face_spacing_m fluxes = [] - for density, potential, diffusivity, slope, sign, drive in ( - (electron_density_m3, electron_transport_potential_V, evaluation.electron_diffusivity_m2_s, - evaluation.electron_d_diffusivity_d_field, -1.0, electron_electrochemical_step), - (hole_density_m3, hole_transport_potential_V, evaluation.hole_diffusivity_m2_s, - evaluation.hole_d_diffusivity_d_field, 1.0, hole_electrochemical_step), + for density, potential, explicit_step, diffusivity, slope, sign, drive in ( + (electron_density_m3, electron_transport_potential_V, electron_potential_step_V, + evaluation.electron_diffusivity_m2_s, evaluation.electron_d_diffusivity_d_field, -1.0, + electron_electrochemical_step), + (hole_density_m3, hole_transport_potential_V, hole_potential_step_V, + evaluation.hole_diffusivity_m2_s, evaluation.hole_d_diffusivity_d_field, 1.0, + hole_electrochemical_step), ): c, psi = self._nodes(density, "carrier density"), self._nodes(potential, "transport potential") if np.any(c <= 0): raise ValueError("SG carrier densities must be positive") - step = sign * (psi[right] - psi[left]) / self.thermal_voltage_V + dpsi = (psi[right] - psi[left] if explicit_step is None + else np.asarray(explicit_step, dtype=float)) + step = sign * dpsi / self.thermal_voltage_V coefficient = diffusivity / h evaluated = stable_sg_particle_flux(c[left], c[right], step, coefficient, electrochemical_step=drive) per_volt = sign / self.thermal_voltage_V * evaluated.energy_step_derivative diff --git a/src/solarlab/equations/ionic_1d.py b/src/solarlab/equations/ionic_1d.py index 795dcbdc..144066d8 100644 --- a/src/solarlab/equations/ionic_1d.py +++ b/src/solarlab/equations/ionic_1d.py @@ -21,7 +21,11 @@ from solarlab.contracts.arrays import integer_indices from solarlab.contracts.units import ELEMENTARY_CHARGE_C from solarlab.equations.dc_1d import CompiledDevice1D, DC1DProblem, State1D, Vector -from solarlab.mesh.geometry import ControlVolumeGeometry1D, HALF_ENDPOINT_V1 +from solarlab.mesh.geometry import ( + HALF_ENDPOINT_V1, + PHYSICAL_HALF_ENDPOINT_V2, + ControlVolumeGeometry1D, +) from solarlab.physics.band_structure.temperature import ion_diffusivity_at_temperature from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger from solarlab.physics.ions import ( @@ -152,7 +156,10 @@ def __post_init__(self) -> None: raise ValueError("ionic binding: shared sites require both complete populations") if np.any(self.positive_ion_reference_m3 <= 0.0) or np.any(self.positive_ion_reference_m3 >= self.positive_ion_site_limit_m3): raise ValueError("finite-site reference must lie strictly between zero and capacity") - if self.ion_geometry.name != HALF_ENDPOINT_V1 or self.ion_geometry.interfaces: + if ( + self.ion_geometry.name not in {HALF_ENDPOINT_V1, PHYSICAL_HALF_ENDPOINT_V2} + or self.ion_geometry.interfaces + ): raise ValueError("first ionic domain requires geometric half cells without interfaces") if not np.array_equal(self.ion_geometry.nodes_m, self.nodes_m[indices]): raise ValueError("ion and electronic nodes must coincide") diff --git a/src/solarlab/equations/ionic_2d.py b/src/solarlab/equations/ionic_2d.py index c850fefb..3d89d3c4 100644 --- a/src/solarlab/equations/ionic_2d.py +++ b/src/solarlab/equations/ionic_2d.py @@ -27,7 +27,12 @@ from solarlab.contracts.units import ELEMENTARY_CHARGE_C from solarlab.discretization.bernoulli import bernoulli, bernoulli_derivative from solarlab.equations.dc_1d import CapabilityError, quasi_fermi_potential_tangents -from solarlab.equations.dc_2d import CompiledDevice2D, State2D +from solarlab.equations.dc_2d import ( + CompiledDevice2D, + State2D, + evaluate_2d_carrier_face_fluxes, + has_prospective_2d_transport, +) from solarlab.mesh.geometry_2d import RECTANGULAR_HALF_ENDPOINT_2D_V1, RectangularGeometry2D from solarlab.physics.electrostatics.charge import ChargeEntry, ChargeLedger from solarlab.physics.ions import ( @@ -772,6 +777,16 @@ def carrier_fluxes(self, u: ArrayLike) -> CarrierFaceFluxes: comp = self.device.electronic_component values = np.asarray(u, dtype=float)[:3 * comp.node_count] phi, n, p = comp.fields(values, voltage_V=self.voltage_V) + if has_prospective_2d_transport(comp): + return evaluate_2d_carrier_face_fluxes( + comp, + phi, + n, + p, + values[comp.node_count:2 * comp.node_count], + values[2 * comp.node_count:3 * comp.node_count], + derivatives=False, + ).fluxes left, right = comp.geometry.contract_geometry.pairs.T potentials = comp.band_structure.transport_potentials(phi) if comp.field_transport is not None: @@ -1003,42 +1018,81 @@ def emit(r: ArrayLike, c: ArrayLike, v: ArrayLike) -> None: emit(d.ion_node_indices, 3 * count + np.arange(d.ion_node_count, dtype=np.intp), Q * ion_vol * dp_dy) # 2. Carrier transport + bulk/grain recombination + optional reabsorption + optional cross-node SRH - c_fluxes = self.carrier_fluxes(values) rate = self.recombination_rate(n, p, derivatives=True) assert rate.d_rate_dn is not None and rate.d_rate_dp is not None source_n = -np.asarray(rate.d_rate_dn) * n source_p = np.asarray(rate.d_rate_dp) * p source_phi = (source_n + source_p) / thermal - evaluated_transport = None if comp.field_transport is None else comp.field_transport.evaluate(phi) - for offset, sign, density, flux in ( - (count, 1.0, n, c_fluxes.electron), - (2 * count, -1.0, p, c_fluxes.hole), - ): - drive = sign * (values[offset + right] - values[offset + left]) - phi_left, phi_right = quasi_fermi_potential_tangents(flux, drive, sign, thermal) - if evaluated_transport is not None: - diff = (evaluated_transport.electron_diffusivity_m2_s if offset == count - else evaluated_transport.hole_diffusivity_m2_s) - slope = (evaluated_transport.electron_d_diffusivity_d_field if offset == count - else evaluated_transport.hole_d_diffusivity_d_field) - field_chain = (flux.flux / diff) * slope / comp.geometry.face_spacing_m - phi_left = phi_left + field_chain - phi_right = phi_right - field_chain - z_left = sign * flux.left_density_derivative * density[left] - z_right = sign * flux.right_density_derivative * density[right] + if has_prospective_2d_transport(comp): + prospective = evaluate_2d_carrier_face_fluxes( + comp, + phi, + n, + p, + values[count:2 * count], + values[2 * count:3 * count], + derivatives=True, + ) fm = geom.face_measures - emit(offset + left, left, -fm * phi_left) - emit(offset + left, right, -fm * phi_right) - emit(offset + left, offset + left, -fm * z_left) - emit(offset + left, offset + right, -fm * z_right) - emit(offset + right, left, fm * phi_left) - emit(offset + right, right, fm * phi_right) - emit(offset + right, offset + left, fm * z_left) - emit(offset + right, offset + right, fm * z_right) - emit(offset + nodes, nodes, vol * source_phi) - emit(offset + nodes, count + nodes, vol * source_n) - emit(offset + nodes, 2 * count + nodes, vol * source_p) + for offset, phi_left, phi_right, z_left, z_right in ( + ( + count, + prospective.e_phi_left, + prospective.e_phi_right, + prospective.e_z_left, + prospective.e_z_right, + ), + ( + 2 * count, + prospective.h_phi_left, + prospective.h_phi_right, + prospective.h_z_left, + prospective.h_z_right, + ), + ): + emit(offset + left, left, -fm * phi_left) + emit(offset + left, right, -fm * phi_right) + emit(offset + left, offset + left, -fm * z_left) + emit(offset + left, offset + right, -fm * z_right) + emit(offset + right, left, fm * phi_left) + emit(offset + right, right, fm * phi_right) + emit(offset + right, offset + left, fm * z_left) + emit(offset + right, offset + right, fm * z_right) + emit(offset + nodes, nodes, vol * source_phi) + emit(offset + nodes, count + nodes, vol * source_n) + emit(offset + nodes, 2 * count + nodes, vol * source_p) + else: + c_fluxes = self.carrier_fluxes(values) + evaluated_transport = None if comp.field_transport is None else comp.field_transport.evaluate(phi) + for offset, sign, density, flux in ( + (count, 1.0, n, c_fluxes.electron), + (2 * count, -1.0, p, c_fluxes.hole), + ): + drive = sign * (values[offset + right] - values[offset + left]) + phi_left, phi_right = quasi_fermi_potential_tangents(flux, drive, sign, thermal) + if evaluated_transport is not None: + diff = (evaluated_transport.electron_diffusivity_m2_s if offset == count + else evaluated_transport.hole_diffusivity_m2_s) + slope = (evaluated_transport.electron_d_diffusivity_d_field if offset == count + else evaluated_transport.hole_d_diffusivity_d_field) + field_chain = (flux.flux / diff) * slope / comp.geometry.face_spacing_m + phi_left = phi_left + field_chain + phi_right = phi_right - field_chain + z_left = sign * flux.left_density_derivative * density[left] + z_right = sign * flux.right_density_derivative * density[right] + fm = geom.face_measures + emit(offset + left, left, -fm * phi_left) + emit(offset + left, right, -fm * phi_right) + emit(offset + left, offset + left, -fm * z_left) + emit(offset + left, offset + right, -fm * z_right) + emit(offset + right, left, fm * phi_left) + emit(offset + right, right, fm * phi_right) + emit(offset + right, offset + left, fm * z_left) + emit(offset + right, offset + right, fm * z_right) + emit(offset + nodes, nodes, vol * source_phi) + emit(offset + nodes, count + nodes, vol * source_n) + emit(offset + nodes, 2 * count + nodes, vol * source_p) # Optional self-consistent radiative reabsorption nonlocal rank-1 coupling if d.radiative_reabsorption: diff --git a/src/solarlab/physics/interface_transport/__init__.py b/src/solarlab/physics/interface_transport/__init__.py index ba7a6207..708648d6 100644 --- a/src/solarlab/physics/interface_transport/__init__.py +++ b/src/solarlab/physics/interface_transport/__init__.py @@ -1,13 +1,24 @@ -"""Finite heterointerface transport and two-sided trace elimination (P04-09).""" +"""Finite heterointerface transport and two-sided trace elimination (P04-09, P08-03).""" from solarlab.physics.interface_transport.thermionic import ( A_STAR_FREE_ELECTRON_A_M2_K2, ELECTRON_MASS_KG, + LEGACY_UNNORMALIZED_THERMIONIC_V1, PLANCK_CONSTANT_J_S, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, TE_BARRIER_THRESHOLD_EV, + THERMIONIC_MODEL_VERSIONS, + ReciprocalThermionicCompositeEvaluation, + ReciprocalThermionicEvaluation, ThermionicCapEvaluation, + ThermionicCarrierKind, + ThermionicCombinationMode, + ThermionicModelVersion, + ThermionicStatisticsKind, TwoSidedCrossFluxEvaluation, cap_particle_flux_thermionic, + combine_sg_and_reciprocal_thermionic_flux, effective_mass_from_dos, emission_velocity, fermi_dirac_one, @@ -15,6 +26,10 @@ fermi_dirac_zero, fermi_richardson_flux, is_free_electron_default, + physical_barrier_steps_eV, + physical_carrier_barrier_step_eV, + reciprocal_richardson, + reciprocal_thermionic_flux_m2_s, resolve_layer_richardson, richardson_from_dos, scaps_thermionic_flux, @@ -39,14 +54,25 @@ "ELECTRON_MASS_KG", "EquilibriumReferencedSheetCharge", "FixedOccupancyTwoSidedResult", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", "TwoSidedBulkState", "TwoSidedCrossFluxEvaluation", "TwoSidedInterfacePhysics", "TwoSidedInterfaceQSSResult", "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", "effective_mass_from_dos", "emission_velocity", "fermi_dirac_one", @@ -54,6 +80,10 @@ "fermi_dirac_zero", "fermi_richardson_flux", "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", "remove_shared_interface_nodes", "resolve_layer_richardson", "richardson_from_dos", diff --git a/src/solarlab/physics/interface_transport/thermionic.py b/src/solarlab/physics/interface_transport/thermionic.py index 57e46a0c..d123515c 100644 --- a/src/solarlab/physics/interface_transport/thermionic.py +++ b/src/solarlab/physics/interface_transport/thermionic.py @@ -844,6 +844,8 @@ class ReciprocalThermionicEvaluation: d_flux_d_c_right_m_s: float d_flux_d_log_c_left_m2_s: float d_flux_d_log_c_right_m2_s: float + left_barrier_weight: float = 0.0 + right_barrier_weight: float = 0.0 def reciprocal_thermionic_flux_m2_s( @@ -923,10 +925,13 @@ def reciprocal_thermionic_flux_m2_s( term_r = -d_dr * c_r if barrier_step > 0.0: g_step = -term_l / vt + w_leg_l, w_leg_r = 1.0, 0.0 elif barrier_step < 0.0: g_step = -term_r / vt + w_leg_l, w_leg_r = 0.0, 1.0 else: g_step = -0.5 * (term_l + term_r) / vt + w_leg_l, w_leg_r = 0.5, 0.5 ec_step = ( float(electrochemical_step) if electrochemical_step is not None @@ -949,6 +954,8 @@ def reciprocal_thermionic_flux_m2_s( d_flux_d_c_right_m_s=d_dr, d_flux_d_log_c_left_m2_s=term_l, d_flux_d_log_c_right_m2_s=-term_r, + left_barrier_weight=w_leg_l, + right_barrier_weight=w_leg_r, ) if dos_left_m3 is None or dos_right_m3 is None: @@ -1077,6 +1084,8 @@ def reciprocal_thermionic_flux_m2_s( d_flux_d_c_right_m_s=d_c_r, d_flux_d_log_c_left_m2_s=d_log_l, d_flux_d_log_c_right_m2_s=d_log_r, + left_barrier_weight=w_l, + right_barrier_weight=w_r, ) @@ -1095,6 +1104,8 @@ class ReciprocalThermionicCompositeEvaluation: d_flux_d_c_right_m_s: float d_flux_d_log_c_left_m2_s: float d_flux_d_log_c_right_m2_s: float + sg_weight: float = 0.0 + te_weight: float = 0.0 def combine_sg_and_reciprocal_thermionic_flux( @@ -1285,4 +1296,6 @@ def combine_sg_and_reciprocal_thermionic_flux( d_flux_d_c_right_m_s=d_c_r, d_flux_d_log_c_left_m2_s=d_log_l, d_flux_d_log_c_right_m2_s=d_log_r, + sg_weight=w_sg, + te_weight=w_te, ) diff --git a/src/solarlab/physics/interface_transport/two_sided.py b/src/solarlab/physics/interface_transport/two_sided.py index 97ab2e08..345cecad 100644 --- a/src/solarlab/physics/interface_transport/two_sided.py +++ b/src/solarlab/physics/interface_transport/two_sided.py @@ -32,7 +32,15 @@ sheet_charge_row_weights, solve_electrostatic_traces, ) -from solarlab.physics.interface_transport.thermionic import fermi_dirac_richardson_flux +from solarlab.physics.interface_transport.thermionic import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + THERMIONIC_MODEL_VERSIONS, + ThermionicModelVersion, + ThermionicStatisticsKind, + TwoSidedCrossFluxEvaluation, + fermi_dirac_richardson_flux, + reciprocal_thermionic_flux_m2_s, +) from solarlab.physics.recombination.interface import ( SharedInterfaceTrapEvaluation, evaluate_shared_interface_trap, @@ -135,6 +143,12 @@ class TwoSidedInterfacePhysics: n1_right_m3: float = 0.0 p1_left_m3: float = 0.0 p1_right_m3: float = 0.0 + thermionic_mode: ThermionicModelVersion = LEGACY_UNNORMALIZED_THERMIONIC_V1 + carrier_statistics: ThermionicStatisticsKind = "fermi_dirac" + a_star_n_left_A_m2_K2: float | None = None + a_star_n_right_A_m2_K2: float | None = None + a_star_p_left_A_m2_K2: float | None = None + a_star_p_right_A_m2_K2: float | None = None def __post_init__(self) -> None: for name in ( @@ -167,6 +181,23 @@ def __post_init__(self) -> None: for name in ("conduction_band_step_eV", "hole_transport_step_eV"): if not math.isfinite(float(getattr(self, name))): raise ValueError(f"{name} must be finite") + if self.thermionic_mode not in THERMIONIC_MODEL_VERSIONS: + raise ValueError( + f"unknown thermionic_mode {self.thermionic_mode!r}; expected one of {THERMIONIC_MODEL_VERSIONS}" + ) + if self.carrier_statistics not in ("maxwell_boltzmann", "fermi_dirac"): + raise ValueError( + f"unknown carrier_statistics {self.carrier_statistics!r}; expected 'maxwell_boltzmann' or 'fermi_dirac'" + ) + for opt_name in ( + "a_star_n_left_A_m2_K2", + "a_star_n_right_A_m2_K2", + "a_star_p_left_A_m2_K2", + "a_star_p_right_A_m2_K2", + ): + opt_val = getattr(self, opt_name) + if opt_val is not None: + _positive(opt_val, opt_name) @dataclass(frozen=True) @@ -650,6 +681,149 @@ def _evaluate_trap_for_two_sided( ) +def _evaluate_two_sided_cross_flux( + state: RealArray, + *, + u_delta: RealArray, + drop_left_V: float, + drop_right_V: float, + potential_jump_V: float, + physics: TwoSidedInterfacePhysics, + bulk: TwoSidedBulkState, +) -> TwoSidedCrossFluxEvaluation: + """Evaluate cross-interface thermionic emission under V1 (default) or opt-in V2.""" + vt_local = float(physics.thermal_voltage_V) + xi_l = float(drop_left_V) / vt_local + xi_r_from_bulk = -float(drop_right_V) / vt_local + if physics.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1: + base_log_to_dos = np.array( + [ + math.log(float(bulk.n_left_m3) / float(physics.N_C_left_m3)) + xi_l, + math.log(float(bulk.p_left_m3) / float(physics.N_V_left_m3)) - xi_l, + math.log(float(bulk.n_right_m3) / float(physics.N_C_right_m3)) + xi_r_from_bulk, + math.log(float(bulk.p_right_m3) / float(physics.N_V_right_m3)) - xi_r_from_bulk, + ], + dtype=np.float64, + ) + return fermi_dirac_richardson_flux( + state, + phi_trace_left_V=0.0, + phi_trace_right_V=float(potential_jump_V), + conduction_band_step_eV=physics.conduction_band_step_eV, + hole_transport_step_eV=physics.hole_transport_step_eV, + N_C_left_m3=physics.N_C_left_m3, + N_C_right_m3=physics.N_C_right_m3, + N_V_left_m3=physics.N_V_left_m3, + N_V_right_m3=physics.N_V_right_m3, + richardson_n_A_m2_K2=physics.richardson_n_A_m2_K2, + richardson_p_A_m2_K2=physics.richardson_p_A_m2_K2, + temperature_K=physics.temperature_K, + thermal_voltage_V=physics.thermal_voltage_V, + transmission=physics.transmission, + base_log_to_dos=base_log_to_dos, + u_delta=u_delta, + electrochemical_steps=( + bulk.electron_electrochemical_step, + bulk.hole_electrochemical_step, + ), + ) + + u0, u1, u2, u3 = (float(v) for v in u_delta) + log_n_l = math.log(float(bulk.n_left_m3)) + xi_l + u0 + log_p_l = math.log(float(bulk.p_left_m3)) - xi_l + u1 + log_n_r = math.log(float(bulk.n_right_m3)) + xi_r_from_bulk + u2 + log_p_r = math.log(float(bulk.p_right_m3)) - xi_r_from_bulk + u3 + + ec_n_trace: float | None = None + ec_p_trace: float | None = None + if physics.carrier_statistics == "maxwell_boltzmann": + if ( + bulk.electron_electrochemical_step is not None + and -690.0 < log_n_l < 700.0 + and -690.0 < log_n_r < 700.0 + ): + ec_n_trace = float(bulk.electron_electrochemical_step) + (u2 - u0) + if ( + bulk.hole_electrochemical_step is not None + and -690.0 < log_p_l < 700.0 + and -690.0 < log_p_r < 700.0 + ): + ec_p_trace = float(bulk.hole_electrochemical_step) + (u3 - u1) + + a_n_l = ( + physics.richardson_n_A_m2_K2 + if physics.a_star_n_left_A_m2_K2 is None + else physics.a_star_n_left_A_m2_K2 + ) + a_n_r = ( + physics.richardson_n_A_m2_K2 + if physics.a_star_n_right_A_m2_K2 is None + else physics.a_star_n_right_A_m2_K2 + ) + a_p_l = ( + physics.richardson_p_A_m2_K2 + if physics.a_star_p_left_A_m2_K2 is None + else physics.a_star_p_left_A_m2_K2 + ) + a_p_r = ( + physics.richardson_p_A_m2_K2 + if physics.a_star_p_right_A_m2_K2 is None + else physics.a_star_p_right_A_m2_K2 + ) + + eval_n = reciprocal_thermionic_flux_m2_s( + float(state[_N_LEFT]), + float(state[_N_RIGHT]), + carrier="electron", + phi_left_V=0.0, + phi_right_V=float(potential_jump_V), + band_offset_eV=physics.conduction_band_step_eV, + temperature_K=physics.temperature_K, + a_star_left_A_m2_K2=a_n_l, + a_star_right_A_m2_K2=a_n_r, + dos_left_m3=physics.N_C_left_m3, + dos_right_m3=physics.N_C_right_m3, + transmission=physics.transmission, + statistics=physics.carrier_statistics, + model_version=physics.thermionic_mode, + thermal_voltage_V=physics.thermal_voltage_V, + electrochemical_step=ec_n_trace, + ) + eval_p = reciprocal_thermionic_flux_m2_s( + float(state[_P_LEFT]), + float(state[_P_RIGHT]), + carrier="hole", + phi_left_V=0.0, + phi_right_V=float(potential_jump_V), + band_offset_eV=physics.hole_transport_step_eV, + temperature_K=physics.temperature_K, + a_star_left_A_m2_K2=a_p_l, + a_star_right_A_m2_K2=a_p_r, + dos_left_m3=physics.N_V_left_m3, + dos_right_m3=physics.N_V_right_m3, + transmission=physics.transmission, + statistics=physics.carrier_statistics, + model_version=physics.thermionic_mode, + thermal_voltage_V=physics.thermal_voltage_V, + electrochemical_step=ec_p_trace, + ) + cross = np.array([eval_n.flux_m2_s, eval_p.flux_m2_s], dtype=np.float64) + d_log: RealArray = np.zeros((2, 4), dtype=np.float64) + d_log[0, _N_LEFT] = eval_n.d_flux_d_log_c_left_m2_s + d_log[0, _N_RIGHT] = eval_n.d_flux_d_log_c_right_m2_s + d_log[1, _P_LEFT] = eval_p.d_flux_d_log_c_left_m2_s + d_log[1, _P_RIGHT] = eval_p.d_flux_d_log_c_right_m2_s + d_trace = np.array( + [ + [eval_n.d_flux_d_phi_left_m2_s_V, eval_n.d_flux_d_phi_right_m2_s_V], + [eval_p.d_flux_d_phi_left_m2_s_V, eval_p.d_flux_d_phi_right_m2_s_V], + ], + dtype=np.float64, + ) + scale = np.array([eval_n.one_way_scale_m2_s, eval_p.one_way_scale_m2_s], dtype=np.float64) + return TwoSidedCrossFluxEvaluation(cross, d_log, d_trace, scale) + + def _carrier_balance_terms( u_delta: RealArray, drop_left_V: float, @@ -678,39 +852,14 @@ def _carrier_balance_terms( bulk_flux, d_bulk_u, d_bulk_trace_u, d_bulk_coords_u = _bulk_sg_flux_and_derivatives_u( u_delta, state, drop_left_V, drop_right_V, geometry, physics, bulk ) - vt_local = float(physics.thermal_voltage_V) - xi_l = float(drop_left_V) / vt_local - xi_r_from_bulk = -float(drop_right_V) / vt_local - base_log_to_dos = np.array( - [ - math.log(float(bulk.n_left_m3) / float(physics.N_C_left_m3)) + xi_l, - math.log(float(bulk.p_left_m3) / float(physics.N_V_left_m3)) - xi_l, - math.log(float(bulk.n_right_m3) / float(physics.N_C_right_m3)) + xi_r_from_bulk, - math.log(float(bulk.p_right_m3) / float(physics.N_V_right_m3)) - xi_r_from_bulk, - ], - dtype=np.float64, - ) - cross_eval = fermi_dirac_richardson_flux( + cross_eval = _evaluate_two_sided_cross_flux( state, - phi_trace_left_V=0.0, - phi_trace_right_V=float(potential_jump_V), - conduction_band_step_eV=physics.conduction_band_step_eV, - hole_transport_step_eV=physics.hole_transport_step_eV, - N_C_left_m3=physics.N_C_left_m3, - N_C_right_m3=physics.N_C_right_m3, - N_V_left_m3=physics.N_V_left_m3, - N_V_right_m3=physics.N_V_right_m3, - richardson_n_A_m2_K2=physics.richardson_n_A_m2_K2, - richardson_p_A_m2_K2=physics.richardson_p_A_m2_K2, - temperature_K=physics.temperature_K, - thermal_voltage_V=physics.thermal_voltage_V, - transmission=physics.transmission, - base_log_to_dos=base_log_to_dos, u_delta=u_delta, - electrochemical_steps=( - bulk.electron_electrochemical_step, - bulk.hole_electrochemical_step, - ), + drop_left_V=drop_left_V, + drop_right_V=drop_right_V, + potential_jump_V=potential_jump_V, + physics=physics, + bulk=bulk, ) trap = _evaluate_trap_for_two_sided(state, physics, charge) if trap is None: @@ -1556,39 +1705,14 @@ def _fixed_occupancy_balance_terms( bulk_flux, d_bulk_u, d_bulk_trace_u, d_bulk_coords_u = _bulk_sg_flux_and_derivatives_u( u_delta, state, drop_left_V, drop_right_V, geometry, physics, bulk ) - vt_local = float(physics.thermal_voltage_V) - xi_l = float(drop_left_V) / vt_local - xi_r_from_bulk = -float(drop_right_V) / vt_local - base_log_to_dos = np.array( - [ - math.log(float(bulk.n_left_m3) / float(physics.N_C_left_m3)) + xi_l, - math.log(float(bulk.p_left_m3) / float(physics.N_V_left_m3)) - xi_l, - math.log(float(bulk.n_right_m3) / float(physics.N_C_right_m3)) + xi_r_from_bulk, - math.log(float(bulk.p_right_m3) / float(physics.N_V_right_m3)) - xi_r_from_bulk, - ], - dtype=np.float64, - ) - cross_eval = fermi_dirac_richardson_flux( + cross_eval = _evaluate_two_sided_cross_flux( state, - phi_trace_left_V=0.0, - phi_trace_right_V=float(potential_jump_V), - conduction_band_step_eV=physics.conduction_band_step_eV, - hole_transport_step_eV=physics.hole_transport_step_eV, - N_C_left_m3=physics.N_C_left_m3, - N_C_right_m3=physics.N_C_right_m3, - N_V_left_m3=physics.N_V_left_m3, - N_V_right_m3=physics.N_V_right_m3, - richardson_n_A_m2_K2=physics.richardson_n_A_m2_K2, - richardson_p_A_m2_K2=physics.richardson_p_A_m2_K2, - temperature_K=physics.temperature_K, - thermal_voltage_V=physics.thermal_voltage_V, - transmission=physics.transmission, - base_log_to_dos=base_log_to_dos, u_delta=u_delta, - electrochemical_steps=( - bulk.electron_electrochemical_step, - bulk.hole_electrochemical_step, - ), + drop_left_V=drop_left_V, + drop_right_V=drop_right_V, + potential_jump_V=potential_jump_V, + physics=physics, + bulk=bulk, ) vn = float(physics.surface_recombination_velocity_n_m_s) diff --git a/src/solarlab/physics/presets.py b/src/solarlab/physics/presets.py index 93c7c257..593ab04b 100644 --- a/src/solarlab/physics/presets.py +++ b/src/solarlab/physics/presets.py @@ -9,16 +9,54 @@ from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass +from typing import Any, Literal +from solarlab.discretization.face_average import ( + DIELECTRIC_RULES, + LAYER_SERIES_CAPACITANCE_V2, + NODAL_HARMONIC_DIELECTRIC_V1, +) +from solarlab.materials.source import SourceDocument +from solarlab.mesh.geometry import ( + GEOMETRY_NAMES, + HALF_ENDPOINT_V1, + INTEGER_ENDPOINT_V1, + PHYSICAL_HALF_ENDPOINT_V2, +) +from solarlab.physics.interface_transport.thermionic import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + THERMIONIC_MODEL_VERSIONS, + ThermionicCombinationMode, + ThermionicModelVersion, +) from solarlab.physics.registry import ( - CapabilityContext, EvidenceRef, ModelRef, ModelRegistry, Scope, + CapabilityContext, CapabilityRule, EvidenceRef, ModelDefinition, ModelRef, ModelRegistry, Scope, _strings, _token, _verify_evidence_sources, metadata_digest, metadata_value, ) from solarlab.physics.selection import ( ModelChoice, ParameterSource, Selection, Topology, _choices, select_models, ) +from solarlab.physics.transport.electrochemical_flux import ( + BAND_STEP_MODES, + HOLE_SEPARATE_INCREMENT_V1, + LEGACY_SUMMED_POTENTIAL_V1, +) -__all__ = ["HistoricalDisable", "NamedPreset", "PresetSelection", "select_preset"] +__all__ = [ + "HistoricalDisable", + "NamedPreset", + "P08CompilerOptions", + "P08ModelVersionMapping", + "P08_MODEL_VERSION_MAPPINGS", + "P08_SOURCE_PATHS", + "P08_V1_MODEL_REFS", + "P08_V2_MODEL_REFS", + "PresetSelection", + "build_p08_model_registry", + "build_p08_preset", + "select_preset", +] @dataclass(frozen=True, slots=True) @@ -126,3 +164,399 @@ def select_preset( registry, topology, context, dict(preset.defaults), parameter_sources, overrides, instance_parameter_sources=instance_parameter_sources, )) + + +OpticalModelChoice = Literal["beer_lambert", "beer_lambert_spectral", "tmm"] + + +@dataclass(frozen=True, slots=True) +class P08ModelVersionMapping: + """Explicit pre-P08 (v1) to prospective P08 (v2) model-version correspondence.""" + + item_id: str + family: str + local_instance_id: str + v1_model: ModelRef + v2_model: ModelRef + v1_token: str + v2_token: str + v1_source_path: str + v2_source_path: str + layer_parameters: tuple[str, ...] + v1_label: str + v2_label: str + semantic_delta: str + + +P08_MODEL_VERSION_MAPPINGS: tuple[P08ModelVersionMapping, ...] = ( + P08ModelVersionMapping( + item_id="P08-02a", + family="electrostatics_face_permittivity", + local_instance_id="face_permittivity", + v1_model=ModelRef("electrostatics.face_permittivity", 1), + v2_model=ModelRef("electrostatics.face_permittivity", 2), + v1_token=NODAL_HARMONIC_DIELECTRIC_V1, + v2_token=LAYER_SERIES_CAPACITANCE_V2, + v1_source_path="solarlab/discretization/face_average.py", + v2_source_path="solarlab/physics/electrostatics/poisson.py", + layer_parameters=("eps_r",), + v1_label="Unweighted nodal harmonic face permittivity (v1)", + v2_label="Sub-face material-extent series dielectric capacitance (v2)", + semantic_delta=( + "Replaces unweighted nodal harmonic face means and shared-node right-layer " + "permittivity bleed with exact sub-face material-extent series capacitance " + "C_f = eps_0 / (d_L/eps_L + d_R/eps_R) and 2D cell-parallel horizontal permittivity." + ), + ), + P08ModelVersionMapping( + item_id="P08-02b", + family="control_volume_geometry", + local_instance_id="control_volume", + v1_model=ModelRef("mesh.endpoint_control_volume", 1), + v2_model=ModelRef("mesh.endpoint_control_volume", 2), + v1_token=INTEGER_ENDPOINT_V1, + v2_token=PHYSICAL_HALF_ENDPOINT_V2, + v1_source_path="solarlab/mesh/geometry.py", + v2_source_path="solarlab/mesh/geometry.py", + layer_parameters=("N_A", "N_D"), + v1_label="Historical integer-endpoint 1D control volumes (v1)", + v2_label="Coupled physical half-endpoint control volumes sum(w)==L (v2)", + semantic_delta=( + "Couples contact half-cells (w_0 = dx_0/2, w_{N-1} = dx_{N-1}/2, sum(w) == L) " + "simultaneously across carrier storage, mobile ions, optical generation, Poisson " + "contact displacement, and 1D/2D column ports." + ), + ), + P08ModelVersionMapping( + item_id="P08-02c", + family="band_step_differencing", + local_instance_id="band_step", + v1_model=ModelRef("transport.band_step_differencing", 1), + v2_model=ModelRef("transport.band_step_differencing", 2), + v1_token=LEGACY_SUMMED_POTENTIAL_V1, + v2_token=HOLE_SEPARATE_INCREMENT_V1, + v1_source_path="solarlab/physics/transport/electrochemical_flux.py", + v2_source_path="solarlab/physics/transport/electrochemical_flux.py", + layer_parameters=("mu_n", "mu_p"), + v1_label="Summed nodal transport-potential differencing (v1)", + v2_label="Separate electrostatic and band-offset face increments (v2)", + semantic_delta=( + "Forms (d_phi + d_chi_t) + d_Eg_t per face before summation so ~5.5 eV valence-band " + "offsets cannot quantize sub-millivolt intra-layer electrostatic steps in binary64." + ), + ), + P08ModelVersionMapping( + item_id="P08-03", + family="interface_thermionic", + local_instance_id="thermionic", + v1_model=ModelRef("interface_transport.thermionic_emission", 1), + v2_model=ModelRef("prospective_interface_p08", 2), + v1_token=LEGACY_UNNORMALIZED_THERMIONIC_V1, + v2_token=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + v1_source_path="solarlab/physics/interface_transport/thermionic.py", + v2_source_path="solarlab/physics/interface_transport/thermionic.py", + layer_parameters=("A_star_n", "A_star_p", "chi", "Eg", "Nc300", "Nv300"), + v1_label="Legacy density-weighted unnormalized thermionic cap (v1)", + v2_label="Reciprocal unequal-DOS physical Bethe/Richardson emission (v2)", + semantic_delta=( + "Separates unfolded physical band-edge steps (chi_phys, Eg_phys), per-side DOS " + "activities (c_L/N_L, c_R/N_R), reciprocal min(A*_L, A*_R), transmission T, and " + "cancellation-free expm1 electrochemical drive with C^infinity flatband corners." + ), + ), + P08ModelVersionMapping( + item_id="P08-04", + family="optical_generation", + local_instance_id="optics", + v1_model=ModelRef("monochromatic_beer_lambert_1d", 1), + v2_model=ModelRef("spectral_control_volume_beer_lambert", 2), + v1_token="beer_lambert", + v2_token="beer_lambert_spectral", + v1_source_path="solarlab/physics/generation/beer_lambert.py", + v2_source_path="solarlab/physics/generation/beer_lambert_spectral.py", + layer_parameters=("alpha", "n_optical", "incoherent"), + v1_label="Pre-P08 monochromatic Beer-Lambert / coherent TMM optics (v1)", + v2_label="Wavelength-resolved control-volume single-pass Beer-Lambert (v2)", + semantic_delta=( + "Integrates spectral alpha(lambda) = 4*pi*k(lambda)/lambda over exact physical " + "control-volume optical depths with closed front-substrate + electrical + transmitted " + "photon budget." + ), + ), +) + +P08_SOURCE_PATHS: tuple[str, ...] = tuple( + sorted( + {m.v1_source_path for m in P08_MODEL_VERSION_MAPPINGS} + | {m.v2_source_path for m in P08_MODEL_VERSION_MAPPINGS} + ) +) +P08_V1_MODEL_REFS: tuple[ModelRef, ...] = tuple(m.v1_model for m in P08_MODEL_VERSION_MAPPINGS) +P08_V2_MODEL_REFS: tuple[ModelRef, ...] = tuple(m.v2_model for m in P08_MODEL_VERSION_MAPPINGS) + + +@dataclass(frozen=True, slots=True) +class P08CompilerOptions: + """Explicit opt-in selector bundle for Stage P08 prospective physics channels. + + Default ``P08CompilerOptions()`` leaves every field at its pre-P08 ``v1`` + setting, preserving 0-ULP / 0-byte manifest and SHA-256 parity with the + ``refactor/wave2-n-baseline`` baseline. + """ + + dielectric_rule: str | None = None + geometry_name: str | None = None + band_step_mode: str = LEGACY_SUMMED_POTENTIAL_V1 + thermionic_mode: ThermionicModelVersion | None = None + combination_mode: ThermionicCombinationMode | None = None + optical_model: OpticalModelChoice | None = None + + def __post_init__(self) -> None: + if self.dielectric_rule is not None and self.dielectric_rule not in DIELECTRIC_RULES: + raise ValueError(f"unknown dielectric_rule {self.dielectric_rule!r}") + if self.geometry_name is not None and self.geometry_name not in GEOMETRY_NAMES: + raise ValueError(f"unknown geometry_name {self.geometry_name!r}") + if self.band_step_mode not in BAND_STEP_MODES: + raise ValueError(f"unknown band_step_mode {self.band_step_mode!r}") + if self.thermionic_mode is not None and self.thermionic_mode not in THERMIONIC_MODEL_VERSIONS: + raise ValueError(f"unknown thermionic_mode {self.thermionic_mode!r}") + if self.combination_mode is not None and self.combination_mode not in ( + "harmonic_series", + "compact_support", + "legacy_logistic", + "hard", + ): + raise ValueError(f"unknown combination_mode {self.combination_mode!r}") + if ( + self.combination_mode is not None + and (self.thermionic_mode is None or self.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1) + ): + raise ValueError( + "combination_mode requires thermionic_mode='reciprocal_physical_thermionic_v2' " + "or 'scaps_effective_velocity_thermionic_v1'" + ) + if self.optical_model is not None and self.optical_model not in ( + "beer_lambert", + "beer_lambert_spectral", + "tmm", + ): + raise ValueError(f"unknown optical_model {self.optical_model!r}") + + @classmethod + def all_prospective_v2( + cls, + *, + combination_mode: ThermionicCombinationMode = "harmonic_series", + optical_model: OpticalModelChoice | None = "beer_lambert_spectral", + ) -> P08CompilerOptions: + """Construct the full Stage P08 prospective V2 physics bundle.""" + return cls( + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + geometry_name=PHYSICAL_HALF_ENDPOINT_V2, + band_step_mode=HOLE_SEPARATE_INCREMENT_V1, + thermionic_mode=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + combination_mode=combination_mode, + optical_model=optical_model, + ) + + @property + def is_v1_default(self) -> bool: + return ( + self.dielectric_rule is None + and self.geometry_name is None + and self.band_step_mode == LEGACY_SUMMED_POTENTIAL_V1 + and (self.thermionic_mode is None or self.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1) + and self.combination_mode is None + and self.optical_model is None + ) + + def active_model_refs(self) -> tuple[ModelRef, ...]: + """Return the resolved (v1 or v2) ModelRef tuple for the five P08 families.""" + dielectric_v2 = ( + self.dielectric_rule == LAYER_SERIES_CAPACITANCE_V2 + or (self.dielectric_rule is None and self.geometry_name == PHYSICAL_HALF_ENDPOINT_V2) + ) + geometry_v2 = self.geometry_name == PHYSICAL_HALF_ENDPOINT_V2 + band_v2 = self.band_step_mode == HOLE_SEPARATE_INCREMENT_V1 + dielectric_ref = ( + P08_MODEL_VERSION_MAPPINGS[0].v2_model + if dielectric_v2 + else P08_MODEL_VERSION_MAPPINGS[0].v1_model + ) + geometry_ref = ( + P08_MODEL_VERSION_MAPPINGS[1].v2_model + if geometry_v2 + else P08_MODEL_VERSION_MAPPINGS[1].v1_model + ) + band_ref = ( + P08_MODEL_VERSION_MAPPINGS[2].v2_model + if band_v2 + else P08_MODEL_VERSION_MAPPINGS[2].v1_model + ) + if self.thermionic_mode == RECIPROCAL_PHYSICAL_THERMIONIC_V2: + if self.combination_mode == "compact_support": + te_ref = ModelRef("prospective_interface_p08_compact_support", 2) + elif self.combination_mode == "legacy_logistic": + te_ref = ModelRef("prospective_interface_p08_logistic", 2) + elif self.combination_mode == "hard": + te_ref = ModelRef("prospective_interface_p08_hard", 2) + else: + te_ref = P08_MODEL_VERSION_MAPPINGS[3].v2_model + elif self.thermionic_mode == "scaps_effective_velocity_thermionic_v1": + te_ref = ModelRef("prospective_interface_p08_scaps_velocity", 2) + else: + te_ref = P08_MODEL_VERSION_MAPPINGS[3].v1_model + + if self.optical_model == "beer_lambert_spectral": + optics_ref = P08_MODEL_VERSION_MAPPINGS[4].v2_model + elif self.optical_model == "tmm": + optics_ref = ModelRef("tmm_spectral_generation_p08", 2) + else: + optics_ref = P08_MODEL_VERSION_MAPPINGS[4].v1_model + return (dielectric_ref, geometry_ref, band_ref, te_ref, optics_ref) + + def compiler_kwargs_1d(self) -> dict[str, Any]: + """Keyword arguments for ``compile_device_1d`` / ``compile_ionic_device_1d``.""" + kwargs: dict[str, Any] = {} + if self.dielectric_rule is not None: + kwargs["dielectric_rule"] = self.dielectric_rule + if self.geometry_name is not None: + kwargs["geometry_name"] = self.geometry_name + if self.band_step_mode != LEGACY_SUMMED_POTENTIAL_V1: + kwargs["band_step_mode"] = self.band_step_mode + if self.thermionic_mode is not None: + kwargs["thermionic_mode"] = self.thermionic_mode + if self.combination_mode is not None: + kwargs["combination_mode"] = self.combination_mode + if self.optical_model is not None: + kwargs["optical_model"] = self.optical_model + return kwargs + + def compiler_kwargs_2d(self) -> dict[str, Any]: + """Keyword arguments for ``compile_device_2d`` / ``compile_ionic_device_2d``.""" + kwargs = self.compiler_kwargs_1d() + if "geometry_name" in kwargs and kwargs["geometry_name"] in { + HALF_ENDPOINT_V1, + PHYSICAL_HALF_ENDPOINT_V2, + }: + kwargs["stack_geometry"] = kwargs.pop("geometry_name") + return kwargs + + +def build_p08_model_registry(sources: Mapping[str, SourceDocument]) -> ModelRegistry: + """Build a source-bound ModelRegistry covering both v1 and v2 P08 model versions.""" + missing = [path for path in P08_SOURCE_PATHS if path not in sources] + if missing: + raise ValueError("missing P08 source documents: " + ", ".join(missing)) + definitions: list[ModelDefinition] = [] + for mapping in P08_MODEL_VERSION_MAPPINGS: + variants: list[tuple[ModelRef, str, str]] = [ + (mapping.v1_model, mapping.v1_label, mapping.v1_source_path), + (mapping.v2_model, mapping.v2_label, mapping.v2_source_path), + ] + if mapping.item_id == "P08-03": + variants.extend([ + ( + ModelRef("prospective_interface_p08_compact_support", 2), + "Reciprocal unequal-DOS physical Bethe/Richardson emission (compact_support, v2)", + mapping.v2_source_path, + ), + ( + ModelRef("prospective_interface_p08_logistic", 2), + "Reciprocal unequal-DOS physical Bethe/Richardson emission (legacy_logistic, v2)", + mapping.v2_source_path, + ), + ( + ModelRef("prospective_interface_p08_hard", 2), + "Reciprocal unequal-DOS physical Bethe/Richardson emission (hard cap, v2)", + mapping.v2_source_path, + ), + ( + ModelRef("prospective_interface_p08_scaps_velocity", 2), + "SCAPS effective-velocity interface thermionic emission (v2)", + mapping.v2_source_path, + ), + ]) + elif mapping.item_id == "P08-04": + variants.append( + ( + ModelRef("tmm_spectral_generation_p08", 2), + "Explicit P08 coherent TMM spectral optical generation (v2)", + mapping.v2_source_path, + ) + ) + for ref, label, src_path in variants: + doc = sources[src_path] + if type(doc) is not SourceDocument or doc.id != src_path: + raise ValueError(f"source document for {src_path!r} must have matching id") + cap = CapabilityRule( + "source_bound_p08_" + mapping.local_instance_id, + (1, 2), + ("dc", "transient", "ac"), + (EvidenceRef(doc.id, doc.sha256, "source"),), + backends=("solarlab_assembled", "metadata_only"), + statistics=("maxwell_boltzmann", "fermi_dirac"), + ) + definitions.append( + ModelDefinition( + ref=ref, + label=label, + family=mapping.family, + scopes=("layer",), + support="node", + parameters=mapping.layer_parameters, + reads=(), + owns=(), + capability=cap, + parameter_schema="full_layer", + ) + ) + return ModelRegistry(tuple(definitions)) + + +def build_p08_preset( + options: P08CompilerOptions, + sources: Mapping[str, SourceDocument], + *, + preset_id: str | None = None, + version: int | None = None, +) -> NamedPreset: + """Build an immutable NamedPreset for either pre-P08 v1 or prospective P08 v2 options.""" + missing = [path for path in P08_SOURCE_PATHS if path not in sources] + if missing: + raise ValueError("missing P08 source documents: " + ", ".join(missing)) + active_refs = options.active_model_refs() + choices = tuple( + ModelChoice(mapping.local_instance_id, ref, parameter_schema="full_layer") + for mapping, ref in zip(P08_MODEL_VERSION_MAPPINGS, active_refs) + ) + evidence = tuple( + EvidenceRef(sources[path].id, sources[path].sha256, "source") + for path in P08_SOURCE_PATHS + ) + is_v1 = all(ref.version == 1 for ref in active_refs) + resolved_id = preset_id or ("solarlab_baseline_physics" if is_v1 else "solarlab_prospective_p08") + resolved_ver = version if version is not None else (1 if is_v1 else 2) + label = ( + "SolarLab pre-P08 v1 baseline physics preset" + if is_v1 + else "SolarLab Stage P08 prospective v2 physics preset" + ) + disables: tuple[HistoricalDisable, ...] = () + if is_v1: + disables = tuple( + HistoricalDisable( + "prospective_" + mapping.local_instance_id + "_v2", + (mapping.v2_model,), + EvidenceRef(sources[mapping.v2_source_path].id, sources[mapping.v2_source_path].sha256, "source"), + ) + for mapping in P08_MODEL_VERSION_MAPPINGS + ) + return NamedPreset( + id=resolved_id, + version=resolved_ver, + label=label, + defaults=(("layer", choices),), + evidence=evidence, + historical_disables=disables, + ) diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json index b3b70187..0d431de6 100644 --- a/src/solarlab/reproducibility/PublicAPI.json +++ b/src/solarlab/reproducibility/PublicAPI.json @@ -243,7 +243,15 @@ "solarlab.physics.presets": [ "HistoricalDisable", "NamedPreset", + "P08CompilerOptions", + "P08ModelVersionMapping", + "P08_MODEL_VERSION_MAPPINGS", + "P08_SOURCE_PATHS", + "P08_V1_MODEL_REFS", + "P08_V2_MODEL_REFS", "PresetSelection", + "build_p08_model_registry", + "build_p08_preset", "select_preset" ], "solarlab.physics.registry": [ @@ -313,7 +321,9 @@ "solarlab.device.compile_1d": [ "CapabilityError", "CompiledDevice1D", + "bind_spectral_beer_lambert_1d", "compile_device_1d", + "p08_identity_inputs", "unsupported" ], "solarlab.equations": [ @@ -666,6 +676,684 @@ "time_method_setting", "verify_integration", "verify_time_method" + ], + "solarlab.discretization": [ + "DIELECTRIC_RULES", + "LAYER_SERIES_CAPACITANCE_V2", + "LegacyFaceJacobian", + "NODAL_HARMONIC_DIELECTRIC_V1", + "VACUUM_PERMITTIVITY_F_M", + "arithmetic_face_mean", + "bernoulli", + "bernoulli_derivative", + "flux_divergence", + "guarded_harmonic_face_mean", + "harmonic_face_mean", + "harmonic_mean", + "legacy_sg_current_n", + "legacy_sg_current_n_jacobian", + "legacy_sg_current_p", + "legacy_sg_current_p_jacobian", + "series_face_capacitance", + "subface_series_capacitance" + ], + "solarlab.discretization.face_average": [ + "DIELECTRIC_RULES", + "LAYER_SERIES_CAPACITANCE_V2", + "NODAL_HARMONIC_DIELECTRIC_V1", + "VACUUM_PERMITTIVITY_F_M", + "arithmetic_face_mean", + "guarded_harmonic_face_mean", + "harmonic_face_mean", + "harmonic_mean", + "series_face_capacitance", + "subface_series_capacitance" + ], + "solarlab.mesh": [ + "ControlVolumeGeometry1D", + "ElectricalStack", + "GEOMETRY_NAMES", + "HALF_ENDPOINT_V1", + "INTEGER_ENDPOINT_V1", + "InterfacePlane", + "InterfaceStencil", + "LEFT_LAYER_WINS", + "PHYSICAL_BOUNDARY_TWO_SIDED_V1", + "PHYSICAL_HALF_ENDPOINT_V2", + "PortFace", + "RIGHT_LAYER_WINS", + "StackLayer", + "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", + "build_geometry", + "build_interface_stencils", + "multilayer_grid", + "node_owner", + "physical_half_endpoint_geometry", + "remove_shared_interface_nodes", + "tanh_grid" + ], + "solarlab.mesh.geometry": [ + "ControlVolumeGeometry1D", + "GEOMETRY_NAMES", + "HALF_ENDPOINT_V1", + "INTEGER_ENDPOINT_V1", + "InterfacePlane", + "NO_SHARED_NODES", + "PHYSICAL_BOUNDARY_TWO_SIDED_V1", + "PHYSICAL_HALF_ENDPOINT_V2", + "PortFace", + "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", + "build_geometry", + "dual_cell_faces", + "half_endpoint_widths", + "half_endpoint_geometry", + "integer_endpoint_geometry", + "integer_endpoint_widths", + "physical_boundary_two_sided_geometry", + "physical_cell_faces", + "physical_half_endpoint_geometry", + "two_sided_trace_geometry", + "two_sided_trace_widths" + ], + "solarlab.physics.electrostatics": [ + "ChargeEntry", + "ChargeLedger", + "InterfaceTraceDeclaration", + "PoissonFactorization", + "PoissonOperator1D", + "SPACE_CHARGE_GROUP", + "SheetChargeEntry", + "TraceElectrostatics", + "add_interface_sheet_charge", + "add_sheet_charge_to_interior_residual", + "cell_parallel_permittivities", + "contact_displacement", + "electrostatic_trace_residual_and_jacobian", + "interface_trace_layout", + "layer_permittivities_from_geometry", + "layer_series_face_capacitances", + "rectangular_2d_face_capacitances", + "require_carrier_trace", + "require_occupancy", + "sheet_charge_row_weights", + "solve_electrostatic_traces" + ], + "solarlab.physics.electrostatics.poisson": [ + "PoissonFactorization", + "PoissonOperator1D", + "add_interface_sheet_charge", + "cell_parallel_permittivities", + "contact_displacement", + "layer_permittivities_from_geometry", + "layer_series_face_capacitances", + "rectangular_2d_face_capacitances" + ], + "solarlab.physics.transport": [ + "BLAKEMORE", + "GeneralizedCarrierFaceStatistics", + "RECOMBINATION_OFF", + "TransportCapabilityError", + "TransportCapabilityRequest", + "generalized_carrier_face_statistics", + "legacy_carrier_face_currents", + "legacy_face_diffusivity", + "legacy_fermi_dirac_face_currents", + "legacy_generalized_sg_current_n", + "legacy_generalized_sg_current_p", + "require_carrier_transport" + ], + "solarlab.physics.transport.electrochemical_flux": [ + "BAND_STEP_MODES", + "CarrierFaceFlux", + "CarrierFaceFluxes", + "HOLE_SEPARATE_INCREMENT_V1", + "LEGACY_SUMMED_POTENTIAL_V1", + "carrier_particle_fluxes", + "carrier_transport_potential_steps", + "electrochemical_step_from_densities", + "electron_current_from_particle_flux", + "hole_current_from_particle_flux", + "stable_sg_particle_flux" + ], + "solarlab.physics.contacts": [ + "BLOCKING", + "BUILT_IN_POTENTIAL_MODES", + "BuiltInPotentialSources", + "CONTACT_ALIGNMENT_CLASSES", + "CONTACT_SIDES", + "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "CarrierExchangeChannel", + "ContactAlignmentClass", + "ContactClosureCapabilityError", + "ContactEndpoint", + "ContactMaterial", + "ContactPotentialBoundary", + "ContactThermodynamicAssessment", + "ContactThermodynamicError", + "DOPING_EQUILIBRIUM", + "EXCHANGE_KINDS", + "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", + "FIXED_RESERVOIR", + "FLAT_BAND_CONTACT_VELOCITY_M_S", + "LEGACY_MANUAL", + "LEGACY_MANUAL_CONTACT_OFFSET", + "LegacyBandContact", + "METAL_FLOOR", + "METAL_WORK_FUNCTION", + "PARAMETER_FREE_CONTACT_ALIGNMENT", + "RESERVOIR_SOURCES", + "ROBIN", + "SCHOTTKY_BARRIER", + "SEMICONDUCTOR_WORK_FUNCTION", + "STATISTICS_CLOSURE", + "SemiconductorContactState", + "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", + "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", + "doping_equilibrium_densities", + "exchange_kind", + "junction_polarity", + "legacy_band_contact_potential", + "legacy_band_fermi_level", + "legacy_selective_contact_current", + "metal_reservoir_floor", + "require_contact_thermodynamic_certificate", + "resolve_built_in_potential_mode", + "resolve_exchange_velocities", + "schottky_equilibrium_n", + "schottky_equilibrium_p", + "semiconductor_contact_state", + "semiconductor_work_function" + ], + "solarlab.physics.contacts.thermodynamics": [ + "CONTACT_ALIGNMENT_CLASSES", + "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "ContactAlignmentClass", + "ContactEndpoint", + "ContactThermodynamicAssessment", + "ContactThermodynamicError", + "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", + "LEGACY_MANUAL_CONTACT_OFFSET", + "PARAMETER_FREE_CONTACT_ALIGNMENT", + "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", + "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", + "require_contact_thermodynamic_certificate" + ], + "solarlab.physics.interface_transport": [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ChargedTwoSidedInterfaceQSSResult", + "ELECTRON_MASS_KG", + "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", + "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", + "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", + "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", + "TwoSidedBulkState", + "TwoSidedCrossFluxEvaluation", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", + "remove_shared_interface_nodes", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", + "solve_two_sided_interface_qss", + "thermionic_emission_bound_m2_s" + ], + "solarlab.physics.interface_transport.thermionic": [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ELECTRON_MASS_KG", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", + "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", + "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", + "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", + "TwoSidedCrossFluxEvaluation", + "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "thermionic_emission_bound_m2_s" + ], + "solarlab.physics.interface_transport.two_sided": [ + "ChargedTwoSidedInterfaceQSSResult", + "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", + "TwoSidedBulkState", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "remove_shared_interface_nodes", + "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", + "solve_two_sided_interface_qss" + ], + "solarlab.physics.generation": [ + "BASELINE_GENERATION_REFERENCE", + "BeerLambertBinding", + "ControlVolumes", + "FixedGenerationProfile", + "GENERATION_SOURCE_UNIT", + "GenerationProfile", + "INCIDENCE_SIDES", + "OpticalLayerSpec", + "OpticalStackBinding", + "PhotonBudget", + "SPECTRAL_BEER_LAMBERT_MODEL_ID", + "SPECTRAL_PHOTON_FLUX_UNIT", + "SpectralBeerLambertBinding", + "SpectralPhotonFlux", + "StaleGenerationProfileError", + "TMMLayer", + "beer_lambert_absorbed_photon_flux", + "beer_lambert_generation", + "beer_lambert_optical_depth", + "constant_index_optical_constants", + "control_volume_digest", + "dropped_multipass_fraction", + "face_optical_depth", + "fixed_generation_reference", + "graded_slice_centres", + "sample_nk_table", + "sample_tabulated", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth", + "tmm_absorbed_photon_flux_per_cell", + "tmm_absorption_profile", + "tmm_cumulative_absorptance", + "tmm_point_generation", + "tmm_reflectance", + "tmm_transmittance", + "wavelength_grid_m" + ], + "solarlab.physics.generation.beer_lambert": [ + "BeerLambertBinding", + "beer_lambert_absorbed_photon_flux", + "beer_lambert_generation", + "beer_lambert_optical_depth", + "face_optical_depth" + ], + "solarlab.physics.generation.beer_lambert_spectral": [ + "SPECTRAL_BEER_LAMBERT_MODEL_ID", + "SpectralBeerLambertBinding", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth" + ], + "solarlab.reproducibility.scaps_beer_lambert": [ + "EXTRA_SWEEP_POINTS", + "HIGH_DOPING_MIN_N_GRID", + "SCAPS_BEER_LAMBERT_RESOURCE", + "SCAPS_BEER_LAMBERT_STUDY_ID", + "STANDARD_JV_SWEEP_HINTS", + "SWEEPS", + "apply_reference_point", + "load_scaps_beer_lambert_catalog", + "reference_catalog", + "validate_reference_point" + ], + "solarlab.device.compile_2d": [ + "CLASSICAL_2D_CONTACTS_V1", + "CLASSICAL_2D_DC_V1", + "CLASSICAL_2D_PERIODIC_CONTACTS_V1", + "CLASSICAL_2D_PERIODIC_DC_V1", + "compile_device_2d" + ], + "solarlab.device.compile_ionic_2d": [ + "CompiledIonicDevice2D", + "build_radiative_reabsorption_2d", + "build_two_sided_interface_srh_2d", + "compile_ionic_device_2d" + ], + "solarlab.equations.assembly.classical_1d": [ + "AssembledDC1DProblem", + "BulkRecombination", + "CarrierExchange", + "CarrierGeneration", + "CarrierReservoirs", + "CarrierStorage", + "CarrierTransport", + "ClassicalDC1D", + "GaussDisplacement", + "PotentialContacts", + "SpaceCharge", + "assembled_problem_factory", + "classical_dc_1d" + ], + "solarlab.equations.assembly.two_dimensional": [ + "AssembledDC2DProblem", + "BulkRecombination2D", + "CarrierExchange2D", + "CarrierGeneration2D", + "CarrierReservoirs2D", + "CarrierTransport2D", + "ClassicalDC2D", + "ElectrodeQuasiFermiFields2D", + "GaussDisplacement2D", + "PotentialContacts2D", + "SpaceCharge2D", + "assembled_problem_factory_2d", + "classical_dc_2d" + ], + "solarlab.physics.defects": [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "SUPPORTED_DISTRIBUTIONS", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "advance_metastable_configuration", + "build_defect_energy_quadrature", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "peak_density_from_integrated_density", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_frozen_metastable_charge_neutrality", + "solve_monovalent_defect_charge_neutrality", + "solve_multivalent_defect_charge_neutrality", + "stable_expit", + "validate_defect_energy_quadrature_order" + ], + "solarlab.physics.defects.dynamic_single_level": [ + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_monovalent_defect_charge_neutrality", + "stable_expit" + ], + "solarlab.physics.defects.distributions": [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "SUPPORTED_DISTRIBUTIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "build_defect_energy_quadrature", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "peak_density_from_integrated_density", + "validate_defect_energy_quadrature_order" + ], + "solarlab.physics.defects.multivalent": [ + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "solve_multivalent_defect_charge_neutrality" + ], + "solarlab.physics.defects.metastable": [ + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "advance_metastable_configuration", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "solve_frozen_metastable_charge_neutrality" + ], + "solarlab.device.compile_dynamic_defect_1d": [ + "CapabilityError", + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "compile_dynamic_defect_device_1d", + "compile_metastable_device_1d" + ], + "solarlab.equations.dynamic_defect_1d": [ + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "DynamicDefectState1D", + "DynamicInterfaceTrapBinding1D", + "StationaryDefectEvaluation1D", + "StationaryDefectModel1D", + "TwoSidedIonicComponent1D" + ], + "solarlab.equations.assembly.dynamic_defects_1d": [ + "AssembledDynamicDefect1DProblem", + "DynamicBulkCarrierCaptureTerm", + "DynamicBulkTrapRateTerm", + "DynamicBulkTrapStorageTerm", + "DynamicDefectACSweepPoint", + "DynamicDefectACSweepResult", + "DynamicDefectFields", + "DynamicDefectSmallSignal1D", + "DynamicDefectSpaceCharge", + "DynamicDefectSteadyOptions", + "DynamicDefectSteadyResult", + "DynamicDefectStorage1D", + "DynamicDefectSystem1D", + "DynamicInterfaceTrapRateTerm", + "DynamicInterfaceTrapStorageTerm", + "DynamicInterfaceTrapTieTerm", + "StationaryDefectRecombinationTerm", + "dynamic_defect_step_accounting", + "dynamic_defect_system_1d", + "solve_dynamic_defect_steady_1d" + ], + "solarlab.experiments.dynamic_defect_impedance": [ + "DYNAMIC_DEFECT_IMPEDANCE_SCHEMA", + "DynamicDefectCapability", + "DynamicDefectImpedanceCapabilityError", + "DynamicDefectImpedanceError", + "DynamicDefectImpedanceOptions", + "DynamicDefectImpedanceProtocol", + "DynamicDefectImpedanceResult", + "build_dynamic_defect_impedance_protocol", + "classify_dynamic_defect_capability", + "solve_bulk_defect_impedance", + "solve_dynamic_defect_impedance", + "solve_interface_defect_impedance" + ], + "solarlab.experiments.defect_ion_impedance": [ + "DefectIonCapability", + "DefectIonImpedanceCapabilityError", + "DefectIonImpedanceError", + "DefectIonImpedanceOptions", + "DefectIonImpedanceResult", + "solve_defect_ion_impedance" + ], + "solarlab.experiments.capacitance_frequency": [ + "DefectCFError", + "DefectCFOptions", + "DefectCFResult", + "capacitance_frequency_from_admittance", + "capacitance_frequency_from_sweep", + "run_defect_capacitance_frequency" + ], + "solarlab.experiments.dynamic_defect_transient": [ + "DynamicDefectTransientCapability", + "DynamicDefectTransientCapabilityError", + "DynamicDefectTransientError", + "DynamicDefectTransientOptions", + "DynamicDefectTransientResult", + "VoltageInterpolation", + "classify_dynamic_defect_transient_capability", + "solve_bulk_defect_ion_transient", + "solve_bulk_defect_transient", + "solve_dynamic_defect_transient", + "solve_interface_defect_ion_transient", + "solve_interface_defect_transient" + ], + "solarlab.experiments.metastable_transient": [ + "METASTABLE_TRANSIENT_SCHEME", + "FrozenMetastableJVPoint", + "FrozenMetastableJVResult", + "MetastableCapabilityError", + "MetastablePreparationError", + "MetastableTransientCertificate", + "MetastableTransientError", + "MetastableTransientResult", + "PreparedMetastableState", + "prepare_metastable_state", + "solve_frozen_metastable_jv", + "solve_frozen_metastable_steady", + "solve_metastable_transient" ] }, "public_imports": { @@ -865,7 +1553,15 @@ "HistoricalDisable", "NamedPreset", "PresetSelection", - "select_preset" + "select_preset", + "P08CompilerOptions", + "P08ModelVersionMapping", + "P08_MODEL_VERSION_MAPPINGS", + "P08_SOURCE_PATHS", + "P08_V1_MODEL_REFS", + "P08_V2_MODEL_REFS", + "build_p08_model_registry", + "build_p08_preset" ], "solarlab.physics.registry": [ "CapabilityContext", @@ -966,7 +1662,10 @@ "solarlab.device.compile_1d": [ "CapabilityError", "CompiledDevice1D", - "compile_device_1d" + "compile_device_1d", + "bind_spectral_beer_lambert_1d", + "p08_identity_inputs", + "unsupported" ], "solarlab.equations": [ "CapabilityError", @@ -1332,6 +2031,684 @@ "Steady2DOptions", "Steady2DResult", "solve_steady_state_2d" + ], + "solarlab.discretization": [ + "DIELECTRIC_RULES", + "LAYER_SERIES_CAPACITANCE_V2", + "LegacyFaceJacobian", + "NODAL_HARMONIC_DIELECTRIC_V1", + "VACUUM_PERMITTIVITY_F_M", + "arithmetic_face_mean", + "bernoulli", + "bernoulli_derivative", + "flux_divergence", + "guarded_harmonic_face_mean", + "harmonic_face_mean", + "harmonic_mean", + "legacy_sg_current_n", + "legacy_sg_current_n_jacobian", + "legacy_sg_current_p", + "legacy_sg_current_p_jacobian", + "series_face_capacitance", + "subface_series_capacitance" + ], + "solarlab.discretization.face_average": [ + "DIELECTRIC_RULES", + "LAYER_SERIES_CAPACITANCE_V2", + "NODAL_HARMONIC_DIELECTRIC_V1", + "VACUUM_PERMITTIVITY_F_M", + "arithmetic_face_mean", + "guarded_harmonic_face_mean", + "harmonic_face_mean", + "harmonic_mean", + "series_face_capacitance", + "subface_series_capacitance" + ], + "solarlab.mesh": [ + "ControlVolumeGeometry1D", + "ElectricalStack", + "GEOMETRY_NAMES", + "HALF_ENDPOINT_V1", + "INTEGER_ENDPOINT_V1", + "InterfacePlane", + "InterfaceStencil", + "LEFT_LAYER_WINS", + "PHYSICAL_BOUNDARY_TWO_SIDED_V1", + "PHYSICAL_HALF_ENDPOINT_V2", + "PortFace", + "RIGHT_LAYER_WINS", + "StackLayer", + "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", + "build_geometry", + "build_interface_stencils", + "multilayer_grid", + "node_owner", + "physical_half_endpoint_geometry", + "remove_shared_interface_nodes", + "tanh_grid" + ], + "solarlab.mesh.geometry": [ + "ControlVolumeGeometry1D", + "GEOMETRY_NAMES", + "HALF_ENDPOINT_V1", + "INTEGER_ENDPOINT_V1", + "InterfacePlane", + "NO_SHARED_NODES", + "PHYSICAL_BOUNDARY_TWO_SIDED_V1", + "PHYSICAL_HALF_ENDPOINT_V2", + "PortFace", + "TWO_SIDED_TRACE_V1", + "areal_interface_to_cell_source", + "build_geometry", + "dual_cell_faces", + "half_endpoint_widths", + "half_endpoint_geometry", + "integer_endpoint_geometry", + "integer_endpoint_widths", + "physical_boundary_two_sided_geometry", + "physical_cell_faces", + "physical_half_endpoint_geometry", + "two_sided_trace_geometry", + "two_sided_trace_widths" + ], + "solarlab.physics.electrostatics": [ + "ChargeEntry", + "ChargeLedger", + "InterfaceTraceDeclaration", + "PoissonFactorization", + "PoissonOperator1D", + "SPACE_CHARGE_GROUP", + "SheetChargeEntry", + "TraceElectrostatics", + "add_interface_sheet_charge", + "add_sheet_charge_to_interior_residual", + "cell_parallel_permittivities", + "contact_displacement", + "electrostatic_trace_residual_and_jacobian", + "interface_trace_layout", + "layer_permittivities_from_geometry", + "layer_series_face_capacitances", + "rectangular_2d_face_capacitances", + "require_carrier_trace", + "require_occupancy", + "sheet_charge_row_weights", + "solve_electrostatic_traces" + ], + "solarlab.physics.electrostatics.poisson": [ + "PoissonFactorization", + "PoissonOperator1D", + "add_interface_sheet_charge", + "cell_parallel_permittivities", + "contact_displacement", + "layer_permittivities_from_geometry", + "layer_series_face_capacitances", + "rectangular_2d_face_capacitances" + ], + "solarlab.physics.transport": [ + "BLAKEMORE", + "GeneralizedCarrierFaceStatistics", + "RECOMBINATION_OFF", + "TransportCapabilityError", + "TransportCapabilityRequest", + "generalized_carrier_face_statistics", + "legacy_carrier_face_currents", + "legacy_face_diffusivity", + "legacy_fermi_dirac_face_currents", + "legacy_generalized_sg_current_n", + "legacy_generalized_sg_current_p", + "require_carrier_transport" + ], + "solarlab.physics.transport.electrochemical_flux": [ + "BAND_STEP_MODES", + "CarrierFaceFlux", + "CarrierFaceFluxes", + "HOLE_SEPARATE_INCREMENT_V1", + "LEGACY_SUMMED_POTENTIAL_V1", + "carrier_particle_fluxes", + "carrier_transport_potential_steps", + "electrochemical_step_from_densities", + "electron_current_from_particle_flux", + "hole_current_from_particle_flux", + "stable_sg_particle_flux" + ], + "solarlab.physics.contacts": [ + "BLOCKING", + "BUILT_IN_POTENTIAL_MODES", + "BuiltInPotentialSources", + "CONTACT_ALIGNMENT_CLASSES", + "CONTACT_SIDES", + "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "CarrierExchangeChannel", + "ContactAlignmentClass", + "ContactClosureCapabilityError", + "ContactEndpoint", + "ContactMaterial", + "ContactPotentialBoundary", + "ContactThermodynamicAssessment", + "ContactThermodynamicError", + "DOPING_EQUILIBRIUM", + "EXCHANGE_KINDS", + "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", + "FIXED_RESERVOIR", + "FLAT_BAND_CONTACT_VELOCITY_M_S", + "LEGACY_MANUAL", + "LEGACY_MANUAL_CONTACT_OFFSET", + "LegacyBandContact", + "METAL_FLOOR", + "METAL_WORK_FUNCTION", + "PARAMETER_FREE_CONTACT_ALIGNMENT", + "RESERVOIR_SOURCES", + "ROBIN", + "SCHOTTKY_BARRIER", + "SEMICONDUCTOR_WORK_FUNCTION", + "STATISTICS_CLOSURE", + "SemiconductorContactState", + "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", + "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", + "doping_equilibrium_densities", + "exchange_kind", + "junction_polarity", + "legacy_band_contact_potential", + "legacy_band_fermi_level", + "legacy_selective_contact_current", + "metal_reservoir_floor", + "require_contact_thermodynamic_certificate", + "resolve_built_in_potential_mode", + "resolve_exchange_velocities", + "schottky_equilibrium_n", + "schottky_equilibrium_p", + "semiconductor_contact_state", + "semiconductor_work_function" + ], + "solarlab.physics.contacts.thermodynamics": [ + "CONTACT_ALIGNMENT_CLASSES", + "CONTACT_THERMODYNAMIC_TOLERANCE_EV", + "ContactAlignmentClass", + "ContactEndpoint", + "ContactThermodynamicAssessment", + "ContactThermodynamicError", + "EXTERNAL_METAL_CONTACT_ALIGNMENT", + "FITTED_MANUAL_CONTACT_ALIGNMENT", + "LEGACY_MANUAL_CONTACT_OFFSET", + "PARAMETER_FREE_CONTACT_ALIGNMENT", + "assess_contact_thermodynamics", + "certify_parameter_free_contact_equilibrium", + "classify_contact_alignment_mode", + "contact_quasi_fermi_levels", + "require_contact_thermodynamic_certificate" + ], + "solarlab.physics.interface_transport": [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ChargedTwoSidedInterfaceQSSResult", + "ELECTRON_MASS_KG", + "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", + "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", + "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", + "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", + "TwoSidedBulkState", + "TwoSidedCrossFluxEvaluation", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", + "remove_shared_interface_nodes", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", + "solve_two_sided_interface_qss", + "thermionic_emission_bound_m2_s" + ], + "solarlab.physics.interface_transport.thermionic": [ + "A_STAR_FREE_ELECTRON_A_M2_K2", + "ELECTRON_MASS_KG", + "LEGACY_UNNORMALIZED_THERMIONIC_V1", + "PLANCK_CONSTANT_J_S", + "RECIPROCAL_PHYSICAL_THERMIONIC_V2", + "ReciprocalThermionicCompositeEvaluation", + "ReciprocalThermionicEvaluation", + "SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1", + "TE_BARRIER_THRESHOLD_EV", + "THERMIONIC_MODEL_VERSIONS", + "ThermionicCapEvaluation", + "ThermionicCarrierKind", + "ThermionicCombinationMode", + "ThermionicModelVersion", + "ThermionicStatisticsKind", + "TwoSidedCrossFluxEvaluation", + "cap_particle_flux_thermionic", + "combine_sg_and_reciprocal_thermionic_flux", + "effective_mass_from_dos", + "emission_velocity", + "fermi_dirac_one", + "fermi_dirac_richardson_flux", + "fermi_dirac_zero", + "fermi_richardson_flux", + "is_free_electron_default", + "physical_barrier_steps_eV", + "physical_carrier_barrier_step_eV", + "reciprocal_richardson", + "reciprocal_thermionic_flux_m2_s", + "resolve_layer_richardson", + "richardson_from_dos", + "scaps_thermionic_flux", + "thermionic_emission_bound_m2_s" + ], + "solarlab.physics.interface_transport.two_sided": [ + "ChargedTwoSidedInterfaceQSSResult", + "EquilibriumReferencedSheetCharge", + "FixedOccupancyTwoSidedResult", + "TwoSidedBulkState", + "TwoSidedInterfacePhysics", + "TwoSidedInterfaceQSSResult", + "remove_shared_interface_nodes", + "solve_charged_two_sided_interface_qss", + "solve_fixed_occupancy_two_sided_interface", + "solve_two_sided_interface_qss" + ], + "solarlab.physics.generation": [ + "BASELINE_GENERATION_REFERENCE", + "BeerLambertBinding", + "ControlVolumes", + "FixedGenerationProfile", + "GENERATION_SOURCE_UNIT", + "GenerationProfile", + "INCIDENCE_SIDES", + "OpticalLayerSpec", + "OpticalStackBinding", + "PhotonBudget", + "SPECTRAL_BEER_LAMBERT_MODEL_ID", + "SPECTRAL_PHOTON_FLUX_UNIT", + "SpectralBeerLambertBinding", + "SpectralPhotonFlux", + "StaleGenerationProfileError", + "TMMLayer", + "beer_lambert_absorbed_photon_flux", + "beer_lambert_generation", + "beer_lambert_optical_depth", + "constant_index_optical_constants", + "control_volume_digest", + "dropped_multipass_fraction", + "face_optical_depth", + "fixed_generation_reference", + "graded_slice_centres", + "sample_nk_table", + "sample_tabulated", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth", + "tmm_absorbed_photon_flux_per_cell", + "tmm_absorption_profile", + "tmm_cumulative_absorptance", + "tmm_point_generation", + "tmm_reflectance", + "tmm_transmittance", + "wavelength_grid_m" + ], + "solarlab.physics.generation.beer_lambert": [ + "BeerLambertBinding", + "beer_lambert_absorbed_photon_flux", + "beer_lambert_generation", + "beer_lambert_optical_depth", + "face_optical_depth" + ], + "solarlab.physics.generation.beer_lambert_spectral": [ + "SPECTRAL_BEER_LAMBERT_MODEL_ID", + "SpectralBeerLambertBinding", + "spectral_beer_lambert_absorbed_photon_flux_per_cell", + "spectral_beer_lambert_absorption_coefficients", + "spectral_beer_lambert_absorption_profile", + "spectral_beer_lambert_optical_depth" + ], + "solarlab.reproducibility.scaps_beer_lambert": [ + "EXTRA_SWEEP_POINTS", + "HIGH_DOPING_MIN_N_GRID", + "SCAPS_BEER_LAMBERT_RESOURCE", + "SCAPS_BEER_LAMBERT_STUDY_ID", + "STANDARD_JV_SWEEP_HINTS", + "SWEEPS", + "apply_reference_point", + "load_scaps_beer_lambert_catalog", + "reference_catalog", + "validate_reference_point" + ], + "solarlab.device.compile_2d": [ + "CLASSICAL_2D_CONTACTS_V1", + "CLASSICAL_2D_DC_V1", + "CLASSICAL_2D_PERIODIC_CONTACTS_V1", + "CLASSICAL_2D_PERIODIC_DC_V1", + "compile_device_2d" + ], + "solarlab.device.compile_ionic_2d": [ + "CompiledIonicDevice2D", + "build_radiative_reabsorption_2d", + "build_two_sided_interface_srh_2d", + "compile_ionic_device_2d" + ], + "solarlab.equations.assembly.classical_1d": [ + "AssembledDC1DProblem", + "BulkRecombination", + "CarrierExchange", + "CarrierGeneration", + "CarrierReservoirs", + "CarrierStorage", + "CarrierTransport", + "ClassicalDC1D", + "GaussDisplacement", + "PotentialContacts", + "SpaceCharge", + "assembled_problem_factory", + "classical_dc_1d" + ], + "solarlab.equations.assembly.two_dimensional": [ + "AssembledDC2DProblem", + "BulkRecombination2D", + "CarrierExchange2D", + "CarrierGeneration2D", + "CarrierReservoirs2D", + "CarrierTransport2D", + "ClassicalDC2D", + "ElectrodeQuasiFermiFields2D", + "GaussDisplacement2D", + "PotentialContacts2D", + "SpaceCharge2D", + "assembled_problem_factory_2d", + "classical_dc_2d" + ], + "solarlab.physics.defects": [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "SUPPORTED_DISTRIBUTIONS", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "advance_metastable_configuration", + "build_defect_energy_quadrature", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "peak_density_from_integrated_density", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_frozen_metastable_charge_neutrality", + "solve_monovalent_defect_charge_neutrality", + "solve_multivalent_defect_charge_neutrality", + "stable_expit", + "validate_defect_energy_quadrature_order" + ], + "solarlab.physics.defects.dynamic_single_level": [ + "DynamicBulkTrapEvaluation", + "DynamicBulkTrapLayout", + "DynamicBulkTrapMode", + "DynamicInterfaceTrapEvaluation", + "DynamicInterfaceTrapSpec", + "MonovalentDefectClosureResult", + "MonovalentDefectNeutralityState", + "MonovalentDefectRegion", + "MonovalentSpeciesSpec", + "SUPPORTED_MONOVALENT_TRANSITIONS", + "TRANSITION_ACCEPTOR", + "TRANSITION_DONOR", + "TRANSITION_NEUTRAL", + "bulk_trap_charge_density", + "compile_dynamic_bulk_trap_layout", + "evaluate_dynamic_bulk_traps", + "evaluate_dynamic_bulk_traps_about_qss", + "evaluate_dynamic_interface_trap", + "evaluate_monovalent_defect_closure", + "evaluate_monovalent_region_closure", + "logit_occupancy_secant", + "occupancy_from_logit_increment", + "occupancy_logit", + "one_minus_occupancy_from_logit_increment", + "quasi_steady_bulk_trap_logit", + "quasi_steady_bulk_trap_occupancy", + "solve_monovalent_defect_charge_neutrality", + "stable_expit" + ], + "solarlab.physics.defects.distributions": [ + "DEFAULT_DEFECT_ENERGY_QUADRATURE_ORDER", + "DENSITY_INTEGRATED", + "DENSITY_PEAK", + "DIST_CONDUCTION_BAND_TAIL", + "DIST_GAUSSIAN", + "DIST_SINGLE_LEVEL", + "DIST_UNIFORM", + "DIST_VALENCE_BAND_TAIL", + "DefectDistributionSpec", + "DefectEnergyQuadrature", + "MAXIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "MINIMUM_DEFECT_ENERGY_QUADRATURE_ORDER", + "SUPPORTED_DISTRIBUTIONS", + "SpatialDensityProfileSpec", + "SpatialProfileKnot", + "WIDTH_GAUSSIAN_SIGMA", + "WIDTH_NOT_APPLICABLE", + "WIDTH_SCAPS_CHARACTERISTIC", + "WIDTH_UNIFORM_FULL", + "build_defect_energy_quadrature", + "density_weighted_mean_occupancy", + "distribution_shape_integral_eV", + "evaluate_spatial_density_profile", + "integrated_density_from_peak_density", + "peak_density_from_integrated_density", + "validate_defect_energy_quadrature_order" + ], + "solarlab.physics.defects.multivalent": [ + "MultivalentConfigurationSpec", + "MultivalentDefectClosureResult", + "MultivalentDefectNeutralityState", + "MultivalentDefectRegion", + "MultivalentSpeciesSpec", + "MultivalentTransitionKineticsSpec", + "evaluate_multivalent_defect_closure", + "evaluate_multivalent_region_closure", + "solve_multivalent_defect_charge_neutrality" + ], + "solarlab.physics.defects.metastable": [ + "DOUBLE_ELECTRON_CAPTURE", + "DOUBLE_HOLE_CAPTURE", + "ELECTRON_CAPTURE_PLUS_HOLE_EMISSION", + "FrozenMetastableEvaluation", + "FrozenMetastableRegion", + "HOLE_CAPTURE_PLUS_ELECTRON_EMISSION", + "MetastableConfigurationClosureResult", + "MetastableConversionKineticsSpec", + "MetastableDefectSpec", + "MetastableDynamicStep", + "advance_metastable_configuration", + "configuration_charge_transfer_C_m3", + "configuration_from_logit", + "configuration_logit", + "evaluate_frozen_metastable_region", + "evaluate_metastable_configuration_closure", + "solve_frozen_metastable_charge_neutrality" + ], + "solarlab.device.compile_dynamic_defect_1d": [ + "CapabilityError", + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "compile_dynamic_defect_device_1d", + "compile_metastable_device_1d" + ], + "solarlab.equations.dynamic_defect_1d": [ + "CompiledDynamicDefectDevice1D", + "CompiledMetastableDevice1D", + "DynamicDefectState1D", + "DynamicInterfaceTrapBinding1D", + "StationaryDefectEvaluation1D", + "StationaryDefectModel1D", + "TwoSidedIonicComponent1D" + ], + "solarlab.equations.assembly.dynamic_defects_1d": [ + "AssembledDynamicDefect1DProblem", + "DynamicBulkCarrierCaptureTerm", + "DynamicBulkTrapRateTerm", + "DynamicBulkTrapStorageTerm", + "DynamicDefectACSweepPoint", + "DynamicDefectACSweepResult", + "DynamicDefectFields", + "DynamicDefectSmallSignal1D", + "DynamicDefectSpaceCharge", + "DynamicDefectSteadyOptions", + "DynamicDefectSteadyResult", + "DynamicDefectStorage1D", + "DynamicDefectSystem1D", + "DynamicInterfaceTrapRateTerm", + "DynamicInterfaceTrapStorageTerm", + "DynamicInterfaceTrapTieTerm", + "StationaryDefectRecombinationTerm", + "dynamic_defect_step_accounting", + "dynamic_defect_system_1d", + "solve_dynamic_defect_steady_1d" + ], + "solarlab.experiments.dynamic_defect_impedance": [ + "DYNAMIC_DEFECT_IMPEDANCE_SCHEMA", + "DynamicDefectCapability", + "DynamicDefectImpedanceCapabilityError", + "DynamicDefectImpedanceError", + "DynamicDefectImpedanceOptions", + "DynamicDefectImpedanceProtocol", + "DynamicDefectImpedanceResult", + "build_dynamic_defect_impedance_protocol", + "classify_dynamic_defect_capability", + "solve_bulk_defect_impedance", + "solve_dynamic_defect_impedance", + "solve_interface_defect_impedance" + ], + "solarlab.experiments.defect_ion_impedance": [ + "DefectIonCapability", + "DefectIonImpedanceCapabilityError", + "DefectIonImpedanceError", + "DefectIonImpedanceOptions", + "DefectIonImpedanceResult", + "solve_defect_ion_impedance" + ], + "solarlab.experiments.capacitance_frequency": [ + "DefectCFError", + "DefectCFOptions", + "DefectCFResult", + "capacitance_frequency_from_admittance", + "capacitance_frequency_from_sweep", + "run_defect_capacitance_frequency" + ], + "solarlab.experiments.dynamic_defect_transient": [ + "DynamicDefectTransientCapability", + "DynamicDefectTransientCapabilityError", + "DynamicDefectTransientError", + "DynamicDefectTransientOptions", + "DynamicDefectTransientResult", + "VoltageInterpolation", + "classify_dynamic_defect_transient_capability", + "solve_bulk_defect_ion_transient", + "solve_bulk_defect_transient", + "solve_dynamic_defect_transient", + "solve_interface_defect_ion_transient", + "solve_interface_defect_transient" + ], + "solarlab.experiments.metastable_transient": [ + "METASTABLE_TRANSIENT_SCHEME", + "FrozenMetastableJVPoint", + "FrozenMetastableJVResult", + "MetastableCapabilityError", + "MetastablePreparationError", + "MetastableTransientCertificate", + "MetastableTransientError", + "MetastableTransientResult", + "PreparedMetastableState", + "prepare_metastable_state", + "solve_frozen_metastable_jv", + "solve_frozen_metastable_steady", + "solve_metastable_transient" ] }, "checked_consumers": [ diff --git a/tests/integration/test_p08_05_compiler_wiring.py b/tests/integration/test_p08_05_compiler_wiring.py new file mode 100644 index 00000000..2cfeb95b --- /dev/null +++ b/tests/integration/test_p08_05_compiler_wiring.py @@ -0,0 +1,828 @@ +"""Integration tests for P08-05 opt-in compiler/registry wiring and Gate G8 closeout. + +Verifies: +(a) 0-byte manifest and exact SHA-256 identity invariance under default ``v1`` + across all 5 compilers (1D deduplicated & two-sided trace, single/dual ionic + 1D, 2D, and ionic 2D) relative to the Wave 2 baseline ``582f019e``. +(b) Pairwise-distinct ``compiled.identity`` and ``H_physics`` (``physics_identity``) + digests under every P08 ``v2`` option, ``HistoricalDisable`` / ``D20`` pre-P08 + CBO pinning enforcement, permanent ``CapabilityError`` refusal of falsified + ``interface_shared_occupancy``, and strict certificate non-reuse across + ``v1 <-> v2`` in ``solve_transient``, ``solve_impedance``, ``solve_ionic_transient``, + and ``solve_ionic_impedance``. +(c) End-to-end compiled 1D all-V2 (``LAYER_SERIES_CAPACITANCE_V2`` + + ``PHYSICAL_HALF_ENDPOINT_V2`` + ``HOLE_SEPARATE_INCREMENT_V1`` + + ``RECIPROCAL_PHYSICAL_THERMIONIC_V2`` + ``beer_lambert_spectral``): + 0-ULP ``DC1DProblem`` vs ``AssembledDC1DProblem`` parity, FD Jacobian + consistency, dark equilibrium, illuminated steady J-V, ``two_sided_trace`` + +3.0 V super-flatband continuation, Backward Euler transient step-accounting + conservation, and 3-grid spatial refinement convergence. +(d) Compiled 2D all-V2: 0-ULP ``DC2DProblem`` vs ``AssembledDC2DProblem`` and + ``Ionic2DProblem`` vs ``AssembledIonic2DProblem`` parity, exact 2D series + capacitor, and 1D-vs-2D all-V2 column steady-state consistency. +""" + +from __future__ import annotations + +import hashlib +import json +import math +from pathlib import Path +from typing import Any, Literal, cast + +import numpy as np +from numpy.typing import NDArray +import pytest + +from examples.research_1d.ionic_steady import controls as ionic_steady_controls +from examples.research_1d.transient import json_value +from solarlab.config.device_inputs import DeviceInput +from solarlab.config.identity import BuildSource, physics_identity +from solarlab.config.model_parameters import device_topology, layer_parameter_source +from solarlab.config.resolve_device import resolve_device +from solarlab.device.compile_1d import CapabilityError, compile_device_1d, p08_identity_inputs +from solarlab.device.compile_2d import compile_device_2d +from solarlab.device.compile_ionic_1d import compile_ionic_device_1d +from solarlab.device.compile_ionic_2d import compile_ionic_device_2d +from solarlab.device.compile_multiple_ionic_1d import compile_multiple_ionic_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.resolved import PreparedDevice +from solarlab.discretization import LAYER_SERIES_CAPACITANCE_V2, VACUUM_PERMITTIVITY_F_M +from solarlab.equations.assembly.classical_1d import AssembledDC1DProblem +from solarlab.equations.assembly.ionic_2d import AssembledIonic2DProblem +from solarlab.equations.assembly.two_dimensional import AssembledDC2DProblem +from solarlab.equations.dc_1d import DC1DProblem +from solarlab.equations.dc_2d import DC2DProblem +from solarlab.equations.ionic_2d import Ionic2DProblem +from solarlab.experiments.impedance import solve_impedance +from solarlab.experiments.ionic_impedance import solve_ionic_impedance +from solarlab.experiments.ionic_transient import ( + IonicTransientOptions, + load_ionic_steady_initial, + solve_ionic_transient, +) +from solarlab.experiments.jv.steady import run_steady_jv +from solarlab.experiments.transient import TransientOptions, TransientProtocol, solve_transient +from solarlab.experiments.two_dimensional.inputs import JV2DInput +from solarlab.materials.resources import ResourceLibrary, ResourceTable +from solarlab.materials.source import SourceDocument +from solarlab.mesh import PHYSICAL_HALF_ENDPOINT_V2 +from solarlab.physics.contacts import ( + CONTACT_THERMODYNAMIC_TOLERANCE_EV, + ContactEndpoint, + ContactThermodynamicError, + assess_contact_thermodynamics, + require_contact_thermodynamic_certificate, +) +from solarlab.physics.generation import sample_tabulated +from solarlab.physics.interface_transport import ( + LEGACY_UNNORMALIZED_THERMIONIC_V1, + RECIPROCAL_PHYSICAL_THERMIONIC_V2, + SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, +) +from solarlab.physics.presets import ( + P08_MODEL_VERSION_MAPPINGS, + P08_SOURCE_PATHS, + P08_V1_MODEL_REFS, + P08_V2_MODEL_REFS, + P08CompilerOptions, + build_p08_model_registry, + build_p08_preset, + select_preset, +) +from solarlab.physics.registry import CapabilityContext, Scope +from solarlab.physics.selection import ModelChoice +from solarlab.physics.transport.electrochemical_flux import HOLE_SEPARATE_INCREMENT_V1 +from solarlab.solvers.nonlinear.ionic_1d import solve_ionic_steady_state +from solarlab.solvers.nonlinear.problem import SolveBudget +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import ( + SteadyOptions, + solve_equilibrium, + solve_steady_state, +) +from solarlab.solvers.nonlinear.steady_2d import Steady2DOptions, solve_steady_state_2d +from solarlab_research.cbo_scan import InterfaceCBOScanError, enforce_pre_p08_cbo_pinning + +ROOT = Path(__file__).resolve().parents[2] +DATA_DIR = ROOT / "perovskite-sim" / "perovskite_sim" / "data" + +# Portable checkout-independent SHA-256 digests captured on +# refactor/wave2-n-baseline @ 582f019ef5743d43546219590a5ae094ca300594 +# using repo-relative SourceDocument("examples/research_1d/device.json", ...). +PINNED_V1_COMPILE_1D_SHA256 = "f61600398765ade465c1eea97a892aa10d8014fa564ac75a5b8d41e645c38c46" +PINNED_V1_HET_DEDUP_DEVICE_SHA256 = "2908b0632e5a96e512e5d77d24a483152589bce082372b5f909db87b6313fee4" +PINNED_V1_HET_DEDUP_IFACE_SHA256 = "4b60ec8744e26ea34fc32a8441bdbc35d35ee151653cb7052414db34d641880b" +PINNED_V1_HET_TRACE_DEVICE_SHA256 = "43c649df0ec56f7ff4f0bb0046e2629c88bb25f332bd1785841d0872e07a8c39" +PINNED_V1_HET_TRACE_IFACE_SHA256 = "372af71b2cbd97b3cbc66b6971e4c32818f6c5a9a4391ae02da913a40f0f8aa4" +PINNED_V1_IONIC_1D_SHA256 = "80dbb4f30a2820a2a73219fdd62a0117374b842b22b5781758c2a492f2183215" +PINNED_V1_MULTI_IONIC_1D_SHA256 = "76483953cfbdc4d53d1acb5d0c1db06d61ed4a24dd6d200f89ba19c9886b2986" +PINNED_V1_COMPILE_2D_SHA256 = "1a9d23b527817d742bc7c974b32d7527ef06b3b8678bde231e7fe76e444d1408" +PINNED_V1_IONIC_2D_SHA256 = "d62f674f33dec4298a3c8319c13f23c80749f081b742320b5f8ce776312e719d" + + +def load_device() -> PreparedDevice: + """Load the research 1D stack with a portable repo-relative SourceDocument ID.""" + rel_id = "examples/research_1d/device.json" + raw = (ROOT / rel_id).read_bytes() + source = SourceDocument(rel_id, raw) + document = json.loads(raw) + catalog = { + **document["default_catalog"], + "evidence": [[source.id, source.sha256]], + } + return resolve_device( + DeviceInput.model_validate(document["device"]), + DefaultCatalog.from_mapping(catalog), + ResourceLibrary(), + sources=(source,), + ) + + +def prepare_confined_ion_device(*, diffusion_only: bool = True) -> PreparedDevice: + """Prepare the confined absorber ion stack with portable repo-relative source IDs.""" + template = load_device() + data = template.to_input().editing_data() + data["id"] = "confined_absorber_positive_ion" + data["settings"]["ion_steric_diffusion_only"] = diffusion_only + absorber = next(layer for layer in data["layers"] if layer["role"].lower() == "absorber") + absorber["parameters"].update(P0=1.0e24, P_lim=1.0e27, D_ion=1.0e-16, E_a_ion=0.58) + return resolve_device( + DeviceInput.model_validate(data), + template.defaults, + template.resources, + sources=template.sources, + ) + + +def _with_edits(prepared: PreparedDevice, mutate_fn: Any, *, resources: ResourceLibrary | None = None) -> PreparedDevice: + data = prepared.to_input().editing_data() + mutate_fn(data) + return resolve_device( + DeviceInput.model_validate(data), + prepared.defaults, + prepared.resources if resources is None else resources, + sources=prepared.sources, + ) + + +def _heterojunction_astar_device(base: PreparedDevice) -> PreparedDevice: + def mutate(data: dict[str, Any]) -> None: + astars_n = (2.0e5, 4.5e5, 6.0e5) + astars_p = (3.0e5, 5.0e5, 7.0e5) + for layer, an, ap in zip(data["layers"], astars_n, astars_p): + layer.setdefault("parameters", {})["A_star_n"] = an + layer["parameters"]["A_star_p"] = ap + + return _with_edits(base, mutate) + + +def _two_domain_ionic_device(base_ion: PreparedDevice) -> PreparedDevice: + def mutate(data: dict[str, Any]) -> None: + for layer in data["layers"]: + p = layer.setdefault("parameters", {}) + if layer["id"] in ("htl", "etl"): + p.update(P0=1.0e23, P_lim=1.0e26, D_ion=1.0e-15, E_a_ion=0.0) + else: + p.update(P0=0.0, D_ion=0.0) + + return _with_edits(base_ion, mutate) + + +def _spectral_heterojunction_device(base: PreparedDevice, *, two_sided_trace: bool = False) -> PreparedDevice: + """3-layer heterojunction with unequal DOS/permittivity/A* and spectral nk + AM1.5G.""" + raw = np.loadtxt(DATA_DIR / "am15g.csv", delimiter=",", comments="#") + wl_nm = np.linspace(320.0, 920.0, 61) + flux = sample_tabulated(raw[:, 0], raw[:, 1], wl_nm, name="am15g") + spec_lines = ["wavelength_nm,spectral_flux_m-2_s-1_m-1\n"] + [ + f"{repr(float(w))},{repr(float(f))}\n" for w, f in zip(wl_nm, flux) + ] + spec_table = ResourceTable( + "am15g_61", + "spectrum", + SourceDocument("am15g_61.csv", "".join(spec_lines).encode("utf-8")), + ) + nk_tables = tuple( + ResourceTable( + mat, + "nk", + SourceDocument(f"nk:{mat}.csv", (DATA_DIR / "nk" / f"{mat}.csv").read_bytes()), + ) + for mat in ("spiro_OMeTAD", "MAPbI3", "TiO2") + ) + merged_resources = ResourceLibrary((*base.resources.tables, spec_table, *nk_tables)) + + def mutate(data: dict[str, Any]) -> None: + data["spectrum"] = "am15g_61" + specs = ( + ("spiro_OMeTAD", 2.0e5, 3.0e5), + ("MAPbI3", 4.5e5, 5.0e5), + ("TiO2", 6.0e5, 7.0e5), + ) + for layer, (nk_name, an, ap) in zip(data["layers"], specs): + p = layer.setdefault("parameters", {}) + p.update( + optical_material=nk_name, + A_star_n=an, + A_star_p=ap, + incoherent=False, + ) + if layer["role"] == "absorber": + p.update(tau_n=2.0e-8, tau_p=2.0e-8) + if two_sided_trace: + for iface in data.get("interfaces", []): + iface["v_n"] = None + iface["v_p"] = None + + return _with_edits(base, mutate, resources=merged_resources) + + +def _transient_options( + *, + predictor: Literal["previous", "generation_inventory"] = "previous", +) -> TransientOptions: + return TransientOptions( + poisson_tolerance=1.0e-11, + continuity_tolerance_A_m2=1.0e-6, + contact_log_tolerance=1.0e-11, + potential_step_V=0.1, + quasi_fermi_step=2.0, + newton_budget=SolveBudget( + max_iterations=80, + max_residual_evaluations=5000, + max_jacobian_evaluations=1000, + max_backtracks=30, + ), + max_steps=64, + wall_s=15.0, + predictor=predictor, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + + +def _p08_build_source() -> tuple[BuildSource, dict[str, SourceDocument]]: + docs = { + rel_path: SourceDocument(rel_path, (ROOT / "src" / rel_path).read_bytes()) + for rel_path in P08_SOURCE_PATHS + } + build = BuildSource( + "582f019ef5743d43546219590a5ae094ca300594", + tuple(docs[k] for k in sorted(docs)), + ) + return build, docs + + +# --------------------------------------------------------------------------- +# (a) Default v1 0-Byte Manifest & Exact SHA-256 Baseline Invariance +# --------------------------------------------------------------------------- + + +def test_p08_05_default_v1_preserves_exact_wave2_baseline_digests() -> None: + """Default v1 compilation matches 582f019e SHA-256 digests bit-for-bit across all 5 compilers.""" + base = load_device() + c1d = compile_device_1d(base, intervals_per_layer=(8, 12, 8)) + assert c1d.identity == PINNED_V1_COMPILE_1D_SHA256 + + # Default P08CompilerOptions() forwards zero extra kwargs and produces the exact same digest + v1_opts = P08CompilerOptions() + assert v1_opts.is_v1_default + assert v1_opts.active_model_refs() == P08_V1_MODEL_REFS + assert v1_opts.compiler_kwargs_1d() == {} + assert v1_opts.compiler_kwargs_2d() == {} + assert ( + compile_device_1d(base, intervals_per_layer=(8, 12, 8), **v1_opts.compiler_kwargs_1d()).identity + == PINNED_V1_COMPILE_1D_SHA256 + ) + + # Deduplicated & two-sided trace heterojunctions + het_dedup = _heterojunction_astar_device(base) + c_dedup = compile_device_1d(het_dedup, intervals_per_layer=(8, 12, 8)) + assert c_dedup.identity == PINNED_V1_HET_DEDUP_DEVICE_SHA256 + assert c_dedup.interface_model is not None + assert c_dedup.interface_model.identity_sha256 == PINNED_V1_HET_DEDUP_IFACE_SHA256 + assert c_dedup.interface_model.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 + + c_trace = compile_device_1d( + het_dedup, + intervals_per_layer=(8, 12, 8), + interface_topology="two_sided_trace", + ) + assert c_trace.identity == PINNED_V1_HET_TRACE_DEVICE_SHA256 + assert c_trace.interface_model is not None + assert c_trace.interface_model.identity_sha256 == PINNED_V1_HET_TRACE_IFACE_SHA256 + assert c_trace.interface_model.thermionic_mode == LEGACY_UNNORMALIZED_THERMIONIC_V1 + + # Single-domain and multi-domain 1D mobile ions + ion_dev = prepare_confined_ion_device() + c_ion1d = compile_ionic_device_1d( + ion_dev, + intervals_per_layer=(6, 10, 6), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + assert c_ion1d.identity == PINNED_V1_IONIC_1D_SHA256 + elec_comp_manifest = cast(dict[str, Any], c_ion1d.binding_manifest["electronic_component"]) + assert "p08_options" not in elec_comp_manifest + + multi_ion_dev = _two_domain_ionic_device(ion_dev) + c_multi1d = compile_multiple_ionic_device_1d( + multi_ion_dev, + intervals_per_layer=(6, 8, 6), + ion_domains=(("htl", ("blocking", "blocking")), ("etl", ("blocking", "blocking"))), + ) + assert c_multi1d.identity == PINNED_V1_MULTI_IONIC_1D_SHA256 + + # 2D electronic and 2D ionic compilers + sp = JV2DInput(kind="jv_2d", lateral_length="0.4 um", Nx=2, Ny_per_layer=6, lateral_bc="neumann") + c2d = compile_device_2d(het_dedup, sp) + assert c2d.identity == PINNED_V1_COMPILE_2D_SHA256 + + c_ion2d = compile_ionic_device_2d( + ion_dev, + sp, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + assert c_ion2d.identity == PINNED_V1_IONIC_2D_SHA256 + + +# --------------------------------------------------------------------------- +# (b) Distinct V2 Identities, H_physics Separation, D20 Pinning & Non-Reuse +# --------------------------------------------------------------------------- + + +def test_p08_05_v2_options_shift_compiled_and_physics_identities_and_enforce_g8_guards( + tmp_path: Path, +) -> None: + """Every P08 V2 option produces distinct compiled.identity & H_physics and blocks certificate reuse.""" + base = load_device() + spec_dev = _spectral_heterojunction_device(base, two_sided_trace=False) + build, docs = _p08_build_source() + + option_variants: dict[str, P08CompilerOptions] = { + "v1_default": P08CompilerOptions(), + "p08_02a_series_eps": P08CompilerOptions(dielectric_rule=LAYER_SERIES_CAPACITANCE_V2), + "p08_02b_half_endpoint": P08CompilerOptions(geometry_name=PHYSICAL_HALF_ENDPOINT_V2), + "p08_02c_hole_increment": P08CompilerOptions(band_step_mode=HOLE_SEPARATE_INCREMENT_V1), + "p08_03_reciprocal_harmonic": P08CompilerOptions( + thermionic_mode=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + combination_mode="harmonic_series", + ), + "p08_03_reciprocal_compact": P08CompilerOptions( + thermionic_mode=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + combination_mode="compact_support", + ), + "p08_03_scaps_velocity": P08CompilerOptions( + thermionic_mode=SCAPS_EFFECTIVE_VELOCITY_THERMIONIC_V1, + ), + "p08_04_spectral_bl": P08CompilerOptions(optical_model="beer_lambert_spectral"), + "all_v2": P08CompilerOptions.all_prospective_v2(), + } + + compiled_digests: dict[str, str] = {} + h_physics_digests: dict[str, str] = {} + for label, opts in option_variants.items(): + compiled = compile_device_1d(spec_dev, intervals_per_layer=(4, 6, 4), **opts.compiler_kwargs_1d()) + compiled_digests[label] = compiled.identity + id_inputs = p08_identity_inputs(spec_dev, build, options=opts) + h_physics_digests[label] = physics_identity(id_inputs).sha256 + + assert len(set(compiled_digests.values())) == len(option_variants) + assert len(set(h_physics_digests.values())) == len(option_variants) + + # HistoricalDisable tracking when overriding v1 preset into prospective v2 models + registry = build_p08_model_registry(docs) + v1_preset = build_p08_preset(P08CompilerOptions(), docs) + assert len(v1_preset.historical_disables) == 5 + topology = device_topology(spec_dev) + param_sources = { + Scope("layer", (layer.id,)): layer_parameter_source(layer) + for layer in spec_dev.layers + if layer.id in topology.electrical_layer_ids + } + ctx = CapabilityContext(1, "dc", "solarlab_assembled", "maxwell_boltzmann", temperature_K=300.0) + layer_scope = Scope("layer", (spec_dev.layers[1].id,)) + override_v2 = { + layer_scope: { + P08_MODEL_VERSION_MAPPINGS[3].family: ( + ModelChoice( + P08_MODEL_VERSION_MAPPINGS[3].local_instance_id, + P08_MODEL_VERSION_MAPPINGS[3].v2_model, + parameter_schema="full_layer", + ), + ) + } + } + selected_override = select_preset(v1_preset, registry, topology, ctx, param_sources, overrides=override_v2) + assert selected_override.reenabled_historical_mechanisms == ("prospective_thermionic_v2",) + + # D20 RS/CBO pre-P08 pinning rejects every V2 ModelRef unless explicitly opted in + for v2_ref in P08_V2_MODEL_REFS: + with pytest.raises(InterfaceCBOScanError, match="D20 model-pinning violation"): + enforce_pre_p08_cbo_pinning(base, requested_models=(v2_ref,)) + admitted = enforce_pre_p08_cbo_pinning( + base, requested_models=(v2_ref,), allow_prospective_p08_models=True + ) + assert admitted == (v2_ref,) + + # Permanent pre-solve refusal of falsified interface_shared_occupancy across 1D, 2D & ionic 2D + falsified_dev = _with_edits( + prepare_confined_ion_device(), + lambda d: d.setdefault("settings", {}).update(interface_shared_occupancy=True), + ) + sp = JV2DInput(kind="jv_2d", lateral_length="0.4 um", Nx=2, Ny_per_layer=4, lateral_bc="neumann") + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_device_1d(_with_edits(base, lambda d: d.setdefault("settings", {}).update(interface_shared_occupancy=True))) + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_device_2d(_with_edits(base, lambda d: d.setdefault("settings", {}).update(interface_shared_occupancy=True)), sp) + with pytest.raises(CapabilityError, match="interface_shared_occupancy"): + compile_ionic_device_2d( + falsified_dev, + sp, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + + # Fixed 5 meV contact thermodynamic gate & historical 6.024958093130e-3 eV SCAPS label remain enforced + assert CONTACT_THERMODYNAMIC_TOLERANCE_EV == 5.0e-3 + vt_300 = 8.617333262145e-5 * 300.0 + nc_l, nv_l, chi_l, eg_l = 2.2e24, 1.8e25, 3.50, 2.05 + nc_r, nv_r, chi_r, eg_r = 2.2e24, 1.8e25, 4.00, 3.20 + p_l = 1.0e24 + n_l = nc_l * nv_l * math.exp(-eg_l / vt_300) / p_l + n_r = 1.0e24 + p_r = nc_r * nv_r * math.exp(-eg_r / vt_300) / n_r + wf_left = chi_l + eg_l - vt_300 * math.log(nv_l / p_l) + wf_right = chi_r - vt_300 * math.log(n_r / nc_r) + v_bi_compatible = wf_left - wf_right + scaps_offset_assessment = assess_contact_thermodynamics( + built_in_potential_mode="legacy_manual", + left=ContactEndpoint(n_l, p_l, nc_l, nv_l, chi_l, eg_l), + right=ContactEndpoint(n_r, p_r, nc_r, nv_r, chi_r, eg_r), + V_bi_bc=v_bi_compatible + 6.024958093130195e-3, + thermal_voltage_V=vt_300, + semiconductor_potential_V=v_bi_compatible, + has_band_reference=True, + ) + assert scaps_offset_assessment.status == "inconsistent" + assert scaps_offset_assessment.historical_label == "legacy_manual_v_bi_contact_offset" + with pytest.raises(ContactThermodynamicError): + require_contact_thermodynamic_certificate(scaps_offset_assessment) + + # Certificate non-reuse across v1 <-> v2 on 1D transient & small-signal impedance + dev_v1 = compile_device_1d(spec_dev, intervals_per_layer=(4, 6, 4)) + dev_v2 = compile_device_1d( + spec_dev, + intervals_per_layer=(4, 6, 4), + **P08CompilerOptions.all_prospective_v2().compiler_kwargs_1d(), + ) + eq_v1 = solve_equilibrium(dev_v1) + protocol = TransientProtocol( + times_s=np.array([0.0, 1.0e-6]), + voltage_V=np.array([0.0, 0.0]), + generation_scale=np.array([0.0, 0.0]), + ) + with pytest.raises(ValueError, match="steady point identity"): + solve_transient( + dev_v2, + eq_v1, + protocol, + options=_transient_options(), + initial_options=SteadyOptions(), + ) + with pytest.raises(ValueError, match="steady point identity"): + solve_impedance(dev_v2, eq_v1, [100.0]) + + # Certificate non-reuse across v1 <-> v2 on ionic transient & ionic impedance + ion_prep = prepare_confined_ion_device(diffusion_only=True) + ion_v1 = compile_ionic_device_1d( + ion_prep, + intervals_per_layer=(4, 6, 4), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + ion_v2 = compile_ionic_device_1d( + ion_prep, + intervals_per_layer=(4, 6, 4), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + geometry_name=PHYSICAL_HALF_ENDPOINT_V2, + band_step_mode=HOLE_SEPARATE_INCREMENT_V1, + ) + assert ion_v1.identity != ion_v2.identity + ion_ctrl = ionic_steady_controls(ion_v1.ion_node_count) + ion_ss_v1 = solve_ionic_steady_state(ion_v1, voltage_V=0.0, generation_scale=0.0, options=ion_ctrl) + assert ion_ss_v1.accepted + artifact_doc = { + "summary": { + "accepted": True, + "compiled_identity": ion_v1.identity, + "voltage_V": 0.0, + "generation_scale": 0.0, + }, + "result": ion_ss_v1, + } + artifact_text = json.dumps(json_value(artifact_doc), indent=2, allow_nan=False) + "\n" + artifact_sha = hashlib.sha256(artifact_text.encode()).hexdigest() + artifact_path = tmp_path / "ion_v1_initial.json" + artifact_path.write_text(artifact_text) + + initial_v1 = load_ionic_steady_initial(ion_v1, artifact_path, artifact_sha, controls=ion_ctrl) + with pytest.raises(ValueError, match="different compiled device"): + load_ionic_steady_initial(ion_v2, artifact_path, artifact_sha, controls=ion_ctrl) + with pytest.raises(ValueError, match="different compiled device"): + solve_ionic_transient( + ion_v2, + initial_v1, + protocol, + options=IonicTransientOptions(_transient_options(), 1.0e6, 1.0), + ) + with pytest.raises(ValueError, match="different compiled device"): + solve_ionic_impedance(ion_v2, initial_v1, [10.0]) + + +# --------------------------------------------------------------------------- +# (c) End-to-End 1D All-V2 Parity, Conservation, +3 V Stress & Refinement +# --------------------------------------------------------------------------- + + +def test_p08_05_compiled_1d_all_v2_parity_conservation_and_spatial_refinement() -> None: + """End-to-end 1D all-V2: 0-ULP Assembled parity, FD Jacobian, BE conservation & grid refinement.""" + base = load_device() + all_v2 = P08CompilerOptions.all_prospective_v2() + + # 1. Deduplicated all-V2 0-ULP parity, FD Jacobian, DC J-V, and BE transient conservation + spec_dedup = _spectral_heterojunction_device(base, two_sided_trace=False) + dev_dedup = compile_device_1d(spec_dedup, intervals_per_layer=(6, 10, 6), **all_v2.compiler_kwargs_1d()) + total_thickness = sum(layer.thickness for layer in spec_dedup.layers if layer.role != "substrate") + assert abs(float(np.sum(dev_dedup.geometry.cell_measures_m)) - total_thickness) <= 1.0e-15 * total_thickness + + rng = np.random.default_rng(20261116) + u_pert = np.r_[dev_dedup.reference_potential_V, np.zeros(2 * dev_dedup.node_count)] + u_pert[: dev_dedup.node_count] += 0.03 * np.sin(np.linspace(0.0, np.pi, dev_dedup.node_count)) + u_pert[dev_dedup.node_count :] += rng.normal(0.0, 0.15, size=2 * dev_dedup.node_count) + phi_l_dedup, phi_r_dedup = dev_dedup.contact_potentials(0.45) + u_pert[0] = phi_l_dedup + u_pert[dev_dedup.node_count - 1] = phi_r_dedup + + p_ref = DC1DProblem(dev_dedup, voltage_V=0.45, generation_scale=1.0) + p_asm = AssembledDC1DProblem(dev_dedup, voltage_V=0.45, generation_scale=1.0) + np.testing.assert_array_equal(p_ref.residual(u_pert), p_asm.residual(u_pert)) + np.testing.assert_array_equal(p_ref.fluxes(u_pert).electron.flux, p_asm.fluxes(u_pert).electron.flux) + np.testing.assert_array_equal(p_ref.fluxes(u_pert).hole.flux, p_asm.fluxes(u_pert).hole.flux) + np.testing.assert_array_equal(p_ref.jacobian(u_pert).toarray(), p_asm.jacobian(u_pert).toarray()) + + # 4th-order central finite-difference check on AssembledDC1DProblem Jacobian + j_exact = p_asm.jacobian(u_pert).toarray() + j_fd = np.zeros_like(j_exact) + eps = 1.0e-6 + for col in range(u_pert.size): + step = np.zeros_like(u_pert) + step[col] = eps + r_p1 = p_asm.residual(u_pert + step) + r_m1 = p_asm.residual(u_pert - step) + r_p2 = p_asm.residual(u_pert + 2.0 * step) + r_m2 = p_asm.residual(u_pert - 2.0 * step) + j_fd[:, col] = (-r_p2 + 8.0 * r_p1 - 8.0 * r_m1 + r_m2) / (12.0 * eps) + rel_jac_err = np.linalg.norm(j_exact - j_fd) / max(np.linalg.norm(j_exact), 1.0) + assert rel_jac_err <= 1.0e-9 + + # Dark equilibrium, illuminated J-V, and Backward Euler transient conservation + steady_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-6, + current_spread_tolerance_A_m2=1.0e-6, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + eq_dedup = solve_equilibrium(dev_dedup, options=steady_opts) + assert float(np.max(np.abs(eq_dedup.contact_current_density_A_m2))) <= 1.0e-13 + + jv_res = run_steady_jv( + dev_dedup, + np.linspace(0.0, 1.10, 23), + generation_scale=1.0, + options=steady_opts, + ) + jsc_a_m2 = jv_res.metrics.short_circuit_current_A_m2 + voc_v = jv_res.metrics.open_circuit_voltage_V + assert jsc_a_m2 is not None and jsc_a_m2 > 50.0 + assert voc_v is not None and 0.6 < voc_v < 1.15 + + tr_times = np.concatenate(([0.0], np.geomspace(1.0e-9, 1.0e-6, 6))) + tr_volts = np.linspace(0.0, 0.45, tr_times.size) + tr_gen = np.concatenate(([0.0], np.ones(6))) + tr_proto = TransientProtocol(times_s=tr_times, voltage_V=tr_volts, generation_scale=tr_gen) + tr_opts = _transient_options(predictor="generation_inventory") + tr_res = solve_transient( + dev_dedup, + eq_dedup, + tr_proto, + options=tr_opts, + initial_options=steady_opts, + method="backward_euler", + ) + assert tr_res.completed and not tr_res.failed_attempts + for attempt in tr_res.attempts: + assert attempt.accepted and isinstance(attempt.accounting, dict) + assert float(cast(float, attempt.accounting["continuity_defect_bound_A_m2"])) <= 1.0e-6 + assert abs(float(cast(float, attempt.accounting["global_charge_balance_A_m2"]))) <= 1.0e-6 + assert float(np.max(np.abs(np.asarray(attempt.accounting["maxwell_identity_error_A_m2"])))) <= 1.0e-9 + + # 2. Two-sided trace all-V2 0-ULP parity and +3.0 V super-flatband forward injection + spec_trace = _spectral_heterojunction_device(base, two_sided_trace=True) + trace_v2_opts = P08CompilerOptions( + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + band_step_mode=HOLE_SEPARATE_INCREMENT_V1, + thermionic_mode=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + optical_model="beer_lambert_spectral", + ) + dev_trace = compile_device_1d( + spec_trace, + intervals_per_layer=(6, 8, 6), + interface_topology="two_sided_trace", + **trace_v2_opts.compiler_kwargs_1d(), + ) + u_tr = np.r_[dev_trace.reference_potential_V, np.zeros(2 * dev_trace.node_count)] + u_tr[dev_trace.node_count :] += rng.normal(0.0, 0.1, size=2 * dev_trace.node_count) + _, phi_r_tr = dev_trace.contact_potentials(0.5) + u_tr[dev_trace.node_count - 1] = phi_r_tr + pt_ref = DC1DProblem(dev_trace, voltage_V=0.5, generation_scale=1.0) + pt_asm = AssembledDC1DProblem(dev_trace, voltage_V=0.5, generation_scale=1.0) + np.testing.assert_array_equal(pt_ref.residual(u_tr), pt_asm.residual(u_tr)) + np.testing.assert_array_equal(pt_ref.jacobian(u_tr).toarray(), pt_asm.jacobian(u_tr).toarray()) + + eq_trace = solve_equilibrium(dev_trace, options=steady_opts) + assert float(np.max(np.abs(eq_trace.contact_current_density_A_m2))) <= 1.0e-13 + high_inj_opts = SteadyOptions( + continuity_tolerance_A_m2=1.0e-3, + current_spread_tolerance_A_m2=1.0e-3, + max_bias_step_V=0.05, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + prev_state = solve_steady_state(dev_trace, voltage_V=0.0, generation_scale=1.0, options=high_inj_opts) + for bias_v in np.linspace(0.05, 3.0, 60): + prev_state = solve_steady_state( + dev_trace, + voltage_V=float(bias_v), + generation_scale=1.0, + initial_state=prev_state.state, + options=high_inj_opts, + ) + assert np.all(np.isfinite(prev_state.state.u)) + assert float(np.min(prev_state.state.electron_density_m3)) > 0.0 + assert float(np.min(prev_state.state.hole_density_m3)) > 0.0 + + # 3. Spatial refinement convergence on compiled 1D all-V2 (N_per_layer = 4, 8, 16, 32) + uniform_grid_dev = _with_edits( + spec_dedup, + lambda d: [g.update(alpha=1.0) for g in d.get("electrical_grid", [])], + ) + j_by_n: list[float] = [] + for n_per in (4, 8, 16, 32): + dev_n = compile_device_1d( + uniform_grid_dev, + intervals_per_layer=(n_per, n_per, n_per), + **all_v2.compiler_kwargs_1d(), + ) + ss_n = solve_steady_state(dev_n, voltage_V=0.65, generation_scale=1.0, options=steady_opts) + j_by_n.append(float(ss_n.contact_current_density_A_m2[1])) + err_4 = abs(j_by_n[0] - j_by_n[3]) + err_8 = abs(j_by_n[1] - j_by_n[3]) + err_16 = abs(j_by_n[2] - j_by_n[3]) + assert err_4 > err_8 > err_16 > 0.0 + empirical_order = math.log2(err_8 / err_16) + assert empirical_order >= 1.7 + + +# --------------------------------------------------------------------------- +# (d) Compiled 2D All-V2 Parity, Series Capacitor & 1D-vs-2D Column Consistency +# --------------------------------------------------------------------------- + + +def test_p08_05_compiled_2d_all_v2_parity_capacitor_and_column_consistency() -> None: + """Compiled 2D all-V2 matches AssembledDC2DProblem 0-ULP, 1D column DC, and exact series capacitor.""" + base = load_device() + spec_dedup = _spectral_heterojunction_device(base, two_sided_trace=False) + all_v2 = P08CompilerOptions.all_prospective_v2() + + dev_1d = compile_device_1d( + spec_dedup, + intervals_per_layer=(5, 5, 5), + **all_v2.compiler_kwargs_1d(), + ) + sp = JV2DInput(kind="jv_2d", lateral_length="0.4 um", Nx=2, Ny_per_layer=5, lateral_bc="neumann") + dev_2d = compile_device_2d(spec_dedup, sp, **all_v2.compiler_kwargs_2d()) + + # 1. 0-ULP parity between DC2DProblem and AssembledDC2DProblem + FD Jacobian check + rng = np.random.default_rng(20261117) + u2 = dev_2d.extrude_coordinates( + np.r_[dev_2d.column.reference_potential_V, np.zeros(2 * dev_2d.column.node_count)] + ).copy() + mask_int: NDArray[np.bool_] = np.ones(dev_2d.geometry.shape, dtype=bool) + mask_int[0, :] = False + mask_int[-1, :] = False + u2[: dev_2d.node_count][mask_int.ravel()] += rng.normal(0.0, 0.02, size=int(np.sum(mask_int))) + u2[dev_2d.node_count :] += rng.normal(0.0, 0.12, size=2 * dev_2d.node_count) + ny, nx = dev_2d.geometry.shape + top_nodes = np.arange(nx) + bot_nodes = np.arange((ny - 1) * nx, ny * nx) + _, phi_r_2d = dev_2d.column.contact_potentials(0.4) + u2[bot_nodes] = phi_r_2d + + p2_ref = DC2DProblem(dev_2d, voltage_V=0.4, generation_scale=1.0) + p2_asm = AssembledDC2DProblem(dev_2d, voltage_V=0.4, generation_scale=1.0) + np.testing.assert_array_equal(p2_ref.residual(u2), p2_asm.residual(u2)) + np.testing.assert_array_equal(p2_ref.fluxes(u2).electron.flux, p2_asm.fluxes(u2).electron.flux) + np.testing.assert_array_equal(p2_ref.fluxes(u2).hole.flux, p2_asm.fluxes(u2).hole.flux) + np.testing.assert_array_equal(p2_ref.jacobian(u2).toarray(), p2_asm.jacobian(u2).toarray()) + + j2_exact = p2_asm.jacobian(u2).toarray() + j2_fd = np.zeros_like(j2_exact) + eps = 1.0e-6 + for col in range(u2.size): + step = np.zeros_like(u2) + step[col] = eps + j2_fd[:, col] = (p2_asm.residual(u2 + step) - p2_asm.residual(u2 - step)) / (2.0 * eps) + assert np.linalg.norm(j2_exact - j2_fd) / max(np.linalg.norm(j2_exact), 1.0) <= 1.0e-7 + + # 2. 1D-vs-2D uniform-column all-V2 steady-state agreement + ss_1d = solve_steady_state(dev_1d, voltage_V=0.55, generation_scale=1.0) + ss_2d = solve_steady_state_2d( + dev_2d, + voltage_V=0.55, + generation_scale=1.0, + initial_state=dev_2d.state(dev_2d.extrude_coordinates(ss_1d.state.u), voltage_V=0.55), + options=Steady2DOptions(), + ) + assert ss_2d.accepted and ss_2d.state is not None and ss_2d.diagnostics is not None + j_2d = np.asarray(ss_2d.diagnostics["terminal_mean_current_density_A_m2"], dtype=np.float64) + j_1d = np.asarray(ss_1d.contact_current_density_A_m2, dtype=np.float64) + assert float(np.max(np.abs(j_2d - j_1d))) <= 1.0e-11 * max(float(np.max(np.abs(j_1d))), 1.0) + phi_2d = ss_2d.state.potential_V + np.testing.assert_allclose(phi_2d[:, 0], phi_2d[:, 1], rtol=0.0, atol=1.0e-13) + np.testing.assert_allclose(phi_2d[:, 0], ss_1d.state.potential_V, rtol=1.0e-11, atol=1.0e-11) + + # 3. Charge-free 3-layer compiled 2D series capacitor exactness under LAYER_SERIES_CAPACITANCE_V2 + inv_c_series = math.fsum( + layer.thickness / (VACUUM_PERMITTIVITY_F_M * float(cast(float, dict(layer.parameters)["eps_r"]))) + for layer in spec_dedup.layers + if layer.role != "substrate" + ) + c_series_exact = 1.0 / inv_c_series + # Solve pure 2D Laplace operator assembled from dev_2d.face_capacitance_F_m2 with 1 V drop + pairs = dev_2d.geometry.contract_geometry.pairs + cap_w = dev_2d.face_capacitance_F_m2 * dev_2d.geometry.contract_geometry.face_measures + lap: NDArray[np.float64] = np.zeros((dev_2d.node_count, dev_2d.node_count), dtype=float) + for (i_l, i_r), cw in zip(pairs, cap_w): + lap[i_l, i_l] -= cw + lap[i_l, i_r] += cw + lap[i_r, i_l] += cw + lap[i_r, i_r] -= cw + rhs: NDArray[np.float64] = np.zeros(dev_2d.node_count, dtype=float) + for idx in top_nodes: + lap[idx, :] = 0.0 + lap[idx, idx] = 1.0 + rhs[idx] = 1.0 + for idx in bot_nodes: + lap[idx, :] = 0.0 + lap[idx, idx] = 1.0 + rhs[idx] = 0.0 + phi_cap = np.linalg.solve(lap, rhs).reshape(ny, nx) + dy0 = float(dev_2d.geometry.y_geometry.nodes_m[1] - dev_2d.geometry.y_geometry.nodes_m[0]) + eps0_layer = float(cast(float, dict(spec_dedup.layers[0].parameters)["eps_r"])) + d_top = VACUUM_PERMITTIVITY_F_M * eps0_layer * (phi_cap[0, 0] - phi_cap[1, 0]) / dy0 + assert abs(d_top - c_series_exact) / c_series_exact <= 2.0e-14 + + # 4. Compiled 2D ionic V2 0-ULP parity between Ionic2DProblem and AssembledIonic2DProblem + ion_prep = prepare_confined_ion_device(diffusion_only=True) + c_ion2d_v2 = compile_ionic_device_2d( + ion_prep, + sp, + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + dielectric_rule=LAYER_SERIES_CAPACITANCE_V2, + stack_geometry=PHYSICAL_HALF_ENDPOINT_V2, + band_step_mode=HOLE_SEPARATE_INCREMENT_V1, + thermionic_mode=RECIPROCAL_PHYSICAL_THERMIONIC_V2, + ) + assert c_ion2d_v2.identity != PINNED_V1_IONIC_2D_SHA256 + u_ion2 = np.r_[ + c_ion2d_v2.electronic_component.extrude_coordinates( + np.r_[ + c_ion2d_v2.electronic_component.column.reference_potential_V, + np.zeros(2 * c_ion2d_v2.electronic_component.column.node_count), + ] + ), + np.zeros(c_ion2d_v2.ion_node_count), + ] + u_ion2[c_ion2d_v2.node_count : 3 * c_ion2d_v2.node_count] += rng.normal( + 0.0, 0.08, size=2 * c_ion2d_v2.node_count + ) + u_ion2[3 * c_ion2d_v2.node_count :] += rng.normal(0.0, 0.05, size=c_ion2d_v2.ion_node_count) + _, phi_r_ion2 = c_ion2d_v2.electronic_component.column.contact_potentials(0.2) + ny_i, nx_i = c_ion2d_v2.electronic_component.geometry.shape + u_ion2[np.arange((ny_i - 1) * nx_i, ny_i * nx_i)] = phi_r_ion2 + pi2_ref = Ionic2DProblem(c_ion2d_v2, voltage_V=0.2, generation_scale=0.0) + pi2_asm = AssembledIonic2DProblem(c_ion2d_v2, voltage_V=0.2, generation_scale=0.0) + np.testing.assert_array_equal(pi2_ref.residual(u_ion2), pi2_asm.residual(u_ion2)) + np.testing.assert_allclose(pi2_ref.jacobian(u_ion2).toarray(), pi2_asm.jacobian(u_ion2).toarray(), rtol=1.0e-15, atol=0.0) From 443725b1e5c9738f295f87a627691e76e8278a9f Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 19 Nov 2026 17:47:51 +0800 Subject: [PATCH 28/46] M(packaging,materials): bundle packaged resources/presets, add standalone CLI, and exclude perovskite-sim from target wheel/sdist (P09-01) --- .github/workflows/ci.yml | 15 +- pyproject.toml | 52 +- scripts/ci/scheduled_suite.py | 1 - src/solarlab/cli.py | 325 ++++ src/solarlab/materials/__init__.py | 32 +- src/solarlab/materials/data/__init__.py | 1 + src/solarlab/materials/data/am15g.csv | 1347 +++++++++++++++++ .../materials/data/default_catalog_v1.json | 309 ++++ .../materials/data/layer_templates.yaml | 340 +++++ src/solarlab/materials/data/nk/Ag.csv | 162 ++ src/solarlab/materials/data/nk/Au.csv | 162 ++ src/solarlab/materials/data/nk/C60.csv | 162 ++ src/solarlab/materials/data/nk/Cu.csv | 50 + src/solarlab/materials/data/nk/FA_Cs_1p77.csv | 162 ++ src/solarlab/materials/data/nk/FTO.csv | 162 ++ src/solarlab/materials/data/nk/ITO.csv | 162 ++ src/solarlab/materials/data/nk/MAPbI3.csv | 162 ++ src/solarlab/materials/data/nk/NiOx.csv | 162 ++ src/solarlab/materials/data/nk/PCBM.csv | 162 ++ src/solarlab/materials/data/nk/PEDOT_PSS.csv | 162 ++ src/solarlab/materials/data/nk/SnO2.csv | 162 ++ src/solarlab/materials/data/nk/SnPb_1p22.csv | 162 ++ src/solarlab/materials/data/nk/TiO2.csv | 162 ++ src/solarlab/materials/data/nk/glass.csv | 162 ++ src/solarlab/materials/data/nk/manifest.yaml | 238 +++ .../materials/data/nk/spiro_OMeTAD.csv | 162 ++ .../data/presets/calado2016_fig1f.device.json | 123 ++ .../data/presets/calado2016_fig1f.v2.json | 139 ++ .../data/presets/calado2016_fig1f.yaml | 115 ++ .../presets/calado2016_ion_sweep.device.json | 151 ++ .../data/presets/calado2016_ion_sweep.v2.json | 167 ++ .../data/presets/calado2016_ion_sweep.yaml | 109 ++ .../data/presets/classical_pin.device.json | 152 ++ .../data/presets/scaps_mirror_v2.device.json | 235 +++ .../data/presets/scaps_mirror_v2.v2.json | 251 +++ .../data/presets/scaps_mirror_v2.yaml | 185 +++ .../data/references/csi_pn_cv_intercept.yaml | 56 + .../references/csi_vannijen2025_pn_cv.yaml | 141 ++ src/solarlab/materials/packaged.py | 294 ++++ src/solarlab/materials/wheel_hook.py | 31 + src/solarlab/reproducibility/PublicAPI.json | 76 +- src/solarlab/reproducibility/release.py | 13 +- .../test_legacy_behavior_execution.py | 4 +- tests/refactor/test_package_preparation.py | 98 +- tests/refactor/test_release_bundle.py | 622 ++++++-- .../test_packaged_resources_and_cli.py | 241 +++ 46 files changed, 8164 insertions(+), 179 deletions(-) create mode 100644 src/solarlab/cli.py create mode 100644 src/solarlab/materials/data/__init__.py create mode 100644 src/solarlab/materials/data/am15g.csv create mode 100644 src/solarlab/materials/data/default_catalog_v1.json create mode 100644 src/solarlab/materials/data/layer_templates.yaml create mode 100644 src/solarlab/materials/data/nk/Ag.csv create mode 100644 src/solarlab/materials/data/nk/Au.csv create mode 100644 src/solarlab/materials/data/nk/C60.csv create mode 100644 src/solarlab/materials/data/nk/Cu.csv create mode 100644 src/solarlab/materials/data/nk/FA_Cs_1p77.csv create mode 100644 src/solarlab/materials/data/nk/FTO.csv create mode 100644 src/solarlab/materials/data/nk/ITO.csv create mode 100644 src/solarlab/materials/data/nk/MAPbI3.csv create mode 100644 src/solarlab/materials/data/nk/NiOx.csv create mode 100644 src/solarlab/materials/data/nk/PCBM.csv create mode 100644 src/solarlab/materials/data/nk/PEDOT_PSS.csv create mode 100644 src/solarlab/materials/data/nk/SnO2.csv create mode 100644 src/solarlab/materials/data/nk/SnPb_1p22.csv create mode 100644 src/solarlab/materials/data/nk/TiO2.csv create mode 100644 src/solarlab/materials/data/nk/glass.csv create mode 100644 src/solarlab/materials/data/nk/manifest.yaml create mode 100644 src/solarlab/materials/data/nk/spiro_OMeTAD.csv create mode 100644 src/solarlab/materials/data/presets/calado2016_fig1f.device.json create mode 100644 src/solarlab/materials/data/presets/calado2016_fig1f.v2.json create mode 100644 src/solarlab/materials/data/presets/calado2016_fig1f.yaml create mode 100644 src/solarlab/materials/data/presets/calado2016_ion_sweep.device.json create mode 100644 src/solarlab/materials/data/presets/calado2016_ion_sweep.v2.json create mode 100644 src/solarlab/materials/data/presets/calado2016_ion_sweep.yaml create mode 100644 src/solarlab/materials/data/presets/classical_pin.device.json create mode 100644 src/solarlab/materials/data/presets/scaps_mirror_v2.device.json create mode 100644 src/solarlab/materials/data/presets/scaps_mirror_v2.v2.json create mode 100644 src/solarlab/materials/data/presets/scaps_mirror_v2.yaml create mode 100644 src/solarlab/materials/data/references/csi_pn_cv_intercept.yaml create mode 100644 src/solarlab/materials/data/references/csi_vannijen2025_pn_cv.yaml create mode 100644 src/solarlab/materials/packaged.py create mode 100644 src/solarlab/materials/wheel_hook.py create mode 100644 tests/unit/materials/test_packaged_resources_and_cli.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38056e6f..6b095557 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -163,21 +163,32 @@ jobs: "$UV_PROJECT_ENVIRONMENT/bin/python" -I -B - <<'PY' import importlib.metadata import importlib.resources + import importlib.util import pathlib import sys import solarlab import solarlab_research import solarlab_server + from solarlab.cli import main as cli_main from solarlab.config import behavior + from solarlab.materials import ( + load_packaged_default_catalog, + load_packaged_resource_library, + load_packaged_template_library, + ) from solarlab_server.app import create_app - from perovskite_sim.models.parameters import MaterialParams prefix = pathlib.Path(sys.prefix).resolve() for module in (solarlab, solarlab_research, solarlab_server): assert pathlib.Path(module.__file__).resolve().is_relative_to(prefix) assert importlib.resources.files(module).joinpath("py.typed").is_file() - assert MaterialParams.__module__ == "perovskite_sim.models.parameters" + assert importlib.util.find_spec("perovskite_sim") is None + assert importlib.util.find_spec("backend") is None assert create_app.__module__ == "solarlab_server.app" + assert cli_main.__module__ == "solarlab.cli" + assert load_packaged_default_catalog().content_sha256 + assert load_packaged_resource_library().get("MAPbI3", "nk").shape[1] == 3 + assert len(load_packaged_template_library().templates) > 0 assert pathlib.Path(behavior.__file__).resolve().is_relative_to(prefix) assert importlib.metadata.version("solarlab") == "0.1.0" PY diff --git a/pyproject.toml b/pyproject.toml index ea6dc9ac..e46aa692 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,13 @@ dev = [ ] notebook = ["jupyterlab>=4.0"] +[project.scripts] +solarlab = "solarlab.cli:main" +solarlab-server = "solarlab.cli:server_main" +solarlab-cbo-scan = "solarlab_research.scripts.cbo_scan:main" +solarlab-r1-short-window = "solarlab_research.scripts.r1_short_window:main" +solarlab-r1-verify-sources = "solarlab_research.scripts.r1_verify_sources:main" + [tool.uv] # Preserve the observed transitive baseline as well as the direct pins above. # contourpy 1.4 requires 3.12; uv selects a compatible release on Python 3.11. @@ -91,6 +98,7 @@ check_untyped_defs = true disallow_untyped_defs = true [tool.pytest.ini_options] +pythonpath = ["perovskite-sim"] testpaths = ["tests"] addopts = "-ra -m 'not slow'" markers = [ @@ -102,9 +110,9 @@ markers = [ "validation: physics trend validation against literature windows (V_oc vs Eg, FF vs mobility, etc.)", ] -# Transitional P03-01 build: one legacy source tree, explicitly mapped beside -# the three new packages. P09-01 excludes the legacy engine from the release; -# P09-03 retires its source only after every consumer has migrated. +# Target P09-01 build: ship only first-party packages (solarlab, +# solarlab_research, solarlab_server) plus prebuilt web/dist SPA assets when +# present. Legacy perovskite-sim is excluded from both wheel and sdist. [tool.hatch.build] reproducible = true exclude = ["**/__pycache__/**", "**/*.pyc", "**/*.pyo", "**/.DS_Store"] @@ -114,9 +122,11 @@ only-include = [ "src/solarlab", "src/solarlab_research", "src/solarlab_server", - "perovskite-sim/perovskite_sim", ] -sources = ["src", "perovskite-sim"] +sources = ["src"] + +[tool.hatch.build.targets.wheel.hooks.custom] +path = "src/solarlab/materials/wheel_hook.py" [tool.hatch.build.targets.sdist] only-include = [ @@ -129,9 +139,6 @@ only-include = [ "src/solarlab", "src/solarlab_research", "src/solarlab_server", - "perovskite-sim/perovskite_sim", - "perovskite-sim/pyproject.toml", - "perovskite-sim/uv.lock", "tests/refactor/test_package_preparation.py", "tests/refactor/test_configuration_preparation.py", "tests/refactor/test_registry_preparation.py", @@ -153,18 +160,16 @@ only-include = [ "tests/refactor/test_package_boundaries.py", "tests/refactor/test_experiment_registry_startup.py", "tests/refactor/test_input_domain_closure.py", - "tests/refactor/test_legacy_behavior_execution.py", - "tests/refactor/test_legacy_execution_context.py", "tests/refactor/test_effective_behavior_identity.py", "tests/refactor/test_configuration_migration.py", - "tests/refactor/legacy_driver_observer.py", "tests/refactor/fixtures/r1_common_state_preparation.json", "tests/refactor/fixtures/r1_pair_common_state_preparation.json", "tests/refactor/fixtures/r1_execution_policy.json", - "perovskite-sim/tests/fixtures/OneDimensionalMechanismR1ReferenceBindingV1.json", - "perovskite-sim/tests/fixtures/configs/dynamic_interface_defect_ion_transient_absorber_only.yaml", - "perovskite-sim/reproducibility/OneDimensionalMechanismR1DynamicsInputV1.json", "reproducibility/RefactorTransitionBoundariesV1.json", + "reproducibility/ScapsComparisonContractV1.json", + "reproducibility/HysteresisReferenceContractV1.json", + "reproducibility/HysteresisReferenceContractV2.json", + "reproducibility/PerformanceCasesV1.json", "scripts/generate_configuration_schema.py", "web/src", "web/tests", @@ -178,14 +183,6 @@ only-include = [ "web/vitest.config.ts", "web/Dockerfile", "web/.gitignore", - "perovskite-sim/tests/fixtures/IonDiffusivityFigureReference.json", - "perovskite-sim/tests/fixtures/configs/cigs_graded_optics.yaml", - "perovskite-sim/tests/fixtures/configs/wkb_resolved_electron_barrier.yaml", - "perovskite-sim/tests/fixtures/configs/nip_MAPbI3.yaml", - "perovskite-sim/tests/fixtures/configs/tandem_lin2019.yaml", - "perovskite-sim/tests/fixtures/configs/nip_wideGap_FACs_1p77.yaml", - "perovskite-sim/tests/fixtures/configs/nip_SnPb_1p22.yaml", - "perovskite-sim/configs/scaps_mirror_v2.yaml", "tests/runtime/test_run_store.py", "tests/runtime/test_execution.py", "tests/runtime/execution_workers.py", @@ -195,6 +192,9 @@ only-include = [ "tests/runtime/test_configuration_preview.py", ] +[tool.hatch.build.targets.sdist.hooks.custom] +path = "src/solarlab/materials/wheel_hook.py" + [tool.importlinter] root_packages = ["solarlab", "solarlab_research", "solarlab_server"] include_external_packages = true @@ -207,6 +207,12 @@ forbidden_modules = [ "solarlab_research", "solarlab_server", "perovskite_sim", "backend", ] +[[tool.importlinter.contracts]] +name = "Research package has no legacy dependency" +type = "forbidden" +source_modules = ["solarlab_research"] +forbidden_modules = ["perovskite_sim", "backend"] + [[tool.importlinter.contracts]] name = "Companion packages are independent" type = "independence" @@ -264,6 +270,6 @@ name = "Shared contracts do not import implementation layers" type = "layers" containers = ["solarlab"] layers = [ - "config : device : materials : reproducibility : units : physics : experiments : sweeps : (io) : (mesh) : (discretization) : (equations) : (solvers)", + "config : device : materials : reproducibility : units : physics : experiments : sweeps : cli : (io) : (mesh) : (discretization) : (equations) : (solvers)", "(contracts)", ] diff --git a/scripts/ci/scheduled_suite.py b/scripts/ci/scheduled_suite.py index fbec166f..b94f813f 100644 --- a/scripts/ci/scheduled_suite.py +++ b/scripts/ci/scheduled_suite.py @@ -76,7 +76,6 @@ def _recorder_dumps(value: Any, *, indent: int | str | None = None, "solarlab": "src/solarlab", "solarlab_research": "src/solarlab_research", "solarlab_server": "src/solarlab_server", - "perovskite_sim": "perovskite-sim/perovskite_sim", } # These files contain individually expensive protocols or several old producers. # Split by test function; parameter reprs are not portable selector identities. diff --git a/src/solarlab/cli.py b/src/solarlab/cli.py new file mode 100644 index 00000000..503e5b2e --- /dev/null +++ b/src/solarlab/cli.py @@ -0,0 +1,325 @@ +"""Standalone SolarLab command-line entrypoints (``solarlab`` and ``solarlab-server``). + +Provides installation/resource verification, 1D steady-state J-V execution on +packaged or user V2 configurations, delegation to ``solarlab_research`` tools, +and a standalone ``solarlab-server`` launcher that delegates to +``solarlab_server.cli:main`` when available or boots ``solarlab_server.app`` +with packaged material resources. +""" + +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import importlib +import importlib.metadata +import importlib.util +import inspect +import json +from pathlib import Path +import sys +from typing import Any + +import numpy as np + +from dataclasses import asdict +from solarlab.config.resolve_device import resolve_device +from solarlab.config.schema import configuration_schema_representation +from solarlab.device.compile_1d import CapabilityError, compile_device_1d +from solarlab.device.defaults import DefaultCatalog +from solarlab.device.inputs import DeviceInput +from solarlab.device.resolved import PreparedDevice +from solarlab.experiments.jv.steady import run_steady_jv +from solarlab.io.run_store import RunStore +from solarlab.materials import ( + load_packaged_default_catalog, + load_packaged_preset_device_mapping, + load_packaged_preset_sources, + load_packaged_resource_library, + load_packaged_template_library, +) +from solarlab.materials.source import SourceDocument +from solarlab.solvers.nonlinear.production import POISSON_CONTACT_BALANCE_V1 +from solarlab.solvers.nonlinear.steady_1d import SteadyOptions, SteadyStateError + +__all__ = ["main", "server_main"] + + +def _package_version() -> str: + try: + return importlib.metadata.version("solarlab") + except importlib.metadata.PackageNotFoundError: + return "0.1.0" + + +def _load_prepared_device( + *, preset: str, config_path: Path | None +) -> PreparedDevice: + defaults: DefaultCatalog = load_packaged_default_catalog() + resources = load_packaged_resource_library() + if config_path is not None: + raw_bytes = config_path.read_bytes() + source = SourceDocument(config_path.name, raw_bytes) + payload = json.loads(raw_bytes.decode("utf-8")) + if not isinstance(payload, dict): + raise ValueError("configuration JSON must contain an object") + if "device" in payload and "default_catalog" in payload: + cat_map = { + **payload["default_catalog"], + "evidence": [[source.id, source.sha256]], + } + return resolve_device( + DeviceInput.model_validate(payload["device"]), + DefaultCatalog.from_mapping(cat_map), + resources, + sources=(source,), + ) + device_dict = payload.get("input", payload) + return resolve_device( + DeviceInput.model_validate(device_dict), + defaults, + resources, + sources=(source, *load_packaged_preset_sources()), + ) + mapping = load_packaged_preset_device_mapping(preset) + return resolve_device( + DeviceInput.model_validate(mapping), + defaults, + resources, + sources=load_packaged_preset_sources(), + ) + + +def _cmd_check_install(args: argparse.Namespace) -> int: + defaults = load_packaged_default_catalog() + resources = load_packaged_resource_library() + templates = load_packaged_template_library() + presets = load_packaged_preset_sources() + _, schema_sha256 = configuration_schema_representation() + legacy_present = importlib.util.find_spec("perovskite_sim") is not None + backend_present = importlib.util.find_spec("backend") is not None + report = { + "schema": "solarlab.install-check.v1", + "version": _package_version(), + "default_catalog_sha256": defaults.content_sha256, + "resource_library_sha256": resources.content_sha256, + "resource_count": len(resources.tables), + "template_library_sha256": templates.content_sha256, + "template_count": len(templates.templates), + "preset_source_count": len(presets), + "configuration_schema_sha256": schema_sha256, + "legacy_package_present": legacy_present, + "legacy_backend_present": backend_present, + "scientific_qualification": False, + } + if args.require_no_legacy and (legacy_present or backend_present): + print(json.dumps(report, indent=2, sort_keys=True), file=sys.stderr) + return 1 + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 + + +_STEADY_JV_PRESETS: tuple[str, ...] = ("classical_pin",) + + +def _cmd_steady_jv(args: argparse.Namespace) -> int: + try: + if args.n_points < 2: + raise ValueError("--n-points must be at least 2") + prepared = _load_prepared_device(preset=args.preset, config_path=args.config) + compiled = compile_device_1d( + prepared, intervals_per_layer=args.intervals_per_layer + ) + voltages = np.linspace(float(args.v_min), float(args.v_max), int(args.n_points)) + options = SteadyOptions( + continuity_tolerance_A_m2=1.0e-6, + current_spread_tolerance_A_m2=1.0e-6, + max_bias_step_V=0.05, + convergence_policy=POISSON_CONTACT_BALANCE_V1, + ) + result = run_steady_jv( + compiled, + voltages, + generation_scale=float(args.generation_scale), + options=options, + ) + except (CapabilityError, SteadyStateError, ValueError) as exc: + err_payload = { + "schema": "solarlab.cli.error.v1", + "error_type": type(exc).__name__, + "message": str(exc), + } + print(json.dumps(err_payload, sort_keys=True), file=sys.stderr) + return 1 + payload: dict[str, Any] = { + "schema": "solarlab.cli.steady-jv.v1", + "device_id": compiled.device_id, + "compiled_identity": compiled.identity, + "completed": True, + "n_points": int(result.voltage_V.size), + "voltages_V": [float(v) for v in result.voltage_V], + "output_current_A_m2": [float(j) for j in result.output_current_A_m2], + "metrics": asdict(result.metrics), + "scientific_qualification": False, + } + encoded = json.dumps(payload, indent=2, sort_keys=True) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(encoded + "\n", encoding="utf-8") + else: + print(encoded) + return 0 + + +def _delegate_research(module_name: str, extra_args: list[str]) -> int: + module = importlib.import_module(module_name) + entry = getattr(module, "main") + rc = entry(extra_args) + return int(rc) if isinstance(rc, int) else 0 + + +def main(argv: Sequence[str] | None = None) -> int: + """Entrypoint for the ``solarlab`` console script.""" + parser = argparse.ArgumentParser( + prog="solarlab", + description="SolarLab semiconductor device simulator CLI.", + ) + parser.add_argument( + "--version", + action="version", + version=f"solarlab {_package_version()}", + ) + subparsers = parser.add_subparsers(dest="command") + + p_check = subparsers.add_parser( + "check-install", + help="Verify packaged default catalog, optical tables, templates, and schema.", + ) + p_check.add_argument( + "--require-no-legacy", + action="store_true", + help="Exit non-zero if perovskite_sim or backend is importable.", + ) + + p_jv = subparsers.add_parser( + "steady-jv", + help="Run a 1D ion-free steady-state J-V sweep on classical_pin or a V2 JSON file.", + ) + p_jv.add_argument( + "--preset", + choices=_STEADY_JV_PRESETS, + default="classical_pin", + help="Packaged 1D ion-free steady device preset (default: classical_pin).", + ) + p_jv.add_argument( + "--config", + type=Path, + default=None, + help="Optional path to a V2 DeviceInput JSON document.", + ) + p_jv.add_argument("--v-min", type=float, default=0.0) + p_jv.add_argument("--v-max", type=float, default=1.25) + p_jv.add_argument("--n-points", type=int, default=26) + p_jv.add_argument("--generation-scale", type=float, default=1.0) + p_jv.add_argument("--intervals-per-layer", type=int, default=12) + p_jv.add_argument("--output", type=Path, default=None) + + p_cbo = subparsers.add_parser( + "cbo-scan", + help="Delegate to solarlab_research.scripts.cbo_scan.", + ) + p_cbo.add_argument("research_args", nargs=argparse.REMAINDER) + + args = parser.parse_args(list(argv) if argv is not None else None) + if args.command is None: + parser.print_help() + return 0 + if args.command == "check-install": + return _cmd_check_install(args) + if args.command == "steady-jv": + return _cmd_steady_jv(args) + if args.command == "cbo-scan": + forwarded = list(args.research_args) + if forwarded and forwarded[0] == "--": + forwarded = forwarded[1:] + return _delegate_research("solarlab_research.scripts.cbo_scan", forwarded) + parser.error(f"unknown subcommand: {args.command}") + return 2 + + +def server_main(argv: Sequence[str] | None = None) -> int: + """Entrypoint for the ``solarlab-server`` console script. + + Delegates to ``solarlab_server.cli:main`` when available; otherwise boots + ``solarlab_server.app:create_app`` with packaged ``DefaultCatalog`` and + ``ResourceLibrary`` over an explicit ``--store-dir``. + """ + server_cli_name = "solarlab_server.cli" + if importlib.util.find_spec(server_cli_name) is not None: + server_cli = importlib.import_module(server_cli_name) + delegate = getattr(server_cli, "main", None) + if callable(delegate): + sig = inspect.signature(delegate) + if len(sig.parameters) >= 1: + rc = delegate(argv) + elif argv is None: + rc = delegate() + else: + old_argv = sys.argv[:] + try: + sys.argv = ["solarlab-server", *argv] + rc = delegate() + finally: + sys.argv = old_argv + return int(rc) if isinstance(rc, int) else 0 + + parser = argparse.ArgumentParser( + prog="solarlab-server", + description="Launch the local SolarLab HTTP server over an explicit RunStore.", + ) + parser.add_argument( + "--store-dir", + type=Path, + required=True, + help="Path to the local RunStore directory (initialized if absent).", + ) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8000) + parser.add_argument( + "--check-only", + action="store_true", + help="Construct and verify the FastAPI application without starting uvicorn.", + ) + args = parser.parse_args(list(argv) if argv is not None else None) + store_root = args.store_dir.expanduser().resolve() + if not (store_root / "store.sqlite3").is_file(): + with RunStore(store_root): + pass + + app_mod = importlib.import_module("solarlab_server.app") + cfg_mod = importlib.import_module("solarlab_server.configuration") + preview = cfg_mod.ConfigurationPreviewContext( + defaults=load_packaged_default_catalog(), + resources=load_packaged_resource_library(), + sources=load_packaged_preset_sources(), + ) + app = app_mod.create_app(store_root, configuration_preview=preview) + if args.check_only: + print( + json.dumps( + { + "schema": "solarlab.server-check.v1", + "store_root": str(store_root), + "routes": len(app.routes), + }, + sort_keys=True, + ) + ) + return 0 + uvicorn = importlib.import_module("uvicorn") + uvicorn.run(app, host=args.host, port=args.port) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/solarlab/materials/__init__.py b/src/solarlab/materials/__init__.py index 62a26aa7..c317cd89 100644 --- a/src/solarlab/materials/__init__.py +++ b/src/solarlab/materials/__init__.py @@ -1,3 +1,33 @@ """Material and layer-template data, independent of numerical engines.""" -__all__: tuple[str, ...] = () +from solarlab.materials.packaged import ( + PACKAGED_NK_MATERIALS, + PACKAGED_PRESET_NAMES, + load_packaged_am15g_table, + load_packaged_default_catalog, + load_packaged_default_catalog_mapping, + load_packaged_layer_templates_bytes, + load_packaged_nk_manifest_bytes, + load_packaged_nk_table, + load_packaged_preset_device_mapping, + load_packaged_preset_sources, + load_packaged_preset_v2_documents, + load_packaged_resource_library, + load_packaged_template_library, +) + +__all__ = [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library", +] diff --git a/src/solarlab/materials/data/__init__.py b/src/solarlab/materials/data/__init__.py new file mode 100644 index 00000000..047cca63 --- /dev/null +++ b/src/solarlab/materials/data/__init__.py @@ -0,0 +1 @@ +"""Packaged immutable optical, spectral, template, preset, and default-catalog data.""" diff --git a/src/solarlab/materials/data/am15g.csv b/src/solarlab/materials/data/am15g.csv new file mode 100644 index 00000000..613dd608 --- /dev/null +++ b/src/solarlab/materials/data/am15g.csv @@ -0,0 +1,1347 @@ +# AM1.5G global tilt photon flux derived from ASTM G-173-03 reference spectrum. +# Source: pvlib.spectrum.get_reference_spectra() (NREL ASTM G-173 mirror). +# Column 1: wavelength [nm]. Column 2: photon flux [photons/m^2/s/m]. +# Conversion: Phi(lam) = E(lam) [W/m^2/nm] * 1e9 [nm/m] * lam [m] / (h*c). +# Range: 280-1500 nm at native ASTM sampling. +# wavelength_nm,spectral_flux_m-2_s-1_m-1 +2.800000e+02,6.668453e+04 +2.805000e+02,1.737834e+06 +2.810000e+02,8.048291e+06 +2.815000e+02,2.219468e+08 +2.820000e+02,1.695879e+09 +2.825000e+02,6.461626e+09 +2.830000e+02,2.628773e+10 +2.835000e+02,5.046480e+10 +2.840000e+02,1.038955e+12 +2.845000e+02,3.559892e+12 +2.850000e+02,1.149816e+13 +2.855000e+02,6.124512e+13 +2.860000e+02,1.970164e+14 +2.865000e+02,1.208958e+15 +2.870000e+02,3.953961e+15 +2.875000e+02,1.578000e+16 +2.880000e+02,9.037778e+16 +2.885000e+02,2.492510e+17 +2.890000e+02,8.185768e+17 +2.895000e+02,3.023911e+18 +2.900000e+02,8.783889e+18 +2.905000e+02,2.015641e+19 +2.910000e+02,5.134865e+19 +2.915000e+02,1.601423e+20 +2.920000e+02,3.943908e+20 +2.925000e+02,6.285277e+20 +2.930000e+02,1.275370e+21 +2.935000e+02,3.354989e+21 +2.940000e+02,6.178238e+21 +2.945000e+02,9.771618e+21 +2.950000e+02,1.825144e+22 +2.955000e+02,4.139344e+22 +2.960000e+02,7.138168e+22 +2.965000e+02,1.064907e+23 +2.970000e+02,1.447288e+23 +2.975000e+02,2.786827e+23 +2.980000e+02,4.348683e+23 +2.985000e+02,5.377955e+23 +2.990000e+02,7.407244e+23 +2.995000e+02,1.297663e+24 +3.000000e+02,1.541195e+24 +3.005000e+02,1.883376e+24 +3.010000e+02,2.924469e+24 +3.015000e+02,4.084970e+24 +3.020000e+02,4.440654e+24 +3.025000e+02,6.523762e+24 +3.030000e+02,1.082151e+25 +3.035000e+02,1.371937e+25 +3.040000e+02,1.449277e+25 +3.045000e+02,1.832262e+25 +3.050000e+02,2.527738e+25 +3.055000e+02,2.878837e+25 +3.060000e+02,2.861675e+25 +3.065000e+02,3.256873e+25 +3.070000e+02,4.303990e+25 +3.075000e+02,5.516265e+25 +3.080000e+02,5.866657e+25 +3.085000e+02,6.434182e+25 +3.090000e+02,6.305234e+25 +3.095000e+02,6.747331e+25 +3.100000e+02,7.949419e+25 +3.105000e+02,1.024451e+26 +3.110000e+02,1.298235e+26 +3.115000e+02,1.318481e+26 +3.120000e+02,1.466605e+26 +3.125000e+02,1.557178e+26 +3.130000e+02,1.691176e+26 +3.135000e+02,1.697665e+26 +3.140000e+02,1.891955e+26 +3.145000e+02,2.067698e+26 +3.150000e+02,2.160580e+26 +3.155000e+02,1.880187e+26 +3.160000e+02,1.964296e+26 +3.165000e+02,2.395683e+26 +3.170000e+02,2.738099e+26 +3.175000e+02,2.916157e+26 +3.180000e+02,2.816534e+26 +3.185000e+02,2.980818e+26 +3.190000e+02,3.287243e+26 +3.195000e+02,3.150695e+26 +3.200000e+02,3.306730e+26 +3.205000e+02,3.956948e+26 +3.210000e+02,4.043757e+26 +3.215000e+02,3.858914e+26 +3.220000e+02,3.599074e+26 +3.225000e+02,3.524462e+26 +3.230000e+02,3.451389e+26 +3.235000e+02,4.048705e+26 +3.240000e+02,4.491433e+26 +3.245000e+02,4.626436e+26 +3.250000e+02,4.563704e+26 +3.255000e+02,5.314979e+26 +3.260000e+02,6.255957e+26 +3.265000e+02,6.693227e+26 +3.270000e+02,6.552689e+26 +3.275000e+02,6.341621e+26 +3.280000e+02,5.798320e+26 +3.285000e+02,6.145838e+26 +3.290000e+02,6.995064e+26 +3.295000e+02,7.775848e+26 +3.300000e+02,7.831006e+26 +3.305000e+02,7.120959e+26 +3.310000e+02,6.708827e+26 +3.315000e+02,6.976626e+26 +3.320000e+02,7.290828e+26 +3.325000e+02,7.351354e+26 +3.330000e+02,7.198964e+26 +3.335000e+02,6.837062e+26 +3.340000e+02,6.977285e+26 +3.345000e+02,7.494924e+26 +3.350000e+02,7.823007e+26 +3.355000e+02,7.653122e+26 +3.360000e+02,7.022786e+26 +3.365000e+02,6.473376e+26 +3.370000e+02,6.341507e+26 +3.375000e+02,6.804722e+26 +3.380000e+02,7.386518e+26 +3.385000e+02,7.758021e+26 +3.390000e+02,7.910784e+26 +3.395000e+02,8.108913e+26 +3.400000e+02,8.588807e+26 +3.405000e+02,8.582754e+26 +3.410000e+02,8.092040e+26 +3.415000e+02,8.068834e+26 +3.420000e+02,8.424810e+26 +3.425000e+02,8.753170e+26 +3.430000e+02,8.890616e+26 +3.435000e+02,8.405561e+26 +3.440000e+02,7.246103e+26 +3.445000e+02,6.990254e+26 +3.450000e+02,7.971428e+26 +3.455000e+02,8.510680e+26 +3.460000e+02,8.321993e+26 +3.465000e+02,8.487345e+26 +3.470000e+02,8.630081e+26 +3.475000e+02,8.339877e+26 +3.480000e+02,8.323322e+26 +3.485000e+02,8.480018e+26 +3.490000e+02,8.180860e+26 +3.495000e+02,8.410925e+26 +3.500000e+02,9.302695e+26 +3.505000e+02,1.001171e+27 +3.510000e+02,9.748754e+26 +3.515000e+02,9.382200e+26 +3.520000e+02,9.177412e+26 +3.525000e+02,8.688435e+26 +3.530000e+02,9.247733e+26 +3.535000e+02,1.018407e+27 +3.540000e+02,1.078121e+27 +3.545000e+02,1.091387e+27 +3.550000e+02,1.092640e+27 +3.555000e+02,1.056382e+27 +3.560000e+02,9.926156e+26 +3.565000e+02,9.321836e+26 +3.570000e+02,8.208258e+26 +3.575000e+02,8.317298e+26 +3.580000e+02,7.750600e+26 +3.585000e+02,7.205568e+26 +3.590000e+02,8.485571e+26 +3.595000e+02,1.023404e+27 +3.600000e+02,1.084053e+27 +3.605000e+02,1.025924e+27 +3.610000e+02,9.454405e+26 +3.615000e+02,9.273142e+26 +3.620000e+02,9.734995e+26 +3.625000e+02,1.067730e+27 +3.630000e+02,1.099921e+27 +3.635000e+02,1.071243e+27 +3.640000e+02,1.110959e+27 +3.645000e+02,1.102026e+27 +3.650000e+02,1.145817e+27 +3.655000e+02,1.262734e+27 +3.660000e+02,1.354817e+27 +3.665000e+02,1.358993e+27 +3.670000e+02,1.335480e+27 +3.675000e+02,1.311936e+27 +3.680000e+02,1.236747e+27 +3.685000e+02,1.230098e+27 +3.690000e+02,1.287588e+27 +3.695000e+02,1.385202e+27 +3.700000e+02,1.406411e+27 +3.705000e+02,1.273163e+27 +3.710000e+02,1.294996e+27 +3.715000e+02,1.347479e+27 +3.720000e+02,1.263018e+27 +3.725000e+02,1.204878e+27 +3.730000e+02,1.162049e+27 +3.735000e+02,1.048912e+27 +3.740000e+02,1.047567e+27 +3.745000e+02,1.041182e+27 +3.750000e+02,1.112477e+27 +3.755000e+02,1.231764e+27 +3.760000e+02,1.277280e+27 +3.765000e+02,1.258319e+27 +3.770000e+02,1.351752e+27 +3.775000e+02,1.509946e+27 +3.780000e+02,1.628784e+27 +3.785000e+02,1.589458e+27 +3.790000e+02,1.419290e+27 +3.795000e+02,1.273944e+27 +3.800000e+02,1.340548e+27 +3.805000e+02,1.438048e+27 +3.810000e+02,1.465025e+27 +3.815000e+02,1.322025e+27 +3.820000e+02,1.128397e+27 +3.825000e+02,9.774475e+26 +3.830000e+02,8.772510e+26 +3.835000e+02,8.504028e+26 +3.840000e+02,9.852628e+26 +3.845000e+02,1.187676e+27 +3.850000e+02,1.305431e+27 +3.855000e+02,1.249062e+27 +3.860000e+02,1.206708e+27 +3.865000e+02,1.256329e+27 +3.870000e+02,1.269196e+27 +3.875000e+02,1.252440e+27 +3.880000e+02,1.241907e+27 +3.885000e+02,1.234785e+27 +3.890000e+02,1.342258e+27 +3.895000e+02,1.489611e+27 +3.900000e+02,1.564735e+27 +3.905000e+02,1.579951e+27 +3.910000e+02,1.675805e+27 +3.915000e+02,1.701716e+27 +3.920000e+02,1.568694e+27 +3.925000e+02,1.309166e+27 +3.930000e+02,9.491411e+26 +3.935000e+02,7.557625e+26 +3.940000e+02,9.831327e+26 +3.945000e+02,1.358098e+27 +3.950000e+02,1.606132e+27 +3.955000e+02,1.713011e+27 +3.960000e+02,1.508190e+27 +3.965000e+02,1.098154e+27 +3.970000e+02,8.517596e+26 +3.975000e+02,1.259568e+27 +3.980000e+02,1.708031e+27 +3.985000e+02,2.019938e+27 +3.990000e+02,2.147809e+27 +3.995000e+02,2.216466e+27 +4.000000e+02,2.243404e+27 +4.010000e+02,2.342275e+27 +4.020000e+02,2.440802e+27 +4.030000e+02,2.355986e+27 +4.040000e+02,2.400067e+27 +4.050000e+02,2.346882e+27 +4.060000e+02,2.294632e+27 +4.070000e+02,2.259101e+27 +4.080000e+02,2.364883e+27 +4.090000e+02,2.532307e+27 +4.100000e+02,2.164091e+27 +4.110000e+02,2.428618e+27 +4.120000e+02,2.588007e+27 +4.130000e+02,2.488879e+27 +4.140000e+02,2.468020e+27 +4.150000e+02,2.560890e+27 +4.160000e+02,2.643709e+27 +4.170000e+02,2.584568e+27 +4.180000e+02,2.478188e+27 +4.190000e+02,2.585574e+27 +4.200000e+02,2.374814e+27 +4.210000e+02,2.703671e+27 +4.220000e+02,2.673129e+27 +4.230000e+02,2.594499e+27 +4.240000e+02,2.586332e+27 +4.250000e+02,2.671807e+27 +4.260000e+02,2.602392e+27 +4.270000e+02,2.520153e+27 +4.280000e+02,2.550833e+27 +4.290000e+02,2.367609e+27 +4.300000e+02,1.893264e+27 +4.310000e+02,1.722615e+27 +4.320000e+02,2.872177e+27 +4.330000e+02,2.678504e+27 +4.340000e+02,2.480192e+27 +4.350000e+02,2.726790e+27 +4.360000e+02,2.997980e+27 +4.370000e+02,3.067333e+27 +4.380000e+02,2.698409e+27 +4.390000e+02,2.602248e+27 +4.400000e+02,2.990044e+27 +4.410000e+02,2.955546e+27 +4.420000e+02,3.170738e+27 +4.430000e+02,3.223183e+27 +4.440000e+02,3.147982e+27 +4.450000e+02,3.274922e+27 +4.460000e+02,2.943029e+27 +4.470000e+02,3.353548e+27 +4.480000e+02,3.401194e+27 +4.490000e+02,3.400649e+27 +4.500000e+02,3.532817e+27 +4.510000e+02,3.671896e+27 +4.520000e+02,3.522806e+27 +4.530000e+02,3.260366e+27 +4.540000e+02,3.504797e+27 +4.550000e+02,3.487092e+27 +4.560000e+02,3.609534e+27 +4.570000e+02,3.647357e+27 +4.580000e+02,3.576947e+27 +4.590000e+02,3.556336e+27 +4.600000e+02,3.540927e+27 +4.610000e+02,3.673016e+27 +4.620000e+02,3.715405e+27 +4.630000e+02,3.736499e+27 +4.640000e+02,3.630814e+27 +4.650000e+02,3.593227e+27 +4.660000e+02,3.676726e+27 +4.670000e+02,3.520051e+27 +4.680000e+02,3.679784e+27 +4.690000e+02,3.702521e+27 +4.700000e+02,3.567271e+27 +4.710000e+02,3.635086e+27 +4.720000e+02,3.831704e+27 +4.730000e+02,3.690524e+27 +4.740000e+02,3.739369e+27 +4.750000e+02,3.870166e+27 +4.760000e+02,3.745562e+27 +4.770000e+02,3.775763e+27 +4.780000e+02,3.905437e+27 +4.790000e+02,3.837892e+27 +4.800000e+02,3.909938e+27 +4.810000e+02,3.917115e+27 +4.820000e+02,3.939575e+27 +4.830000e+02,3.899605e+27 +4.840000e+02,3.833609e+27 +4.850000e+02,3.829077e+27 +4.860000e+02,3.111072e+27 +4.870000e+02,3.491345e+27 +4.880000e+02,3.786433e+27 +4.890000e+02,3.574118e+27 +4.900000e+02,4.002002e+27 +4.910000e+02,3.854696e+27 +4.920000e+02,3.682732e+27 +4.930000e+02,3.946837e+27 +4.940000e+02,3.860840e+27 +4.950000e+02,4.107877e+27 +4.960000e+02,3.914175e+27 +4.970000e+02,3.989119e+27 +4.980000e+02,3.888091e+27 +4.990000e+02,3.895396e+27 +5.000000e+02,3.889107e+27 +5.010000e+02,3.777590e+27 +5.020000e+02,3.782098e+27 +5.030000e+02,3.963591e+27 +5.040000e+02,3.701006e+27 +5.050000e+02,3.974775e+27 +5.060000e+02,4.142869e+27 +5.070000e+02,3.971374e+27 +5.080000e+02,3.878193e+27 +5.090000e+02,4.072367e+27 +5.100000e+02,3.974591e+27 +5.110000e+02,4.056470e+27 +5.120000e+02,4.171889e+27 +5.130000e+02,3.926952e+27 +5.140000e+02,3.851547e+27 +5.150000e+02,3.970262e+27 +5.160000e+02,4.014597e+27 +5.170000e+02,3.277763e+27 +5.180000e+02,3.755831e+27 +5.190000e+02,3.646554e+27 +5.200000e+02,3.988390e+27 +5.210000e+02,4.024910e+27 +5.220000e+02,4.123032e+27 +5.230000e+02,3.893711e+27 +5.240000e+02,4.195543e+27 +5.250000e+02,4.170778e+27 +5.260000e+02,4.062213e+27 +5.270000e+02,3.559503e+27 +5.280000e+02,4.081911e+27 +5.290000e+02,4.279784e+27 +5.300000e+02,4.121119e+27 +5.310000e+02,4.355040e+27 +5.320000e+02,4.284504e+27 +5.330000e+02,3.833197e+27 +5.340000e+02,4.113512e+27 +5.350000e+02,4.183968e+27 +5.360000e+02,4.370954e+27 +5.370000e+02,4.052007e+27 +5.380000e+02,4.262409e+27 +5.390000e+02,4.165595e+27 +5.400000e+02,4.030062e+27 +5.410000e+02,3.881199e+27 +5.420000e+02,4.232163e+27 +5.430000e+02,4.170266e+27 +5.440000e+02,4.324733e+27 +5.450000e+02,4.234737e+27 +5.460000e+02,4.202927e+27 +5.470000e+02,4.265422e+27 +5.480000e+02,4.151561e+27 +5.490000e+02,4.289309e+27 +5.500000e+02,4.263620e+27 +5.510000e+02,4.266656e+27 +5.520000e+02,4.361933e+27 +5.530000e+02,4.245396e+27 +5.540000e+02,4.336462e+27 +5.550000e+02,4.368038e+27 +5.560000e+02,4.300895e+27 +5.570000e+02,4.202640e+27 +5.580000e+02,4.300636e+27 +5.590000e+02,4.075619e+27 +5.600000e+02,4.155361e+27 +5.610000e+02,4.404245e+27 +5.620000e+02,4.200474e+27 +5.630000e+02,4.366947e+27 +5.640000e+02,4.288959e+27 +5.650000e+02,4.323584e+27 +5.660000e+02,4.095598e+27 +5.670000e+02,4.372855e+27 +5.680000e+02,4.340536e+27 +5.690000e+02,4.241335e+27 +5.700000e+02,4.251372e+27 +5.710000e+02,4.119418e+27 +5.720000e+02,4.357858e+27 +5.730000e+02,4.383937e+27 +5.740000e+02,4.368760e+27 +5.750000e+02,4.277376e+27 +5.760000e+02,4.249149e+27 +5.770000e+02,4.363709e+27 +5.780000e+02,4.236551e+27 +5.790000e+02,4.305091e+27 +5.800000e+02,4.385521e+27 +5.810000e+02,4.413264e+27 +5.820000e+02,4.488539e+27 +5.830000e+02,4.542916e+27 +5.840000e+02,4.541595e+27 +5.850000e+02,4.512854e+27 +5.860000e+02,4.411123e+27 +5.870000e+02,4.515576e+27 +5.880000e+02,4.420554e+27 +5.890000e+02,3.823193e+27 +5.900000e+02,4.071750e+27 +5.910000e+02,4.362184e+27 +5.920000e+02,4.277775e+27 +5.930000e+02,4.346795e+27 +5.940000e+02,4.333193e+27 +5.950000e+02,4.285674e+27 +5.960000e+02,4.423992e+27 +5.970000e+02,4.444338e+27 +5.980000e+02,4.397294e+27 +5.990000e+02,4.404346e+27 +6.000000e+02,4.456099e+27 +6.010000e+02,4.410882e+27 +6.020000e+02,4.351853e+27 +6.030000e+02,4.451363e+27 +6.040000e+02,4.536889e+27 +6.050000e+02,4.536482e+27 +6.060000e+02,4.521710e+27 +6.070000e+02,4.556367e+27 +6.080000e+02,4.548876e+27 +6.090000e+02,4.521714e+27 +6.100000e+02,4.509793e+27 +6.110000e+02,4.494117e+27 +6.120000e+02,4.569252e+27 +6.130000e+02,4.511914e+27 +6.140000e+02,4.381727e+27 +6.150000e+02,4.550164e+27 +6.160000e+02,4.437554e+27 +6.170000e+02,4.388227e+27 +6.180000e+02,4.562094e+27 +6.190000e+02,4.590977e+27 +6.200000e+02,4.600266e+27 +6.210000e+02,4.627381e+27 +6.220000e+02,4.467939e+27 +6.230000e+02,4.442505e+27 +6.240000e+02,4.434871e+27 +6.250000e+02,4.413032e+27 +6.260000e+02,4.415681e+27 +6.270000e+02,4.550569e+27 +6.280000e+02,4.309339e+27 +6.290000e+02,4.469141e+27 +6.300000e+02,4.415987e+27 +6.310000e+02,4.498281e+27 +6.320000e+02,4.339014e+27 +6.330000e+02,4.623113e+27 +6.340000e+02,4.558924e+27 +6.350000e+02,4.621737e+27 +6.360000e+02,4.523359e+27 +6.370000e+02,4.685036e+27 +6.380000e+02,4.723545e+27 +6.390000e+02,4.711326e+27 +6.400000e+02,4.620111e+27 +6.410000e+02,4.629911e+27 +6.420000e+02,4.646184e+27 +6.430000e+02,4.701651e+27 +6.440000e+02,4.688539e+27 +6.450000e+02,4.729912e+27 +6.460000e+02,4.601636e+27 +6.470000e+02,4.587914e+27 +6.480000e+02,4.551292e+27 +6.490000e+02,4.416849e+27 +6.500000e+02,4.448196e+27 +6.510000e+02,4.734585e+27 +6.520000e+02,4.552801e+27 +6.530000e+02,4.704424e+27 +6.540000e+02,4.659610e+27 +6.550000e+02,4.451088e+27 +6.560000e+02,3.913651e+27 +6.570000e+02,4.098879e+27 +6.580000e+02,4.589398e+27 +6.590000e+02,4.612960e+27 +6.600000e+02,4.648866e+27 +6.610000e+02,4.636277e+27 +6.620000e+02,4.605299e+27 +6.630000e+02,4.620600e+27 +6.640000e+02,4.668684e+27 +6.650000e+02,4.758403e+27 +6.660000e+02,4.761871e+27 +6.670000e+02,4.735107e+27 +6.680000e+02,4.758348e+27 +6.690000e+02,4.847646e+27 +6.700000e+02,4.788109e+27 +6.710000e+02,4.786135e+27 +6.720000e+02,4.726625e+27 +6.730000e+02,4.774991e+27 +6.740000e+02,4.775301e+27 +6.750000e+02,4.742968e+27 +6.760000e+02,4.805125e+27 +6.770000e+02,4.768268e+27 +6.780000e+02,4.800910e+27 +6.790000e+02,4.767315e+27 +6.800000e+02,4.781867e+27 +6.810000e+02,4.770387e+27 +6.820000e+02,4.800051e+27 +6.830000e+02,4.755171e+27 +6.840000e+02,4.730799e+27 +6.850000e+02,4.740819e+27 +6.860000e+02,4.640684e+27 +6.870000e+02,3.348598e+27 +6.880000e+02,3.881167e+27 +6.890000e+02,3.911781e+27 +6.900000e+02,4.106072e+27 +6.910000e+02,4.290126e+27 +6.920000e+02,4.420351e+27 +6.930000e+02,4.398830e+27 +6.940000e+02,4.354519e+27 +6.950000e+02,4.448261e+27 +6.960000e+02,4.444150e+27 +6.970000e+02,4.702817e+27 +6.980000e+02,4.635423e+27 +6.990000e+02,4.545647e+27 +7.000000e+02,4.518673e+27 +7.010000e+02,4.467254e+27 +7.020000e+02,4.478928e+27 +7.030000e+02,4.511143e+27 +7.040000e+02,4.634867e+27 +7.050000e+02,4.689718e+27 +7.060000e+02,4.671491e+27 +7.070000e+02,4.658889e+27 +7.080000e+02,4.650509e+27 +7.090000e+02,4.673853e+27 +7.100000e+02,4.709038e+27 +7.110000e+02,4.708512e+27 +7.120000e+02,4.685027e+27 +7.130000e+02,4.636690e+27 +7.140000e+02,4.683091e+27 +7.150000e+02,4.530556e+27 +7.160000e+02,4.583390e+27 +7.170000e+02,3.996035e+27 +7.180000e+02,3.721485e+27 +7.190000e+02,3.341478e+27 +7.200000e+02,3.572008e+27 +7.210000e+02,3.942106e+27 +7.220000e+02,4.509488e+27 +7.230000e+02,4.165234e+27 +7.240000e+02,3.846981e+27 +7.250000e+02,3.788424e+27 +7.260000e+02,3.951901e+27 +7.270000e+02,3.970886e+27 +7.280000e+02,3.811430e+27 +7.290000e+02,3.840887e+27 +7.300000e+02,4.147130e+27 +7.310000e+02,3.938639e+27 +7.320000e+02,4.250248e+27 +7.330000e+02,4.413987e+27 +7.340000e+02,4.565963e+27 +7.350000e+02,4.505952e+27 +7.360000e+02,4.467992e+27 +7.370000e+02,4.466642e+27 +7.380000e+02,4.558152e+27 +7.390000e+02,4.428913e+27 +7.400000e+02,4.542938e+27 +7.410000e+02,4.531545e+27 +7.420000e+02,4.539528e+27 +7.430000e+02,4.639902e+27 +7.440000e+02,4.682852e+27 +7.450000e+02,4.686896e+27 +7.460000e+02,4.683047e+27 +7.470000e+02,4.691957e+27 +7.480000e+02,4.669620e+27 +7.490000e+02,4.659273e+27 +7.500000e+02,4.659452e+27 +7.510000e+02,4.644872e+27 +7.520000e+02,4.667713e+27 +7.530000e+02,4.649660e+27 +7.540000e+02,4.714289e+27 +7.550000e+02,4.706479e+27 +7.560000e+02,4.655245e+27 +7.570000e+02,4.657211e+27 +7.580000e+02,4.691600e+27 +7.590000e+02,4.564058e+27 +7.600000e+02,1.017850e+27 +7.610000e+02,5.898150e+26 +7.620000e+02,2.637862e+27 +7.630000e+02,1.457748e+27 +7.640000e+02,2.072183e+27 +7.650000e+02,2.641893e+27 +7.660000e+02,3.141245e+27 +7.670000e+02,3.761433e+27 +7.680000e+02,4.306175e+27 +7.690000e+02,4.365980e+27 +7.700000e+02,4.499574e+27 +7.710000e+02,4.535692e+27 +7.720000e+02,4.577329e+27 +7.730000e+02,4.580534e+27 +7.740000e+02,4.586460e+27 +7.750000e+02,4.592385e+27 +7.760000e+02,4.608859e+27 +7.770000e+02,4.587026e+27 +7.780000e+02,4.587446e+27 +7.790000e+02,4.613735e+27 +7.800000e+02,4.569004e+27 +7.810000e+02,4.563460e+27 +7.820000e+02,4.590955e+27 +7.830000e+02,4.577906e+27 +7.840000e+02,4.552968e+27 +7.850000e+02,4.578534e+27 +7.860000e+02,4.586741e+27 +7.870000e+02,4.536318e+27 +7.880000e+02,4.484562e+27 +7.890000e+02,4.471188e+27 +7.900000e+02,4.338855e+27 +7.910000e+02,4.403280e+27 +7.920000e+02,4.366983e+27 +7.930000e+02,4.341359e+27 +7.940000e+02,4.385606e+27 +7.950000e+02,4.375121e+27 +7.960000e+02,4.304488e+27 +7.970000e+02,4.378504e+27 +7.980000e+02,4.467556e+27 +7.990000e+02,4.386274e+27 +8.000000e+02,4.319272e+27 +8.010000e+02,4.372253e+27 +8.020000e+02,4.382960e+27 +8.030000e+02,4.307981e+27 +8.040000e+02,4.363939e+27 +8.050000e+02,4.273323e+27 +8.060000e+02,4.452698e+27 +8.070000e+02,4.411504e+27 +8.080000e+02,4.401513e+27 +8.090000e+02,4.295779e+27 +8.100000e+02,4.305574e+27 +8.110000e+02,4.300275e+27 +8.120000e+02,4.197253e+27 +8.130000e+02,4.127934e+27 +8.140000e+02,3.702582e+27 +8.150000e+02,3.672954e+27 +8.160000e+02,3.418379e+27 +8.170000e+02,3.503469e+27 +8.180000e+02,3.387349e+27 +8.190000e+02,3.732045e+27 +8.200000e+02,3.557820e+27 +8.210000e+02,4.123256e+27 +8.220000e+02,3.937638e+27 +8.230000e+02,2.787090e+27 +8.240000e+02,3.878734e+27 +8.250000e+02,4.025852e+27 +8.260000e+02,3.882950e+27 +8.270000e+02,4.099309e+27 +8.280000e+02,3.542136e+27 +8.290000e+02,3.878232e+27 +8.300000e+02,3.827380e+27 +8.310000e+02,3.865082e+27 +8.320000e+02,3.745505e+27 +8.330000e+02,4.011005e+27 +8.340000e+02,3.921859e+27 +8.350000e+02,4.216938e+27 +8.360000e+02,4.092114e+27 +8.370000e+02,4.252320e+27 +8.380000e+02,4.214413e+27 +8.390000e+02,4.229115e+27 +8.400000e+02,4.295048e+27 +8.410000e+02,4.276452e+27 +8.420000e+02,4.226137e+27 +8.430000e+02,4.266252e+27 +8.440000e+02,4.190628e+27 +8.450000e+02,4.324017e+27 +8.460000e+02,4.338503e+27 +8.470000e+02,4.228506e+27 +8.480000e+02,4.235505e+27 +8.490000e+02,4.213958e+27 +8.500000e+02,3.824227e+27 +8.510000e+02,4.176632e+27 +8.520000e+02,4.157264e+27 +8.530000e+02,4.143207e+27 +8.540000e+02,3.659080e+27 +8.550000e+02,3.929707e+27 +8.560000e+02,4.193588e+27 +8.570000e+02,4.278257e+27 +8.580000e+02,4.284545e+27 +8.590000e+02,4.288458e+27 +8.600000e+02,4.278081e+27 +8.610000e+02,4.277117e+27 +8.620000e+02,4.315498e+27 +8.630000e+02,4.346615e+27 +8.640000e+02,4.258834e+27 +8.650000e+02,4.194439e+27 +8.660000e+02,3.701254e+27 +8.670000e+02,3.995598e+27 +8.680000e+02,4.191333e+27 +8.690000e+02,4.153990e+27 +8.700000e+02,4.237561e+27 +8.710000e+02,4.182449e+27 +8.720000e+02,4.244273e+27 +8.730000e+02,4.206731e+27 +8.740000e+02,4.137677e+27 +8.750000e+02,4.082725e+27 +8.760000e+02,4.201607e+27 +8.770000e+02,4.221326e+27 +8.780000e+02,4.209432e+27 +8.790000e+02,4.144267e+27 +8.800000e+02,4.162316e+27 +8.810000e+02,4.029737e+27 +8.820000e+02,4.140163e+27 +8.830000e+02,4.130721e+27 +8.840000e+02,4.152221e+27 +8.850000e+02,4.206727e+27 +8.860000e+02,4.047745e+27 +8.870000e+02,4.066156e+27 +8.880000e+02,4.122864e+27 +8.890000e+02,4.182419e+27 +8.900000e+02,4.139542e+27 +8.910000e+02,4.152761e+27 +8.920000e+02,4.080949e+27 +8.930000e+02,3.925756e+27 +8.940000e+02,3.831276e+27 +8.950000e+02,3.665568e+27 +8.960000e+02,3.439444e+27 +8.970000e+02,3.005856e+27 +8.980000e+02,3.244913e+27 +8.990000e+02,2.483281e+27 +9.000000e+02,3.364501e+27 +9.010000e+02,2.718404e+27 +9.020000e+02,3.032828e+27 +9.030000e+02,3.131561e+27 +9.040000e+02,3.843504e+27 +9.050000e+02,3.722560e+27 +9.060000e+02,3.537350e+27 +9.070000e+02,2.915538e+27 +9.080000e+02,2.981055e+27 +9.090000e+02,3.222931e+27 +9.100000e+02,2.861642e+27 +9.110000e+02,3.063868e+27 +9.120000e+02,3.162956e+27 +9.130000e+02,2.887944e+27 +9.140000e+02,2.882595e+27 +9.150000e+02,3.124673e+27 +9.160000e+02,2.658202e+27 +9.170000e+02,3.370673e+27 +9.180000e+02,2.739102e+27 +9.190000e+02,3.417811e+27 +9.200000e+02,3.446401e+27 +9.210000e+02,3.618681e+27 +9.220000e+02,3.250226e+27 +9.230000e+02,3.461821e+27 +9.240000e+02,3.356074e+27 +9.250000e+02,3.311278e+27 +9.260000e+02,3.278544e+27 +9.270000e+02,3.674595e+27 +9.280000e+02,2.754785e+27 +9.290000e+02,2.578121e+27 +9.300000e+02,2.022975e+27 +9.310000e+02,1.917870e+27 +9.320000e+02,1.411574e+27 +9.330000e+02,1.166740e+27 +9.340000e+02,6.761282e+26 +9.350000e+02,1.180679e+27 +9.360000e+02,7.606002e+26 +9.370000e+02,7.706581e+26 +9.380000e+02,9.471390e+26 +9.390000e+02,1.885473e+27 +9.400000e+02,2.232638e+27 +9.410000e+02,1.761966e+27 +9.420000e+02,1.922083e+27 +9.430000e+02,1.321328e+27 +9.440000e+02,1.358133e+27 +9.450000e+02,1.751663e+27 +9.460000e+02,9.267862e+26 +9.470000e+02,1.769243e+27 +9.480000e+02,1.308719e+27 +9.490000e+02,2.359833e+27 +9.500000e+02,7.042578e+26 +9.510000e+02,2.316070e+27 +9.520000e+02,1.288746e+27 +9.530000e+02,1.648521e+27 +9.540000e+02,2.036808e+27 +9.550000e+02,1.640203e+27 +9.560000e+02,1.579549e+27 +9.570000e+02,1.303993e+27 +9.580000e+02,2.223305e+27 +9.590000e+02,1.804842e+27 +9.600000e+02,2.032945e+27 +9.610000e+02,2.231187e+27 +9.620000e+02,2.139267e+27 +9.630000e+02,2.448312e+27 +9.640000e+02,2.225535e+27 +9.650000e+02,2.447130e+27 +9.660000e+02,2.444851e+27 +9.670000e+02,2.445679e+27 +9.680000e+02,3.177699e+27 +9.690000e+02,3.347422e+27 +9.700000e+02,3.098860e+27 +9.710000e+02,3.489976e+27 +9.720000e+02,3.364782e+27 +9.730000e+02,2.970658e+27 +9.740000e+02,2.820779e+27 +9.750000e+02,2.895237e+27 +9.760000e+02,2.809964e+27 +9.770000e+02,3.141043e+27 +9.780000e+02,3.028313e+27 +9.790000e+02,3.145059e+27 +9.800000e+02,2.983149e+27 +9.810000e+02,3.523005e+27 +9.820000e+02,3.421794e+27 +9.830000e+02,3.308839e+27 +9.840000e+02,3.652367e+27 +9.850000e+02,3.412363e+27 +9.860000e+02,3.726849e+27 +9.870000e+02,3.673241e+27 +9.880000e+02,3.653785e+27 +9.890000e+02,3.729376e+27 +9.900000e+02,3.649469e+27 +9.910000e+02,3.759467e+27 +9.920000e+02,3.750476e+27 +9.930000e+02,3.685573e+27 +9.940000e+02,3.773450e+27 +9.950000e+02,3.765525e+27 +9.960000e+02,3.754669e+27 +9.970000e+02,3.712615e+27 +9.980000e+02,3.712119e+27 +9.990000e+02,3.714329e+27 +1.000000e+03,3.701687e+27 +1.001000e+03,3.751245e+27 +1.002000e+03,3.672419e+27 +1.003000e+03,3.708247e+27 +1.004000e+03,3.656044e+27 +1.005000e+03,3.449118e+27 +1.006000e+03,3.608430e+27 +1.007000e+03,3.688108e+27 +1.008000e+03,3.688320e+27 +1.009000e+03,3.655763e+27 +1.010000e+03,3.656437e+27 +1.011000e+03,3.678583e+27 +1.012000e+03,3.661792e+27 +1.013000e+03,3.659495e+27 +1.014000e+03,3.678779e+27 +1.015000e+03,3.618485e+27 +1.016000e+03,3.638008e+27 +1.017000e+03,3.601041e+27 +1.018000e+03,3.660185e+27 +1.019000e+03,3.533279e+27 +1.020000e+03,3.589019e+27 +1.021000e+03,3.606878e+27 +1.022000e+03,3.548415e+27 +1.023000e+03,3.579593e+27 +1.024000e+03,3.559895e+27 +1.025000e+03,3.599234e+27 +1.026000e+03,3.596702e+27 +1.027000e+03,3.583095e+27 +1.028000e+03,3.590724e+27 +1.029000e+03,3.555003e+27 +1.030000e+03,3.580598e+27 +1.031000e+03,3.567518e+27 +1.032000e+03,3.573628e+27 +1.033000e+03,3.516040e+27 +1.034000e+03,3.540369e+27 +1.035000e+03,3.555203e+27 +1.036000e+03,3.556969e+27 +1.037000e+03,3.523599e+27 +1.038000e+03,3.510014e+27 +1.039000e+03,3.537665e+27 +1.040000e+03,3.516673e+27 +1.041000e+03,3.520369e+27 +1.042000e+03,3.525009e+27 +1.043000e+03,3.492951e+27 +1.044000e+03,3.512487e+27 +1.045000e+03,3.495808e+27 +1.046000e+03,3.407636e+27 +1.047000e+03,3.462547e+27 +1.048000e+03,3.496453e+27 +1.049000e+03,3.479828e+27 +1.050000e+03,3.460258e+27 +1.051000e+03,3.466622e+27 +1.052000e+03,3.448578e+27 +1.053000e+03,3.441307e+27 +1.054000e+03,3.430090e+27 +1.055000e+03,3.444020e+27 +1.056000e+03,3.436333e+27 +1.057000e+03,3.431127e+27 +1.058000e+03,3.399008e+27 +1.059000e+03,3.298636e+27 +1.060000e+03,3.393000e+27 +1.061000e+03,3.318005e+27 +1.062000e+03,3.382347e+27 +1.063000e+03,3.330574e+27 +1.064000e+03,3.384967e+27 +1.065000e+03,3.372976e+27 +1.066000e+03,3.311747e+27 +1.067000e+03,3.331988e+27 +1.068000e+03,3.330380e+27 +1.069000e+03,3.154941e+27 +1.070000e+03,3.257166e+27 +1.071000e+03,3.324477e+27 +1.072000e+03,3.320835e+27 +1.073000e+03,3.260572e+27 +1.074000e+03,3.360660e+27 +1.075000e+03,3.206526e+27 +1.076000e+03,3.329705e+27 +1.077000e+03,3.276576e+27 +1.078000e+03,3.273487e+27 +1.079000e+03,3.284834e+27 +1.080000e+03,3.246993e+27 +1.081000e+03,3.160807e+27 +1.082000e+03,3.210411e+27 +1.083000e+03,3.261028e+27 +1.084000e+03,3.156973e+27 +1.085000e+03,3.240614e+27 +1.086000e+03,3.029293e+27 +1.087000e+03,3.102508e+27 +1.088000e+03,3.248863e+27 +1.089000e+03,3.175208e+27 +1.090000e+03,3.049394e+27 +1.091000e+03,3.231348e+27 +1.092000e+03,3.195225e+27 +1.093000e+03,2.809359e+27 +1.094000e+03,2.972027e+27 +1.095000e+03,2.870119e+27 +1.096000e+03,2.776517e+27 +1.097000e+03,3.194834e+27 +1.098000e+03,2.779815e+27 +1.099000e+03,2.808958e+27 +1.100000e+03,2.689965e+27 +1.101000e+03,2.754432e+27 +1.102000e+03,2.600880e+27 +1.103000e+03,2.589580e+27 +1.104000e+03,2.599042e+27 +1.105000e+03,2.817173e+27 +1.106000e+03,2.215512e+27 +1.107000e+03,2.691869e+27 +1.108000e+03,2.318413e+27 +1.109000e+03,2.304483e+27 +1.110000e+03,2.676534e+27 +1.111000e+03,1.854271e+27 +1.112000e+03,2.315139e+27 +1.113000e+03,1.504398e+27 +1.114000e+03,1.681561e+27 +1.115000e+03,1.402530e+27 +1.116000e+03,1.131255e+27 +1.117000e+03,4.477006e+26 +1.118000e+03,1.224290e+27 +1.119000e+03,6.375066e+26 +1.120000e+03,8.000057e+26 +1.121000e+03,1.048853e+27 +1.122000e+03,4.613853e+26 +1.123000e+03,7.245851e+26 +1.124000e+03,6.150623e+26 +1.125000e+03,8.171126e+26 +1.126000e+03,2.924279e+26 +1.127000e+03,8.921499e+26 +1.128000e+03,5.634418e+26 +1.129000e+03,6.019413e+26 +1.130000e+03,4.014638e+26 +1.131000e+03,1.683024e+27 +1.132000e+03,1.334104e+27 +1.133000e+03,8.744272e+26 +1.134000e+03,2.382806e+26 +1.135000e+03,8.834557e+25 +1.136000e+03,7.363471e+26 +1.137000e+03,1.647593e+27 +1.138000e+03,1.164613e+27 +1.139000e+03,1.711557e+27 +1.140000e+03,1.469099e+27 +1.141000e+03,1.110703e+27 +1.142000e+03,1.292309e+27 +1.143000e+03,1.794268e+27 +1.144000e+03,6.522677e+26 +1.145000e+03,8.417838e+26 +1.146000e+03,9.094405e+26 +1.147000e+03,3.416900e+26 +1.148000e+03,1.566905e+27 +1.149000e+03,1.264079e+27 +1.150000e+03,7.042024e+26 +1.151000e+03,1.178554e+27 +1.152000e+03,1.436023e+27 +1.153000e+03,1.382129e+27 +1.154000e+03,8.277191e+26 +1.155000e+03,1.820839e+27 +1.156000e+03,1.634680e+27 +1.157000e+03,1.832263e+27 +1.158000e+03,1.817116e+27 +1.159000e+03,1.965832e+27 +1.160000e+03,1.672922e+27 +1.161000e+03,2.031177e+27 +1.162000e+03,2.047492e+27 +1.163000e+03,2.743326e+27 +1.164000e+03,2.354901e+27 +1.165000e+03,2.279040e+27 +1.166000e+03,2.200815e+27 +1.167000e+03,2.408439e+27 +1.168000e+03,2.466831e+27 +1.169000e+03,2.489894e+27 +1.170000e+03,2.701881e+27 +1.171000e+03,2.642765e+27 +1.172000e+03,2.683490e+27 +1.173000e+03,2.695169e+27 +1.174000e+03,1.991215e+27 +1.175000e+03,2.675985e+27 +1.176000e+03,2.822655e+27 +1.177000e+03,2.798747e+27 +1.178000e+03,2.134868e+27 +1.179000e+03,2.870927e+27 +1.180000e+03,2.617812e+27 +1.181000e+03,2.705940e+27 +1.182000e+03,1.923026e+27 +1.183000e+03,2.612616e+27 +1.184000e+03,2.502471e+27 +1.185000e+03,2.430375e+27 +1.186000e+03,2.848806e+27 +1.187000e+03,2.723332e+27 +1.188000e+03,2.003717e+27 +1.189000e+03,2.488139e+27 +1.190000e+03,2.769993e+27 +1.191000e+03,2.677650e+27 +1.192000e+03,2.840476e+27 +1.193000e+03,2.728630e+27 +1.194000e+03,2.818434e+27 +1.195000e+03,2.688808e+27 +1.196000e+03,2.596833e+27 +1.197000e+03,2.875228e+27 +1.198000e+03,2.616916e+27 +1.199000e+03,2.202442e+27 +1.200000e+03,2.707851e+27 +1.201000e+03,2.642574e+27 +1.202000e+03,2.645319e+27 +1.203000e+03,2.628867e+27 +1.204000e+03,2.196958e+27 +1.205000e+03,2.650405e+27 +1.206000e+03,2.919371e+27 +1.207000e+03,2.611906e+27 +1.208000e+03,2.635963e+27 +1.209000e+03,2.521410e+27 +1.210000e+03,2.761543e+27 +1.211000e+03,2.574596e+27 +1.212000e+03,2.592402e+27 +1.213000e+03,2.867313e+27 +1.214000e+03,2.652783e+27 +1.215000e+03,2.616618e+27 +1.216000e+03,2.855061e+27 +1.217000e+03,2.789282e+27 +1.218000e+03,2.816468e+27 +1.219000e+03,2.740784e+27 +1.220000e+03,2.813170e+27 +1.221000e+03,2.860101e+27 +1.222000e+03,2.776812e+27 +1.223000e+03,2.733955e+27 +1.224000e+03,2.760961e+27 +1.225000e+03,2.851278e+27 +1.226000e+03,2.889588e+27 +1.227000e+03,2.674828e+27 +1.228000e+03,2.884349e+27 +1.229000e+03,2.890595e+27 +1.230000e+03,2.848489e+27 +1.231000e+03,2.925169e+27 +1.232000e+03,2.892193e+27 +1.233000e+03,2.817822e+27 +1.234000e+03,2.920681e+27 +1.235000e+03,2.891216e+27 +1.236000e+03,2.918695e+27 +1.237000e+03,2.885623e+27 +1.238000e+03,2.916500e+27 +1.239000e+03,2.886110e+27 +1.240000e+03,2.876267e+27 +1.241000e+03,2.886083e+27 +1.242000e+03,2.891535e+27 +1.243000e+03,2.863014e+27 +1.244000e+03,2.851164e+27 +1.245000e+03,2.861416e+27 +1.246000e+03,2.881904e+27 +1.247000e+03,2.871725e+27 +1.248000e+03,2.881190e+27 +1.249000e+03,2.890164e+27 +1.250000e+03,2.876054e+27 +1.251000e+03,2.850204e+27 +1.252000e+03,2.842335e+27 +1.253000e+03,2.824168e+27 +1.254000e+03,2.800540e+27 +1.255000e+03,2.847440e+27 +1.256000e+03,2.783508e+27 +1.257000e+03,2.754655e+27 +1.258000e+03,2.817895e+27 +1.259000e+03,2.707890e+27 +1.260000e+03,2.734462e+27 +1.261000e+03,2.611957e+27 +1.262000e+03,2.513713e+27 +1.263000e+03,2.544444e+27 +1.264000e+03,2.363773e+27 +1.265000e+03,2.519880e+27 +1.266000e+03,2.455400e+27 +1.267000e+03,2.476155e+27 +1.268000e+03,2.365062e+27 +1.269000e+03,1.574842e+27 +1.270000e+03,2.477031e+27 +1.271000e+03,2.612131e+27 +1.272000e+03,2.617644e+27 +1.273000e+03,2.603425e+27 +1.274000e+03,2.604764e+27 +1.275000e+03,2.646540e+27 +1.276000e+03,2.678164e+27 +1.277000e+03,2.700062e+27 +1.278000e+03,2.751201e+27 +1.279000e+03,2.733587e+27 +1.280000e+03,2.719486e+27 +1.281000e+03,2.665572e+27 +1.282000e+03,2.407567e+27 +1.283000e+03,2.630851e+27 +1.284000e+03,2.719840e+27 +1.285000e+03,2.742723e+27 +1.286000e+03,2.765251e+27 +1.287000e+03,2.734941e+27 +1.288000e+03,2.722542e+27 +1.289000e+03,2.656327e+27 +1.290000e+03,2.681052e+27 +1.291000e+03,2.715691e+27 +1.292000e+03,2.576786e+27 +1.293000e+03,2.685465e+27 +1.294000e+03,2.633083e+27 +1.295000e+03,2.641181e+27 +1.296000e+03,2.541638e+27 +1.297000e+03,2.424310e+27 +1.298000e+03,2.560328e+27 +1.299000e+03,2.671442e+27 +1.300000e+03,2.310941e+27 +1.301000e+03,2.372711e+27 +1.302000e+03,2.568087e+27 +1.303000e+03,2.270949e+27 +1.304000e+03,1.973416e+27 +1.305000e+03,2.521514e+27 +1.306000e+03,2.528114e+27 +1.307000e+03,2.012960e+27 +1.308000e+03,2.284601e+27 +1.309000e+03,2.531286e+27 +1.310000e+03,1.985926e+27 +1.311000e+03,2.202065e+27 +1.312000e+03,2.201829e+27 +1.313000e+03,2.072303e+27 +1.314000e+03,1.907254e+27 +1.315000e+03,1.892023e+27 +1.316000e+03,2.147725e+27 +1.317000e+03,2.069666e+27 +1.318000e+03,2.211301e+27 +1.319000e+03,1.783172e+27 +1.320000e+03,1.719203e+27 +1.321000e+03,1.986109e+27 +1.322000e+03,2.010972e+27 +1.323000e+03,1.550413e+27 +1.324000e+03,1.749541e+27 +1.325000e+03,2.149407e+27 +1.326000e+03,1.872471e+27 +1.327000e+03,1.778623e+27 +1.328000e+03,1.567704e+27 +1.329000e+03,1.188138e+27 +1.330000e+03,1.534781e+27 +1.331000e+03,9.702192e+26 +1.332000e+03,9.775866e+26 +1.333000e+03,1.362495e+27 +1.334000e+03,1.136600e+27 +1.335000e+03,1.553589e+27 +1.336000e+03,1.234009e+27 +1.337000e+03,1.107455e+27 +1.338000e+03,1.199215e+27 +1.339000e+03,1.191820e+27 +1.340000e+03,1.135371e+27 +1.341000e+03,1.150260e+27 +1.342000e+03,1.202395e+27 +1.343000e+03,8.593676e+26 +1.344000e+03,5.118029e+26 +1.345000e+03,7.382975e+26 +1.346000e+03,3.942637e+26 +1.347000e+03,4.076642e+26 +1.348000e+03,3.220020e+25 +1.349000e+03,1.097361e+26 +1.350000e+03,1.089068e+26 +1.351000e+03,3.148769e+25 +1.352000e+03,1.032081e+25 +1.353000e+03,6.545252e+23 +1.354000e+03,1.977310e+24 +1.355000e+03,2.457961e+22 +1.356000e+03,3.281384e+23 +1.357000e+03,4.903914e+23 +1.358000e+03,2.867704e+22 +1.359000e+03,5.024230e+21 +1.360000e+03,1.465403e+22 +1.361000e+03,3.297800e+19 +1.362000e+03,1.239375e+17 +1.363000e+03,2.165696e+22 +1.364000e+03,9.330934e+21 +1.365000e+03,6.236911e+16 +1.366000e+03,8.795863e+22 +1.367000e+03,3.424578e+22 +1.368000e+03,1.019916e+15 +1.369000e+03,3.560738e+21 +1.370000e+03,2.013848e+21 +1.371000e+03,1.361789e+20 +1.372000e+03,1.899234e+22 +1.373000e+03,3.068927e+23 +1.374000e+03,1.239297e+24 +1.375000e+03,2.237992e+24 +1.376000e+03,1.783550e+24 +1.377000e+03,8.505538e+23 +1.378000e+03,7.692453e+24 +1.379000e+03,3.621249e+23 +1.380000e+03,5.667915e+23 +1.381000e+03,1.648764e+22 +1.382000e+03,1.786039e+22 +1.383000e+03,3.064544e+20 +1.384000e+03,4.298007e+21 +1.385000e+03,1.457131e+22 +1.386000e+03,1.759323e+22 +1.387000e+03,1.389202e+24 +1.388000e+03,2.813248e+22 +1.389000e+03,4.062438e+24 +1.390000e+03,3.451688e+24 +1.391000e+03,2.407725e+24 +1.392000e+03,1.666521e+23 +1.393000e+03,8.124711e+23 +1.394000e+03,5.300081e+23 +1.395000e+03,4.714688e+21 +1.396000e+03,4.442514e+19 +1.397000e+03,3.450012e+23 +1.398000e+03,8.940688e+24 +1.399000e+03,5.720527e+24 +1.400000e+03,2.288127e+19 +1.401000e+03,7.425185e+19 +1.402000e+03,1.295324e+25 +1.403000e+03,1.680962e+25 +1.404000e+03,5.222612e+24 +1.405000e+03,2.577660e+21 +1.406000e+03,1.447303e+25 +1.407000e+03,1.236480e+24 +1.408000e+03,1.169030e+25 +1.409000e+03,4.391958e+24 +1.410000e+03,3.311479e+24 +1.411000e+03,1.501746e+25 +1.412000e+03,1.876273e+25 +1.413000e+03,1.661147e+26 +1.414000e+03,2.589474e+24 +1.415000e+03,1.308261e+24 +1.416000e+03,2.535183e+26 +1.417000e+03,8.388098e+25 +1.418000e+03,9.678926e+25 +1.419000e+03,1.531690e+25 +1.420000e+03,5.913051e+25 +1.421000e+03,6.555234e+25 +1.422000e+03,3.315394e+26 +1.423000e+03,6.604648e+25 +1.424000e+03,1.216867e+26 +1.425000e+03,1.854380e+26 +1.426000e+03,1.995090e+26 +1.427000e+03,3.559228e+26 +1.428000e+03,3.277193e+25 +1.429000e+03,2.735065e+26 +1.430000e+03,4.434525e+26 +1.431000e+03,3.613148e+26 +1.432000e+03,1.816199e+25 +1.433000e+03,2.585025e+26 +1.434000e+03,1.513231e+26 +1.435000e+03,1.547083e+26 +1.436000e+03,2.772390e+26 +1.437000e+03,2.161527e+26 +1.438000e+03,9.601165e+25 +1.439000e+03,3.697313e+26 +1.440000e+03,2.870727e+26 +1.441000e+03,2.306824e+26 +1.442000e+03,2.636322e+26 +1.443000e+03,3.273480e+26 +1.444000e+03,4.491751e+26 +1.445000e+03,3.619036e+26 +1.446000e+03,1.681162e+26 +1.447000e+03,2.638033e+26 +1.448000e+03,8.433108e+26 +1.449000e+03,7.449806e+26 +1.450000e+03,2.000930e+26 +1.451000e+03,8.232905e+25 +1.452000e+03,4.558301e+26 +1.453000e+03,5.996339e+26 +1.454000e+03,1.007105e+27 +1.455000e+03,4.845249e+26 +1.456000e+03,6.487421e+26 +1.457000e+03,8.581608e+26 +1.458000e+03,1.001361e+27 +1.459000e+03,1.197713e+27 +1.460000e+03,6.278281e+26 +1.461000e+03,6.639659e+26 +1.462000e+03,9.612001e+26 +1.463000e+03,3.183483e+26 +1.464000e+03,1.119053e+27 +1.465000e+03,6.886978e+26 +1.466000e+03,4.811548e+26 +1.467000e+03,2.662606e+26 +1.468000e+03,5.686078e+26 +1.469000e+03,7.013899e+26 +1.470000e+03,3.676247e+26 +1.471000e+03,1.321678e+26 +1.472000e+03,3.465834e+26 +1.473000e+03,5.205360e+26 +1.474000e+03,7.222834e+26 +1.475000e+03,1.370937e+27 +1.476000e+03,5.110450e+26 +1.477000e+03,5.185144e+26 +1.478000e+03,4.723181e+26 +1.479000e+03,8.935295e+26 +1.480000e+03,4.517755e+26 +1.481000e+03,8.595477e+26 +1.482000e+03,4.363682e+26 +1.483000e+03,1.109313e+27 +1.484000e+03,1.026987e+27 +1.485000e+03,9.346822e+26 +1.486000e+03,9.231180e+26 +1.487000e+03,4.538524e+26 +1.488000e+03,7.054803e+26 +1.489000e+03,1.422178e+27 +1.490000e+03,1.310996e+27 +1.491000e+03,1.484511e+27 +1.492000e+03,1.234867e+27 +1.493000e+03,1.364669e+27 +1.494000e+03,1.531796e+27 +1.495000e+03,1.373722e+27 +1.496000e+03,1.269131e+27 +1.497000e+03,1.721993e+27 +1.498000e+03,1.430397e+27 +1.499000e+03,1.641965e+27 +1.500000e+03,1.892400e+27 diff --git a/src/solarlab/materials/data/default_catalog_v1.json b/src/solarlab/materials/data/default_catalog_v1.json new file mode 100644 index 00000000..d3ed4f76 --- /dev/null +++ b/src/solarlab/materials/data/default_catalog_v1.json @@ -0,0 +1,309 @@ +{ + "complex_defaults": { + "band_to_band": { + "enabled": false, + "energy_quadrature_order": 32, + "minimum_field_V_m": 1000000.0, + "reduced_effective_mass_rel": 0.1 + }, + "cigs_graded_optics": { + "kk_quadrature_order": 192, + "model": "minoura_2015", + "slices": 25 + }, + "contact": { + "barrier_height_eV": 0.0, + "electron_effective_mass_rel": 0.2, + "enabled": false, + "energy_quadrature_order": 32, + "hole_effective_mass_rel": 0.2, + "side": "both" + }, + "interface_defect_assisted": { + "electron_effective_mass_rel": 0.2, + "enabled": false, + "hole_effective_mass_rel": 0.2, + "requires_explicit_occupancy": true + }, + "intraband": { + "carrier": "both", + "electron_effective_mass_rel": 0.2, + "enabled": false, + "energy_quadrature_order": 32, + "hole_effective_mass_rel": 0.2 + } + }, + "constants": { + "K_B": 1.380649e-23, + "Q": 1.602176634e-19, + "T": 300.0 + }, + "contacts": { + "S_n_left": null, + "S_n_right": null, + "S_p_left": null, + "S_p_right": null + }, + "defect_degeneracy": 1.0, + "defect_model": "effective_lifetime", + "defect_schema_version": null, + "device": { + "Phi": 2.5e+21, + "T": 300.0, + "V_bi": 1.1, + "band_grading": false, + "built_in_potential_mode": null, + "contact_phi_B_eV": 0.0, + "dos_band_potentials": true, + "flat_band_contacts": false, + "flat_band_metal_contacts": false, + "graded_optics": false, + "het_recomb_despike": 0.0, + "interface_charge_closure": "off", + "interface_charge_rebaseline_acknowledged": false, + "interface_plane_closure": false, + "interface_plane_generation": false, + "interface_plane_projection": false, + "interface_shared_occupancy": false, + "interface_tunneling": false, + "interface_two_sided": false, + "ion_steric_diffusion_only": true, + "ion_steric_shared_site": true, + "jv_solver_policy": "general", + "mode": "full", + "phi_left": 0.0, + "te_physical_norm": false, + "tunnel_mass_eff": 0.2, + "work_function_left_eV": null, + "work_function_right_eV": null + }, + "distribution_width_convention": "not_applicable", + "evidence": [ + [ + "backend/main.py", + "7dd1292f6f34f0f065a50686802c20a8484edcc9e4a7d98287799c076f9da01f" + ], + [ + "constants.py", + "9ae428b44bbe5f475b638d9c3339e69930249e2b1c39ba0acbfd0764fcaade76" + ], + [ + "experiments/dark_jv.py", + "7dd01ad1fe88fb0ac2d8d69722aebe8ec5d2cdedd2f5c0f149bad2477759540c" + ], + [ + "experiments/jv_sweep.py", + "428fbe1c421192e2495ac94fa171df42f2be94dca7733b7a5ab2e07a9628ef96" + ], + [ + "experiments/protocol.py", + "427d372bd2b28bc2c9b6b924ea4cafa42e7315decf5385664f74bcb19137beef" + ], + [ + "experiments/waveform_jv.py", + "cac7648c136190db6bca65697cdb3200ab7b57e81787736a67d706cda333d1e7" + ], + [ + "models/defects.py", + "0bf3cedd435ff8259fb436bbcfcfa3aa586bdee50f89caba161e162c6913159f" + ], + [ + "models/device.py", + "abedb9e39655a5b54997968a7bfa4d1664b7493475dc8e7c55fffa68195330b9" + ], + [ + "models/parameters.py", + "0555a6c9280431889b34328bf1e513c7e6d6789368ea858ff3e1ea5a60db7d9d" + ], + [ + "models/tandem_config.py", + "9aaf4e1fb87f43950c96cabe0ac309cd3416673848b80889fc366be32ad2b595" + ], + [ + "models/tunneling_channels.py", + "988195babef2c7390bfacd0f849b91a3802abfda3e742332642c1c36a610a114" + ], + [ + "physics/band_gap_narrowing.py", + "ee7fe97002c19364750f4aa07be1dc150c2acb450ad74ee637d5b8cc783e0a78" + ], + [ + "physics/cigs_optics.py", + "a7f1cac165c04f8f5d21a530987d65d10fa78af04c77b7e1382149aab59ca811" + ], + [ + "physics/statistics.py", + "f790b5df608ec54ff64ebd1a3203bcec0a00d1bfbc2677a29ccd34208fc29a01" + ], + [ + "scaps_compat/loader.py", + "a03a31b81497df6118592aebce7000befaa1d5de787ad989d880c263000e0cd6" + ], + [ + "solver/tolerances.py", + "1a193fb904bfd593e7581c9c3a25f51e245bbb72ce6b9fcf22bdd9196170e0b6" + ], + [ + "twod/microstructure.py", + "60d06d32976305a4c29b04e7f46188e8a916e007048a9c6507c680e6d4b6ab35" + ] + ], + "experiment_defaults": { + "dark_jv": { + "N_grid": 60, + "V_max": 1.2, + "n_points": 60, + "v_rate": 1.0 + }, + "dark_jv_numerical": { + "atol": 1e-06, + "rtol": 0.0001 + }, + "jv_2d": { + "Nx": 10, + "Ny_per_layer": 20, + "V_max": 1.2, + "V_step": 0.05, + "atol": 1e-08, + "illuminated": true, + "initial_state_settle_s": 0.001, + "interface_srh": "off", + "ion_dynamics": "frozen", + "ion_inventory_rtol": 1e-09, + "lateral_length": 5e-07, + "max_bisect": 6, + "max_nfev_per_solve": 200000, + "protocol_mode": "compatibility", + "rtol": 1e-06, + "save_snapshots": true, + "settle_t": 1e-07 + }, + "jv_2d_componentwise_atol": { + "carrier_fraction": 1e-12, + "interface_fraction": 1e-12, + "ion_fraction": 1e-12, + "minimum_atol": 1e-06, + "refinement_factor": 1.0 + }, + "jv_endpoint": { + "N_grid": 80, + "V_max": null, + "iface_states": false, + "interface_boundary": false, + "interface_transport_model": "fermi_richardson", + "n_points": 40, + "protocol_mode": "compatibility", + "solver": "transient", + "v_rate": 1.0 + }, + "jv_history": { + "illuminated_soak_s": 0.001 + }, + "jv_jobs": { + "N_grid": 60, + "V_max": null, + "iface_states": false, + "illuminated": true, + "interface_boundary": false, + "interface_transport_model": "fermi_richardson", + "n_points": 30, + "protocol_mode": "compatibility", + "solver": "transient", + "v_rate": 1.0 + }, + "jv_numerical": { + "atol": 1e-06, + "rtol": 0.0001 + }, + "jv_waveform_controls": { + "atol_m3": 100.0, + "rtol": 0.0001 + }, + "voc_grain_sweep": { + "Nx": 10, + "Ny_per_layer": 10, + "V_max": 1.2, + "V_step": 0.05, + "gb_width": 1e-08, + "illuminated": true, + "settle_t": 0.001, + "tau_gb_n": 1e-09, + "tau_gb_p": 1e-09 + } + }, + "interface": { + "calibration_factor": 1.0, + "iface_state_calibration_factor": 1.0 + }, + "material": { + "A_star_n": 1201700.0, + "A_star_p": 1201700.0, + "B_rad_T_gamma": 0.0, + "D_ion_neg": 0.0, + "E_a_ion": 0.58, + "Eg": 0.0, + "Eg_back": null, + "N_A_bulk": null, + "N_D_bulk": null, + "Nc300": null, + "Nv300": null, + "P0_neg": 0.0, + "P_lim_neg": 1e+30, + "acceptor_binding_energy_eV": null, + "acceptor_degeneracy": 4.0, + "band_gap_narrowing_model": "off", + "bgn_conduction_band_fraction": 0.5, + "bgn_log_shape": 0.5, + "bgn_reference_density_m3": 1e+23, + "bgn_reference_energy_eV": 0.009, + "carrier_statistics": "maxwell_boltzmann", + "chi": 0.0, + "chi_back": null, + "ct_beta_n": 2.0, + "ct_beta_p": 2.0, + "donor_binding_energy_eV": null, + "donor_degeneracy": 2.0, + "dopant_ionization_model": "fully_ionized", + "doping_decay_length": null, + "doping_edge": "front", + "doping_profile_shape": null, + "grading_N_mult": 1, + "grading_bowing": 0.0, + "grading_char_length": null, + "grading_direction": "front_to_back", + "grading_profile": "linear", + "incoherent": false, + "mu_T_gamma": -1.5, + "n_optical": null, + "optical_material": null, + "pf_gamma_n": 0.0, + "pf_gamma_p": 0.0, + "trap_N_t_bulk": null, + "trap_N_t_interface": null, + "trap_decay_length": null, + "trap_edge": "both", + "trap_profile_shape": "exponential", + "v_sat_n": 0.0, + "v_sat_p": 0.0, + "v_th": 100000.0, + "varshni_alpha": 0.0, + "varshni_beta": 0.0 + }, + "scaps": { + "B_rad": 0.0, + "C_n": 0.0, + "C_p": 0.0, + "D_ion": 0.0, + "P0": 0.0, + "P_lim": 1e+30, + "alpha": 0.0, + "tau_n": 0.001, + "tau_p": 0.001 + }, + "schema": "solarlab.default-catalog.v1", + "structural": { + "grain_boundary_layer_role": "absorber", + "junction_incoherent": false, + "tandem_light_direction": "top_first" + } +} diff --git a/src/solarlab/materials/data/layer_templates.yaml b/src/solarlab/materials/data/layer_templates.yaml new file mode 100644 index 00000000..af9eb90c --- /dev/null +++ b/src/solarlab/materials/data/layer_templates.yaml @@ -0,0 +1,340 @@ +# Layer template library for Phase 2b custom-stack builder. +# Each entry: role, optical_material (or null), description, source, defaults. +# Defaults come from cited published cells; tune at PR review if a stack +# fails to converge during the manual verification pass. + +glass_substrate: + role: substrate + optical_material: glass + description: "BK7-equivalent glass substrate (1 mm) — front side" + source: "Schott BK7 datasheet" + defaults: + thickness: 1.0e-3 + incoherent: true + eps_r: 4.6 + mu_n: 0 + mu_p: 0 + ni: 0 + N_D: 0 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-9 + tau_p: 1.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 0 + Eg: 9.0 + +FTO_front_contact: + role: front_contact + optical_material: FTO + description: "F:SnO2 front contact on glass (degenerate semiconductor approx)" + source: "Filipic 2015, Opt. Express 23, A263" + defaults: + thickness: 5.0e-7 + eps_r: 9.0 + mu_n: 5.0e-3 + mu_p: 1.0e-3 + ni: 1.0e10 + N_D: 1.0e26 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-9 + tau_p: 1.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.4 + Eg: 3.5 + incoherent: false + +ITO_front_contact: + role: front_contact + optical_material: ITO + description: "Sn:In2O3 front contact (sputtered TCO, p-i-n stacks)" + source: "König 2014, Opt. Mater. Express 4, 689" + defaults: + thickness: 1.5e-7 + eps_r: 9.0 + mu_n: 4.0e-3 + mu_p: 1.0e-3 + ni: 1.0e10 + N_D: 1.0e26 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-9 + tau_p: 1.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.4 + Eg: 3.5 + incoherent: false + +TiO2_ETL: + role: ETL + optical_material: TiO2 + description: "Compact TiO2 ETL for planar n-i-p perovskite cells" + source: "Liu et al. 2014, Nature 501, 395" + defaults: + thickness: 5.0e-8 + eps_r: 30 + mu_n: 1.0e-7 + mu_p: 1.0e-7 + ni: 1.0e10 + N_D: 1.0e22 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.0 + Eg: 3.2 + incoherent: false + +SnO2_ETL: + role: ETL + optical_material: SnO2 + description: "Modern SnO2 ETL (replaces TiO2 in many n-i-p stacks)" + source: "Jiang et al. 2017, Nat. Energy 2, 16177" + defaults: + thickness: 5.0e-8 + eps_r: 9 + mu_n: 2.0e-3 + mu_p: 2.0e-4 + ni: 1.0e10 + N_D: 1.0e23 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.0 + Eg: 3.6 + incoherent: false + +C60_ETL: + role: ETL + optical_material: C60 + description: "Fullerene C60 ETL for inverted (p-i-n) cells" + source: "Ren et al. 2015, Adv. Mater. 27, 6729" + defaults: + thickness: 3.0e-8 + eps_r: 4.0 + mu_n: 1.0e-6 + mu_p: 1.0e-6 + ni: 1.0e10 + N_D: 1.0e21 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 3.9 + Eg: 1.7 + incoherent: false + +PCBM_ETL: + role: ETL + optical_material: PCBM + description: "PCBM fullerene derivative ETL (alternative to C60 in p-i-n)" + source: "Ren et al. 2015, Adv. Mater. 27, 6729" + defaults: + thickness: 5.0e-8 + eps_r: 4.0 + mu_n: 1.0e-6 + mu_p: 1.0e-6 + ni: 1.0e10 + N_D: 1.0e21 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 3.9 + Eg: 2.0 + incoherent: false + +MAPbI3_absorber: + role: absorber + optical_material: MAPbI3 + description: "Methylammonium lead iodide perovskite absorber (~400 nm)" + source: "Phillips et al. 2018, Sci. Rep. 8, 6473" + defaults: + thickness: 4.0e-7 + eps_r: 24.1 + mu_n: 2.0e-4 + mu_p: 2.0e-4 + ni: 1.0e12 + N_D: 0 + N_A: 0 + D_ion: 1.0e-16 + P_lim: 1.6e25 + P0: 1.6e25 + tau_n: 3.0e-9 + tau_p: 3.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 9.0e-17 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.0 + Eg: 1.6 + incoherent: false + +spiro_HTL: + role: HTL + optical_material: spiro_OMeTAD + description: "spiro-OMeTAD HTL (n-i-p stacks)" + source: "Saliba et al. 2016, Energy Environ. Sci. 9, 1989" + defaults: + thickness: 2.0e-7 + eps_r: 3.0 + mu_n: 1.0e-8 + mu_p: 1.0e-8 + ni: 1.0e10 + N_D: 0 + N_A: 1.0e22 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 2.45 + Eg: 3.0 + incoherent: false + +PEDOT_PSS_HTL: + role: HTL + optical_material: PEDOT_PSS + description: "PEDOT:PSS HTL (p-i-n stacks)" + source: "Lee et al. 2018, J. Mater. Chem. A 6, 6105" + defaults: + thickness: 4.0e-8 + eps_r: 3.0 + mu_n: 1.0e-8 + mu_p: 1.0e-8 + ni: 1.0e10 + N_D: 0 + N_A: 1.0e22 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-7 + tau_p: 1.0e-7 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 3.4 + Eg: 1.6 + incoherent: false + +Au_back_contact: + role: back_contact + optical_material: Au + description: "Gold back contact (degenerate semiconductor approx, n-i-p)" + source: "Johnson & Christy 1972, Phys. Rev. B 6, 4370" + defaults: + thickness: 1.0e-7 + eps_r: 6.9 + mu_n: 1.0e-3 + mu_p: 1.0e-3 + ni: 1.0e10 + N_D: 0 + N_A: 1.0e26 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-9 + tau_p: 1.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.0 + Eg: 3.0 + incoherent: false + +Ag_back_contact: + role: back_contact + optical_material: Ag + description: "Silver back contact / reflector (p-i-n stacks)" + source: "Johnson & Christy 1972, Phys. Rev. B 6, 4370" + defaults: + thickness: 1.0e-7 + eps_r: 6.0 + mu_n: 1.0e-3 + mu_p: 1.0e-3 + ni: 1.0e10 + N_D: 1.0e26 + N_A: 0 + D_ion: 0 + P_lim: 0 + P0: 0 + tau_n: 1.0e-9 + tau_p: 1.0e-9 + n1: 1.0e10 + p1: 1.0e10 + B_rad: 0 + C_n: 0 + C_p: 0 + alpha: 0 + chi: 4.3 + Eg: 3.0 + incoherent: false diff --git a/src/solarlab/materials/data/nk/Ag.csv b/src/solarlab/materials/data/nk/Ag.csv new file mode 100644 index 00000000..862fc925 --- /dev/null +++ b/src/solarlab/materials/data/nk/Ag.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.3453,0.9849 +305.0,1.2521,0.8184 +310.0,1.1450,0.6409 +315.0,0.9881,0.5167 +320.0,0.8232,0.4012 +325.0,0.5448,0.5731 +330.0,0.2565,0.7699 +335.0,0.1605,0.9286 +340.0,0.1468,1.0709 +345.0,0.1315,1.2012 +350.0,0.1144,1.3196 +355.0,0.0982,1.4329 +360.0,0.0873,1.5198 +365.0,0.0764,1.6066 +370.0,0.0669,1.6890 +375.0,0.0596,1.7651 +380.0,0.0522,1.8412 +385.0,0.0500,1.9093 +390.0,0.0500,1.9741 +395.0,0.0500,2.0389 +400.0,0.0500,2.1035 +405.0,0.0500,2.1680 +410.0,0.0500,2.2325 +415.0,0.0490,2.2935 +420.0,0.0461,2.3478 +425.0,0.0432,2.4022 +430.0,0.0403,2.4566 +435.0,0.0400,2.5050 +440.0,0.0400,2.5528 +445.0,0.0400,2.6006 +450.0,0.0400,2.6484 +455.0,0.0420,2.6994 +460.0,0.0444,2.7511 +465.0,0.0469,2.8028 +470.0,0.0493,2.8545 +475.0,0.0500,2.9019 +480.0,0.0500,2.9476 +485.0,0.0500,2.9933 +490.0,0.0500,3.0391 +495.0,0.0500,3.0848 +500.0,0.0500,3.1309 +505.0,0.0500,3.1771 +510.0,0.0500,3.2233 +515.0,0.0500,3.2695 +520.0,0.0500,3.3157 +525.0,0.0515,3.3628 +530.0,0.0533,3.4101 +535.0,0.0551,3.4574 +540.0,0.0569,3.5047 +545.0,0.0587,3.5519 +550.0,0.0596,3.5974 +555.0,0.0581,3.6380 +560.0,0.0566,3.6786 +565.0,0.0551,3.7192 +570.0,0.0536,3.7598 +575.0,0.0521,3.8004 +580.0,0.0506,3.8409 +585.0,0.0508,3.8826 +590.0,0.0523,3.9249 +595.0,0.0537,3.9673 +600.0,0.0552,4.0097 +605.0,0.0566,4.0520 +610.0,0.0580,4.0944 +615.0,0.0595,4.1367 +620.0,0.0593,4.1768 +625.0,0.0581,4.2156 +630.0,0.0569,4.2543 +635.0,0.0557,4.2931 +640.0,0.0546,4.3318 +645.0,0.0534,4.3706 +650.0,0.0522,4.4094 +655.0,0.0511,4.4481 +660.0,0.0499,4.4869 +665.0,0.0488,4.5264 +670.0,0.0477,4.5658 +675.0,0.0466,4.6053 +680.0,0.0454,4.6447 +685.0,0.0443,4.6842 +690.0,0.0432,4.7236 +695.0,0.0421,4.7631 +700.0,0.0410,4.8025 +705.0,0.0399,4.8419 +710.0,0.0389,4.8811 +715.0,0.0380,4.9204 +720.0,0.0370,4.9596 +725.0,0.0360,4.9988 +730.0,0.0350,5.0380 +735.0,0.0341,5.0773 +740.0,0.0331,5.1165 +745.0,0.0321,5.1557 +750.0,0.0312,5.1949 +755.0,0.0302,5.2342 +760.0,0.0306,5.2718 +765.0,0.0314,5.3091 +770.0,0.0322,5.3463 +775.0,0.0329,5.3836 +780.0,0.0337,5.4208 +785.0,0.0345,5.4581 +790.0,0.0352,5.4953 +795.0,0.0360,5.5326 +800.0,0.0368,5.5698 +805.0,0.0375,5.6071 +810.0,0.0383,5.6443 +815.0,0.0391,5.6816 +820.0,0.0398,5.7188 +825.0,0.0400,5.7592 +830.0,0.0400,5.8004 +835.0,0.0400,5.8417 +840.0,0.0400,5.8829 +845.0,0.0400,5.9242 +850.0,0.0400,5.9655 +855.0,0.0400,6.0067 +860.0,0.0400,6.0480 +865.0,0.0400,6.0892 +870.0,0.0400,6.1305 +875.0,0.0400,6.1717 +880.0,0.0400,6.2130 +885.0,0.0400,6.2542 +890.0,0.0400,6.2955 +895.0,0.0400,6.3342 +900.0,0.0400,6.3711 +905.0,0.0400,6.4081 +910.0,0.0400,6.4450 +915.0,0.0400,6.4820 +920.0,0.0400,6.5190 +925.0,0.0400,6.5559 +930.0,0.0400,6.5929 +935.0,0.0400,6.6298 +940.0,0.0400,6.6668 +945.0,0.0400,6.7037 +950.0,0.0400,6.7407 +955.0,0.0400,6.7777 +960.0,0.0400,6.8146 +965.0,0.0400,6.8516 +970.0,0.0400,6.8885 +975.0,0.0400,6.9255 +980.0,0.0400,6.9624 +985.0,0.0400,6.9997 +990.0,0.0400,7.0383 +995.0,0.0400,7.0769 +1000.0,0.0400,7.1155 +1005.0,0.0400,7.1155 +1010.0,0.0400,7.1155 +1015.0,0.0400,7.1155 +1020.0,0.0400,7.1155 +1025.0,0.0400,7.1155 +1030.0,0.0400,7.1155 +1035.0,0.0400,7.1155 +1040.0,0.0400,7.1155 +1045.0,0.0400,7.1155 +1050.0,0.0400,7.1155 +1055.0,0.0400,7.1155 +1060.0,0.0400,7.1155 +1065.0,0.0400,7.1155 +1070.0,0.0400,7.1155 +1075.0,0.0400,7.1155 +1080.0,0.0400,7.1155 +1085.0,0.0400,7.1155 +1090.0,0.0400,7.1155 +1095.0,0.0400,7.1155 +1100.0,0.0400,7.1155 diff --git a/src/solarlab/materials/data/nk/Au.csv b/src/solarlab/materials/data/nk/Au.csv new file mode 100644 index 00000000..b76625f7 --- /dev/null +++ b/src/solarlab/materials/data/nk/Au.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.5258,1.8878 +305.0,1.5300,1.8907 +310.0,1.5300,1.8927 +315.0,1.5344,1.8952 +320.0,1.5396,1.8978 +325.0,1.5151,1.8918 +330.0,1.4881,1.8850 +335.0,1.4800,1.8792 +340.0,1.4800,1.8737 +345.0,1.4843,1.8699 +350.0,1.4928,1.8678 +355.0,1.4988,1.8677 +360.0,1.4915,1.8783 +365.0,1.4842,1.8889 +370.0,1.4769,1.9009 +375.0,1.4696,1.9148 +380.0,1.4622,1.9288 +385.0,1.4622,1.9372 +390.0,1.4653,1.9432 +395.0,1.4685,1.9491 +400.0,1.4684,1.9530 +405.0,1.4652,1.9549 +410.0,1.4621,1.9568 +415.0,1.4590,1.9570 +420.0,1.4561,1.9541 +425.0,1.4532,1.9512 +430.0,1.4503,1.9483 +435.0,1.4346,1.9405 +440.0,1.4174,1.9322 +445.0,1.4002,1.9238 +450.0,1.3831,1.9155 +455.0,1.3660,1.9010 +460.0,1.3489,1.8851 +465.0,1.3319,1.8693 +470.0,1.3148,1.8534 +475.0,1.2703,1.8466 +480.0,1.2152,1.8434 +485.0,1.1601,1.8401 +490.0,1.1050,1.8369 +495.0,1.0499,1.8336 +500.0,0.9711,1.8737 +505.0,0.8871,1.9233 +510.0,0.8031,1.9729 +515.0,0.7191,2.0225 +520.0,0.6351,2.0721 +525.0,0.5919,2.1364 +530.0,0.5576,2.2039 +535.0,0.5233,2.2714 +540.0,0.4890,2.3389 +545.0,0.4547,2.4064 +550.0,0.4241,2.4721 +555.0,0.4033,2.5329 +560.0,0.3824,2.5938 +565.0,0.3615,2.6547 +570.0,0.3406,2.7156 +575.0,0.3197,2.7765 +580.0,0.2988,2.8374 +585.0,0.2833,2.8972 +590.0,0.2718,2.9561 +595.0,0.2603,3.0150 +600.0,0.2487,3.0740 +605.0,0.2372,3.1329 +610.0,0.2257,3.1919 +615.0,0.2141,3.2508 +620.0,0.2048,3.3039 +625.0,0.1966,3.3536 +630.0,0.1884,3.4034 +635.0,0.1802,3.4531 +640.0,0.1720,3.5029 +645.0,0.1638,3.5527 +650.0,0.1556,3.6024 +655.0,0.1474,3.6522 +660.0,0.1399,3.7015 +665.0,0.1388,3.7466 +670.0,0.1377,3.7917 +675.0,0.1366,3.8368 +680.0,0.1354,3.8820 +685.0,0.1343,3.9271 +690.0,0.1332,3.9722 +695.0,0.1321,4.0173 +700.0,0.1310,4.0624 +705.0,0.1301,4.1073 +710.0,0.1311,4.1499 +715.0,0.1320,4.1925 +720.0,0.1330,4.2351 +725.0,0.1340,4.2777 +730.0,0.1350,4.3204 +735.0,0.1359,4.3630 +740.0,0.1369,4.4056 +745.0,0.1379,4.4482 +750.0,0.1388,4.4909 +755.0,0.1398,4.5335 +760.0,0.1412,4.5752 +765.0,0.1428,4.6168 +770.0,0.1443,4.6583 +775.0,0.1458,4.6999 +780.0,0.1474,4.7414 +785.0,0.1489,4.7830 +790.0,0.1504,4.8245 +795.0,0.1520,4.8661 +800.0,0.1535,4.9077 +805.0,0.1551,4.9492 +810.0,0.1566,4.9908 +815.0,0.1581,5.0323 +820.0,0.1597,5.0739 +825.0,0.1606,5.1149 +830.0,0.1613,5.1558 +835.0,0.1620,5.1967 +840.0,0.1627,5.2376 +845.0,0.1634,5.2785 +850.0,0.1641,5.3194 +855.0,0.1648,5.3603 +860.0,0.1655,5.4012 +865.0,0.1662,5.4421 +870.0,0.1669,5.4830 +875.0,0.1676,5.5239 +880.0,0.1683,5.5648 +885.0,0.1690,5.6057 +890.0,0.1697,5.6466 +895.0,0.1716,5.6854 +900.0,0.1743,5.7227 +905.0,0.1771,5.7601 +910.0,0.1798,5.7974 +915.0,0.1825,5.8348 +920.0,0.1852,5.8721 +925.0,0.1879,5.9094 +930.0,0.1907,5.9468 +935.0,0.1934,5.9841 +940.0,0.1961,6.0214 +945.0,0.1988,6.0588 +950.0,0.2015,6.0961 +955.0,0.2042,6.1334 +960.0,0.2070,6.1708 +965.0,0.2097,6.2081 +970.0,0.2124,6.2455 +975.0,0.2151,6.2828 +980.0,0.2178,6.3201 +985.0,0.2205,6.3577 +990.0,0.2229,6.3962 +995.0,0.2253,6.4346 +1000.0,0.2277,6.4731 +1005.0,0.2277,6.4731 +1010.0,0.2277,6.4731 +1015.0,0.2277,6.4731 +1020.0,0.2277,6.4731 +1025.0,0.2277,6.4731 +1030.0,0.2277,6.4731 +1035.0,0.2277,6.4731 +1040.0,0.2277,6.4731 +1045.0,0.2277,6.4731 +1050.0,0.2277,6.4731 +1055.0,0.2277,6.4731 +1060.0,0.2277,6.4731 +1065.0,0.2277,6.4731 +1070.0,0.2277,6.4731 +1075.0,0.2277,6.4731 +1080.0,0.2277,6.4731 +1085.0,0.2277,6.4731 +1090.0,0.2277,6.4731 +1095.0,0.2277,6.4731 +1100.0,0.2277,6.4731 diff --git a/src/solarlab/materials/data/nk/C60.csv b/src/solarlab/materials/data/nk/C60.csv new file mode 100644 index 00000000..ffb98660 --- /dev/null +++ b/src/solarlab/materials/data/nk/C60.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,0.5878,1.7479 +305.0,0.6566,1.8930 +310.0,0.7422,2.0441 +315.0,0.8491,2.2008 +320.0,0.9832,2.3614 +325.0,1.1518,2.5217 +330.0,1.3635,2.6736 +335.0,1.6258,2.8022 +340.0,1.9409,2.8847 +345.0,2.2976,2.8916 +350.0,2.6639,2.7971 +355.0,2.9907,2.5981 +360.0,3.2335,2.3238 +365.0,3.3758,2.0223 +370.0,3.4300,1.7354 +375.0,3.4218,1.4854 +380.0,3.3753,1.2785 +385.0,3.3082,1.1118 +390.0,3.2315,0.9795 +395.0,3.1516,0.8756 +400.0,3.0720,0.7952 +405.0,2.9944,0.7346 +410.0,2.9197,0.6912 +415.0,2.8486,0.6639 +420.0,2.7820,0.6520 +425.0,2.7217,0.6561 +430.0,2.6708,0.6768 +435.0,2.6345,0.7143 +440.0,2.6209,0.7658 +445.0,2.6383,0.8232 +450.0,2.6913,0.8708 +455.0,2.7731,0.8894 +460.0,2.8639,0.8668 +465.0,2.9404,0.8064 +470.0,2.9887,0.7246 +475.0,3.0081,0.6385 +480.0,3.0055,0.5592 +485.0,2.9888,0.4911 +490.0,2.9646,0.4343 +495.0,2.9369,0.3876 +500.0,2.9081,0.3492 +505.0,2.8798,0.3174 +510.0,2.8524,0.2908 +515.0,2.8265,0.2684 +520.0,2.8021,0.2493 +525.0,2.7792,0.2329 +530.0,2.7578,0.2186 +535.0,2.7377,0.2060 +540.0,2.7189,0.1950 +545.0,2.7012,0.1851 +550.0,2.6846,0.1763 +555.0,2.6690,0.1683 +560.0,2.6543,0.1611 +565.0,2.6405,0.1546 +570.0,2.6274,0.1486 +575.0,2.6150,0.1431 +580.0,2.6032,0.1380 +585.0,2.5921,0.1333 +590.0,2.5815,0.1289 +595.0,2.5714,0.1249 +600.0,2.5618,0.1211 +605.0,2.5526,0.1175 +610.0,2.5439,0.1142 +615.0,2.5355,0.1110 +620.0,2.5275,0.1081 +625.0,2.5198,0.1053 +630.0,2.5125,0.1027 +635.0,2.5054,0.1002 +640.0,2.4987,0.0978 +645.0,2.4922,0.0956 +650.0,2.4859,0.0934 +655.0,2.4799,0.0914 +660.0,2.4741,0.0895 +665.0,2.4685,0.0876 +670.0,2.4631,0.0858 +675.0,2.4579,0.0841 +680.0,2.4529,0.0825 +685.0,2.4480,0.0809 +690.0,2.4433,0.0795 +695.0,2.4388,0.0780 +700.0,2.4344,0.0766 +705.0,2.4302,0.0753 +710.0,2.4261,0.0740 +715.0,2.4221,0.0728 +720.0,2.4182,0.0716 +725.0,2.4145,0.0705 +730.0,2.4108,0.0693 +735.0,2.4073,0.0683 +740.0,2.4039,0.0672 +745.0,2.4006,0.0662 +750.0,2.3973,0.0653 +755.0,2.3942,0.0643 +760.0,2.3911,0.0634 +765.0,2.3882,0.0625 +770.0,2.3853,0.0617 +775.0,2.3824,0.0608 +780.0,2.3797,0.0600 +785.0,2.3770,0.0592 +790.0,2.3744,0.0585 +795.0,2.3719,0.0577 +800.0,2.3694,0.0570 +805.0,2.3670,0.0563 +810.0,2.3647,0.0556 +815.0,2.3624,0.0550 +820.0,2.3601,0.0543 +825.0,2.3580,0.0537 +830.0,2.3558,0.0531 +835.0,2.3537,0.0525 +840.0,2.3517,0.0519 +845.0,2.3497,0.0513 +850.0,2.3478,0.0508 +855.0,2.3459,0.0502 +860.0,2.3440,0.0497 +865.0,2.3422,0.0492 +870.0,2.3404,0.0487 +875.0,2.3387,0.0482 +880.0,2.3370,0.0477 +885.0,2.3353,0.0472 +890.0,2.3337,0.0467 +895.0,2.3321,0.0463 +900.0,2.3306,0.0458 +905.0,2.3290,0.0454 +910.0,2.3275,0.0450 +915.0,2.3261,0.0446 +920.0,2.3246,0.0441 +925.0,2.3232,0.0437 +930.0,2.3219,0.0434 +935.0,2.3205,0.0430 +940.0,2.3192,0.0426 +945.0,2.3179,0.0422 +950.0,2.3166,0.0418 +955.0,2.3154,0.0415 +960.0,2.3141,0.0411 +965.0,2.3129,0.0408 +970.0,2.3118,0.0405 +975.0,2.3106,0.0401 +980.0,2.3095,0.0398 +985.0,2.3083,0.0395 +990.0,2.3072,0.0392 +995.0,2.3062,0.0389 +1000.0,2.3051,0.0386 +1005.0,2.3051,0.0386 +1010.0,2.3051,0.0386 +1015.0,2.3051,0.0386 +1020.0,2.3051,0.0386 +1025.0,2.3051,0.0386 +1030.0,2.3051,0.0386 +1035.0,2.3051,0.0386 +1040.0,2.3051,0.0386 +1045.0,2.3051,0.0386 +1050.0,2.3051,0.0386 +1055.0,2.3051,0.0386 +1060.0,2.3051,0.0386 +1065.0,2.3051,0.0386 +1070.0,2.3051,0.0386 +1075.0,2.3051,0.0386 +1080.0,2.3051,0.0386 +1085.0,2.3051,0.0386 +1090.0,2.3051,0.0386 +1095.0,2.3051,0.0386 +1100.0,2.3051,0.0386 diff --git a/src/solarlab/materials/data/nk/Cu.csv b/src/solarlab/materials/data/nk/Cu.csv new file mode 100644 index 00000000..e00fb9b3 --- /dev/null +++ b/src/solarlab/materials/data/nk/Cu.csv @@ -0,0 +1,50 @@ +wavelength_nm,n,k +187.9,0.94,1.337 +191.6,0.95,1.388 +195.3,0.97,1.440 +199.3,0.98,1.493 +203.3,0.99,1.550 +207.3,1.01,1.599 +211.9,1.04,1.651 +216.4,1.08,1.699 +221.4,1.13,1.737 +226.2,1.18,1.768 +231.3,1.23,1.792 +237.1,1.28,1.802 +242.6,1.34,1.799 +249.0,1.37,1.783 +255.1,1.41,1.741 +261.6,1.41,1.691 +268.9,1.45,1.668 +276.1,1.46,1.646 +284.4,1.45,1.633 +292.4,1.42,1.633 +300.9,1.40,1.679 +310.7,1.38,1.729 +320.4,1.38,1.783 +331.5,1.34,1.821 +342.5,1.36,1.864 +354.2,1.37,1.916 +367.9,1.36,1.975 +381.5,1.33,2.045 +397.4,1.32,2.116 +413.3,1.28,2.207 +430.5,1.25,2.305 +450.9,1.24,2.397 +471.4,1.25,2.483 +495.9,1.22,2.564 +520.9,1.18,2.608 +548.6,1.02,2.577 +582.1,0.70,2.704 +616.8,0.30,3.205 +659.5,0.22,3.747 +704.5,0.21,4.205 +756.0,0.24,4.665 +821.1,0.26,5.180 +892.0,0.30,5.768 +984.0,0.32,6.421 +1088.0,0.36,7.217 +1216.0,0.48,8.245 +1393.0,0.60,9.439 +1610.0,0.76,11.12 +1937.0,1.09,13.43 diff --git a/src/solarlab/materials/data/nk/FA_Cs_1p77.csv b/src/solarlab/materials/data/nk/FA_Cs_1p77.csv new file mode 100644 index 00000000..ec282be1 --- /dev/null +++ b/src/solarlab/materials/data/nk/FA_Cs_1p77.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.579404,0.986637 +305.0,1.628525,1.012061 +310.0,1.680655,1.036431 +315.0,1.736777,1.058347 +320.0,1.797177,1.075706 +325.0,1.861159,1.086178 +330.0,1.927132,1.087975 +335.0,1.992935,1.080105 +340.0,2.056183,1.062555 +345.0,2.114680,1.036350 +350.0,2.166714,1.003169 +355.0,2.211194,0.965152 +360.0,2.247709,0.924551 +365.0,2.276446,0.883465 +370.0,2.298075,0.843707 +375.0,2.313610,0.806682 +380.0,2.324262,0.773346 +385.0,2.331318,0.744239 +390.0,2.336028,0.719489 +395.0,2.339523,0.698926 +400.0,2.342786,0.682121 +405.0,2.346585,0.668415 +410.0,2.351456,0.657074 +415.0,2.357715,0.647304 +420.0,2.365463,0.638332 +425.0,2.374611,0.629467 +430.0,2.384925,0.620137 +435.0,2.396071,0.609927 +440.0,2.407662,0.598572 +445.0,2.419299,0.585959 +450.0,2.430609,0.572108 +455.0,2.441272,0.557134 +460.0,2.451031,0.541231 +465.0,2.459703,0.524632 +470.0,2.467174,0.507585 +475.0,2.473392,0.490340 +480.0,2.478362,0.473126 +485.0,2.482132,0.456147 +490.0,2.484780,0.439571 +495.0,2.486404,0.423532 +500.0,2.487118,0.408137 +505.0,2.487039,0.393453 +510.0,2.486281,0.379523 +515.0,2.484956,0.366373 +520.0,2.483166,0.354004 +525.0,2.481003,0.342410 +530.0,2.478553,0.331574 +535.0,2.475888,0.321465 +540.0,2.473072,0.312058 +545.0,2.470162,0.303323 +550.0,2.467208,0.295230 +555.0,2.464255,0.287744 +560.0,2.461341,0.280838 +565.0,2.458502,0.274482 +570.0,2.455769,0.268647 +575.0,2.453173,0.263314 +580.0,2.450745,0.258453 +585.0,2.448512,0.254040 +590.0,2.446502,0.250055 +595.0,2.444744,0.246475 +600.0,2.443267,0.243282 +605.0,2.442102,0.240454 +610.0,2.441283,0.237969 +615.0,2.440845,0.235808 +620.0,2.440829,0.233950 +625.0,2.441282,0.232377 +630.0,2.442257,0.231064 +635.0,2.443819,0.229988 +640.0,2.446048,0.229123 +645.0,2.449046,0.228440 +650.0,2.452954,0.227898 +655.0,2.457963,0.227422 +660.0,2.464272,0.226772 +665.0,2.471643,0.225135 +670.0,2.480719,0.223124 +675.0,2.492236,0.221878 +680.0,2.506205,0.216913 +685.0,2.521520,0.206774 +690.0,2.536425,0.188529 +695.0,2.548044,0.162442 +700.0,2.553779,0.130809 +705.0,2.551444,0.097825 +710.0,2.542604,0.068402 +715.0,2.529215,0.044089 +720.0,2.512762,0.027236 +725.0,2.496325,0.016198 +730.0,2.480360,0.009357 +735.0,2.465968,0.005264 +740.0,2.453140,0.003171 +745.0,2.441878,0.002110 +750.0,2.431929,0.001364 +755.0,2.423091,0.000757 +760.0,2.415069,0.000465 +765.0,2.407783,0.000281 +770.0,2.401112,0.000169 +775.0,2.394967,0.000102 +780.0,2.389271,0.000100 +785.0,2.383967,0.000100 +790.0,2.379004,0.000100 +795.0,2.374342,0.000100 +800.0,2.369948,0.000100 +805.0,2.365794,0.000100 +810.0,2.361855,0.000100 +815.0,2.358113,0.000100 +820.0,2.354550,0.000100 +825.0,2.351150,0.000100 +830.0,2.347900,0.000100 +835.0,2.344790,0.000100 +840.0,2.341808,0.000100 +845.0,2.338946,0.000100 +850.0,2.336195,0.000100 +855.0,2.333548,0.000100 +860.0,2.330999,0.000100 +865.0,2.328542,0.000100 +870.0,2.326170,0.000100 +875.0,2.323880,0.000100 +880.0,2.321667,0.000100 +885.0,2.319526,0.000100 +890.0,2.317453,0.000100 +895.0,2.315446,0.000100 +900.0,2.313501,0.000100 +905.0,2.311614,0.000100 +910.0,2.309784,0.000100 +915.0,2.308007,0.000100 +920.0,2.306280,0.000100 +925.0,2.304603,0.000100 +930.0,2.302972,0.000100 +935.0,2.301385,0.000100 +940.0,2.299841,0.000100 +945.0,2.298338,0.000100 +950.0,2.296873,0.000100 +955.0,2.295447,0.000100 +960.0,2.294057,0.000100 +965.0,2.292701,0.000100 +970.0,2.291379,0.000100 +975.0,2.290089,0.000100 +980.0,2.288830,0.000100 +985.0,2.287600,0.000100 +990.0,2.286400,0.000100 +995.0,2.285227,0.000100 +1000.0,2.284081,0.000100 +1005.0,2.282961,0.000100 +1010.0,2.281866,0.000100 +1015.0,2.280795,0.000100 +1020.0,2.279748,0.000100 +1025.0,2.278723,0.000100 +1030.0,2.277720,0.000100 +1035.0,2.276738,0.000100 +1040.0,2.275777,0.000100 +1045.0,2.274835,0.000100 +1050.0,2.273913,0.000100 +1055.0,2.273010,0.000100 +1060.0,2.272125,0.000100 +1065.0,2.271257,0.000100 +1070.0,2.270407,0.000100 +1075.0,2.269573,0.000100 +1080.0,2.268756,0.000100 +1085.0,2.267954,0.000100 +1090.0,2.267167,0.000100 +1095.0,2.266395,0.000100 +1100.0,2.265638,0.000100 diff --git a/src/solarlab/materials/data/nk/FTO.csv b/src/solarlab/materials/data/nk/FTO.csv new file mode 100644 index 00000000..93a3c4ca --- /dev/null +++ b/src/solarlab/materials/data/nk/FTO.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +3.000000e+02,2.341246e+00,6.453023e-02 +3.050000e+02,2.311728e+00,5.597950e-02 +3.100000e+02,2.286648e+00,4.928653e-02 +3.150000e+02,2.265062e+00,4.394420e-02 +3.200000e+02,2.246273e+00,3.960910e-02 +3.250000e+02,2.229758e+00,3.604169e-02 +3.300000e+02,2.215114e+00,3.307064e-02 +3.350000e+02,2.202026e+00,3.057063e-02 +3.400000e+02,2.190246e+00,2.844822e-02 +3.450000e+02,2.179576e+00,2.663254e-02 +3.500000e+02,2.169855e+00,2.506900e-02 +3.550000e+02,2.160951e+00,2.371497e-02 +3.600000e+02,2.152755e+00,2.253674e-02 +3.650000e+02,2.145176e+00,2.150739e-02 +3.700000e+02,2.138139e+00,2.060514e-02 +3.750000e+02,2.131578e+00,1.981228e-02 +3.800000e+02,2.125439e+00,1.911421e-02 +3.850000e+02,2.119675e+00,1.849887e-02 +3.900000e+02,2.114246e+00,1.795616e-02 +3.950000e+02,2.109116e+00,1.747763e-02 +4.000000e+02,2.104255e+00,1.705612e-02 +4.050000e+02,2.099636e+00,1.668554e-02 +4.100000e+02,2.095235e+00,1.636070e-02 +4.150000e+02,2.091033e+00,1.607712e-02 +4.200000e+02,2.087011e+00,1.583097e-02 +4.250000e+02,2.083152e+00,1.561890e-02 +4.300000e+02,2.079441e+00,1.543801e-02 +4.350000e+02,2.075867e+00,1.528576e-02 +4.400000e+02,2.072418e+00,1.515993e-02 +4.450000e+02,2.069082e+00,1.505858e-02 +4.500000e+02,2.065851e+00,1.497998e-02 +4.550000e+02,2.062716e+00,1.492260e-02 +4.600000e+02,2.059669e+00,1.488510e-02 +4.650000e+02,2.056704e+00,1.486628e-02 +4.700000e+02,2.053814e+00,1.486507e-02 +4.750000e+02,2.050992e+00,1.488052e-02 +4.800000e+02,2.048235e+00,1.491177e-02 +4.850000e+02,2.045536e+00,1.495806e-02 +4.900000e+02,2.042892e+00,1.501871e-02 +4.950000e+02,2.040299e+00,1.509309e-02 +5.000000e+02,2.037752e+00,1.518066e-02 +5.050000e+02,2.035248e+00,1.528091e-02 +5.100000e+02,2.032784e+00,1.539340e-02 +5.150000e+02,2.030357e+00,1.551771e-02 +5.200000e+02,2.027964e+00,1.565348e-02 +5.250000e+02,2.025603e+00,1.580038e-02 +5.300000e+02,2.023270e+00,1.595810e-02 +5.350000e+02,2.020965e+00,1.612638e-02 +5.400000e+02,2.018685e+00,1.630498e-02 +5.450000e+02,2.016428e+00,1.649365e-02 +5.500000e+02,2.014192e+00,1.669222e-02 +5.550000e+02,2.011976e+00,1.690049e-02 +5.600000e+02,2.009778e+00,1.711831e-02 +5.650000e+02,2.007596e+00,1.734552e-02 +5.700000e+02,2.005429e+00,1.758199e-02 +5.750000e+02,2.003277e+00,1.782761e-02 +5.800000e+02,2.001136e+00,1.808227e-02 +5.850000e+02,1.999008e+00,1.834587e-02 +5.900000e+02,1.996890e+00,1.861832e-02 +5.950000e+02,1.994781e+00,1.889957e-02 +6.000000e+02,1.992681e+00,1.918953e-02 +6.050000e+02,1.990589e+00,1.948814e-02 +6.100000e+02,1.988503e+00,1.979537e-02 +6.150000e+02,1.986424e+00,2.011117e-02 +6.200000e+02,1.984349e+00,2.043549e-02 +6.250000e+02,1.982279e+00,2.076832e-02 +6.300000e+02,1.980213e+00,2.110962e-02 +6.350000e+02,1.978151e+00,2.145937e-02 +6.400000e+02,1.976090e+00,2.181757e-02 +6.450000e+02,1.974032e+00,2.218419e-02 +6.500000e+02,1.971975e+00,2.255924e-02 +6.550000e+02,1.969920e+00,2.294272e-02 +6.600000e+02,1.967864e+00,2.333462e-02 +6.650000e+02,1.965809e+00,2.373495e-02 +6.700000e+02,1.963753e+00,2.414372e-02 +6.750000e+02,1.961697e+00,2.456095e-02 +6.800000e+02,1.959639e+00,2.498664e-02 +6.850000e+02,1.957580e+00,2.542082e-02 +6.900000e+02,1.955518e+00,2.586350e-02 +6.950000e+02,1.953454e+00,2.631472e-02 +7.000000e+02,1.951388e+00,2.677449e-02 +7.050000e+02,1.949319e+00,2.724284e-02 +7.100000e+02,1.947246e+00,2.771980e-02 +7.150000e+02,1.945170e+00,2.820541e-02 +7.200000e+02,1.943089e+00,2.869970e-02 +7.250000e+02,1.941005e+00,2.920270e-02 +7.300000e+02,1.938917e+00,2.971445e-02 +7.350000e+02,1.936823e+00,3.023500e-02 +7.400000e+02,1.934725e+00,3.076437e-02 +7.450000e+02,1.932622e+00,3.130262e-02 +7.500000e+02,1.930514e+00,3.184978e-02 +7.550000e+02,1.928400e+00,3.240591e-02 +7.600000e+02,1.926281e+00,3.297104e-02 +7.650000e+02,1.924155e+00,3.354524e-02 +7.700000e+02,1.922024e+00,3.412853e-02 +7.750000e+02,1.919886e+00,3.472099e-02 +7.800000e+02,1.917743e+00,3.532265e-02 +7.850000e+02,1.915592e+00,3.593358e-02 +7.900000e+02,1.913435e+00,3.655381e-02 +7.950000e+02,1.911272e+00,3.718342e-02 +8.000000e+02,1.909101e+00,3.782245e-02 +8.050000e+02,1.906923e+00,3.847097e-02 +8.100000e+02,1.904738e+00,3.912902e-02 +8.150000e+02,1.902546e+00,3.979668e-02 +8.200000e+02,1.900346e+00,4.047399e-02 +8.250000e+02,1.898139e+00,4.116103e-02 +8.300000e+02,1.895924e+00,4.185785e-02 +8.350000e+02,1.893702e+00,4.256451e-02 +8.400000e+02,1.891472e+00,4.328108e-02 +8.450000e+02,1.889233e+00,4.400763e-02 +8.500000e+02,1.886987e+00,4.474421e-02 +8.550000e+02,1.884733e+00,4.549090e-02 +8.600000e+02,1.882470e+00,4.624776e-02 +8.650000e+02,1.880199e+00,4.701486e-02 +8.700000e+02,1.877920e+00,4.779226e-02 +8.750000e+02,1.875633e+00,4.858005e-02 +8.800000e+02,1.873337e+00,4.937828e-02 +8.850000e+02,1.871032e+00,5.018703e-02 +8.900000e+02,1.868719e+00,5.100637e-02 +8.950000e+02,1.866397e+00,5.183638e-02 +9.000000e+02,1.864067e+00,5.267712e-02 +9.050000e+02,1.861728e+00,5.352867e-02 +9.100000e+02,1.859380e+00,5.439111e-02 +9.150000e+02,1.857023e+00,5.526451e-02 +9.200000e+02,1.854657e+00,5.614895e-02 +9.250000e+02,1.852282e+00,5.704450e-02 +9.300000e+02,1.849898e+00,5.795124e-02 +9.350000e+02,1.847505e+00,5.886926e-02 +9.400000e+02,1.845103e+00,5.979862e-02 +9.450000e+02,1.842692e+00,6.073941e-02 +9.500000e+02,1.840272e+00,6.169172e-02 +9.550000e+02,1.837842e+00,6.265562e-02 +9.600000e+02,1.835403e+00,6.363119e-02 +9.650000e+02,1.832955e+00,6.461852e-02 +9.700000e+02,1.830498e+00,6.561769e-02 +9.750000e+02,1.828032e+00,6.662878e-02 +9.800000e+02,1.825556e+00,6.765189e-02 +9.850000e+02,1.823070e+00,6.868710e-02 +9.900000e+02,1.820576e+00,6.973448e-02 +9.950000e+02,1.818072e+00,7.079414e-02 +1.000000e+03,1.815558e+00,7.186616e-02 +1005.0,1.815558e+00,7.186616e-02 +1010.0,1.815558e+00,7.186616e-02 +1015.0,1.815558e+00,7.186616e-02 +1020.0,1.815558e+00,7.186616e-02 +1025.0,1.815558e+00,7.186616e-02 +1030.0,1.815558e+00,7.186616e-02 +1035.0,1.815558e+00,7.186616e-02 +1040.0,1.815558e+00,7.186616e-02 +1045.0,1.815558e+00,7.186616e-02 +1050.0,1.815558e+00,7.186616e-02 +1055.0,1.815558e+00,7.186616e-02 +1060.0,1.815558e+00,7.186616e-02 +1065.0,1.815558e+00,7.186616e-02 +1070.0,1.815558e+00,7.186616e-02 +1075.0,1.815558e+00,7.186616e-02 +1080.0,1.815558e+00,7.186616e-02 +1085.0,1.815558e+00,7.186616e-02 +1090.0,1.815558e+00,7.186616e-02 +1095.0,1.815558e+00,7.186616e-02 +1100.0,1.815558e+00,7.186616e-02 diff --git a/src/solarlab/materials/data/nk/ITO.csv b/src/solarlab/materials/data/nk/ITO.csv new file mode 100644 index 00000000..c263dfe2 --- /dev/null +++ b/src/solarlab/materials/data/nk/ITO.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.7559,0.5215 +305.0,1.8804,0.5907 +310.0,2.0273,0.5939 +315.0,2.1496,0.5338 +320.0,2.2225,0.4442 +325.0,2.2520,0.3567 +330.0,2.2549,0.2845 +335.0,2.2446,0.2289 +340.0,2.2288,0.1870 +345.0,2.2116,0.1554 +350.0,2.1945,0.1312 +355.0,2.1785,0.1125 +360.0,2.1637,0.0978 +365.0,2.1501,0.0861 +370.0,2.1377,0.0766 +375.0,2.1264,0.0688 +380.0,2.1159,0.0624 +385.0,2.1063,0.0570 +390.0,2.0974,0.0525 +395.0,2.0892,0.0486 +400.0,2.0814,0.0453 +405.0,2.0741,0.0424 +410.0,2.0673,0.0399 +415.0,2.0608,0.0377 +420.0,2.0546,0.0358 +425.0,2.0488,0.0342 +430.0,2.0431,0.0327 +435.0,2.0377,0.0314 +440.0,2.0325,0.0302 +445.0,2.0274,0.0292 +450.0,2.0225,0.0283 +455.0,2.0178,0.0275 +460.0,2.0131,0.0268 +465.0,2.0086,0.0261 +470.0,2.0042,0.0256 +475.0,1.9998,0.0251 +480.0,1.9956,0.0246 +485.0,1.9914,0.0242 +490.0,1.9872,0.0239 +495.0,1.9832,0.0236 +500.0,1.9791,0.0234 +505.0,1.9751,0.0231 +510.0,1.9712,0.0230 +515.0,1.9672,0.0228 +520.0,1.9633,0.0227 +525.0,1.9595,0.0226 +530.0,1.9556,0.0226 +535.0,1.9518,0.0225 +540.0,1.9480,0.0225 +545.0,1.9441,0.0225 +550.0,1.9403,0.0226 +555.0,1.9365,0.0226 +560.0,1.9328,0.0227 +565.0,1.9290,0.0228 +570.0,1.9252,0.0229 +575.0,1.9214,0.0230 +580.0,1.9176,0.0232 +585.0,1.9138,0.0234 +590.0,1.9100,0.0235 +595.0,1.9061,0.0237 +600.0,1.9023,0.0239 +605.0,1.8985,0.0242 +610.0,1.8946,0.0244 +615.0,1.8907,0.0247 +620.0,1.8869,0.0249 +625.0,1.8830,0.0252 +630.0,1.8791,0.0255 +635.0,1.8751,0.0258 +640.0,1.8712,0.0262 +645.0,1.8672,0.0265 +650.0,1.8632,0.0269 +655.0,1.8592,0.0272 +660.0,1.8552,0.0276 +665.0,1.8511,0.0280 +670.0,1.8471,0.0284 +675.0,1.8430,0.0288 +680.0,1.8388,0.0292 +685.0,1.8347,0.0297 +690.0,1.8305,0.0301 +695.0,1.8263,0.0306 +700.0,1.8221,0.0311 +705.0,1.8179,0.0316 +710.0,1.8136,0.0321 +715.0,1.8093,0.0326 +720.0,1.8049,0.0331 +725.0,1.8006,0.0337 +730.0,1.7962,0.0342 +735.0,1.7918,0.0348 +740.0,1.7873,0.0354 +745.0,1.7828,0.0360 +750.0,1.7783,0.0366 +755.0,1.7738,0.0372 +760.0,1.7692,0.0379 +765.0,1.7646,0.0385 +770.0,1.7600,0.0392 +775.0,1.7553,0.0399 +780.0,1.7506,0.0406 +785.0,1.7458,0.0413 +790.0,1.7410,0.0420 +795.0,1.7362,0.0428 +800.0,1.7314,0.0435 +805.0,1.7265,0.0443 +810.0,1.7216,0.0451 +815.0,1.7166,0.0459 +820.0,1.7116,0.0467 +825.0,1.7066,0.0475 +830.0,1.7015,0.0484 +835.0,1.6964,0.0492 +840.0,1.6913,0.0501 +845.0,1.6861,0.0510 +850.0,1.6808,0.0519 +855.0,1.6756,0.0529 +860.0,1.6703,0.0538 +865.0,1.6649,0.0548 +870.0,1.6595,0.0558 +875.0,1.6541,0.0568 +880.0,1.6486,0.0578 +885.0,1.6431,0.0589 +890.0,1.6375,0.0599 +895.0,1.6319,0.0610 +900.0,1.6263,0.0621 +905.0,1.6206,0.0633 +910.0,1.6148,0.0644 +915.0,1.6091,0.0656 +920.0,1.6032,0.0668 +925.0,1.5973,0.0680 +930.0,1.5914,0.0692 +935.0,1.5855,0.0705 +940.0,1.5794,0.0717 +945.0,1.5734,0.0731 +950.0,1.5672,0.0744 +955.0,1.5611,0.0757 +960.0,1.5549,0.0771 +965.0,1.5486,0.0785 +970.0,1.5423,0.0799 +975.0,1.5359,0.0814 +980.0,1.5295,0.0829 +985.0,1.5230,0.0844 +990.0,1.5165,0.0859 +995.0,1.5099,0.0875 +1000.0,1.5033,0.0891 +1005.0,1.5033,0.0891 +1010.0,1.5033,0.0891 +1015.0,1.5033,0.0891 +1020.0,1.5033,0.0891 +1025.0,1.5033,0.0891 +1030.0,1.5033,0.0891 +1035.0,1.5033,0.0891 +1040.0,1.5033,0.0891 +1045.0,1.5033,0.0891 +1050.0,1.5033,0.0891 +1055.0,1.5033,0.0891 +1060.0,1.5033,0.0891 +1065.0,1.5033,0.0891 +1070.0,1.5033,0.0891 +1075.0,1.5033,0.0891 +1080.0,1.5033,0.0891 +1085.0,1.5033,0.0891 +1090.0,1.5033,0.0891 +1095.0,1.5033,0.0891 +1100.0,1.5033,0.0891 diff --git a/src/solarlab/materials/data/nk/MAPbI3.csv b/src/solarlab/materials/data/nk/MAPbI3.csv new file mode 100644 index 00000000..54c7e132 --- /dev/null +++ b/src/solarlab/materials/data/nk/MAPbI3.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,2.6214,0.5722 +305.0,2.6357,0.5740 +310.0,2.6497,0.5756 +315.0,2.6636,0.5772 +320.0,2.6771,0.5787 +325.0,2.6903,0.5800 +330.0,2.7031,0.5813 +335.0,2.7154,0.5824 +340.0,2.7271,0.5835 +345.0,2.7381,0.5845 +350.0,2.7485,0.5853 +355.0,2.7580,0.5861 +360.0,2.7668,0.5868 +365.0,2.7746,0.5873 +370.0,2.7816,0.5878 +375.0,2.7875,0.5882 +380.0,2.7924,0.5885 +385.0,2.7963,0.5887 +390.0,2.7991,0.5888 +395.0,2.8008,0.5888 +400.0,2.8014,0.5887 +405.0,2.8008,0.5885 +410.0,2.7992,0.5882 +415.0,2.7965,0.5878 +420.0,2.7927,0.5873 +425.0,2.7879,0.5867 +430.0,2.7820,0.5861 +435.0,2.7752,0.5853 +440.0,2.7674,0.5844 +445.0,2.7587,0.5835 +450.0,2.7493,0.5824 +455.0,2.7390,0.5812 +460.0,2.7280,0.5800 +465.0,2.7164,0.5786 +470.0,2.7043,0.5771 +475.0,2.6916,0.5756 +480.0,2.6785,0.5739 +485.0,2.6650,0.5721 +490.0,2.6513,0.5703 +495.0,2.6373,0.5683 +500.0,2.6232,0.5662 +505.0,2.6090,0.5640 +510.0,2.5949,0.5617 +515.0,2.5807,0.5593 +520.0,2.5667,0.5568 +525.0,2.5529,0.5541 +530.0,2.5393,0.5514 +535.0,2.5259,0.5485 +540.0,2.5129,0.5455 +545.0,2.5002,0.5424 +550.0,2.4880,0.5392 +555.0,2.4761,0.5358 +560.0,2.4647,0.5324 +565.0,2.4537,0.5288 +570.0,2.4433,0.5250 +575.0,2.4333,0.5211 +580.0,2.4239,0.5171 +585.0,2.4150,0.5130 +590.0,2.4066,0.5087 +595.0,2.3987,0.5042 +600.0,2.3913,0.4996 +605.0,2.3845,0.4949 +610.0,2.3781,0.4900 +615.0,2.3723,0.4849 +620.0,2.3670,0.4796 +625.0,2.3621,0.4742 +630.0,2.3578,0.4686 +635.0,2.3539,0.4628 +640.0,2.3504,0.4568 +645.0,2.3475,0.4506 +650.0,2.3449,0.4441 +655.0,2.3429,0.4375 +660.0,2.3413,0.4306 +665.0,2.3402,0.4235 +670.0,2.3396,0.4161 +675.0,2.3395,0.4085 +680.0,2.3400,0.4006 +685.0,2.3411,0.3923 +690.0,2.3430,0.3838 +695.0,2.3456,0.3748 +700.0,2.3492,0.3656 +705.0,2.3539,0.3559 +710.0,2.3600,0.3458 +715.0,2.3677,0.3352 +720.0,2.3773,0.3241 +725.0,2.3893,0.3124 +730.0,2.4040,0.3001 +735.0,2.4215,0.2871 +740.0,2.4414,0.2732 +745.0,2.4625,0.2584 +750.0,2.4821,0.2424 +755.0,2.4963,0.2251 +760.0,2.5015,0.2060 +765.0,2.4959,0.1847 +770.0,2.4811,0.1602 +775.0,2.4610,0.1308 +780.0,2.4393,0.0917 +785.0,2.4187,0.0289 +790.0,2.4006,0.0149 +795.0,2.3852,0.0078 +800.0,2.3724,0.0041 +805.0,2.3724,0.0035 +810.0,2.3724,0.0029 +815.0,2.3724,0.0025 +820.0,2.3724,0.0021 +825.0,2.3724,0.0018 +830.0,2.3724,0.0015 +835.0,2.3724,0.0013 +840.0,2.3724,0.0011 +845.0,2.3724,0.0009 +850.0,2.3724,0.0008 +855.0,2.3724,0.0007 +860.0,2.3724,0.0006 +865.0,2.3724,0.0005 +870.0,2.3724,0.0004 +875.0,2.3724,0.0003 +880.0,2.3724,0.0003 +885.0,2.3724,0.0002 +890.0,2.3724,0.0002 +895.0,2.3724,0.0002 +900.0,2.3724,0.0001 +905.0,2.3724,0.0001 +910.0,2.3724,0.0001 +915.0,2.3724,0.0001 +920.0,2.3724,0.0001 +925.0,2.3724,0.0001 +930.0,2.3724,0.0001 +935.0,2.3724,0.0000 +940.0,2.3724,0.0000 +945.0,2.3724,0.0000 +950.0,2.3724,0.0000 +955.0,2.3724,0.0000 +960.0,2.3724,0.0000 +965.0,2.3724,0.0000 +970.0,2.3724,0.0000 +975.0,2.3724,0.0000 +980.0,2.3724,0.0000 +985.0,2.3724,0.0000 +990.0,2.3724,0.0000 +995.0,2.3724,0.0000 +1000.0,2.3724,0.0000 +1005.0,2.3724,0.0000 +1010.0,2.3724,0.0000 +1015.0,2.3724,0.0000 +1020.0,2.3724,0.0000 +1025.0,2.3724,0.0000 +1030.0,2.3724,0.0000 +1035.0,2.3724,0.0000 +1040.0,2.3724,0.0000 +1045.0,2.3724,0.0000 +1050.0,2.3724,0.0000 +1055.0,2.3724,0.0000 +1060.0,2.3724,0.0000 +1065.0,2.3724,0.0000 +1070.0,2.3724,0.0000 +1075.0,2.3724,0.0000 +1080.0,2.3724,0.0000 +1085.0,2.3724,0.0000 +1090.0,2.3724,0.0000 +1095.0,2.3724,0.0000 +1100.0,2.3724,0.0000 diff --git a/src/solarlab/materials/data/nk/NiOx.csv b/src/solarlab/materials/data/nk/NiOx.csv new file mode 100644 index 00000000..e1e152fe --- /dev/null +++ b/src/solarlab/materials/data/nk/NiOx.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,2.5500,0.3500 +305.0,2.5550,0.3175 +310.0,2.5600,0.2850 +315.0,2.5650,0.2525 +320.0,2.5700,0.2200 +325.0,2.5675,0.2000 +330.0,2.5650,0.1800 +335.0,2.5625,0.1600 +340.0,2.5600,0.1400 +345.0,2.5550,0.1238 +350.0,2.5500,0.1075 +355.0,2.5450,0.0912 +360.0,2.5400,0.0750 +365.0,2.5325,0.0663 +370.0,2.5250,0.0575 +375.0,2.5175,0.0488 +380.0,2.5100,0.0400 +385.0,2.5025,0.0362 +390.0,2.4950,0.0325 +395.0,2.4875,0.0288 +400.0,2.4800,0.0250 +405.0,2.4740,0.0243 +410.0,2.4680,0.0236 +415.0,2.4620,0.0229 +420.0,2.4560,0.0222 +425.0,2.4500,0.0215 +430.0,2.4440,0.0208 +435.0,2.4380,0.0201 +440.0,2.4320,0.0194 +445.0,2.4260,0.0187 +450.0,2.4200,0.0180 +455.0,2.4160,0.0177 +460.0,2.4120,0.0174 +465.0,2.4080,0.0171 +470.0,2.4040,0.0168 +475.0,2.4000,0.0165 +480.0,2.3960,0.0162 +485.0,2.3920,0.0159 +490.0,2.3880,0.0156 +495.0,2.3840,0.0153 +500.0,2.3800,0.0150 +505.0,2.3770,0.0147 +510.0,2.3740,0.0144 +515.0,2.3710,0.0141 +520.0,2.3680,0.0138 +525.0,2.3650,0.0135 +530.0,2.3620,0.0132 +535.0,2.3590,0.0129 +540.0,2.3560,0.0126 +545.0,2.3530,0.0123 +550.0,2.3500,0.0120 +555.0,2.3470,0.0118 +560.0,2.3440,0.0116 +565.0,2.3410,0.0114 +570.0,2.3380,0.0112 +575.0,2.3350,0.0110 +580.0,2.3320,0.0108 +585.0,2.3290,0.0106 +590.0,2.3260,0.0104 +595.0,2.3230,0.0102 +600.0,2.3200,0.0100 +605.0,2.3170,0.0099 +610.0,2.3140,0.0098 +615.0,2.3110,0.0097 +620.0,2.3080,0.0096 +625.0,2.3050,0.0095 +630.0,2.3020,0.0094 +635.0,2.2990,0.0093 +640.0,2.2960,0.0092 +645.0,2.2930,0.0091 +650.0,2.2900,0.0090 +655.0,2.2870,0.0089 +660.0,2.2840,0.0088 +665.0,2.2810,0.0087 +670.0,2.2780,0.0086 +675.0,2.2750,0.0085 +680.0,2.2720,0.0084 +685.0,2.2690,0.0083 +690.0,2.2660,0.0082 +695.0,2.2630,0.0081 +700.0,2.2600,0.0080 +705.0,2.2580,0.0079 +710.0,2.2560,0.0078 +715.0,2.2540,0.0077 +720.0,2.2520,0.0076 +725.0,2.2500,0.0075 +730.0,2.2480,0.0074 +735.0,2.2460,0.0073 +740.0,2.2440,0.0072 +745.0,2.2420,0.0071 +750.0,2.2400,0.0070 +755.0,2.2380,0.0069 +760.0,2.2360,0.0068 +765.0,2.2340,0.0067 +770.0,2.2320,0.0066 +775.0,2.2300,0.0065 +780.0,2.2280,0.0064 +785.0,2.2260,0.0063 +790.0,2.2240,0.0062 +795.0,2.2220,0.0061 +800.0,2.2200,0.0060 +805.0,2.2190,0.0059 +810.0,2.2180,0.0058 +815.0,2.2170,0.0057 +820.0,2.2160,0.0056 +825.0,2.2150,0.0055 +830.0,2.2140,0.0054 +835.0,2.2130,0.0053 +840.0,2.2120,0.0052 +845.0,2.2110,0.0051 +850.0,2.2100,0.0050 +855.0,2.2080,0.0050 +860.0,2.2060,0.0050 +865.0,2.2040,0.0050 +870.0,2.2020,0.0050 +875.0,2.2000,0.0050 +880.0,2.1980,0.0050 +885.0,2.1960,0.0050 +890.0,2.1940,0.0050 +895.0,2.1920,0.0050 +900.0,2.1900,0.0050 +905.0,2.1890,0.0049 +910.0,2.1880,0.0048 +915.0,2.1870,0.0047 +920.0,2.1860,0.0046 +925.0,2.1850,0.0045 +930.0,2.1840,0.0044 +935.0,2.1830,0.0043 +940.0,2.1820,0.0042 +945.0,2.1810,0.0041 +950.0,2.1800,0.0040 +955.0,2.1790,0.0040 +960.0,2.1780,0.0040 +965.0,2.1770,0.0040 +970.0,2.1760,0.0040 +975.0,2.1750,0.0040 +980.0,2.1740,0.0040 +985.0,2.1730,0.0040 +990.0,2.1720,0.0040 +995.0,2.1710,0.0040 +1000.0,2.1700,0.0040 +1005.0,2.1700,0.0040 +1010.0,2.1700,0.0040 +1015.0,2.1700,0.0040 +1020.0,2.1700,0.0040 +1025.0,2.1700,0.0040 +1030.0,2.1700,0.0040 +1035.0,2.1700,0.0040 +1040.0,2.1700,0.0040 +1045.0,2.1700,0.0040 +1050.0,2.1700,0.0040 +1055.0,2.1700,0.0040 +1060.0,2.1700,0.0040 +1065.0,2.1700,0.0040 +1070.0,2.1700,0.0040 +1075.0,2.1700,0.0040 +1080.0,2.1700,0.0040 +1085.0,2.1700,0.0040 +1090.0,2.1700,0.0040 +1095.0,2.1700,0.0040 +1100.0,2.1700,0.0040 diff --git a/src/solarlab/materials/data/nk/PCBM.csv b/src/solarlab/materials/data/nk/PCBM.csv new file mode 100644 index 00000000..31f4872c --- /dev/null +++ b/src/solarlab/materials/data/nk/PCBM.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,0.5329,1.4158 +305.0,0.5797,1.5365 +310.0,0.6373,1.6604 +315.0,0.7077,1.7876 +320.0,0.7937,1.9180 +325.0,0.8990,2.0503 +330.0,1.0277,2.1821 +335.0,1.1847,2.3088 +340.0,1.3746,2.4230 +345.0,1.6002,2.5129 +350.0,1.8594,2.5631 +355.0,2.1414,2.5562 +360.0,2.4244,2.4797 +365.0,2.6796,2.3338 +370.0,2.8812,2.1351 +375.0,3.0165,1.9108 +380.0,3.0889,1.6870 +385.0,3.1108,1.4818 +390.0,3.0974,1.3034 +395.0,3.0613,1.1534 +400.0,3.0120,1.0302 +405.0,2.9558,0.9306 +410.0,2.8967,0.8516 +415.0,2.8374,0.7905 +420.0,2.7797,0.7453 +425.0,2.7250,0.7146 +430.0,2.6749,0.6977 +435.0,2.6315,0.6938 +440.0,2.5976,0.7019 +445.0,2.5770,0.7202 +450.0,2.5736,0.7446 +455.0,2.5901,0.7680 +460.0,2.6255,0.7816 +465.0,2.6734,0.7771 +470.0,2.7234,0.7510 +475.0,2.7653,0.7062 +480.0,2.7929,0.6500 +485.0,2.8053,0.5904 +490.0,2.8047,0.5330 +495.0,2.7949,0.4809 +500.0,2.7790,0.4353 +505.0,2.7597,0.3959 +510.0,2.7386,0.3621 +515.0,2.7170,0.3331 +520.0,2.6956,0.3083 +525.0,2.6747,0.2868 +530.0,2.6546,0.2681 +535.0,2.6355,0.2517 +540.0,2.6172,0.2373 +545.0,2.6000,0.2244 +550.0,2.5836,0.2130 +555.0,2.5681,0.2028 +560.0,2.5534,0.1935 +565.0,2.5395,0.1851 +570.0,2.5264,0.1774 +575.0,2.5139,0.1704 +580.0,2.5020,0.1640 +585.0,2.4907,0.1580 +590.0,2.4800,0.1526 +595.0,2.4698,0.1475 +600.0,2.4601,0.1427 +605.0,2.4508,0.1383 +610.0,2.4419,0.1342 +615.0,2.4334,0.1303 +620.0,2.4253,0.1266 +625.0,2.4175,0.1232 +630.0,2.4101,0.1199 +635.0,2.4029,0.1169 +640.0,2.3960,0.1140 +645.0,2.3894,0.1112 +650.0,2.3831,0.1086 +655.0,2.3770,0.1062 +660.0,2.3711,0.1038 +665.0,2.3655,0.1015 +670.0,2.3600,0.0994 +675.0,2.3547,0.0973 +680.0,2.3496,0.0954 +685.0,2.3447,0.0935 +690.0,2.3400,0.0917 +695.0,2.3354,0.0900 +700.0,2.3310,0.0883 +705.0,2.3267,0.0867 +710.0,2.3225,0.0852 +715.0,2.3185,0.0837 +720.0,2.3146,0.0823 +725.0,2.3108,0.0809 +730.0,2.3071,0.0796 +735.0,2.3036,0.0783 +740.0,2.3001,0.0771 +745.0,2.2967,0.0759 +750.0,2.2935,0.0747 +755.0,2.2903,0.0736 +760.0,2.2872,0.0726 +765.0,2.2842,0.0715 +770.0,2.2813,0.0705 +775.0,2.2785,0.0695 +780.0,2.2757,0.0686 +785.0,2.2730,0.0676 +790.0,2.2704,0.0667 +795.0,2.2678,0.0659 +800.0,2.2653,0.0650 +805.0,2.2629,0.0642 +810.0,2.2606,0.0634 +815.0,2.2582,0.0626 +820.0,2.2560,0.0618 +825.0,2.2538,0.0611 +830.0,2.2517,0.0604 +835.0,2.2496,0.0597 +840.0,2.2475,0.0590 +845.0,2.2455,0.0583 +850.0,2.2436,0.0577 +855.0,2.2417,0.0570 +860.0,2.2398,0.0564 +865.0,2.2380,0.0558 +870.0,2.2362,0.0552 +875.0,2.2344,0.0546 +880.0,2.2327,0.0541 +885.0,2.2311,0.0535 +890.0,2.2294,0.0530 +895.0,2.2278,0.0524 +900.0,2.2263,0.0519 +905.0,2.2247,0.0514 +910.0,2.2232,0.0509 +915.0,2.2218,0.0504 +920.0,2.2203,0.0500 +925.0,2.2189,0.0495 +930.0,2.2175,0.0490 +935.0,2.2162,0.0486 +940.0,2.2149,0.0482 +945.0,2.2136,0.0477 +950.0,2.2123,0.0473 +955.0,2.2110,0.0469 +960.0,2.2098,0.0465 +965.0,2.2086,0.0461 +970.0,2.2074,0.0457 +975.0,2.2062,0.0453 +980.0,2.2051,0.0449 +985.0,2.2040,0.0446 +990.0,2.2029,0.0442 +995.0,2.2018,0.0438 +1000.0,2.2008,0.0435 +1005.0,2.2008,0.0435 +1010.0,2.2008,0.0435 +1015.0,2.2008,0.0435 +1020.0,2.2008,0.0435 +1025.0,2.2008,0.0435 +1030.0,2.2008,0.0435 +1035.0,2.2008,0.0435 +1040.0,2.2008,0.0435 +1045.0,2.2008,0.0435 +1050.0,2.2008,0.0435 +1055.0,2.2008,0.0435 +1060.0,2.2008,0.0435 +1065.0,2.2008,0.0435 +1070.0,2.2008,0.0435 +1075.0,2.2008,0.0435 +1080.0,2.2008,0.0435 +1085.0,2.2008,0.0435 +1090.0,2.2008,0.0435 +1095.0,2.2008,0.0435 +1100.0,2.2008,0.0435 diff --git a/src/solarlab/materials/data/nk/PEDOT_PSS.csv b/src/solarlab/materials/data/nk/PEDOT_PSS.csv new file mode 100644 index 00000000..67c717b0 --- /dev/null +++ b/src/solarlab/materials/data/nk/PEDOT_PSS.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.3889,0.5305 +305.0,1.4549,0.5410 +310.0,1.5196,0.5355 +315.0,1.5782,0.5160 +320.0,1.6270,0.4862 +325.0,1.6647,0.4505 +330.0,1.6917,0.4127 +335.0,1.7095,0.3756 +340.0,1.7200,0.3409 +345.0,1.7249,0.3094 +350.0,1.7258,0.2815 +355.0,1.7238,0.2570 +360.0,1.7200,0.2357 +365.0,1.7149,0.2172 +370.0,1.7091,0.2011 +375.0,1.7028,0.1873 +380.0,1.6963,0.1753 +385.0,1.6898,0.1650 +390.0,1.6833,0.1560 +395.0,1.6769,0.1483 +400.0,1.6707,0.1416 +405.0,1.6647,0.1358 +410.0,1.6589,0.1309 +415.0,1.6533,0.1267 +420.0,1.6479,0.1231 +425.0,1.6428,0.1202 +430.0,1.6379,0.1177 +435.0,1.6332,0.1157 +440.0,1.6287,0.1142 +445.0,1.6244,0.1130 +450.0,1.6204,0.1122 +455.0,1.6165,0.1118 +460.0,1.6129,0.1117 +465.0,1.6094,0.1118 +470.0,1.6062,0.1123 +475.0,1.6032,0.1130 +480.0,1.6004,0.1140 +485.0,1.5978,0.1152 +490.0,1.5955,0.1166 +495.0,1.5933,0.1182 +500.0,1.5914,0.1199 +505.0,1.5898,0.1219 +510.0,1.5884,0.1240 +515.0,1.5872,0.1262 +520.0,1.5864,0.1286 +525.0,1.5857,0.1310 +530.0,1.5854,0.1336 +535.0,1.5853,0.1362 +540.0,1.5855,0.1388 +545.0,1.5860,0.1414 +550.0,1.5867,0.1441 +555.0,1.5878,0.1467 +560.0,1.5891,0.1492 +565.0,1.5906,0.1517 +570.0,1.5924,0.1540 +575.0,1.5944,0.1562 +580.0,1.5967,0.1583 +585.0,1.5992,0.1602 +590.0,1.6018,0.1620 +595.0,1.6046,0.1635 +600.0,1.6075,0.1649 +605.0,1.6106,0.1660 +610.0,1.6138,0.1669 +615.0,1.6170,0.1675 +620.0,1.6203,0.1680 +625.0,1.6236,0.1682 +630.0,1.6269,0.1682 +635.0,1.6302,0.1680 +640.0,1.6334,0.1675 +645.0,1.6367,0.1669 +650.0,1.6398,0.1661 +655.0,1.6428,0.1651 +660.0,1.6458,0.1639 +665.0,1.6487,0.1626 +670.0,1.6514,0.1612 +675.0,1.6540,0.1596 +680.0,1.6565,0.1579 +685.0,1.6589,0.1562 +690.0,1.6612,0.1543 +695.0,1.6633,0.1524 +700.0,1.6653,0.1504 +705.0,1.6671,0.1484 +710.0,1.6689,0.1464 +715.0,1.6705,0.1443 +720.0,1.6720,0.1422 +725.0,1.6733,0.1401 +730.0,1.6746,0.1380 +735.0,1.6758,0.1359 +740.0,1.6768,0.1338 +745.0,1.6778,0.1317 +750.0,1.6787,0.1296 +755.0,1.6794,0.1276 +760.0,1.6801,0.1255 +765.0,1.6808,0.1236 +770.0,1.6813,0.1216 +775.0,1.6818,0.1197 +780.0,1.6822,0.1178 +785.0,1.6825,0.1159 +790.0,1.6828,0.1141 +795.0,1.6831,0.1123 +800.0,1.6833,0.1105 +805.0,1.6834,0.1088 +810.0,1.6835,0.1072 +815.0,1.6836,0.1055 +820.0,1.6836,0.1039 +825.0,1.6836,0.1024 +830.0,1.6835,0.1009 +835.0,1.6835,0.0994 +840.0,1.6834,0.0979 +845.0,1.6832,0.0965 +850.0,1.6831,0.0951 +855.0,1.6829,0.0938 +860.0,1.6827,0.0925 +865.0,1.6825,0.0912 +870.0,1.6822,0.0900 +875.0,1.6820,0.0887 +880.0,1.6817,0.0876 +885.0,1.6814,0.0864 +890.0,1.6812,0.0853 +895.0,1.6809,0.0842 +900.0,1.6805,0.0831 +905.0,1.6802,0.0821 +910.0,1.6799,0.0811 +915.0,1.6795,0.0801 +920.0,1.6792,0.0791 +925.0,1.6788,0.0782 +930.0,1.6785,0.0773 +935.0,1.6781,0.0764 +940.0,1.6777,0.0755 +945.0,1.6774,0.0747 +950.0,1.6770,0.0739 +955.0,1.6766,0.0731 +960.0,1.6762,0.0723 +965.0,1.6758,0.0715 +970.0,1.6754,0.0708 +975.0,1.6751,0.0701 +980.0,1.6747,0.0693 +985.0,1.6743,0.0687 +990.0,1.6739,0.0680 +995.0,1.6735,0.0673 +1000.0,1.6731,0.0667 +1005.0,1.6731,0.0667 +1010.0,1.6731,0.0667 +1015.0,1.6731,0.0667 +1020.0,1.6731,0.0667 +1025.0,1.6731,0.0667 +1030.0,1.6731,0.0667 +1035.0,1.6731,0.0667 +1040.0,1.6731,0.0667 +1045.0,1.6731,0.0667 +1050.0,1.6731,0.0667 +1055.0,1.6731,0.0667 +1060.0,1.6731,0.0667 +1065.0,1.6731,0.0667 +1070.0,1.6731,0.0667 +1075.0,1.6731,0.0667 +1080.0,1.6731,0.0667 +1085.0,1.6731,0.0667 +1090.0,1.6731,0.0667 +1095.0,1.6731,0.0667 +1100.0,1.6731,0.0667 diff --git a/src/solarlab/materials/data/nk/SnO2.csv b/src/solarlab/materials/data/nk/SnO2.csv new file mode 100644 index 00000000..8aec369b --- /dev/null +++ b/src/solarlab/materials/data/nk/SnO2.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,2.3748,0.4773 +305.0,2.3560,0.3434 +310.0,2.3196,0.2544 +315.0,2.2818,0.1949 +320.0,2.2477,0.1541 +325.0,2.2181,0.1251 +330.0,2.1929,0.1039 +335.0,2.1712,0.0879 +340.0,2.1526,0.0756 +345.0,2.1366,0.0659 +350.0,2.1226,0.0582 +355.0,2.1103,0.0519 +360.0,2.0995,0.0466 +365.0,2.0898,0.0423 +370.0,2.0812,0.0386 +375.0,2.0734,0.0354 +380.0,2.0664,0.0327 +385.0,2.0600,0.0303 +390.0,2.0542,0.0283 +395.0,2.0489,0.0265 +400.0,2.0440,0.0248 +405.0,2.0395,0.0234 +410.0,2.0353,0.0221 +415.0,2.0314,0.0210 +420.0,2.0277,0.0200 +425.0,2.0243,0.0190 +430.0,2.0211,0.0182 +435.0,2.0182,0.0174 +440.0,2.0153,0.0167 +445.0,2.0127,0.0160 +450.0,2.0102,0.0154 +455.0,2.0078,0.0149 +460.0,2.0055,0.0144 +465.0,2.0033,0.0139 +470.0,2.0013,0.0135 +475.0,1.9993,0.0131 +480.0,1.9975,0.0127 +485.0,1.9957,0.0123 +490.0,1.9939,0.0120 +495.0,1.9923,0.0117 +500.0,1.9907,0.0114 +505.0,1.9891,0.0111 +510.0,1.9877,0.0109 +515.0,1.9862,0.0107 +520.0,1.9849,0.0104 +525.0,1.9835,0.0102 +530.0,1.9822,0.0100 +535.0,1.9810,0.0098 +540.0,1.9797,0.0097 +545.0,1.9785,0.0095 +550.0,1.9774,0.0094 +555.0,1.9763,0.0092 +560.0,1.9752,0.0091 +565.0,1.9741,0.0090 +570.0,1.9730,0.0088 +575.0,1.9720,0.0087 +580.0,1.9710,0.0086 +585.0,1.9700,0.0085 +590.0,1.9690,0.0084 +595.0,1.9681,0.0083 +600.0,1.9672,0.0082 +605.0,1.9663,0.0082 +610.0,1.9654,0.0081 +615.0,1.9645,0.0080 +620.0,1.9636,0.0080 +625.0,1.9628,0.0079 +630.0,1.9619,0.0079 +635.0,1.9611,0.0078 +640.0,1.9603,0.0078 +645.0,1.9595,0.0077 +650.0,1.9587,0.0077 +655.0,1.9579,0.0076 +660.0,1.9571,0.0076 +665.0,1.9563,0.0076 +670.0,1.9555,0.0075 +675.0,1.9548,0.0075 +680.0,1.9540,0.0075 +685.0,1.9533,0.0075 +690.0,1.9525,0.0075 +695.0,1.9518,0.0075 +700.0,1.9511,0.0074 +705.0,1.9504,0.0074 +710.0,1.9496,0.0074 +715.0,1.9489,0.0074 +720.0,1.9482,0.0074 +725.0,1.9475,0.0074 +730.0,1.9468,0.0074 +735.0,1.9461,0.0074 +740.0,1.9454,0.0075 +745.0,1.9447,0.0075 +750.0,1.9441,0.0075 +755.0,1.9434,0.0075 +760.0,1.9427,0.0075 +765.0,1.9420,0.0075 +770.0,1.9413,0.0075 +775.0,1.9407,0.0076 +780.0,1.9400,0.0076 +785.0,1.9393,0.0076 +790.0,1.9387,0.0076 +795.0,1.9380,0.0077 +800.0,1.9373,0.0077 +805.0,1.9367,0.0077 +810.0,1.9360,0.0078 +815.0,1.9353,0.0078 +820.0,1.9347,0.0078 +825.0,1.9340,0.0079 +830.0,1.9333,0.0079 +835.0,1.9327,0.0080 +840.0,1.9320,0.0080 +845.0,1.9314,0.0081 +850.0,1.9307,0.0081 +855.0,1.9301,0.0082 +860.0,1.9294,0.0082 +865.0,1.9287,0.0083 +870.0,1.9281,0.0083 +875.0,1.9274,0.0084 +880.0,1.9268,0.0084 +885.0,1.9261,0.0085 +890.0,1.9254,0.0085 +895.0,1.9248,0.0086 +900.0,1.9241,0.0087 +905.0,1.9234,0.0087 +910.0,1.9228,0.0088 +915.0,1.9221,0.0089 +920.0,1.9215,0.0089 +925.0,1.9208,0.0090 +930.0,1.9201,0.0091 +935.0,1.9195,0.0091 +940.0,1.9188,0.0092 +945.0,1.9181,0.0093 +950.0,1.9175,0.0094 +955.0,1.9168,0.0095 +960.0,1.9161,0.0095 +965.0,1.9154,0.0096 +970.0,1.9148,0.0097 +975.0,1.9141,0.0098 +980.0,1.9134,0.0099 +985.0,1.9127,0.0100 +990.0,1.9120,0.0100 +995.0,1.9114,0.0101 +1000.0,1.9107,0.0102 +1005.0,1.9107,0.0102 +1010.0,1.9107,0.0102 +1015.0,1.9107,0.0102 +1020.0,1.9107,0.0102 +1025.0,1.9107,0.0102 +1030.0,1.9107,0.0102 +1035.0,1.9107,0.0102 +1040.0,1.9107,0.0102 +1045.0,1.9107,0.0102 +1050.0,1.9107,0.0102 +1055.0,1.9107,0.0102 +1060.0,1.9107,0.0102 +1065.0,1.9107,0.0102 +1070.0,1.9107,0.0102 +1075.0,1.9107,0.0102 +1080.0,1.9107,0.0102 +1085.0,1.9107,0.0102 +1090.0,1.9107,0.0102 +1095.0,1.9107,0.0102 +1100.0,1.9107,0.0102 diff --git a/src/solarlab/materials/data/nk/SnPb_1p22.csv b/src/solarlab/materials/data/nk/SnPb_1p22.csv new file mode 100644 index 00000000..b60969ba --- /dev/null +++ b/src/solarlab/materials/data/nk/SnPb_1p22.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.404338,0.688156 +305.0,1.422081,0.705018 +310.0,1.442409,0.723941 +315.0,1.462640,0.740502 +320.0,1.483343,0.760558 +325.0,1.506673,0.779401 +330.0,1.532042,0.798553 +335.0,1.558634,0.812559 +340.0,1.585977,0.827087 +345.0,1.612189,0.835674 +350.0,1.639912,0.849177 +355.0,1.666766,0.851121 +360.0,1.689114,0.855506 +365.0,1.709898,0.861774 +370.0,1.730813,0.871152 +375.0,1.754950,0.883059 +380.0,1.779257,0.886821 +385.0,1.801731,0.895167 +390.0,1.827205,0.906046 +395.0,1.855356,0.913219 +400.0,1.884225,0.917417 +405.0,1.912650,0.918862 +410.0,1.941241,0.920813 +415.0,1.970849,0.920056 +420.0,1.999371,0.914343 +425.0,2.025630,0.907910 +430.0,2.050656,0.901751 +435.0,2.075170,0.895122 +440.0,2.098952,0.887075 +445.0,2.121697,0.878402 +450.0,2.143634,0.869520 +455.0,2.164830,0.859878 +460.0,2.185078,0.849649 +465.0,2.204370,0.839288 +470.0,2.222906,0.829040 +475.0,2.240901,0.818892 +480.0,2.258361,0.808544 +485.0,2.275246,0.798327 +490.0,2.291994,0.789058 +495.0,2.309220,0.780221 +500.0,2.326901,0.770528 +505.0,2.344642,0.760053 +510.0,2.362540,0.749615 +515.0,2.381018,0.738891 +520.0,2.400099,0.726790 +525.0,2.419368,0.712857 +530.0,2.438447,0.697259 +535.0,2.457146,0.680019 +540.0,2.475226,0.660847 +545.0,2.492276,0.639526 +550.0,2.507821,0.616170 +555.0,2.521403,0.591004 +560.0,2.532647,0.564435 +565.0,2.541323,0.537106 +570.0,2.547390,0.509567 +575.0,2.550909,0.482282 +580.0,2.552013,0.455655 +585.0,2.550884,0.430049 +590.0,2.547766,0.405811 +595.0,2.542996,0.383247 +600.0,2.536937,0.362468 +605.0,2.529910,0.343352 +610.0,2.522131,0.325781 +615.0,2.513742,0.309652 +620.0,2.504827,0.294865 +625.0,2.495391,0.281344 +630.0,2.485462,0.269243 +635.0,2.475212,0.259021 +640.0,2.465137,0.251097 +645.0,2.455883,0.245466 +650.0,2.447921,0.241089 +655.0,2.441218,0.236868 +660.0,2.435253,0.231936 +665.0,2.429449,0.226450 +670.0,2.423437,0.221064 +675.0,2.417234,0.216349 +680.0,2.411068,0.212660 +685.0,2.405215,0.209884 +690.0,2.399873,0.207853 +695.0,2.395180,0.206411 +700.0,2.391212,0.205344 +705.0,2.387984,0.204354 +710.0,2.385407,0.203160 +715.0,2.383291,0.201520 +720.0,2.381417,0.199364 +725.0,2.379586,0.196857 +730.0,2.377690,0.194168 +735.0,2.375688,0.191444 +740.0,2.373585,0.188810 +745.0,2.371411,0.186341 +750.0,2.369210,0.184099 +755.0,2.367044,0.182142 +760.0,2.364997,0.180515 +765.0,2.363146,0.179176 +770.0,2.361553,0.178026 +775.0,2.360241,0.176971 +780.0,2.359205,0.175925 +785.0,2.358415,0.174814 +790.0,2.357836,0.173598 +795.0,2.357427,0.172249 +800.0,2.357143,0.170744 +805.0,2.356928,0.169061 +810.0,2.356721,0.167189 +815.0,2.356471,0.165182 +820.0,2.356142,0.163131 +825.0,2.355731,0.161119 +830.0,2.355265,0.159221 +835.0,2.354800,0.157504 +840.0,2.354394,0.155991 +845.0,2.354105,0.154620 +850.0,2.353966,0.153325 +855.0,2.353981,0.152048 +860.0,2.354137,0.150733 +865.0,2.354396,0.149334 +870.0,2.354725,0.147856 +875.0,2.355101,0.146369 +880.0,2.355525,0.144940 +885.0,2.356037,0.143628 +890.0,2.356697,0.142489 +895.0,2.357616,0.141569 +900.0,2.358892,0.140835 +905.0,2.360605,0.140058 +910.0,2.362766,0.138999 +915.0,2.365299,0.137439 +920.0,2.368048,0.135179 +925.0,2.370734,0.132037 +930.0,2.372565,0.127857 +935.0,2.375541,0.124927 +940.0,2.378071,0.122087 +945.0,2.381058,0.118664 +950.0,2.384266,0.114301 +955.0,2.387473,0.108689 +960.0,2.390312,0.102059 +965.0,2.392618,0.094330 +970.0,2.394100,0.085838 +975.0,2.394614,0.076518 +980.0,2.393975,0.066938 +985.0,2.392205,0.057257 +990.0,2.389287,0.048138 +995.0,2.385466,0.039753 +1000.0,2.380863,0.032226 +1005.0,2.375661,0.025478 +1010.0,2.370056,0.019824 +1015.0,2.364257,0.015158 +1020.0,2.358404,0.011472 +1025.0,2.352648,0.008525 +1030.0,2.347084,0.006265 +1035.0,2.341736,0.004512 +1040.0,2.336688,0.003202 +1045.0,2.331935,0.002352 +1050.0,2.327464,0.001702 +1055.0,2.323314,0.001211 +1060.0,2.319418,0.000887 +1065.0,2.315767,0.000654 +1070.0,2.312342,0.000482 +1075.0,2.309116,0.000355 +1080.0,2.306068,0.000262 +1085.0,2.303181,0.000193 +1090.0,2.300437,0.000142 +1095.0,2.297825,0.000105 +1100.0,2.295331,0.000100 diff --git a/src/solarlab/materials/data/nk/TiO2.csv b/src/solarlab/materials/data/nk/TiO2.csv new file mode 100644 index 00000000..c500b699 --- /dev/null +++ b/src/solarlab/materials/data/nk/TiO2.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,2.7000,1.1532 +305.0,2.6992,1.1290 +310.0,2.6970,1.1032 +315.0,2.6933,1.0756 +320.0,2.6882,1.0461 +325.0,2.6818,1.0144 +330.0,2.6742,0.9804 +335.0,2.6654,0.9439 +340.0,2.6556,0.9045 +345.0,2.6450,0.8618 +350.0,2.6336,0.8154 +355.0,2.6217,0.7645 +360.0,2.6093,0.7081 +365.0,2.5966,0.6449 +370.0,2.5838,0.5726 +375.0,2.5709,0.4870 +380.0,2.5582,0.3793 +385.0,2.5457,0.2177 +390.0,2.5335,0.0000 +395.0,2.5217,0.0000 +400.0,2.5104,0.0000 +405.0,2.4996,0.0000 +410.0,2.4895,0.0000 +415.0,2.4800,0.0000 +420.0,2.4711,0.0000 +425.0,2.4629,0.0000 +430.0,2.4554,0.0000 +435.0,2.4485,0.0000 +440.0,2.4423,0.0000 +445.0,2.4367,0.0000 +450.0,2.4316,0.0000 +455.0,2.4272,0.0000 +460.0,2.4232,0.0000 +465.0,2.4197,0.0000 +470.0,2.4167,0.0000 +475.0,2.4140,0.0000 +480.0,2.4118,0.0000 +485.0,2.4098,0.0000 +490.0,2.4081,0.0000 +495.0,2.4067,0.0000 +500.0,2.4055,0.0000 +505.0,2.4045,0.0000 +510.0,2.4037,0.0000 +515.0,2.4030,0.0000 +520.0,2.4024,0.0000 +525.0,2.4019,0.0000 +530.0,2.4015,0.0000 +535.0,2.4012,0.0000 +540.0,2.4009,0.0000 +545.0,2.4007,0.0000 +550.0,2.4006,0.0000 +555.0,2.4005,0.0000 +560.0,2.4003,0.0000 +565.0,2.4003,0.0000 +570.0,2.4002,0.0000 +575.0,2.4002,0.0000 +580.0,2.4001,0.0000 +585.0,2.4001,0.0000 +590.0,2.4001,0.0000 +595.0,2.4001,0.0000 +600.0,2.4000,0.0000 +605.0,2.4000,0.0000 +610.0,2.4000,0.0000 +615.0,2.4000,0.0000 +620.0,2.4000,0.0000 +625.0,2.4000,0.0000 +630.0,2.4000,0.0001 +635.0,2.4000,0.0001 +640.0,2.4000,0.0001 +645.0,2.4000,0.0001 +650.0,2.4000,0.0001 +655.0,2.4000,0.0001 +660.0,2.4000,0.0001 +665.0,2.4000,0.0001 +670.0,2.4000,0.0001 +675.0,2.4000,0.0001 +680.0,2.4000,0.0001 +685.0,2.4000,0.0001 +690.0,2.4000,0.0001 +695.0,2.4000,0.0001 +700.0,2.4000,0.0001 +705.0,2.4000,0.0001 +710.0,2.4000,0.0001 +715.0,2.4000,0.0001 +720.0,2.4000,0.0001 +725.0,2.4000,0.0001 +730.0,2.4000,0.0001 +735.0,2.4000,0.0001 +740.0,2.4000,0.0001 +745.0,2.4000,0.0001 +750.0,2.4000,0.0001 +755.0,2.4000,0.0001 +760.0,2.4000,0.0001 +765.0,2.4000,0.0001 +770.0,2.4000,0.0001 +775.0,2.4000,0.0001 +780.0,2.4000,0.0001 +785.0,2.4000,0.0001 +790.0,2.4000,0.0001 +795.0,2.4000,0.0001 +800.0,2.4000,0.0001 +805.0,2.4000,0.0001 +810.0,2.4000,0.0001 +815.0,2.4000,0.0001 +820.0,2.4000,0.0001 +825.0,2.4000,0.0001 +830.0,2.4000,0.0001 +835.0,2.4000,0.0001 +840.0,2.4000,0.0001 +845.0,2.4000,0.0001 +850.0,2.4000,0.0001 +855.0,2.4000,0.0001 +860.0,2.4000,0.0001 +865.0,2.4000,0.0001 +870.0,2.4000,0.0001 +875.0,2.4000,0.0001 +880.0,2.4000,0.0001 +885.0,2.4000,0.0001 +890.0,2.4000,0.0001 +895.0,2.4000,0.0001 +900.0,2.4000,0.0001 +905.0,2.4000,0.0001 +910.0,2.4000,0.0001 +915.0,2.4000,0.0001 +920.0,2.4000,0.0001 +925.0,2.4000,0.0001 +930.0,2.4000,0.0001 +935.0,2.4000,0.0001 +940.0,2.4000,0.0001 +945.0,2.4000,0.0001 +950.0,2.4000,0.0001 +955.0,2.4000,0.0001 +960.0,2.4000,0.0001 +965.0,2.4000,0.0001 +970.0,2.4000,0.0001 +975.0,2.4000,0.0001 +980.0,2.4000,0.0001 +985.0,2.4000,0.0001 +990.0,2.4000,0.0001 +995.0,2.4000,0.0001 +1000.0,2.4000,0.0001 +1005.0,2.4000,0.0001 +1010.0,2.4000,0.0001 +1015.0,2.4000,0.0001 +1020.0,2.4000,0.0001 +1025.0,2.4000,0.0001 +1030.0,2.4000,0.0001 +1035.0,2.4000,0.0001 +1040.0,2.4000,0.0001 +1045.0,2.4000,0.0001 +1050.0,2.4000,0.0001 +1055.0,2.4000,0.0001 +1060.0,2.4000,0.0001 +1065.0,2.4000,0.0001 +1070.0,2.4000,0.0001 +1075.0,2.4000,0.0001 +1080.0,2.4000,0.0001 +1085.0,2.4000,0.0001 +1090.0,2.4000,0.0001 +1095.0,2.4000,0.0001 +1100.0,2.4000,0.0001 diff --git a/src/solarlab/materials/data/nk/glass.csv b/src/solarlab/materials/data/nk/glass.csv new file mode 100644 index 00000000..4f228e2f --- /dev/null +++ b/src/solarlab/materials/data/nk/glass.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.5528,0.0000 +305.0,1.5510,0.0000 +310.0,1.5494,0.0000 +315.0,1.5479,0.0000 +320.0,1.5464,0.0000 +325.0,1.5451,0.0000 +330.0,1.5438,0.0000 +335.0,1.5425,0.0000 +340.0,1.5413,0.0000 +345.0,1.5402,0.0000 +350.0,1.5392,0.0000 +355.0,1.5382,0.0000 +360.0,1.5372,0.0000 +365.0,1.5363,0.0000 +370.0,1.5354,0.0000 +375.0,1.5345,0.0000 +380.0,1.5337,0.0000 +385.0,1.5330,0.0000 +390.0,1.5322,0.0000 +395.0,1.5315,0.0000 +400.0,1.5308,0.0000 +405.0,1.5302,0.0000 +410.0,1.5296,0.0000 +415.0,1.5290,0.0000 +420.0,1.5284,0.0000 +425.0,1.5278,0.0000 +430.0,1.5273,0.0000 +435.0,1.5268,0.0000 +440.0,1.5263,0.0000 +445.0,1.5258,0.0000 +450.0,1.5253,0.0000 +455.0,1.5249,0.0000 +460.0,1.5244,0.0000 +465.0,1.5240,0.0000 +470.0,1.5236,0.0000 +475.0,1.5232,0.0000 +480.0,1.5228,0.0000 +485.0,1.5225,0.0000 +490.0,1.5221,0.0000 +495.0,1.5218,0.0000 +500.0,1.5214,0.0000 +505.0,1.5211,0.0000 +510.0,1.5208,0.0000 +515.0,1.5205,0.0000 +520.0,1.5202,0.0000 +525.0,1.5199,0.0000 +530.0,1.5196,0.0000 +535.0,1.5193,0.0000 +540.0,1.5190,0.0000 +545.0,1.5188,0.0000 +550.0,1.5185,0.0000 +555.0,1.5183,0.0000 +560.0,1.5180,0.0000 +565.0,1.5178,0.0000 +570.0,1.5176,0.0000 +575.0,1.5173,0.0000 +580.0,1.5171,0.0000 +585.0,1.5169,0.0000 +590.0,1.5167,0.0000 +595.0,1.5165,0.0000 +600.0,1.5163,0.0000 +605.0,1.5161,0.0000 +610.0,1.5159,0.0000 +615.0,1.5157,0.0000 +620.0,1.5155,0.0000 +625.0,1.5154,0.0000 +630.0,1.5152,0.0000 +635.0,1.5150,0.0000 +640.0,1.5148,0.0000 +645.0,1.5147,0.0000 +650.0,1.5145,0.0000 +655.0,1.5144,0.0000 +660.0,1.5142,0.0000 +665.0,1.5141,0.0000 +670.0,1.5139,0.0000 +675.0,1.5138,0.0000 +680.0,1.5136,0.0000 +685.0,1.5135,0.0000 +690.0,1.5133,0.0000 +695.0,1.5132,0.0000 +700.0,1.5131,0.0000 +705.0,1.5129,0.0000 +710.0,1.5128,0.0000 +715.0,1.5127,0.0000 +720.0,1.5125,0.0000 +725.0,1.5124,0.0000 +730.0,1.5123,0.0000 +735.0,1.5122,0.0000 +740.0,1.5121,0.0000 +745.0,1.5120,0.0000 +750.0,1.5118,0.0000 +755.0,1.5117,0.0000 +760.0,1.5116,0.0000 +765.0,1.5115,0.0000 +770.0,1.5114,0.0000 +775.0,1.5113,0.0000 +780.0,1.5112,0.0000 +785.0,1.5111,0.0000 +790.0,1.5110,0.0000 +795.0,1.5109,0.0000 +800.0,1.5108,0.0000 +805.0,1.5107,0.0000 +810.0,1.5106,0.0000 +815.0,1.5105,0.0000 +820.0,1.5104,0.0000 +825.0,1.5103,0.0000 +830.0,1.5102,0.0000 +835.0,1.5101,0.0000 +840.0,1.5100,0.0000 +845.0,1.5099,0.0000 +850.0,1.5098,0.0000 +855.0,1.5098,0.0000 +860.0,1.5097,0.0000 +865.0,1.5096,0.0000 +870.0,1.5095,0.0000 +875.0,1.5094,0.0000 +880.0,1.5093,0.0000 +885.0,1.5092,0.0000 +890.0,1.5092,0.0000 +895.0,1.5091,0.0000 +900.0,1.5090,0.0000 +905.0,1.5089,0.0000 +910.0,1.5088,0.0000 +915.0,1.5088,0.0000 +920.0,1.5087,0.0000 +925.0,1.5086,0.0000 +930.0,1.5085,0.0000 +935.0,1.5084,0.0000 +940.0,1.5084,0.0000 +945.0,1.5083,0.0000 +950.0,1.5082,0.0000 +955.0,1.5081,0.0000 +960.0,1.5081,0.0000 +965.0,1.5080,0.0000 +970.0,1.5079,0.0000 +975.0,1.5079,0.0000 +980.0,1.5078,0.0000 +985.0,1.5077,0.0000 +990.0,1.5076,0.0000 +995.0,1.5076,0.0000 +1000.0,1.5075,0.0000 +1005.0,1.5075,0.0000 +1010.0,1.5075,0.0000 +1015.0,1.5075,0.0000 +1020.0,1.5075,0.0000 +1025.0,1.5075,0.0000 +1030.0,1.5075,0.0000 +1035.0,1.5075,0.0000 +1040.0,1.5075,0.0000 +1045.0,1.5075,0.0000 +1050.0,1.5075,0.0000 +1055.0,1.5075,0.0000 +1060.0,1.5075,0.0000 +1065.0,1.5075,0.0000 +1070.0,1.5075,0.0000 +1075.0,1.5075,0.0000 +1080.0,1.5075,0.0000 +1085.0,1.5075,0.0000 +1090.0,1.5075,0.0000 +1095.0,1.5075,0.0000 +1100.0,1.5075,0.0000 diff --git a/src/solarlab/materials/data/nk/manifest.yaml b/src/solarlab/materials/data/nk/manifest.yaml new file mode 100644 index 00000000..a24571e7 --- /dev/null +++ b/src/solarlab/materials/data/nk/manifest.yaml @@ -0,0 +1,238 @@ +Ag: + source: "refractiveindex.info / Johnson & Christy 1972" + reference: "P. B. Johnson and R. W. Christy, Phys. Rev. B 6, 4370 (1972)" + wavelength_range_nm: [300, 1000] + notes: > + Real tabulated n,k for silver from Johnson & Christy 1972 (the community + gold-standard noble-metal optical-constants dataset). Source file is the + refractiveindex.info database YAML + (database/data/main/Ag/nk/Johnson.yml), public-domain CC0. The native + table spans 187.9-1937 nm at 49 wavelengths; we linearly interpolate + onto the uniform 5 nm grid from 300-1000 nm (141 rows) and round to + 4 decimals. Key values: + n(550 nm)=0.0596, k(550 nm)=3.5974; + n(1000 nm)=0.0400, k(1000 nm)=7.1155. + +Au: + source: "refractiveindex.info / Johnson & Christy 1972" + reference: "P. B. Johnson and R. W. Christy, Phys. Rev. B 6, 4370 (1972)" + wavelength_range_nm: [300, 1000] + notes: > + Real tabulated n,k for gold from Johnson & Christy 1972 (the community + gold-standard noble-metal optical-constants dataset). Source file is the + refractiveindex.info database YAML + (database/data/main/Au/nk/Johnson.yml), public-domain CC0. The native + table spans 187.9-1937 nm at 49 wavelengths; we linearly interpolate + onto the uniform 5 nm grid from 300-1000 nm (141 rows) and round to + 4 decimals. Characteristic ~500 nm interband absorption edge is present + in the primary data. Key values: + n(550 nm)=0.4241, k(550 nm)=2.4721; + n(1000 nm)=0.2277, k(1000 nm)=6.4731. + +C60: + source: synthetic-Lorentz + reference: "Two-oscillator Lorentz model; parameters inspired by Ren et al. 2015 thin-film fullerene dispersions" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic two-Lorentz oscillator model producing typical C60 thin-film + n,k with absorption edge near 450 nm and n~2.0-2.7 in visible. + eps(E) = eps_inf + sum_j f_j*E0_j^2/(E0_j^2 - E^2 - i*E*gamma_j). + Parameters: eps_inf=2.3, + oscillator 1 (UV): f=2.2, E0=3.5 eV (354 nm), gamma=0.5 eV; + oscillator 2 (visible tail): f=0.4, E0=2.7 eV (459 nm), gamma=0.3 eV. + k(550 nm)~0.18, k(1000 nm)~0.04. Primary-source data not retrieved + in-loop; parametric fit is the approved fallback. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +Cu: + source: "refractiveindex.info / Johnson & Christy 1972" + reference: "P. B. Johnson and R. W. Christy, Phys. Rev. B 6, 4370 (1972)" + wavelength_range_nm: [187.9, 1937.0] + notes: > + Native room-temperature tabulated n,k for copper from the public-domain + refractiveindex.info Johnson dataset + (database/data/main/Cu/nk/Johnson.yml). Values are retained on the source + wavelength grid rather than resampled; load_nk performs the runtime linear + interpolation. The full 187.9-1937 nm source table is frozen so the + complete 300-1100 nm Lin tandem protocol is interpolated, never clamped, + without substituting Ag or Au for the reported 100 nm Cu contact. + +FTO: + source: synthetic-Drude-Lorentz + reference: "Drude-Lorentz parametric model; parameters calibrated to FTO films reported in Filipic et al. 2015, Opt. Express 23, A263 and Bhachu et al. 2016" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic data generated via single Drude + single Lorentz oscillator model. + eps(omega) = eps_inf - omega_p^2/(omega^2 + i*gamma_D*omega) + + f_L*omega_0^2/(omega_0^2 - omega^2 - i*gamma_L*omega). + Parameters: eps_inf=3.60, omega_p=1.9e15 rad/s, gamma_D=5.0e14 rad/s, + Lorentz resonance omega_0=7.5e15 rad/s (~251 nm, above SnO2 direct bandgap + ~344 nm), gamma_L=4e14 rad/s, f_L=0.6. Drude parameters retuned (2025-04) + to reproduce realistic free-carrier (near-IR) absorption: k(1000 nm)~0.072, + consistent with literature FTO at typical PSC doping levels (k~0.05-0.10 at + 1000 nm). Produces n=1.82-2.34, k=0.017-0.065 across 300-1000 nm. + Key values: n(550 nm)=2.014, k(550 nm)=0.017, k(300 nm)=0.065, + k(800 nm)=0.038, k(1000 nm)=0.072. The Filipic 2015 Opt. Express file is + not present in refractiveindex.info database; this synthetic model is the + approved fallback per the task specification. + 5 nm uniform grid, 300-1000 nm, 141 data rows. + +ITO: + source: synthetic-Drude-Lorentz + reference: "Drude + Lorentz model; parameters inspired by König et al. 2014, Opt. Mater. Express 4, 689 (Sn:In2O3 sputtered films)" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic Drude + single UV Lorentz oscillator. + eps(E) = eps_inf - (hbar*wp)^2/(E*(E + i*hbar*gamma)) + + f*E0^2/(E0^2 - E^2 - i*E*gammaL). + Parameters: eps_inf=3.95, hbar*wp=1.78 eV, hbar*gamma=0.155 eV, + f=0.3, E0=4.0 eV, gammaL=0.5 eV. Reproduces ITO-like dispersion: + n(550 nm)~1.94, k(550 nm)~0.02; free-carrier NIR tail + n(1000 nm)~1.50, k(1000 nm)~0.09. Primary-source data from + refractiveindex.info was not retrieved in-loop; Drude-Lorentz fit + is the approved fallback. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +MAPbI3: + source: refractiveindex.info + reference: "Phillips et al. 2018" + wavelength_range_nm: [300, 1000] + notes: > + MAPbI3 perovskite thin film; shipped baseline. Native 300-800 nm data + (refractiveindex.info / Phillips 2018) resampled onto uniform 5 nm grid, + then extended 805-1000 nm with constant n=n(800 nm) and exponentially + decaying k = k(800 nm)*exp(-(lam-800)/30 nm) reflecting the sharp fall + in absorption below the ~1.6 eV bandgap. k rounded to 4 decimals -> + effectively zero beyond ~820 nm. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +NiOx: + file: NiOx.csv + source: repository-parameterized-fit + reference: >- + Repository history commit b3235885ca67befb7540fb19f01b7102d0a12378; + no raw external ellipsometry dataset or fit script is stored in this repository + wavelength_range_nm: [300, 1100] + notes: >- + The repository history identifies this CSV as a parameterized fit that + replaced a constant n=2.2, k=0 fallback. It records n(550 nm)=2.35, a + modeled absorption edge near 3.5 eV, and weak visible absorption, but does + not preserve raw measurements or a reproducible fitting pipeline. Commit + 538ddab99ea93a0ceee539bf230e89bf0d2723c9 later extended the 1000 nm edge + to 1100 nm by holding n=2.17 and k=0.004 constant. Treat these values as a + repository model input, not as an externally traceable measured dataset. + +PCBM: + source: synthetic-Lorentz + reference: "Two-oscillator Lorentz model; parameters inspired by Ren et al. 2015" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic two-Lorentz oscillator model for PCBM. Slightly red-shifted + relative to C60 with marginally lower n. + eps(E) = eps_inf + sum_j f_j*E0_j^2/(E0_j^2 - E^2 - i*E*gamma_j). + Parameters: eps_inf=2.1, + oscillator 1 (UV): f=2.0, E0=3.4 eV, gamma=0.55 eV; + oscillator 2 (visible tail): f=0.35, E0=2.65 eV (468 nm), gamma=0.35 eV. + k(550 nm)~0.21, k(1000 nm)~0.04. Primary-source data not retrieved + in-loop; parametric fit is the approved fallback. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +PEDOT_PSS: + source: synthetic-Drude-Lorentz + reference: "Drude + two-Lorentz model; parameters inspired by Lee et al. 2018 (conductive PEDOT:PSS formulation)" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic conductive-PEDOT:PSS model with broad mid-visible absorption + and weak free-carrier Drude tail. + eps(E) = eps_inf - (hbar*wp)^2/(E*(E + i*hbar*gamma)) + + sum_j f_j*E0_j^2/(E0_j^2 - E^2 - i*E*gamma_j). + Parameters: eps_inf=2.1, hbar*wp=0.3 eV, hbar*gamma=0.3 eV, + oscillator 1 (visible): f=0.25, E0=2.0 eV (620 nm), gamma=1.1 eV; + oscillator 2 (UV): f=0.4, E0=4.0 eV, gamma=1.0 eV. + n(550 nm)~1.59, k(550 nm)~0.14; n(1000 nm)~1.67, k(1000 nm)~0.07. + Primary-source data not retrieved in-loop; parametric fit is the + approved fallback. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +SnO2: + source: synthetic-Drude-Lorentz + reference: "Drude + UV Lorentz model; SnO2 bandgap parameters inspired by Filipic et al. 2015, Opt. Express 23, A263" + wavelength_range_nm: [300, 1000] + notes: > + Synthetic weak-Drude + single UV Lorentz oscillator. Wide-gap TCO with + near-transparent visible response and weak free-carrier NIR tail. + eps(E) = eps_inf - (hbar*wp)^2/(E*(E + i*hbar*gamma)) + + f*E0^2/(E0^2 - E^2 - i*E*gammaL). + Parameters: eps_inf=3.5, hbar*wp=0.6 eV, hbar*gamma=0.15 eV, + f=0.35, E0=4.3 eV (~288 nm), gammaL=0.4 eV. + n(550 nm)~1.98, k(550 nm)~0.009; n(1000 nm)~1.91, k(1000 nm)~0.010. + The Filipic 2015 Opt. Express file is not present in refractiveindex.info + (confirmed during Task 1); parametric fit is the approved fallback. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +TiO2: + source: refractiveindex.info + reference: "Siefke et al. 2016" + wavelength_range_nm: [300, 1000] + notes: > + Anatase TiO2 ETL. Native 300-800 nm data resampled onto uniform 5 nm + grid, then extended 805-1000 nm by holding n and k constant at the + 800 nm edge value (TiO2 is transparent far below the ~3.2 eV bandgap; + k remains near zero). + 5 nm uniform grid, 300-1000 nm, 141 rows. + +glass: + source: analytical-Sellmeier + reference: "Schott BK7 Sellmeier equation (Schott optical glass datasheet)" + wavelength_range_nm: [300, 1000] + notes: > + Deterministic Sellmeier dispersion for Schott BK7: + n^2 = 1 + B1*L^2/(L^2-C1) + B2*L^2/(L^2-C2) + B3*L^2/(L^2-C3), + with L in micrometres and + B1=1.03961212, B2=0.231792344, B3=1.01046945, + C1=6.00069867e-3 um^2, C2=2.00179144e-2 um^2, C3=1.03560653e2 um^2. + k=0 everywhere (BK7 is transparent 300-1000 nm; residual absorption is + well below 4-decimal precision). + n(550 nm)~1.518, n(1000 nm)~1.508. + 5 nm uniform grid, 300-1000 nm, 141 rows. + +spiro_OMeTAD: + source: refractiveindex.info + reference: "Filipic et al. 2015, Opt. Express 23, A263" + wavelength_range_nm: [300, 1000] + notes: > + Spiro-OMeTAD HTL. Native 300-800 nm data resampled onto uniform 5 nm + grid, then extended 805-1000 nm by holding n and k constant at the + 800 nm edge value (spiro-OMeTAD is transparent in the NIR; k remains + near zero). + 5 nm uniform grid, 300-1000 nm, 141 rows. + +FA_Cs_1p77: + file: FA_Cs_1p77.csv + source: "TODO(benchmark): placeholder stub — Lin 2019 SI / Saliba 2016; rigid bandgap-shift of MAPbI3 data to 1.77 eV edge" + eg_eV: 1.77 + wavelength_range_nm: [300, 1000] + notes: > + Stub generated by rigidly shifting the MAPbI3 (Phillips 2018) wavelength + grid by delta = (1240/1.77 - 1240/1.55) nm = -99.4 nm so that the + absorption edge lands near 701 nm (~1.77 eV). n values are copied + from MAPbI3 without modification. This is a physics-adjacent placeholder; + real FA-Cs optical constants must be loaded from Lin 2019 SI / Saliba + 2016 data before running the tandem benchmark (Task 8). + 5 nm uniform grid, 300-1000 nm, 141 rows. + +SnPb_1p22: + file: SnPb_1p22.csv + source: "TODO(benchmark): placeholder stub — Lin 2019 SI / Hao 2014; rigid bandgap-shift of MAPbI3 data to 1.22 eV edge" + eg_eV: 1.22 + wavelength_range_nm: [300, 1000] + notes: > + Stub generated by rigidly shifting the MAPbI3 (Phillips 2018) wavelength + grid by delta = (1240/1.22 - 1240/1.55) nm = +216.4 nm so that the + absorption edge lands near 1016 nm (~1.22 eV). Because the target edge + falls beyond the 1000 nm grid ceiling, the NIR end (900-1000 nm) retains + significant k from the MAPbI3 tail — physically plausible for Sn-Pb which + absorbs strongly across that range. n values are copied from MAPbI3. + Real Sn-Pb optical constants must be loaded from Lin 2019 SI / Hao 2014 + data before the tandem benchmark (Task 8). + 5 nm uniform grid, 300-1000 nm, 141 rows. diff --git a/src/solarlab/materials/data/nk/spiro_OMeTAD.csv b/src/solarlab/materials/data/nk/spiro_OMeTAD.csv new file mode 100644 index 00000000..774c1202 --- /dev/null +++ b/src/solarlab/materials/data/nk/spiro_OMeTAD.csv @@ -0,0 +1,162 @@ +wavelength_nm,n,k +300.0,1.6177,0.5083 +305.0,1.6229,0.5011 +310.0,1.6279,0.4934 +315.0,1.6326,0.4852 +320.0,1.6369,0.4764 +325.0,1.6407,0.4671 +330.0,1.6439,0.4571 +335.0,1.6465,0.4466 +340.0,1.6484,0.4353 +345.0,1.6496,0.4233 +350.0,1.6500,0.4104 +355.0,1.6496,0.3967 +360.0,1.6484,0.3820 +365.0,1.6465,0.3661 +370.0,1.6439,0.3490 +375.0,1.6407,0.3305 +380.0,1.6369,0.3102 +385.0,1.6326,0.2879 +390.0,1.6279,0.2629 +395.0,1.6229,0.2345 +400.0,1.6177,0.2012 +405.0,1.6123,0.1599 +410.0,1.6070,0.1008 +415.0,1.6017,0.0067 +420.0,1.5965,0.0000 +425.0,1.5915,0.0000 +430.0,1.5868,0.0000 +435.0,1.5823,0.0000 +440.0,1.5782,0.0000 +445.0,1.5744,0.0000 +450.0,1.5710,0.0000 +455.0,1.5679,0.0000 +460.0,1.5651,0.0000 +465.0,1.5627,0.0000 +470.0,1.5605,0.0000 +475.0,1.5587,0.0000 +480.0,1.5571,0.0000 +485.0,1.5558,0.0000 +490.0,1.5547,0.0000 +495.0,1.5537,0.0000 +500.0,1.5530,0.0000 +505.0,1.5523,0.0000 +510.0,1.5518,0.0000 +515.0,1.5514,0.0000 +520.0,1.5511,0.0000 +525.0,1.5508,0.0000 +530.0,1.5506,0.0000 +535.0,1.5505,0.0000 +540.0,1.5504,0.0000 +545.0,1.5503,0.0000 +550.0,1.5502,0.0000 +555.0,1.5501,0.0000 +560.0,1.5501,0.0000 +565.0,1.5501,0.0000 +570.0,1.5501,0.0000 +575.0,1.5500,0.0000 +580.0,1.5500,0.0000 +585.0,1.5500,0.0000 +590.0,1.5500,0.0000 +595.0,1.5500,0.0000 +600.0,1.5500,0.0000 +605.0,1.5500,0.0000 +610.0,1.5500,0.0000 +615.0,1.5500,0.0000 +620.0,1.5500,0.0000 +625.0,1.5500,0.0000 +630.0,1.5500,0.0000 +635.0,1.5500,0.0000 +640.0,1.5500,0.0000 +645.0,1.5500,0.0000 +650.0,1.5500,0.0000 +655.0,1.5500,0.0000 +660.0,1.5500,0.0000 +665.0,1.5500,0.0000 +670.0,1.5500,0.0000 +675.0,1.5500,0.0000 +680.0,1.5500,0.0000 +685.0,1.5500,0.0000 +690.0,1.5500,0.0000 +695.0,1.5500,0.0000 +700.0,1.5500,0.0000 +705.0,1.5500,0.0000 +710.0,1.5500,0.0000 +715.0,1.5500,0.0000 +720.0,1.5500,0.0000 +725.0,1.5500,0.0000 +730.0,1.5500,0.0000 +735.0,1.5500,0.0000 +740.0,1.5500,0.0000 +745.0,1.5500,0.0000 +750.0,1.5500,0.0000 +755.0,1.5500,0.0000 +760.0,1.5500,0.0000 +765.0,1.5500,0.0000 +770.0,1.5500,0.0000 +775.0,1.5500,0.0000 +780.0,1.5500,0.0000 +785.0,1.5500,0.0000 +790.0,1.5500,0.0000 +795.0,1.5500,0.0000 +800.0,1.5500,0.0000 +805.0,1.5500,0.0000 +810.0,1.5500,0.0000 +815.0,1.5500,0.0000 +820.0,1.5500,0.0000 +825.0,1.5500,0.0000 +830.0,1.5500,0.0000 +835.0,1.5500,0.0000 +840.0,1.5500,0.0000 +845.0,1.5500,0.0000 +850.0,1.5500,0.0000 +855.0,1.5500,0.0000 +860.0,1.5500,0.0000 +865.0,1.5500,0.0000 +870.0,1.5500,0.0000 +875.0,1.5500,0.0000 +880.0,1.5500,0.0000 +885.0,1.5500,0.0000 +890.0,1.5500,0.0000 +895.0,1.5500,0.0000 +900.0,1.5500,0.0000 +905.0,1.5500,0.0000 +910.0,1.5500,0.0000 +915.0,1.5500,0.0000 +920.0,1.5500,0.0000 +925.0,1.5500,0.0000 +930.0,1.5500,0.0000 +935.0,1.5500,0.0000 +940.0,1.5500,0.0000 +945.0,1.5500,0.0000 +950.0,1.5500,0.0000 +955.0,1.5500,0.0000 +960.0,1.5500,0.0000 +965.0,1.5500,0.0000 +970.0,1.5500,0.0000 +975.0,1.5500,0.0000 +980.0,1.5500,0.0000 +985.0,1.5500,0.0000 +990.0,1.5500,0.0000 +995.0,1.5500,0.0000 +1000.0,1.5500,0.0000 +1005.0,1.5500,0.0000 +1010.0,1.5500,0.0000 +1015.0,1.5500,0.0000 +1020.0,1.5500,0.0000 +1025.0,1.5500,0.0000 +1030.0,1.5500,0.0000 +1035.0,1.5500,0.0000 +1040.0,1.5500,0.0000 +1045.0,1.5500,0.0000 +1050.0,1.5500,0.0000 +1055.0,1.5500,0.0000 +1060.0,1.5500,0.0000 +1065.0,1.5500,0.0000 +1070.0,1.5500,0.0000 +1075.0,1.5500,0.0000 +1080.0,1.5500,0.0000 +1085.0,1.5500,0.0000 +1090.0,1.5500,0.0000 +1095.0,1.5500,0.0000 +1100.0,1.5500,0.0000 diff --git a/src/solarlab/materials/data/presets/calado2016_fig1f.device.json b/src/solarlab/materials/data/presets/calado2016_fig1f.device.json new file mode 100644 index 00000000..3734574e --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_fig1f.device.json @@ -0,0 +1,123 @@ +{ + "contacts": [ + { + "id": "contact_left", + "layer": "layer_0", + "side": "left" + }, + { + "id": "contact_right", + "layer": "layer_2", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "calado2016_fig1f", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1", + "v_n": "0.0", + "v_p": "0.0" + }, + { + "id": "interface_1", + "left": "layer_1", + "right": "layer_2", + "v_n": "0.0", + "v_p": "0.0" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "p_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "3E+23", + "N_D": "0.0", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "305", + "ni": "3.62E+12", + "p1": "4.36E+22", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "HTL", + "thickness": "2.00E-7" + }, + { + "id": "layer_1", + "name": "MAPbI3", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "2.585E-18", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "0.0", + "P0": "1E+25", + "P_lim": "1E+30", + "alpha": "1E+5", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "3.62E+12", + "ni": "3.62E+12", + "p1": "3.62E+12", + "tau_n": "1.0", + "tau_p": "1.0" + }, + "role": "absorber", + "thickness": "4.00E-7" + }, + { + "id": "layer_2", + "name": "n_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "3E+23", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "4.36E+22", + "ni": "3.62E+12", + "p1": "305", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "ETL", + "thickness": "2.00E-7" + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+22", + "V_bi": "1.3", + "mode": "legacy" + }, + "source_format": "standard" +} diff --git a/src/solarlab/materials/data/presets/calado2016_fig1f.v2.json b/src/solarlab/materials/data/presets/calado2016_fig1f.v2.json new file mode 100644 index 00000000..e88d62ad --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_fig1f.v2.json @@ -0,0 +1,139 @@ +{ + "default_catalog_sha256": "8de934eb0685b1d5fc4843002fceb4a8fdebdb4ac22896ec08a309991730130e", + "input": { + "contacts": [ + { + "id": "contact_left", + "layer": "layer_0", + "side": "left" + }, + { + "id": "contact_right", + "layer": "layer_2", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "calado2016_fig1f", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1", + "v_n": "0.0", + "v_p": "0.0" + }, + { + "id": "interface_1", + "left": "layer_1", + "right": "layer_2", + "v_n": "0.0", + "v_p": "0.0" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "p_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "3E+23", + "N_D": "0.0", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "305", + "ni": "3.62E+12", + "p1": "4.36E+22", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "HTL", + "thickness": "2.00E-7" + }, + { + "id": "layer_1", + "name": "MAPbI3", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "2.585E-18", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "0.0", + "P0": "1E+25", + "P_lim": "1E+30", + "alpha": "1E+5", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "3.62E+12", + "ni": "3.62E+12", + "p1": "3.62E+12", + "tau_n": "1.0", + "tau_p": "1.0" + }, + "role": "absorber", + "thickness": "4.00E-7" + }, + { + "id": "layer_2", + "name": "n_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "3E+23", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "4.36E+22", + "ni": "3.62E+12", + "p1": "305", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "ETL", + "thickness": "2.00E-7" + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+22", + "V_bi": "1.3", + "mode": "legacy" + }, + "source_format": "standard" + }, + "references": {}, + "resource_library_sha256": "6082eb3300b024b07e638fb7fca29dd88119e4c2db0403346bcd4bfe9f9fa60a", + "schema_version": "solarlab.configuration.v2", + "source": { + "id": "calado2016_fig1f.yaml", + "sha256": "825d77f15bcfb3e550cc601231a9b6ce07ca11fe185a3eb7d7ef121d54c0ec2a" + }, + "sources": [ + { + "id": "calado2016_fig1f.yaml", + "sha256": "825d77f15bcfb3e550cc601231a9b6ce07ca11fe185a3eb7d7ef121d54c0ec2a" + } + ] +} diff --git a/src/solarlab/materials/data/presets/calado2016_fig1f.yaml b/src/solarlab/materials/data/presets/calado2016_fig1f.yaml new file mode 100644 index 00000000..8d16a787 --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_fig1f.yaml @@ -0,0 +1,115 @@ +# Calado 2016 Fig 1f parameter anchor (bottom-cathode, contact SRH enabled). +# +# Source: Calado et al., Nat. Commun. 7, 13831 (2016), Supplementary Table 1 +# and Supplementary Note 2 — the p-i-n toy model behind the simulated J-V of +# Fig 1f (HI = 1.84 at 40 mV/s in the paper's P_max,rev/P_max,fwd - 1 metric). +# +# This is an investigation baseline, not a completed paper reproduction. +# See docs/Calado2016ReproductionCheckpoint.md for current evidence. +# The parameters important for the ionic-hysteresis comparison are: +# - D_ion here is the paper's own simulation value 2.585e-18 m^2/s +# (mu_ion = 1e-12 cm^2/Vs, deliberately slowed by the authors to match +# their ~40 s transients). +# - Contacts share the absorber transport (mu = 20 cm^2/Vs everywhere, +# identical flat bands) so minority carriers actually reach the +# contact-volume SRH sink that generates the hysteresis. +# - Contact SRH tau = 2e-15 s (paper value, "while unrealistic" — an +# intentional near-perfect sink), traps at -0.2 eV (n-side) / -1.4 eV +# (p-side) below the conduction band, expressed through n1/p1 with +# N0 = 1e20 cm^-3 and ni = N0 exp(-Eg/2kT), Eg = 1.6 eV. +# +# Known deviations and unresolved comparisons: +# - The paper drives a uniform G = 2.5e21 cm^-3 s^-1 in the i-layer; this +# preset approximates it with weak Beer-Lambert absorption +# (alpha*L = 0.04 => <= 4% front-to-back G variation, absorbed +# photocurrent ~ 16 mA/cm^2). For the exact uniform profile pass +# fixed_generation to run_jv_sweep. +# - run_jv_sweep scans 0 -> V_max -> 0; the paper scans -1 -> +1.2 V with +# an initial dark preparation. Experimental and simulated high-bias +# holds must be distinguished; the simulation Methods specify that +# reverse inherits the final forward state. +# - This Legacy preset uses all-carrier Dirichlet outer contacts. The SI +# instead blocks minority carriers; diagnostics select existing Full +# mode with S_n_left=0 and S_p_right=0 to test those boundaries. +# - With mixed contacts, uniform G, continuous 40 mV/s ramps, dark -1 V +# preparation and a 3 s dark high-bias hold, diagnostic HI is 0.482 +# at N=100, versus extracted paper HI=1.839. N=60 gives 0.479. +# This pair is not a full spatial/time/tolerance convergence certificate. + +device: + mode: legacy + V_bi: 1.3 + Phi: 2.5e22 + interfaces: + - [0.0, 0.0] + - [0.0, 0.0] + +layers: + - name: p_contact + role: HTL + thickness: 200e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 0.0 + N_A: 3e23 + D_ion: 0.0 + P_lim: 1e30 + P0: 0.0 + tau_n: 2e-15 + tau_p: 2e-15 + n1: 3.05e2 # N0 exp(-1.4 eV / kT): deep trap referenced to the CB + p1: 4.36e22 # ni^2 / n1 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 0.0 + chi: 0.0 + Eg: 0.0 + + - name: MAPbI3 + role: absorber + thickness: 400e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 0.0 + N_A: 0.0 + D_ion: 2.585e-18 + P_lim: 1e30 + P0: 1e25 + tau_n: 1.0 # no SRH in the perovskite in the paper's model + tau_p: 1.0 + n1: 3.62e12 + p1: 3.62e12 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 1e5 # alpha*L = 0.04: quasi-uniform G, ~16 mA/cm^2 absorbed + chi: 0.0 + Eg: 0.0 + + - name: n_contact + role: ETL + thickness: 200e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 3e23 + N_A: 0.0 + D_ion: 0.0 + P_lim: 1e30 + P0: 0.0 + tau_n: 2e-15 + tau_p: 2e-15 + n1: 4.36e22 # N0 exp(-0.2 eV / kT): shallow trap below the CB + p1: 3.05e2 # ni^2 / n1 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 0.0 + chi: 0.0 + Eg: 0.0 diff --git a/src/solarlab/materials/data/presets/calado2016_ion_sweep.device.json b/src/solarlab/materials/data/presets/calado2016_ion_sweep.device.json new file mode 100644 index 00000000..f04627ff --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_ion_sweep.device.json @@ -0,0 +1,151 @@ +{ + "contacts": [ + { + "S_n": null, + "S_p": null, + "id": "contact_left", + "layer": "layer_0", + "side": "left" + }, + { + "S_n": null, + "S_p": null, + "id": "contact_right", + "layer": "layer_2", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "calado2016_ion_sweep", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1", + "v_n": "0.0", + "v_p": "0.0" + }, + { + "id": "interface_1", + "left": "layer_1", + "right": "layer_2", + "v_n": "0.0", + "v_p": "0.0" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "p_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "3E+23", + "N_D": "0.0", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "305", + "ni": "3.62E+12", + "p1": "4.36E+22", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "HTL", + "thickness": "2.00E-7" + }, + { + "id": "layer_1", + "name": "MAPbI3", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "2.585E-18", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "0.0", + "P0": "1E+25", + "P_lim": "1E+30", + "alpha": "1E+5", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "3.62E+12", + "ni": "3.62E+12", + "p1": "3.62E+12", + "tau_n": "1.0", + "tau_p": "1.0" + }, + "role": "absorber", + "thickness": "4.00E-7" + }, + { + "id": "layer_2", + "name": "n_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "3E+23", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "4.36E+22", + "ni": "3.62E+12", + "p1": "305", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "ETL", + "thickness": "2.00E-7" + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+22", + "T": 300, + "V_bi": "1.3", + "mode": "full" + }, + "simulation_hints": { + "jv_sweep": { + "N_grid": 60, + "V_max": 1.2, + "n_points": 111, + "v_rate": 0.04, + "waveform": { + "branch_dwell_s": 0.5, + "dark_prep_s": 30.0, + "dark_seed_s": 120.0, + "schema_version": 1, + "start_voltage_V": -1.0, + "turnaround_dark": true, + "turnaround_s": 3.0, + "uniform_generation_rate_m3_s": 2.5e+27 + }, + "waveform_controls": { + "atol_m3": 1.0, + "rtol": 0.0001 + } + }, + "notes": "Internal ion-sweep figure reference; finite-time diagnostic." + }, + "source_format": "standard" +} diff --git a/src/solarlab/materials/data/presets/calado2016_ion_sweep.v2.json b/src/solarlab/materials/data/presets/calado2016_ion_sweep.v2.json new file mode 100644 index 00000000..f3435722 --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_ion_sweep.v2.json @@ -0,0 +1,167 @@ +{ + "default_catalog_sha256": "8de934eb0685b1d5fc4843002fceb4a8fdebdb4ac22896ec08a309991730130e", + "input": { + "contacts": [ + { + "S_n": null, + "S_p": null, + "id": "contact_left", + "layer": "layer_0", + "side": "left" + }, + { + "S_n": null, + "S_p": null, + "id": "contact_right", + "layer": "layer_2", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "calado2016_ion_sweep", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1", + "v_n": "0.0", + "v_p": "0.0" + }, + { + "id": "interface_1", + "left": "layer_1", + "right": "layer_2", + "v_n": "0.0", + "v_p": "0.0" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "p_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "3E+23", + "N_D": "0.0", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "305", + "ni": "3.62E+12", + "p1": "4.36E+22", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "HTL", + "thickness": "2.00E-7" + }, + { + "id": "layer_1", + "name": "MAPbI3", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "2.585E-18", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "0.0", + "P0": "1E+25", + "P_lim": "1E+30", + "alpha": "1E+5", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "3.62E+12", + "ni": "3.62E+12", + "p1": "3.62E+12", + "tau_n": "1.0", + "tau_p": "1.0" + }, + "role": "absorber", + "thickness": "4.00E-7" + }, + { + "id": "layer_2", + "name": "n_contact", + "parameters": { + "B_rad": "1E-16", + "C_n": "0.0", + "C_p": "0.0", + "D_ion": "0.0", + "Eg": "0.0", + "N_A": "0.0", + "N_D": "3E+23", + "P0": "0.0", + "P_lim": "1E+30", + "alpha": "0.0", + "chi": "0.0", + "eps_r": "20.0", + "mu_n": "0.002", + "mu_p": "0.002", + "n1": "4.36E+22", + "ni": "3.62E+12", + "p1": "305", + "tau_n": "2E-15", + "tau_p": "2E-15" + }, + "role": "ETL", + "thickness": "2.00E-7" + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+22", + "T": 300, + "V_bi": "1.3", + "mode": "full" + }, + "simulation_hints": { + "jv_sweep": { + "N_grid": 60, + "V_max": 1.2, + "n_points": 111, + "v_rate": 0.04, + "waveform": { + "branch_dwell_s": 0.5, + "dark_prep_s": 30.0, + "dark_seed_s": 120.0, + "schema_version": 1, + "start_voltage_V": -1.0, + "turnaround_dark": true, + "turnaround_s": 3.0, + "uniform_generation_rate_m3_s": 2.5e+27 + }, + "waveform_controls": { + "atol_m3": 1.0, + "rtol": 0.0001 + } + }, + "notes": "Internal ion-sweep figure reference; finite-time diagnostic." + }, + "source_format": "standard" + }, + "references": {}, + "resource_library_sha256": "6082eb3300b024b07e638fb7fca29dd88119e4c2db0403346bcd4bfe9f9fa60a", + "schema_version": "solarlab.configuration.v2", + "source": { + "id": "calado2016_ion_sweep.yaml", + "sha256": "2b436f161a62c9edb2f0b1bbbcf0d2d6a5f27471d2a5d296952173c4baadea9c" + }, + "sources": [ + { + "id": "calado2016_ion_sweep.yaml", + "sha256": "2b436f161a62c9edb2f0b1bbbcf0d2d6a5f27471d2a5d296952173c4baadea9c" + } + ] +} diff --git a/src/solarlab/materials/data/presets/calado2016_ion_sweep.yaml b/src/solarlab/materials/data/presets/calado2016_ion_sweep.yaml new file mode 100644 index 00000000..41b9281e --- /dev/null +++ b/src/solarlab/materials/data/presets/calado2016_ion_sweep.yaml @@ -0,0 +1,109 @@ +# Reference inputs for the SolarLab dense ion-sweep figure. +# Captured frontend history: -1 -> 1.2 -> -1 V at 0.04 V/s, +# uniform absorber generation, and a 3 s dark turnaround hold. +# This reproduces an internal figure, not the original Calado paper. +# D/D_ref varies only absorber D_ion; c0/c_ref varies only absorber P0. +# D_ref = 2.585e-18 m^2/s; c_ref = 1e25 m^-3. + +simulation_hints: + notes: "Internal ion-sweep figure reference; finite-time diagnostic." + jv_sweep: + N_grid: 60 + n_points: 111 + v_rate: 0.04 + V_max: 1.2 + waveform: + schema_version: 1 + start_voltage_V: -1.0 + dark_seed_s: 120.0 + dark_prep_s: 30.0 + branch_dwell_s: 0.5 + turnaround_s: 3.0 + turnaround_dark: true + uniform_generation_rate_m3_s: 2.5e27 + waveform_controls: + rtol: 1.0e-4 + atol_m3: 1.0 + +device: + mode: full + T: 300 + V_bi: 1.3 + Phi: 2.5e22 + S_n_left: null + S_p_left: null + S_n_right: null + S_p_right: null + interfaces: + - [0.0, 0.0] + - [0.0, 0.0] + +layers: + - name: p_contact + role: HTL + thickness: 200e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 0.0 + N_A: 3e23 + D_ion: 0.0 + P_lim: 1e30 + P0: 0.0 + tau_n: 2e-15 + tau_p: 2e-15 + n1: 3.05e2 + p1: 4.36e22 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 0.0 + chi: 0.0 + Eg: 0.0 + + - name: MAPbI3 + role: absorber + thickness: 400e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 0.0 + N_A: 0.0 + D_ion: 2.585e-18 + P_lim: 1e30 + P0: 1e25 + tau_n: 1.0 + tau_p: 1.0 + n1: 3.62e12 + p1: 3.62e12 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 1e5 + chi: 0.0 + Eg: 0.0 + + - name: n_contact + role: ETL + thickness: 200e-9 + eps_r: 20.0 + mu_n: 2e-3 + mu_p: 2e-3 + ni: 3.62e12 + N_D: 3e23 + N_A: 0.0 + D_ion: 0.0 + P_lim: 1e30 + P0: 0.0 + tau_n: 2e-15 + tau_p: 2e-15 + n1: 4.36e22 + p1: 3.05e2 + B_rad: 1e-16 + C_n: 0.0 + C_p: 0.0 + alpha: 0.0 + chi: 0.0 + Eg: 0.0 diff --git a/src/solarlab/materials/data/presets/classical_pin.device.json b/src/solarlab/materials/data/presets/classical_pin.device.json new file mode 100644 index 00000000..727c46c2 --- /dev/null +++ b/src/solarlab/materials/data/presets/classical_pin.device.json @@ -0,0 +1,152 @@ +{ + "electrical_grid": [ + { + "alpha": 3.0, + "interval_weight": 16.0, + "layer": "htl" + }, + { + "alpha": 3.0, + "interval_weight": 40.0, + "layer": "absorber" + }, + { + "alpha": 3.0, + "interval_weight": 16.0, + "layer": "etl" + } + ], + "id": "classical_pin", + "layers": [ + { + "id": "htl", + "name": "HTL", + "parameters": { + "A_star_n": 0.0, + "A_star_p": 0.0, + "B_rad": 1e-18, + "C_n": 1e-42, + "C_p": 1e-42, + "D_ion": 0.0, + "D_ion_neg": 0.0, + "E_a_ion": 0.0, + "Eg": 1.8, + "N_A": 1e+24, + "N_D": 0.0, + "Nc300": 2e+25, + "Nv300": 3e+25, + "P0": 0.0, + "P0_neg": 0.0, + "P_lim": 1e+28, + "P_lim_neg": 1e+28, + "alpha": 0.0, + "bgn_reference_density_m3": 1e+24, + "bgn_reference_energy_eV": 0.0, + "chi": 3.6, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "eps_r": 3.0, + "mu_n": 3.8681727071833605e-05, + "mu_p": 3.8681727071833605e-05, + "n1": 18609772721.447, + "ni": 18609772721.447, + "p1": 18609772721.447, + "tau_n": 1e-06, + "tau_p": 1e-06 + }, + "role": "HTL", + "thickness": 8e-08 + }, + { + "id": "absorber", + "name": "absorber", + "parameters": { + "A_star_n": 0.0, + "A_star_p": 0.0, + "B_rad": 1e-18, + "C_n": 1e-42, + "C_p": 1e-42, + "D_ion": 0.0, + "D_ion_neg": 0.0, + "E_a_ion": 0.0, + "Eg": 1.6, + "N_A": 0.0, + "N_D": 0.0, + "Nc300": 1e+25, + "Nv300": 1e+25, + "P0": 0.0, + "P0_neg": 0.0, + "P_lim": 1e+28, + "P_lim_neg": 1e+28, + "alpha": 2000000.0, + "bgn_reference_density_m3": 1e+24, + "bgn_reference_energy_eV": 0.0, + "chi": 3.9, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "eps_r": 25.0, + "mu_n": 0.0019340863535916802, + "mu_p": 0.0019340863535916802, + "n1": 363572901223.5858, + "ni": 363572901223.5858, + "p1": 363572901223.5858, + "tau_n": 1e-06, + "tau_p": 1e-06 + }, + "role": "absorber", + "thickness": 3e-07 + }, + { + "id": "etl", + "name": "ETL", + "parameters": { + "A_star_n": 0.0, + "A_star_p": 0.0, + "B_rad": 1e-18, + "C_n": 1e-42, + "C_p": 1e-42, + "D_ion": 0.0, + "D_ion_neg": 0.0, + "E_a_ion": 0.0, + "Eg": 2.0, + "N_A": 0.0, + "N_D": 1e+24, + "Nc300": 4e+25, + "Nv300": 2e+25, + "P0": 0.0, + "P0_neg": 0.0, + "P_lim": 1e+28, + "P_lim_neg": 1e+28, + "alpha": 0.0, + "bgn_reference_density_m3": 1e+24, + "bgn_reference_energy_eV": 0.0, + "chi": 4.0, + "ct_beta_n": 1.0, + "ct_beta_p": 1.0, + "eps_r": 9.0, + "mu_n": 3.8681727071833605e-05, + "mu_p": 3.8681727071833605e-05, + "n1": 449039324.31171566, + "ni": 449039324.31171566, + "p1": 449039324.31171566, + "tau_n": 1e-06, + "tau_p": 1e-06 + }, + "role": "ETL", + "thickness": 8e-08 + } + ], + "name": "Classical p-i-n research device", + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": 2e+21, + "T": 300.0, + "V_bi": 0.0, + "built_in_potential_mode": "semiconductor_work_function", + "dos_band_potentials": true, + "ion_steric_diffusion_only": false, + "ion_steric_shared_site": false, + "mode": "fast" + }, + "source_format": "canonical" +} diff --git a/src/solarlab/materials/data/presets/scaps_mirror_v2.device.json b/src/solarlab/materials/data/presets/scaps_mirror_v2.device.json new file mode 100644 index 00000000..749f6eb3 --- /dev/null +++ b/src/solarlab/materials/data/presets/scaps_mirror_v2.device.json @@ -0,0 +1,235 @@ +{ + "contacts": [ + { + "id": "contact_left", + "layer": "layer_1", + "side": "left" + }, + { + "id": "contact_right", + "layer": "layer_3", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "scaps_mirror_v2", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1" + }, + { + "defect": { + "calibration_factor": 1.0, + "energy_reference": "below_conduction_band", + "id": "interface_defect_1", + "iface_state_calibration_factor": "0.02", + "kinetics": { + "sigma_n_m2": 1e-23, + "sigma_p_m2": 1e-23, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "partner_metadata": { + "defect_id": "interface_defect_1", + "distribution": "single", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.6 + }, + "total_density_m2": 1e+16, + "trap_depth_eV": 0.6 + }, + "id": "interface_1", + "left": "layer_1", + "right": "layer_2" + }, + { + "defect": { + "calibration_factor": 1.0, + "energy_reference": "below_conduction_band", + "id": "interface_defect_2", + "iface_state_calibration_factor": "0.10", + "kinetics": { + "sigma_n_m2": 1e-23, + "sigma_p_m2": 1e-23, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "partner_metadata": { + "E_char_eV": 0.1, + "N_peak_m3": 564000000000000.0, + "defect_id": "interface_defect_2", + "distribution": "gaussian", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.6 + }, + "total_density_m2": 1e+16, + "trap_depth_eV": 0.6 + }, + "id": "interface_2", + "left": "layer_2", + "right": "layer_3" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "glass", + "parameterization": "scaps", + "parameters": { + "Eg": 9.0, + "N_A": 0.0, + "N_D": 0.0, + "Nc300": 1e+25, + "Nv300": 1e+25, + "chi": 1.0, + "eps_r": 2.25, + "incoherent": true, + "mu_n": 0.0, + "mu_p": 0.0, + "optical_material": "glass", + "v_th": 100000.0 + }, + "role": "substrate", + "thickness": 0.001 + }, + { + "id": "layer_1", + "name": "SCAPS_HTL", + "parameterization": "scaps", + "parameters": { + "Eg": 3.25, + "N_A": 1e+24, + "N_D": 0.0, + "Nc300": 2.5e+26, + "Nv300": 2.5e+26, + "chi": 2.4, + "eps_r": 11.75, + "mu_n": 1e-07, + "mu_p": 1e-07, + "optical_material": "spiro_OMeTAD", + "v_th": 100000.0 + }, + "role": "HTL", + "thickness": 2e-08 + }, + { + "bulk_defects": [ + { + "charge_transition": "unresolved", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 1e+18 + }, + "energy_level": { + "reference": "below_conduction_band", + "value_eV": 0.1 + }, + "id": "bulk_0", + "kinetics": { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "name": "Perovskite-CB", + "neutral_reference": "unresolved" + }, + { + "charge_transition": "unresolved", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 1e+18 + }, + "energy_level": { + "reference": "above_valence_band", + "value_eV": 0.1 + }, + "id": "bulk_1", + "kinetics": { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "name": "Perovskite-VB", + "neutral_reference": "unresolved" + } + ], + "defect_model": "effective_lifetime", + "defect_schema_version": "solarlab-explicit-bulk-defects-v1", + "id": "layer_2", + "name": "SCAPS_PVK", + "parameterization": "scaps", + "parameters": { + "B_rad": 1e-18, + "C_n": 2.3e-41, + "C_p": 2.3e-41, + "Eg": 1.53, + "N_A": 0.0, + "N_D": 1e+20, + "Nc300": 1e+25, + "Nv300": 1e+25, + "chi": 3.94, + "eps_r": 31.0, + "mu_n": 0.002, + "mu_p": 0.002, + "optical_material": "MAPbI3", + "v_th": 100000.0 + }, + "role": "absorber", + "scaps_defect_metadata": [ + { + "defect_id": "bulk_0", + "distribution": "single", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.1 + }, + { + "defect_id": "bulk_1", + "distribution": "single", + "energy_reference": "above_valence_band", + "trap_depth_eV": 0.1 + } + ], + "thickness": 8e-07 + }, + { + "id": "layer_3", + "name": "SCAPS_ETL", + "parameterization": "scaps", + "parameters": { + "Eg": 1.9, + "N_A": 0.0, + "N_D": 1e+24, + "Nc300": 8e+25, + "Nv300": 8e+25, + "chi": 4.1, + "eps_r": 4.2, + "mu_n": 1e-06, + "mu_p": 1e-09, + "optical_material": "TiO2", + "v_th": 100000.0 + }, + "role": "ETL", + "thickness": 2.5e-08 + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+21", + "V_bi": "1.30", + "contact_phi_B_eV": "0.42", + "dos_band_potentials": true, + "flat_band_metal_contacts": true, + "het_recomb_despike": "0.53", + "mode": "fast" + }, + "source_format": "scaps" +} diff --git a/src/solarlab/materials/data/presets/scaps_mirror_v2.v2.json b/src/solarlab/materials/data/presets/scaps_mirror_v2.v2.json new file mode 100644 index 00000000..14d1d23a --- /dev/null +++ b/src/solarlab/materials/data/presets/scaps_mirror_v2.v2.json @@ -0,0 +1,251 @@ +{ + "default_catalog_sha256": "8de934eb0685b1d5fc4843002fceb4a8fdebdb4ac22896ec08a309991730130e", + "input": { + "contacts": [ + { + "id": "contact_left", + "layer": "layer_1", + "side": "left" + }, + { + "id": "contact_right", + "layer": "layer_3", + "side": "right" + } + ], + "electrical_grid": [], + "grain_boundaries": [], + "id": "scaps_mirror_v2", + "interfaces": [ + { + "id": "interface_0", + "left": "layer_0", + "right": "layer_1" + }, + { + "defect": { + "calibration_factor": 1.0, + "energy_reference": "below_conduction_band", + "id": "interface_defect_1", + "iface_state_calibration_factor": "0.02", + "kinetics": { + "sigma_n_m2": 1e-23, + "sigma_p_m2": 1e-23, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "partner_metadata": { + "defect_id": "interface_defect_1", + "distribution": "single", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.6 + }, + "total_density_m2": 1e+16, + "trap_depth_eV": 0.6 + }, + "id": "interface_1", + "left": "layer_1", + "right": "layer_2" + }, + { + "defect": { + "calibration_factor": 1.0, + "energy_reference": "below_conduction_band", + "id": "interface_defect_2", + "iface_state_calibration_factor": "0.10", + "kinetics": { + "sigma_n_m2": 1e-23, + "sigma_p_m2": 1e-23, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "partner_metadata": { + "E_char_eV": 0.1, + "N_peak_m3": 564000000000000.0, + "defect_id": "interface_defect_2", + "distribution": "gaussian", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.6 + }, + "total_density_m2": 1e+16, + "trap_depth_eV": 0.6 + }, + "id": "interface_2", + "left": "layer_2", + "right": "layer_3" + } + ], + "layers": [ + { + "id": "layer_0", + "name": "glass", + "parameterization": "scaps", + "parameters": { + "Eg": 9.0, + "N_A": 0.0, + "N_D": 0.0, + "Nc300": 1e+25, + "Nv300": 1e+25, + "chi": 1.0, + "eps_r": 2.25, + "incoherent": true, + "mu_n": 0.0, + "mu_p": 0.0, + "optical_material": "glass", + "v_th": 100000.0 + }, + "role": "substrate", + "thickness": 0.001 + }, + { + "id": "layer_1", + "name": "SCAPS_HTL", + "parameterization": "scaps", + "parameters": { + "Eg": 3.25, + "N_A": 1e+24, + "N_D": 0.0, + "Nc300": 2.5e+26, + "Nv300": 2.5e+26, + "chi": 2.4, + "eps_r": 11.75, + "mu_n": 1e-07, + "mu_p": 1e-07, + "optical_material": "spiro_OMeTAD", + "v_th": 100000.0 + }, + "role": "HTL", + "thickness": 2e-08 + }, + { + "bulk_defects": [ + { + "charge_transition": "unresolved", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 1e+18 + }, + "energy_level": { + "reference": "below_conduction_band", + "value_eV": 0.1 + }, + "id": "bulk_0", + "kinetics": { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "name": "Perovskite-CB", + "neutral_reference": "unresolved" + }, + { + "charge_transition": "unresolved", + "degeneracy": 1.0, + "distribution": { + "kind": "single_level", + "normalization": "integrated_total", + "total_density_m3": 1e+18 + }, + "energy_level": { + "reference": "above_valence_band", + "value_eV": 0.1 + }, + "id": "bulk_1", + "kinetics": { + "sigma_n_m2": 1e-19, + "sigma_p_m2": 1e-19, + "thermal_velocity_n_m_s": 100000.0, + "thermal_velocity_p_m_s": 100000.0 + }, + "name": "Perovskite-VB", + "neutral_reference": "unresolved" + } + ], + "defect_model": "effective_lifetime", + "defect_schema_version": "solarlab-explicit-bulk-defects-v1", + "id": "layer_2", + "name": "SCAPS_PVK", + "parameterization": "scaps", + "parameters": { + "B_rad": 1e-18, + "C_n": 2.3e-41, + "C_p": 2.3e-41, + "Eg": 1.53, + "N_A": 0.0, + "N_D": 1e+20, + "Nc300": 1e+25, + "Nv300": 1e+25, + "chi": 3.94, + "eps_r": 31.0, + "mu_n": 0.002, + "mu_p": 0.002, + "optical_material": "MAPbI3", + "v_th": 100000.0 + }, + "role": "absorber", + "scaps_defect_metadata": [ + { + "defect_id": "bulk_0", + "distribution": "single", + "energy_reference": "below_conduction_band", + "trap_depth_eV": 0.1 + }, + { + "defect_id": "bulk_1", + "distribution": "single", + "energy_reference": "above_valence_band", + "trap_depth_eV": 0.1 + } + ], + "thickness": 8e-07 + }, + { + "id": "layer_3", + "name": "SCAPS_ETL", + "parameterization": "scaps", + "parameters": { + "Eg": 1.9, + "N_A": 0.0, + "N_D": 1e+24, + "Nc300": 8e+25, + "Nv300": 8e+25, + "chi": 4.1, + "eps_r": 4.2, + "mu_n": 1e-06, + "mu_p": 1e-09, + "optical_material": "TiO2", + "v_th": 100000.0 + }, + "role": "ETL", + "thickness": 2.5e-08 + } + ], + "schema_version": "solarlab.device-preparation.v1", + "settings": { + "Phi": "2.5E+21", + "V_bi": "1.30", + "contact_phi_B_eV": "0.42", + "dos_band_potentials": true, + "flat_band_metal_contacts": true, + "het_recomb_despike": "0.53", + "mode": "fast" + }, + "source_format": "scaps" + }, + "references": {}, + "resource_library_sha256": "6082eb3300b024b07e638fb7fca29dd88119e4c2db0403346bcd4bfe9f9fa60a", + "schema_version": "solarlab.configuration.v2", + "source": { + "id": "scaps_mirror_v2.yaml", + "sha256": "5500c9485f6a9518430511019546933277cdc3274fd3a005182394f39d2fcf67" + }, + "sources": [ + { + "id": "scaps_mirror_v2.yaml", + "sha256": "5500c9485f6a9518430511019546933277cdc3274fd3a005182394f39d2fcf67" + } + ] +} diff --git a/src/solarlab/materials/data/presets/scaps_mirror_v2.yaml b/src/solarlab/materials/data/presets/scaps_mirror_v2.yaml new file mode 100644 index 00000000..b693a0fb --- /dev/null +++ b/src/solarlab/materials/data/presets/scaps_mirror_v2.yaml @@ -0,0 +1,185 @@ +# scaps_mirror_v2.yaml — SCAPS-1D partner stack, defect-corrected. +# +# Phase E6 rewrite of configs/scaps_mirror.yaml that closes three defect- +# inventory gaps identified by the 2026-05-28 PDF audit +# (docs/superpowers/specs/2026-05-28-e2a-scaps-yaml-audit-vs-pdf.md): +# +# 1. PVK carried ONE bulk defect (Perovskite-CB Single, E_t=0.1 below CB) +# → SCAPS PDF declares TWO: Perovskite-CB AND Perovskite-VB. +# New schema: `bulk_defects: [...]` list per layer. +# +# 2. HTL/PVK interface defect was absent. +# → PDF declares Single, E_t=0.6, sigma=1e-19, N_t=1e12. +# Added under `interfaces:` block with target HTL/PVK. +# +# 3. PVK/ETL interface defect was encoded as Single + sigma=1e-15 + +# calibration_factor=1e-4 (which hid a 4-order sigma error AND the +# Single→Gaussian distribution mismatch). +# → Rewritten as `distribution: gaussian` with E_char=0.1 eV, +# N_peak=5.64e8 cm^-3, sigma=1e-19. calibration_factor REMOVED. +# +# Base layer parameters (24 fields per layer) audited line-by-line against +# PDF page 1 and confirmed bit-identical to scaps_mirror.yaml. +# +# Phase E6.3 loader extension consumes this schema: +# - `bulk_defects: list` — multi-defect parallel SRH per layer; loader +# combines via 1/tau_total = sum(1/tau_i) and weights n1/p1 by +# inverse-lifetime (matches arithmetic mean for identical taus). +# - `E_t_eV_above_vb` — alternative to `E_t_eV_below_cb` for traps +# referenced from VB; exactly one must be set per defect entry. +# - `distribution: gaussian` — accepted on both bulk and interface +# entries. The loader uses N_t_cm3 (bulk) or N_t_cm2 (interface) +# directly; `E_char_eV` and `N_peak_cm3` are informational fields +# (the PDF column-header units make standard Gaussian normalisation +# ambiguous — see Phase E6.3 docstring in scaps_compat/loader.py). +# - Strict-key validation: typos in defect/interface entries now raise +# ValueError. Pre-E6.3 the loader silently dropped unrecognised +# keys, which masked the calibration_factor unit-error class. + +device: + het_recomb_despike: 0.53 # SCAPS-emulation: de-spike heterointerface bulk-Auger double-count (base 1.121->1.168) + dos_band_potentials: true # effective-DOS QFL fold (now the code default; pinned so the validated baseline is self-contained) + flat_band_metal_contacts: true # work-function contact-reservoir floor: rescues low-N_D,ETL contact starvation so the ETL-doping V_oc trend rises with SCAPS (RMS 39 mV; the trend no de-spike fraction could fix). DORMANT at base doping -> base point + every other sweep bit-identical. + contact_phi_B_eV: 0.42 # metal work-function offset (calibration knob); 0.42 eV minimizes the Nd_ETL RMS vs SCAPS. + V_bi: 1.30 + Phi: 2.5e21 + mode: fast + +layers: + # Phase E10.1 — glass front substrate (optical-only, role:substrate filtered + # from the electrical grid). Real perovskite cells are illuminated through + # glass; omitting it left the air/spiro Fresnel reflection too high (~8 %), + # under-counting absorber J_sc. With glass the front reflection drops to + # ~5 % (air/glass ~4 % + index-matched glass/spiro) and absorber J_sc rises + # 21.7→23.1 mA/cm² — a physical completion of the optical stack, NOT a + # tuning hack. Residual to SCAPS 26.3 is SCAPS' zero-front-reflection + # idealization (we do not remove real reflection — physics gate). + - name: glass + role: substrate # optical-only; filtered from the electrical grid + thickness_nm: 1.0e6 # 1 mm + E_g_eV: 9.0 + chi_eV: 1.0 + eps_r: 2.25 + mu_n_cm2: 0.0 + mu_p_cm2: 0.0 + N_C_cm3: 1.0e19 + N_V_cm3: 1.0e19 + N_D_cm3: 0.0 + N_A_cm3: 0.0 + v_th_cm_s: 1.0e7 + optical_material: glass + incoherent: true + + - name: SCAPS_HTL + role: HTL + thickness_nm: 20.0 + E_g_eV: 3.25 + chi_eV: 2.40 + eps_r: 11.75 + mu_n_cm2: 1.0e-3 + mu_p_cm2: 1.0e-3 + N_C_cm3: 2.5e20 + N_V_cm3: 2.5e20 + N_D_cm3: 0.0 + N_A_cm3: 1.0e18 + v_th_cm_s: 1.0e7 + optical_material: spiro_OMeTAD + # PDF: no HTL bulk defect declared. + + - name: SCAPS_PVK + role: absorber + thickness_nm: 800.0 + E_g_eV: 1.53 + chi_eV: 3.94 + eps_r: 31.0 + mu_n_cm2: 20.0 + mu_p_cm2: 20.0 + N_C_cm3: 1.0e19 + N_V_cm3: 1.0e19 + N_D_cm3: 1.0e14 + N_A_cm3: 0.0 + v_th_cm_s: 1.0e7 + B_rad_cm3_s: 1.0e-12 + C_n_cm6_s: 2.3e-29 + C_p_cm6_s: 2.3e-29 + optical_material: MAPbI3 + # PDF Interface Defects table declares TWO PVK bulk-style defects: + # - Perovskite-CB: Single, sigma=1e-15, N_t=1e12 cm^-3, E_t=0.1 below CB + # - Perovskite-VB: Single, sigma=1e-15, N_t=1e12 cm^-3, E_t=0.1 above VB + # Combined SRH lifetime per node: 1/tau_total = 1/tau_CB + 1/tau_VB. + bulk_defects: + - name: Perovskite-CB + sigma_n_cm2: 1.0e-15 + sigma_p_cm2: 1.0e-15 + N_t_cm3: 1.0e12 + E_t_eV_below_cb: 0.1 + distribution: single + - name: Perovskite-VB + sigma_n_cm2: 1.0e-15 + sigma_p_cm2: 1.0e-15 + N_t_cm3: 1.0e12 + E_t_eV_above_vb: 0.1 + distribution: single + + - name: SCAPS_ETL + role: ETL + thickness_nm: 25.0 + E_g_eV: 1.9 + chi_eV: 4.10 + eps_r: 4.2 + mu_n_cm2: 1.0e-2 + mu_p_cm2: 1.0e-5 + N_C_cm3: 8.0e19 + N_V_cm3: 8.0e19 + N_D_cm3: 1.0e18 + N_A_cm3: 0.0 + v_th_cm_s: 1.0e7 + optical_material: TiO2 + # PDF: no ETL bulk defect declared. + +# PDF Interface Defects table declares TWO heterointerface defects. +interfaces: + # SCAPS sweep result: V_oc range across N_t=[1e9, 1e15] is < 1 mV (flat). + # Interface 1 is effectively passive in the partner model but must be + # declared for completeness (defect inventory must match SCAPS). + - target: HTL/PVK + sigma_n_cm2: 1.0e-19 + sigma_p_cm2: 1.0e-19 + N_t_cm2: 1.0e12 + v_th_cm_s: 1.0e7 + E_t_eV_below_cb: 0.6 + distribution: single + # SS interface-plane-state calibration (2026-06). Attenuates ONLY the + # steady-state interface-plane recombination channel (iface_states=True); + # the transient bulk-node path ignores it (verified delta 0.0 mV). 0.02 + # brings the SS HTL/PVK N_t sweep from 12x over to 1.0x of SCAPS (5.3 vs + # 5.2 mV) — this interface is near-passive in SCAPS. + iface_state_calibration_factor: 0.02 + + # SCAPS sweep result: dominant interface — V_oc range 282 mV across + # N_t=[1e9, 1e15]. SCAPS encodes this as a Gaussian energy distribution + # peaked at E_t=0.6 below CB with characteristic energy E_char=0.1 eV. + # Peak density 5.64e8 cm^-3 is the SCAPS PDF reference for N_t_total=1e12. + # The Phase E6.3 loader uses N_t_cm2=1e12 directly (the SCAPS-input total) + # and treats E_char_eV + N_peak_cm3 as informational metadata — the PDF + # column-header units make the standard Gaussian normalisation ambiguous + # (ratio 5.64e-4 does not match sqrt(2*pi)*E_char ≈ 0.2507), so the YAML + # mirrors the SCAPS GUI inputs verbatim rather than computing a synthetic + # N_t_eff from the peak. + # calibration_factor INTENTIONALLY OMITTED — the v1 1e-4 factor hid the + # 4-order sigma error (1e-15 vs PDF 1e-19) and the Single→Gaussian + # distribution mismatch. Both are corrected here. + - target: PVK/ETL + sigma_n_cm2: 1.0e-19 + sigma_p_cm2: 1.0e-19 + N_t_cm2: 1.0e12 + v_th_cm_s: 1.0e7 + E_t_eV_below_cb: 0.6 + distribution: gaussian + E_char_eV: 0.1 + N_peak_cm3: 5.64e8 + # SS interface-plane-state calibration (2026-06). SS-only (transient + # ignores it, verified delta 0.0 mV). 0.10 lands the SS base V_oc on + # SCAPS (1.1675 vs 1.1676, -0.1 mV) and brings the Nd_ETL sweep from + # ~2x over to 0.84x of SCAPS, while PVK/ETL N_t holds at 63%. + iface_state_calibration_factor: 0.10 diff --git a/src/solarlab/materials/data/references/csi_pn_cv_intercept.yaml b/src/solarlab/materials/data/references/csi_pn_cv_intercept.yaml new file mode 100644 index 00000000..a23025b1 --- /dev/null +++ b/src/solarlab/materials/data/references/csi_pn_cv_intercept.yaml @@ -0,0 +1,56 @@ +schema_version: 1 +topic: crystalline-silicon-pn-junction-capacitance-and-intercept +evidence_scope: interpretation-and-published-fit-provenance + +theory_reference: + citation: >- + Y. F. Chang, The capacitance of p-n junctions, Solid-State Electronics + 10 (1967) 281-287. + doi: https://doi.org/10.1016/0038-1101(67)90014-7 + claims: + - rigorous differential capacitance is the integral of the differential electron or hole concentration + - distributed transition-region carriers make the 1/C2 intercept an inaccurate barrier-height estimator + +experimental_reference: + citation: >- + M. Hufschmidt et al., The influence of edge effects on the determination + of the doping profile of silicon pad diodes, arXiv:1605.00778v1 (2016). + arxiv_url: https://arxiv.org/abs/1605.00778v1 + source_archive_url: https://arxiv.org/src/1605.00778v1 + source_archive_sha256: 9a663c632f4f36f38f8e70bfa6b9f67172b294d9fe3b3b842947eb26ac1cd985 + device: + material: float-zone crystalline silicon + junction: p-plus-n + manufacturer: Hamamatsu + active_thickness_um: 196 + active_thickness_uncertainty_um: 5 + small_pad_side_um: 2003 + large_pad_side_um: 4896 + junction_depth_um: 2 + measurement: + temperature_C: 20 + reverse_bias_range_V: [0.0, 160.0] + reverse_bias_step_V: 0.5 + frequency_range_Hz: [100.0, 2.0e+6] + reported_curve_frequency_Hz: 1.0e+4 + ac_amplitude_range_V: [0.05, 0.5] + reported_curve_ac_amplitude_V: 0.5 + note: capacitance agreed within 1 percent from 200 Hz to 200 kHz + edge_corrected_planar_fit: + reverse_bias_window_V: [5.0, 75.0] + normalized_capacitance_at_120V_pF_cm2: 51.99 + effective_thickness_um: 203 + full_depletion_voltage_V: 89.1 + doping_from_full_depletion_cm3: 2.93e+12 + doping_from_1_over_C2_slope_cm3: 2.86e+12 + v_axis_intercept_magnitude_V: 0.236 + maximum_relative_curve_residual: 0.003 + interpretation: + pn_depletion_thermal_correction: 2kT_over_q + reported_barrier_minus_intercept_range_V: [0.1, 0.4] + warning: the published fit supports doping extraction and intercept interpretation, not a precise barrier-height measurement + +limitations: + - the publication does not provide pointwise planar C-V arrays in machine-readable form + - the external device doping and reverse-bias range differ from configs/cSi_homojunction.yaml + - this resource supports interpretation and provenance, not curve-level external validation diff --git a/src/solarlab/materials/data/references/csi_vannijen2025_pn_cv.yaml b/src/solarlab/materials/data/references/csi_vannijen2025_pn_cv.yaml new file mode 100644 index 00000000..e87bfbbb --- /dev/null +++ b/src/solarlab/materials/data/references/csi_vannijen2025_pn_cv.yaml @@ -0,0 +1,141 @@ +schema_version: 1 +topic: dark-csi-pn-small-signal-admittance +evidence_scope: partial_external_comparison + +article: + citation: >- + D. A. van Nijen et al., The nature of silicon PN junction impedance at + high frequency, Solar Energy Materials and Solar Cells 282 (2025) 113383. + doi: https://doi.org/10.1016/j.solmat.2024.113383 + arxiv: https://arxiv.org/abs/2409.06749 + +dataset: + title: Data underlying the publication - The nature of silicon PN junction impedance at high frequency + repository: 4TU.ResearchData + version_doi: https://doi.org/10.4121/19445ed8-c8d5-4204-a8c6-adaa7a55ece3.v1 + landing_page: https://data.4tu.nl/datasets/19445ed8-c8d5-4204-a8c6-adaa7a55ece3 + archive_name: Data and code.zip + license: CC-BY-4.0 + published_md5: 44fbe7b6d50b4c8b3d6d2e8b5ecc4c94 + verified_archive_sha256: 478826a79faad46d705344e34e19a6e18bca1c7b3b8989a5d105baa874d0c67b + +source_model: + solver: Synopsys Sentaurus Device + dimension: 2-D + illumination: dark + temperature_K: 298.15 + device_thickness_m: 2.0e-4 + device_width_m: 5.0e-4 + contact_width_m: 5.0e-5 + bulk_donor_density_m3: 1.0e+21 + emitter_peak_acceptor_density_m3: 1.0e+25 + emitter_profile: Gaussian from the front surface + emitter_fraction_at_half_junction_depth: 0.1 + emitter_half_junction_depth_m: 5.0e-6 + junction_depth_m: 1.0e-5 + srh_lifetime_s: 1.0e-2 + contact_model: ideal contacts with finite lateral width + +source_protocol: + bias_V: [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7] + frequency_range_Hz: [1.0e-5, 1.0e+9] + selected_frequency_Hz: 101996.13 + ac_amplitude: infinitesimal linearized Sentaurus perturbation + raw_columns: [frequency_Hz, conductance_S_cm2, susceptance_S_cm2] + +extraction: + author_code_semantics: + - Restrict the raw frequency series to 1.0e-5 through 1.0e9 Hz. + - Compute Z = 1 / (G + i*B) in ohm*cm2. + - Compute Rs = min(real(Z)) - 0.001 ohm*cm2 independently at each bias. + - Compute Cj = imag(1 / (Z - Rs)) / (2*pi*f) in F/cm2. + - Multiply Cj by 1.0e4 to obtain F/m2. + calibration_parameters: [] + benchmark_bias_window_V: [0.0, 0.2] + benchmark_window_reason: >- + The article identifies 0.0-0.2 V as the depletion-dominated interval; + higher forward bias contains strong diffusion and geometry-dependent + transport contributions that are outside the local 1-D comparison claim. + +selected_rows: + - bias_V: 0.0 + source_file: PN_000mV.csv + source_file_sha256: 61fa6e7f9ed5beb2badda17389089f883349f137988870801115fef1adcf6414 + frequency_Hz: 101996.13 + conductance_S_cm2: 3.8718839e-6 + susceptance_S_cm2: 4.1626226e-3 + series_resistance_ohm_cm2: 0.21635145991162832 + capacitance_F_m2: 6.495369340246841e-5 + used_for_benchmark: true + - bias_V: 0.1 + source_file: PN_100mV.csv + source_file_sha256: 47f68a9315ccdc9dacbe47229c70370305d5afd5a37fc84a957034d20c726d91 + frequency_Hz: 101996.13 + conductance_S_cm2: 3.9925785e-6 + susceptance_S_cm2: 4.1992561e-3 + series_resistance_ohm_cm2: 0.21633457300243383 + capacitance_F_m2: 6.552532616577149e-5 + used_for_benchmark: true + - bias_V: 0.2 + source_file: PN_200mV.csv + source_file_sha256: f118b372a2923767311a5a42053615911243eb287b0bf7101e34cb451402f728 + frequency_Hz: 101996.13 + conductance_S_cm2: 6.9729465e-6 + susceptance_S_cm2: 4.4218250e-3 + series_resistance_ohm_cm2: 0.2164176002650331 + capacitance_F_m2: 6.899838119228747e-5 + used_for_benchmark: true + - bias_V: 0.3 + source_file: PN_300mV.csv + source_file_sha256: c04b8158d1340a827799cefb7a2102454d48db2f30a8de6cfe97a00b7da5ffb8 + frequency_Hz: 101996.13 + conductance_S_cm2: 1.3433777e-4 + susceptance_S_cm2: 5.5552269e-3 + series_resistance_ohm_cm2: 0.2168291834427328 + capacitance_F_m2: 8.668878393836764e-5 + used_for_benchmark: false + - bias_V: 0.4 + source_file: PN_400mV.csv + source_file_sha256: db91763fe7dda4a658462ed98234337f091582edb41ea4a75cff32a940a751b3 + frequency_Hz: 101996.13 + conductance_S_cm2: 6.285159e-3 + susceptance_S_cm2: 1.5153942e-2 + series_resistance_ohm_cm2: 0.2177262334813204 + capacitance_F_m2: 2.3710829477351246e-4 + used_for_benchmark: false + - bias_V: 0.5 + source_file: PN_500mV.csv + source_file_sha256: dfc485e93de551876786439704e455b4cbb82dd5dc888567789741a2155046eb + frequency_Hz: 101996.13 + conductance_S_cm2: 0.30132995 + susceptance_S_cm2: 0.29890271 + series_resistance_ohm_cm2: 0.2145075876787421 + capacitance_F_m2: 5.306040526300128e-3 + used_for_benchmark: false + - bias_V: 0.6 + source_file: PN_600mV.csv + source_file_sha256: db04c6456f9895e44dc81114148ec11bf62d0e8a92f30bebd7b392c2fe6c6d8d + frequency_Hz: 101996.13 + conductance_S_cm2: 4.4387382 + susceptance_S_cm2: 1.1754833 + series_resistance_ohm_cm2: 0.1510956114909705 + capacitance_F_m2: 0.13101508582152919 + used_for_benchmark: false + - bias_V: 0.7 + source_file: PN_700mV.csv + source_file_sha256: c8210809e8dd60c89b6bf625b0270d7914fe45f088fbaf6e326f32224fcbe0f3 + frequency_Hz: 101996.13 + conductance_S_cm2: 15.559938 + susceptance_S_cm2: 1.1841187 + series_resistance_ohm_cm2: 0.05464356134803734 + capacitance_F_m2: 0.694321565160988 + used_for_benchmark: false + +limitations: + - The source data are independent numerical TCAD results, not measurements. + - The source is 2-D with partial-width contacts; SolarLab's benchmark is 1-D. + - The exact proprietary Sentaurus input deck is not included in the dataset. + - Paper-unspecified Sentaurus physics settings cannot be matched exactly. + - SolarLab truncates the negligible Gaussian tail at 15 um to form its mesh subdomains. + - The source uses infinitesimal AC linearization, while SolarLab records a 10 mV nominal reporting amplitude for its linear operator. + - No pointwise uncertainty or experimental error bars are available. diff --git a/src/solarlab/materials/packaged.py b/src/solarlab/materials/packaged.py new file mode 100644 index 00000000..4d522e40 --- /dev/null +++ b/src/solarlab/materials/packaged.py @@ -0,0 +1,294 @@ +"""Packaged immutable default catalog, optical resources, templates, and presets. + +Reads solely from ``importlib.resources`` package assets under +``solarlab.materials.data``, requiring no git checkout or ``perovskite_sim`` +directory when installed from the release wheel. +""" + +from __future__ import annotations + +import hashlib +import importlib +from importlib import resources +import json +from typing import TYPE_CHECKING, Any + +import yaml + +from solarlab.materials.library import LayerTemplate, MaterialLibrary +from solarlab.materials.parameters import LayerValuesInput +from solarlab.materials.source import SourceDocument + +if TYPE_CHECKING: + from solarlab.materials.resources import ResourceLibrary, ResourceTable + +__all__ = [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library", +] + +_DATA_PACKAGE = "solarlab.materials.data" + +_DEFAULT_SOURCE_IDS: tuple[str, ...] = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", +) + +_MODEL_SOURCE_IDS: tuple[str, ...] = ( + "physics/cigs_optics.py", + "models/tunneling_channels.py", +) + +PACKAGED_NK_MATERIALS: tuple[str, ...] = ( + "Ag", + "Au", + "C60", + "Cu", + "FA_Cs_1p77", + "FTO", + "ITO", + "MAPbI3", + "NiOx", + "PCBM", + "PEDOT_PSS", + "SnO2", + "SnPb_1p22", + "TiO2", + "glass", + "spiro_OMeTAD", +) + +PACKAGED_PRESET_NAMES: tuple[str, ...] = ( + "classical_pin", + "scaps_mirror_v2", + "calado2016_ion_sweep", + "calado2016_fig1f", +) + +_SHIPPED_YAML_PRESETS: tuple[str, ...] = ( + "scaps_mirror_v2.yaml", + "calado2016_ion_sweep.yaml", + "calado2016_fig1f.yaml", +) + + +class _StrictYamlMappingLoader(yaml.SafeLoader): + """YAML SafeLoader rejecting duplicate mapping keys.""" + + +def _construct_unique_mapping( + loader: _StrictYamlMappingLoader, node: yaml.MappingNode +) -> dict[str, Any]: + mapping: dict[str, Any] = {} + for key_node, value_node in node.value: + key = loader.construct_object(key_node, deep=True) + if not isinstance(key, str) or key in mapping: + raise ValueError("packaged YAML mapping keys must be unique strings") + mapping[key] = loader.construct_object(value_node, deep=True) + return mapping + + +_StrictYamlMappingLoader.add_constructor( + "tag:yaml.org,2002:map", _construct_unique_mapping +) + + +def _read_data_bytes(*parts: str) -> bytes: + node = resources.files(_DATA_PACKAGE) + for part in parts: + node = node.joinpath(part) + if not node.is_file(): + joined = "/".join(parts) + raise FileNotFoundError(f"missing packaged material data resource: {joined}") + return node.read_bytes() + + +def load_packaged_default_catalog_mapping(profile: str = "full") -> dict[str, Any]: + """Return the frozen ``solarlab.default-catalog.v1`` mapping for ``profile``. + + Supported profiles: + - ``"full"``: complete 15-source catalog including ``complex_defaults`` and + ``experiment_defaults`` (for ``solarlab_server`` and CLI preparation). + - ``"matrix_v2"``: 11-source catalog matching ``ConfigBenchmarkMatrixV2`` + ``preparation_context``. + - ``"device_only"``: 9-source base device/material catalog. + """ + raw = json.loads(_read_data_bytes("default_catalog_v1.json").decode("utf-8")) + if not isinstance(raw, dict): + raise ValueError("invalid packaged default catalog payload") + if profile == "full": + return raw + if profile == "matrix_v2": + keep = set(_DEFAULT_SOURCE_IDS) | set(_MODEL_SOURCE_IDS) + filtered = {k: v for k, v in raw.items() if k != "experiment_defaults"} + filtered["evidence"] = [pair for pair in raw["evidence"] if pair[0] in keep] + return filtered + if profile == "device_only": + keep = set(_DEFAULT_SOURCE_IDS) + filtered = { + k: v + for k, v in raw.items() + if k not in {"complex_defaults", "experiment_defaults"} + } + filtered["evidence"] = [pair for pair in raw["evidence"] if pair[0] in keep] + return filtered + raise ValueError( + f"unknown packaged default catalog profile {profile!r}; " + "expected 'full', 'matrix_v2', or 'device_only'" + ) + + +def load_packaged_default_catalog(profile: str = "full") -> Any: + """Instantiate an immutable ``DefaultCatalog`` from packaged data.""" + defaults_module = importlib.import_module("solarlab.device.defaults") + return defaults_module.DefaultCatalog.from_mapping( + load_packaged_default_catalog_mapping(profile=profile) + ) + + +def load_packaged_nk_table( + material: str, *, source_id_prefix: str = "solarlab/materials/data" +) -> ResourceTable: + """Load one packaged optical ``(wavelength, n, k)`` ``ResourceTable``.""" + from solarlab.materials.resources import ResourceTable + + if material not in PACKAGED_NK_MATERIALS: + raise FileNotFoundError(f"unknown packaged optical material: {material!r}") + prefix = source_id_prefix.rstrip("/") + source_id = f"{prefix}/nk/{material}.csv" if prefix else f"nk/{material}.csv" + content = _read_data_bytes("nk", f"{material}.csv") + return ResourceTable(material, "nk", SourceDocument(source_id, content)) + + +def load_packaged_am15g_table( + *, source_id_prefix: str = "solarlab/materials/data" +) -> ResourceTable: + """Load the packaged AM1.5G spectral photon-flux ``ResourceTable``.""" + from solarlab.materials.resources import ResourceTable + + prefix = source_id_prefix.rstrip("/") + source_id = f"{prefix}/am15g.csv" if prefix else "am15g.csv" + content = _read_data_bytes("am15g.csv") + return ResourceTable("am15g", "spectrum", SourceDocument(source_id, content)) + + +def load_packaged_resource_library( + *, + include_spectrum: bool = True, + source_id_prefix: str = "solarlab/materials/data", +) -> ResourceLibrary: + """Load the packaged optical ``n,k`` (and optional AM1.5G) ``ResourceLibrary``.""" + from solarlab.materials.resources import ResourceLibrary + + tables: list[ResourceTable] = [ + load_packaged_nk_table(name, source_id_prefix=source_id_prefix) + for name in PACKAGED_NK_MATERIALS + ] + if include_spectrum: + tables.append(load_packaged_am15g_table(source_id_prefix=source_id_prefix)) + return ResourceLibrary(tuple(tables)) + + +def load_packaged_nk_manifest_bytes() -> bytes: + """Return raw bytes of packaged ``nk/manifest.yaml``.""" + return _read_data_bytes("nk", "manifest.yaml") + + +def load_packaged_layer_templates_bytes() -> bytes: + """Return raw bytes of packaged ``layer_templates.yaml``.""" + return _read_data_bytes("layer_templates.yaml") + + +def load_packaged_template_library( + *, source_id: str = "solarlab/materials/data/layer_templates.yaml" +) -> MaterialLibrary: + """Load and validate the packaged scalar ``MaterialLibrary``.""" + payload = load_packaged_layer_templates_bytes() + document = yaml.load(payload.decode("utf-8"), Loader=_StrictYamlMappingLoader) + if not isinstance(document, dict): + raise ValueError("packaged layer_templates.yaml must contain a mapping") + expected_fields = { + "role", + "optical_material", + "description", + "source", + "defaults", + } + templates: list[LayerTemplate] = [] + for template_id, record in document.items(): + if not isinstance(record, dict) or set(record) != expected_fields: + raise ValueError( + f"templates.{template_id}: expected {sorted(expected_fields)}" + ) + if not isinstance(record["defaults"], dict): + raise ValueError(f"templates.{template_id}.defaults: expected a mapping") + if "optical_material" in record["defaults"]: + raise ValueError( + f"templates.{template_id}: competing optical_material keys" + ) + values = {**record["defaults"], "optical_material": record["optical_material"]} + normalized = LayerValuesInput.model_validate(values).normalized_items( + complete=True + ) + templates.append( + LayerTemplate( + template_id, + record["role"], + record["description"], + record["source"], + normalized, + ) + ) + return MaterialLibrary( + source_id, hashlib.sha256(payload).hexdigest(), tuple(templates) + ) + + +def load_packaged_preset_sources() -> tuple[SourceDocument, ...]: + """Return ``SourceDocument`` records for all packaged preset configurations.""" + docs: list[SourceDocument] = [] + for filename in _SHIPPED_YAML_PRESETS: + docs.append(SourceDocument(filename, _read_data_bytes("presets", filename))) + for stem in PACKAGED_PRESET_NAMES: + dev_name = f"{stem}.device.json" + docs.append(SourceDocument(dev_name, _read_data_bytes("presets", dev_name))) + return tuple(docs) + + +def load_packaged_preset_v2_documents() -> dict[str, SourceDocument]: + """Return migrated ``solarlab.configuration.v2`` documents keyed by preset stem.""" + result: dict[str, SourceDocument] = {} + for filename in _SHIPPED_YAML_PRESETS: + stem = filename.removesuffix(".yaml") + v2_name = f"{stem}.v2.json" + result[stem] = SourceDocument(v2_name, _read_data_bytes("presets", v2_name)) + return result + + +def load_packaged_preset_device_mapping(name: str) -> dict[str, Any]: + """Load the V2 ``DeviceInput`` JSON mapping for a packaged preset.""" + stem = name.removesuffix(".yaml").removesuffix(".device.json").removesuffix(".json") + if stem not in PACKAGED_PRESET_NAMES: + raise KeyError(f"unknown packaged preset {name!r}") + data = json.loads(_read_data_bytes("presets", f"{stem}.device.json").decode("utf-8")) + if not isinstance(data, dict): + raise ValueError(f"invalid packaged preset device mapping: {stem}") + return data diff --git a/src/solarlab/materials/wheel_hook.py b/src/solarlab/materials/wheel_hook.py new file mode 100644 index 00000000..8442ce07 --- /dev/null +++ b/src/solarlab/materials/wheel_hook.py @@ -0,0 +1,31 @@ +"""Hatchling build hook mapping compiled ``web/dist`` SPA assets into the release.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from hatchling.builders.hooks.plugin.interface import BuildHookInterface + +__all__ = ["WebDistBuildHook"] + + +class WebDistBuildHook(BuildHookInterface): + """Bundle ``web/dist/**`` into ``solarlab_server/_web_dist/**`` when present.""" + + def initialize(self, version: str, build_data: dict[str, Any]) -> None: + if version == "editable": + return + web_dist = Path(self.root) / "web" / "dist" + if not web_dist.is_dir(): + return + force_include = build_data.setdefault("force_include", {}) + for path in sorted(web_dist.rglob("*")): + if path.is_file() and path.name != ".DS_Store": + rel = path.relative_to(web_dist).as_posix() + target = ( + f"web/dist/{rel}" + if self.target_name == "sdist" + else f"solarlab_server/_web_dist/{rel}" + ) + force_include[str(path)] = target diff --git a/src/solarlab/reproducibility/PublicAPI.json b/src/solarlab/reproducibility/PublicAPI.json index 0d431de6..a2e727ce 100644 --- a/src/solarlab/reproducibility/PublicAPI.json +++ b/src/solarlab/reproducibility/PublicAPI.json @@ -206,7 +206,43 @@ "PreparedSpatialExperiment", "prepare_spatial_experiment" ], - "solarlab.materials": [], + "solarlab.cli": [ + "main", + "server_main" + ], + "solarlab.materials": [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library" + ], + "solarlab.materials.packaged": [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library" + ], + "solarlab.materials.wheel_hook": [ + "WebDistBuildHook" + ], "solarlab.materials.full_parameters": [ "ParameterFieldsInput", "StructuredInput", @@ -1515,7 +1551,43 @@ "RunStore", "StateConflict" ], - "solarlab.materials": [], + "solarlab.cli": [ + "main", + "server_main" + ], + "solarlab.materials": [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library" + ], + "solarlab.materials.packaged": [ + "PACKAGED_NK_MATERIALS", + "PACKAGED_PRESET_NAMES", + "load_packaged_am15g_table", + "load_packaged_default_catalog", + "load_packaged_default_catalog_mapping", + "load_packaged_layer_templates_bytes", + "load_packaged_nk_manifest_bytes", + "load_packaged_nk_table", + "load_packaged_preset_device_mapping", + "load_packaged_preset_sources", + "load_packaged_preset_v2_documents", + "load_packaged_resource_library", + "load_packaged_template_library" + ], + "solarlab.materials.wheel_hook": [ + "WebDistBuildHook" + ], "solarlab.materials.full_parameters": [ "FullParameterInput", "LAYER_OWNED_PARAMETERS", diff --git a/src/solarlab/reproducibility/release.py b/src/solarlab/reproducibility/release.py index b5d5efe4..7ea8b8c3 100644 --- a/src/solarlab/reproducibility/release.py +++ b/src/solarlab/reproducibility/release.py @@ -61,7 +61,12 @@ def __post_init__(self) -> None: raise ValueError("release requires a known content role and bounded immutable bytes") prefix = next((value for value in ("src/", "perovskite-sim/") if self.source_path.startswith(value) and self.source_path[len(value):].split("/")[0] in (*_PACKAGES, "perovskite_sim")), None) - expected = "site/" + self.source_path[len(prefix):] if prefix else "share/" + self.source_path + if prefix is not None: + expected = "site/" + self.source_path[len(prefix):] + elif self.source_path.startswith("web/dist/") and len(self.source_path) > len("web/dist/"): + expected = "site/solarlab_server/_web_dist/" + self.source_path[len("web/dist/"):] + else: + expected = "share/" + self.source_path if self.path != expected or self.role == "package" and prefix is None: raise ValueError("release source-to-install mapping is not the declared package/data layout") @@ -202,6 +207,12 @@ def snapshot_release_bundle( source = path.relative_to(root).as_posix() target = f"site/{package}/" + path.relative_to(folder).as_posix() values[source] = ReleaseFile(source, target, required.pop(source, "package"), _contained(root, source).read_bytes()) + web_dist = root / "web/dist" + if profile == "target" and web_dist.is_dir(): + for path in _files(web_dist): + source = path.relative_to(root).as_posix() + target = "site/solarlab_server/_web_dist/" + path.relative_to(web_dist).as_posix() + values[source] = ReleaseFile(source, target, required.pop(source, "resource"), _contained(root, source).read_bytes()) for source, role in required.items(): values[source] = ReleaseFile(source, "share/" + relative_path(source), role, _contained(root, source).read_bytes()) return ReleaseBundle(build_source_commit, profile, tuple(values.values())) diff --git a/tests/refactor/test_legacy_behavior_execution.py b/tests/refactor/test_legacy_behavior_execution.py index 59a37385..d1198df0 100644 --- a/tests/refactor/test_legacy_behavior_execution.py +++ b/tests/refactor/test_legacy_behavior_execution.py @@ -28,6 +28,7 @@ import time started = time.monotonic_ns() +sys.path.insert(0, sys.argv[3]) request = json.loads(sys.argv[2]) assert all(os.environ.get(key) == value for key, value in request.items()) from perovskite_sim.solver import mol @@ -104,7 +105,8 @@ def start(snapshot): VECLIB_MAXIMUM_THREADS="1", NUMEXPR_NUM_THREADS="1", PYTHONDONTWRITEBYTECODE="1") return subprocess.Popen( [sys.executable, "-I", "-B", "-c", _OBSERVER, - str(ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml"), json.dumps(snapshot)], + str(ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml"), json.dumps(snapshot), + str(package_root.parent)], env=child_environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) diff --git a/tests/refactor/test_package_preparation.py b/tests/refactor/test_package_preparation.py index bb12c4a3..ac3eb2e5 100644 --- a/tests/refactor/test_package_preparation.py +++ b/tests/refactor/test_package_preparation.py @@ -1,4 +1,4 @@ -"""P03 package boundaries; production numerical migration is a separate gate.""" +"""P03/P09 package boundaries, target wheel/sdist exclusions, and console scripts.""" from __future__ import annotations @@ -14,41 +14,70 @@ ROOT = Path(__file__).resolve().parents[2] PACKAGES = ("solarlab", "solarlab_research", "solarlab_server") +EXPECTED_SCRIPTS = { + "solarlab": "solarlab.cli:main", + "solarlab-server": "solarlab.cli:server_main", + "solarlab-cbo-scan": "solarlab_research.scripts.cbo_scan:main", + "solarlab-r1-short-window": "solarlab_research.scripts.r1_short_window:main", + "solarlab-r1-verify-sources": "solarlab_research.scripts.r1_verify_sources:main", +} -def test_transition_lock_preserves_every_existing_dependency_record(): - old = tomllib.loads((ROOT / "perovskite-sim/uv.lock").read_text()) +def test_release_lock_and_console_scripts_preserve_locked_dependencies(): new = tomllib.loads((ROOT / "uv.lock").read_text()) - old_packages = [p for p in old["package"] if p["name"] != "perovskite-sim"] new_packages = [p for p in new["package"] if p["name"] != "solarlab"] - # The new optional Arb observer is the only additional locked package. - assert [p for p in new_packages if p["name"] != "python-flint"] == old_packages added = [p for p in new_packages if p["name"] == "python-flint"] assert len(added) == 1 and added[0]["version"] == "0.8.0" - assert new["requires-python"] == old["requires-python"] - assert new["resolution-markers"] == old["resolution-markers"] - old_metadata = tomllib.loads((ROOT / "perovskite-sim/pyproject.toml").read_text()) + legacy_lock = ROOT / "perovskite-sim/uv.lock" + if legacy_lock.is_file(): + old = tomllib.loads(legacy_lock.read_text()) + old_packages = [p for p in old["package"] if p["name"] != "perovskite-sim"] + assert [p for p in new_packages if p["name"] != "python-flint"] == old_packages + assert new["requires-python"] == old["requires-python"] + assert new["resolution-markers"] == old["resolution-markers"] + metadata = tomllib.loads((ROOT / "pyproject.toml").read_text()) assert metadata["project"]["requires-python"] == ">=3.11" - assert metadata["project"]["dependencies"] == [ - *old_metadata["project"]["dependencies"], "pydantic==2.13.5", - ] - previous_extras = old_metadata["project"]["optional-dependencies"] - extras = metadata["project"]["optional-dependencies"] - expected_dev = list(previous_extras["dev"]) - expected_dev.insert(expected_dev.index("httpx==0.28.1") + 1, "jsonschema==4.26.0") - assert extras == {**previous_extras, "dev": expected_dev, "arb": ["python-flint==0.8.0"]} - assert "scripts" not in metadata["project"] - - -def test_only_the_declared_packages_are_selected_for_the_transition_wheel(): + assert metadata["project"]["scripts"] == EXPECTED_SCRIPTS + + legacy_pyproject = ROOT / "perovskite-sim/pyproject.toml" + if legacy_pyproject.is_file(): + old_metadata = tomllib.loads(legacy_pyproject.read_text()) + assert metadata["project"]["dependencies"] == [ + *old_metadata["project"]["dependencies"], + "pydantic==2.13.5", + ] + previous_extras = old_metadata["project"]["optional-dependencies"] + extras = metadata["project"]["optional-dependencies"] + expected_dev = list(previous_extras["dev"]) + expected_dev.insert( + expected_dev.index("httpx==0.28.1") + 1, "jsonschema==4.26.0" + ) + assert extras == { + **previous_extras, + "dev": expected_dev, + "arb": ["python-flint==0.8.0"], + } + + +def test_only_first_party_packages_and_web_assets_are_selected_for_the_release_wheel(): metadata = tomllib.loads((ROOT / "pyproject.toml").read_text()) wheel = metadata["tool"]["hatch"]["build"]["targets"]["wheel"] - assert set(wheel["only-include"]) == { - *(f"src/{name}" for name in PACKAGES), - "perovskite-sim/perovskite_sim", - } - assert set(wheel["sources"]) == {"src", "perovskite-sim"} + assert set(wheel["only-include"]) == {f"src/{name}" for name in PACKAGES} + assert wheel["sources"] == ["src"] + assert ( + wheel["hooks"]["custom"]["path"] + == "src/solarlab/materials/wheel_hook.py" + ) + sdist = metadata["tool"]["hatch"]["build"]["targets"]["sdist"] + assert not any( + entry.startswith(("perovskite-sim", "perovskite_sim")) + for entry in sdist["only-include"] + ) + assert ( + sdist["hooks"]["custom"]["path"] + == "src/solarlab/materials/wheel_hook.py" + ) assert not (ROOT / "src/perovskite_sim").exists() for name in PACKAGES: assert (ROOT / "src" / name / "py.typed").is_file() @@ -65,16 +94,21 @@ def find_spec(self, fullname, path=None, target=None): sys.meta_path.insert(0, Boundary()) sys.path.insert(0, sys.argv[1]) import solarlab +import solarlab.materials import solarlab.physics.registry import solarlab.physics.selection import solarlab.physics.presets import solarlab.experiments.registry assert solarlab.__all__ == () +assert solarlab.materials.load_packaged_default_catalog().content_sha256 assert not any(name.startswith(('perovskite_sim', 'backend', 'solarlab_server', 'solarlab_research')) for name in sys.modules) """ result = subprocess.run( [sys.executable, "-I", "-B", "-c", script, str(ROOT / "src")], - cwd=tmp_path, capture_output=True, text=True, timeout=30, + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, ) assert result.returncode == 0, result.stdout + result.stderr @@ -86,7 +120,11 @@ def run_import_contracts(package_root: Path, cwd: Path): executable = Path(sys.executable).parent / "lint-imports" return subprocess.run( [str(executable), "--config", str(ROOT / "pyproject.toml"), "--no-cache"], - cwd=cwd, env=env, capture_output=True, text=True, timeout=30, + cwd=cwd, + env=env, + capture_output=True, + text=True, + timeout=30, ) @@ -103,6 +141,8 @@ def test_import_linter_accepts_actual_package_sources(tmp_path): ("solarlab", "perovskite_sim", False), ("solarlab", "backend", False), ("solarlab", "perovskite_sim", True), + ("solarlab_research", "perovskite_sim", False), + ("solarlab_research", "backend", False), ("solarlab_research", "solarlab_server", False), ("solarlab_server", "solarlab_research", False), ("solarlab.materials", "solarlab.config", False), @@ -115,7 +155,7 @@ def test_import_linter_accepts_actual_package_sources(tmp_path): ], ) def test_import_linter_rejects_actual_direct_and_indirect_violations( - tmp_path, source, forbidden, indirect, + tmp_path, source, forbidden, indirect ): for name in PACKAGES: shutil.copytree(ROOT / "src" / name, tmp_path / name) diff --git a/tests/refactor/test_release_bundle.py b/tests/refactor/test_release_bundle.py index 23ae0343..240767d1 100644 --- a/tests/refactor/test_release_bundle.py +++ b/tests/refactor/test_release_bundle.py @@ -1,9 +1,11 @@ -"""Genuine frozen Git sources, wheel installation and complete content checks. +"""Genuine frozen Git sources, target wheel/sdist installation and content checks. The working authoring validator is not relabelled as part of an older commit. -The isolated package is built exclusively from the real named Git snapshot; -the current validator independently checks the resulting bytes and origins. +The isolated target package is built exclusively from the real named Git +snapshot without ``perovskite_sim``; the current validator independently checks +the resulting bytes, packaged material data, web assets, and module origins. """ + from dataclasses import FrozenInstanceError, replace import hashlib import io @@ -13,34 +15,59 @@ import subprocess import sys import tarfile +import zipfile import pytest +from solarlab.config.identity import ( + ExecutionEngine, + execution_identity, + execution_manifest, + verify_execution_manifest, +) from solarlab.materials.source import SourceDocument -from solarlab.config.identity import ExecutionEngine, execution_identity, execution_manifest, verify_execution_manifest from solarlab.reproducibility.release import ( - ReleaseFile, read_release_bundle, snapshot_release_bundle, - verify_release_installation, write_release_bundle, + ReleaseBundle, + ReleaseFile, + read_release_bundle, + snapshot_release_bundle, + verify_release_installation, + write_release_bundle, +) +from test_execution_identity_preparation import ( + device as device, + execution as execution, + identity_inputs, ) -from test_execution_identity_preparation import device as device, execution as execution, identity_inputs ROOT = Path(__file__).resolve().parents[2] REQUIRED = ( - ("uv.lock", "dependency_lock"), ("pyproject.toml", "build_configuration"), + ("uv.lock", "dependency_lock"), + ("pyproject.toml", "build_configuration"), ("src/solarlab/config/identity.py", "validator"), ("src/solarlab/reproducibility/sources.py", "validator"), ("src/solarlab/reproducibility/PublicAPI.json", "contract"), ("reproducibility/RefactorTransitionBoundariesV1.json", "contract"), - ("perovskite-sim/perovskite_sim/data/nk/MAPbI3.csv", "resource"), + ("src/solarlab/materials/data/nk/MAPbI3.csv", "resource"), ("scripts/generate_configuration_schema.py", "build_configuration"), ("generated/configuration-schema.json", "generated_schema"), ) -MODULES = ("solarlab.config.identity", "solarlab.config.schema", "solarlab.experiments.jv.preparation", - "solarlab.sweeps.preparation", "solarlab_server", "solarlab_research") +MODULES = ( + "solarlab.cli", + "solarlab.config.identity", + "solarlab.config.schema", + "solarlab.experiments.jv.preparation", + "solarlab.materials", + "solarlab.sweeps.preparation", + "solarlab_server", + "solarlab_research", +) def command(args, cwd): - result = subprocess.run([str(item) for item in args], cwd=cwd, capture_output=True, timeout=120) + result = subprocess.run( + [str(item) for item in args], cwd=cwd, capture_output=True, timeout=120 + ) assert result.returncode == 0, result.stdout.decode() + result.stderr.decode() return result.stdout @@ -49,81 +76,191 @@ def command(args, cwd): def frozen(tmp_path_factory): root = tmp_path_factory.mktemp("actual-build-source") commit = command(["git", "rev-parse", "HEAD"], ROOT).decode().strip() - paths = ("src", "perovskite-sim/perovskite_sim", "uv.lock", "pyproject.toml", - "reproducibility/RefactorTransitionBoundariesV1.json", "scripts/generate_configuration_schema.py") + paths = ( + "src", + "uv.lock", + "pyproject.toml", + "reproducibility/RefactorTransitionBoundariesV1.json", + "reproducibility/ScapsComparisonContractV1.json", + "reproducibility/HysteresisReferenceContractV1.json", + "reproducibility/HysteresisReferenceContractV2.json", + "reproducibility/PerformanceCasesV1.json", + "scripts/generate_configuration_schema.py", + "examples/research_1d", + "examples/research_2d", + "tests/integration/test_research_1d_workflow.py", + "tests/refactor", + "tests/runtime", + "web", + ".gitignore", + ) archive = command(["git", "archive", commit, "--", *paths], ROOT) with tarfile.open(fileobj=io.BytesIO(archive)) as tar: for member in tar.getmembers(): path = root / member.name - assert path.resolve().is_relative_to(root) and (member.isdir() or member.isfile()) + assert path.resolve().is_relative_to(root) and ( + member.isdir() or member.isfile() + ) if member.isfile(): path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(tar.extractfile(member).read()) - content = command([sys.executable, "-I", "-B", "-c", """ + extracted = tar.extractfile(member) + assert extracted is not None + path.write_bytes(extracted.read()) + # Include prebuilt web/dist if present in checkout, or materialize minimal + # deterministic SPA entry so target wheel/sdist web_dist bundling is verified. + checkout_dist = ROOT / "web/dist" + target_dist = root / "web/dist" + if checkout_dist.is_dir(): + shutil.copytree(checkout_dist, target_dist) + else: + target_dist.mkdir(parents=True, exist_ok=True) + (target_dist / "index.html").write_bytes( + b"SolarLab\n" + ) + content = command( + [ + sys.executable, + "-I", + "-B", + "-c", + """ import sys sys.path.insert(0, sys.argv[1]) from solarlab.config.schema import configuration_schema_representation sys.stdout.buffer.write(configuration_schema_representation()[0]) -""", root / "src"], root) +""", + root / "src", + ], + root, + ) (root / "generated").mkdir() (root / "generated/configuration-schema.json").write_bytes(content) - bundle = snapshot_release_bundle(root, build_source_commit=commit, profile="transition", required_files=REQUIRED) + bundle = snapshot_release_bundle( + root, build_source_commit=commit, profile="target", required_files=REQUIRED + ) return root, bundle -def test_complete_actual_source_bundle_is_immutable_and_preserves_commit_meaning(frozen): +def test_complete_actual_source_bundle_is_immutable_and_preserves_commit_meaning( + frozen, +): source, bundle = frozen + assert bundle.profile == "target" + assert not any( + item.path.startswith("site/perovskite_sim/") for item in bundle.files + ) + assert any( + item.path == "site/solarlab_server/_web_dist/index.html" + for item in bundle.files + ) records = bundle.export() assert records["build_source_commit"] == bundle.build_source_commit - assert records["historical_source_algorithms"] == "unchanged" and not records["scientific_qualification"] + assert ( + records["historical_source_algorithms"] == "unchanged" + and not records["scientific_qualification"] + ) assert hashlib.sha256(bundle.canonical_json).hexdigest() == bundle.sha256 assert not bundle.can_execute - expected = {path.relative_to(source).as_posix() for name in ("solarlab", "solarlab_server", "solarlab_research") - for path in (source / "src" / name).rglob("*") if path.is_file()} + expected = { + path.relative_to(source).as_posix() + for name in ("solarlab", "solarlab_server", "solarlab_research") + for path in (source / "src" / name).rglob("*") + if path.is_file() + } assert expected <= {item.source_path for item in bundle.files} - assert all(item.content == (source / item.source_path).read_bytes() for item in bundle.files) - assert any(item.path.endswith("/py.typed") and item.content == b"" for item in bundle.files) + assert all( + item.content == (source / item.source_path).read_bytes() + for item in bundle.files + ) + assert any( + item.path.endswith("/py.typed") and item.content == b"" + for item in bundle.files + ) build = bundle.implementation() assert build.build_source_commit == bundle.build_source_commit - assert any(item.id == "src/solarlab/config/identity.py" for item in build.files) - assert next(item.content for item in build.files if item.id == "release:content-manifest.v1") == bundle.canonical_json - assert any(item.id == "generated/configuration-schema.json" for item in build.files) - assert {item.role for item in bundle.files} == {role for _, role in REQUIRED} | {"package"} + assert any( + item.id == "src/solarlab/config/identity.py" for item in build.files + ) + assert ( + next( + item.content + for item in build.files + if item.id == "release:content-manifest.v1" + ) + == bundle.canonical_json + ) + assert any( + item.id == "generated/configuration-schema.json" for item in build.files + ) + assert {item.role for item in bundle.files} == { + role for _, role in REQUIRED + } | {"package"} with pytest.raises(FrozenInstanceError): - bundle.profile = "target" + bundle.profile = "transition" # type: ignore[misc] assert replace(bundle, build_source_commit="3" * 40).sha256 != bundle.sha256 records["files"].clear() assert bundle.export()["files"] -def test_complete_release_implementation_fits_the_real_execution_manifest(frozen, device, execution): +def test_complete_release_implementation_fits_the_real_execution_manifest( + frozen, device, execution +): bundle = frozen[1] description = replace(execution, implementation=bundle.implementation()) inputs, engine = identity_inputs(device), ExecutionEngine("solarlab") manifest = execution_manifest(inputs, description, engine=engine) - assert len(manifest.canonical_json) > 2**23 - assert len(manifest.export()["document"]["implementation_content"]) == len(description.implementation.files) - result = verify_execution_manifest(manifest, inputs, description, engine=engine, - environment=description.environment, expected_sha256=manifest.sha256) + assert len(manifest.canonical_json) > 2**21 + assert len(manifest.export()["document"]["implementation_content"]) == len( + description.implementation.files + ) + result = verify_execution_manifest( + manifest, + inputs, + description, + engine=engine, + environment=description.environment, + expected_sha256=manifest.sha256, + ) assert result.sha256 == manifest.execution_sha256 and not result.cache_eligible -def test_generated_schema_and_empty_marker_records_remain_execution_bound(frozen, device, execution): +def test_generated_schema_and_empty_marker_records_remain_execution_bound( + frozen, device, execution +): bundle = frozen[1] - changed = replace(bundle, files=tuple(replace(item, content=item.content+b"\n") - if item.role == "generated_schema" else item for item in bundle.files)) + changed = replace( + bundle, + files=tuple( + replace(item, content=item.content + b"\n") + if item.role == "generated_schema" + else item + for item in bundle.files + ), + ) inputs, engine = identity_inputs(device), ExecutionEngine("solarlab") - first = execution_identity(inputs, replace(execution, implementation=bundle.implementation()), engine=engine) - second = execution_identity(inputs, replace(execution, implementation=changed.implementation()), engine=engine) + first = execution_identity( + inputs, replace(execution, implementation=bundle.implementation()), engine=engine + ) + second = execution_identity( + inputs, + replace(execution, implementation=changed.implementation()), + engine=engine, + ) assert first.sha256 != second.sha256 - assert {item["source_path"] for item in bundle.export()["files"] if item["bytes"] == 0} + assert { + item["source_path"] for item in bundle.export()["files"] if item["bytes"] == 0 + } -def test_bundle_roundtrip_preserves_every_byte_and_rejects_existing_destination(frozen, tmp_path): +def test_bundle_roundtrip_preserves_every_byte_and_rejects_existing_destination( + frozen, tmp_path +): bundle = frozen[1] output = tmp_path / "release" write_release_bundle(bundle, output) - manifest = SourceDocument("ReleaseBundle.json", (output / "ReleaseBundle.json").read_bytes()) + manifest = SourceDocument( + "ReleaseBundle.json", (output / "ReleaseBundle.json").read_bytes() + ) loaded = read_release_bundle(manifest, output, expected_sha256=bundle.sha256) assert loaded == bundle with pytest.raises(FileExistsError): @@ -132,7 +269,9 @@ def test_bundle_roundtrip_preserves_every_byte_and_rejects_existing_destination( read_release_bundle(manifest, output, expected_sha256="0" * 64) -@pytest.mark.parametrize("role", ["dependency_lock", "generated_schema", "validator", "contract", "resource"]) +@pytest.mark.parametrize( + "role", ["dependency_lock", "generated_schema", "validator", "contract", "resource"] +) def test_missing_required_role_refuses(frozen, role): bundle = frozen[1] with pytest.raises(ValueError, match="missing"): @@ -142,75 +281,228 @@ def test_missing_required_role_refuses(frozen, role): def test_target_profile_excludes_legacy_and_paths_are_explicit(frozen): bundle = frozen[1] with pytest.raises(ValueError, match="legacy"): - replace(bundle, profile="target") - for source, path in (("../code.py", "share/code.py"), ("src/solarlab/a.py", "site/solarlab/b.py")): + replace(bundle, profile="transition") + with pytest.raises(ValueError, match="legacy"): + replace( + bundle, + files=( + *bundle.files, + ReleaseFile( + "perovskite-sim/perovskite_sim/__init__.py", + "site/perovskite_sim/__init__.py", + "package", + b"", + ), + ), + ) + for source, path in ( + ("../code.py", "share/code.py"), + ("src/solarlab/a.py", "site/solarlab/b.py"), + ): with pytest.raises(ValueError): ReleaseFile(source, path, "package", b"pass\n") with pytest.raises(ValueError, match="duplicate"): replace(bundle, files=(*bundle.files, bundle.files[0])) +def test_historical_transition_profile_manifest_remains_verifiable(frozen, tmp_path): + """Historical transition bundles remain readable without changing v1 schema.""" + bundle = frozen[1] + legacy_init = ReleaseFile( + "perovskite-sim/perovskite_sim/__init__.py", + "site/perovskite_sim/__init__.py", + "package", + b"# historical transition marker\n", + ) + transition_bundle = ReleaseBundle( + bundle.build_source_commit, + "transition", + (*bundle.files, legacy_init), + ) + assert transition_bundle.profile == "transition" + out = tmp_path / "historical-transition" + write_release_bundle(transition_bundle, out) + manifest = SourceDocument( + "ReleaseBundle.json", (out / "ReleaseBundle.json").read_bytes() + ) + assert ( + read_release_bundle( + manifest, out, expected_sha256=transition_bundle.sha256 + ) + == transition_bundle + ) + + @pytest.fixture(scope="module") def installation(frozen, tmp_path_factory): source, bundle = frozen root = tmp_path_factory.mktemp("isolated-wheel") uv = shutil.which("uv") if uv is None: - pytest.skip("release installation requires uv on PATH; CI installs the pinned uv build tool") - command([uv, "build", "--offline", "--wheel", "--python", sys.executable, "--out-dir", root / "wheels", source], root) - wheel, = (root / "wheels").glob("*.whl") + pytest.skip( + "release installation requires uv on PATH; CI installs the pinned uv build tool" + ) + command( + [ + uv, + "build", + "--offline", + "--python", + sys.executable, + "--out-dir", + root / "dist", + source, + ], + root, + ) + (wheel,) = (root / "dist").glob("*.whl") + (sdist,) = (root / "dist").glob("*.tar.gz") + with zipfile.ZipFile(wheel) as zf: + wnames = zf.namelist() + assert not any( + n.startswith(("perovskite_sim/", "perovskite-sim/", "backend/")) + for n in wnames + ), wnames + assert "solarlab/materials/data/default_catalog_v1.json" in wnames + assert "solarlab_server/_web_dist/index.html" in wnames + with tarfile.open(sdist) as tf: + snames = tf.getnames() + assert not any( + "perovskite-sim/" in n or "perovskite_sim/" in n for n in snames + ), snames + assert any(n.endswith("/web/dist/index.html") for n in snames), snames + installed = root / "installed" - command([uv, "pip", "install", "--offline", "--no-deps", "--python", sys.executable, - "--target", installed / "site", wheel], root) + command( + [ + uv, + "pip", + "install", + "--offline", + "--no-deps", + "--python", + sys.executable, + "--target", + installed / "site", + wheel, + ], + root, + ) for item in bundle.files: if item.path.startswith("share/"): path = installed / item.path path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(item.content) script = """ -import hashlib, importlib, importlib.metadata, json, pathlib, sys +import hashlib, importlib, importlib.metadata, importlib.util, json, pathlib, sys site = pathlib.Path(sys.argv[1]) -sys.path.insert(0, str(site)) +sys.path = [str(site)] + [p for p in sys.path if p] +assert importlib.util.find_spec('perovskite_sim') is None +assert importlib.util.find_spec('backend') is None +for forbidden in ('perovskite_sim', 'backend'): + try: + importlib.import_module(forbidden) + except ModuleNotFoundError: + pass + else: + raise AssertionError(f'{forbidden} must not be importable from target wheel') for name in json.loads(sys.argv[2]): importlib.import_module(name) from solarlab.config.schema import configuration_schema_representation +from solarlab.materials import ( + load_packaged_default_catalog, + load_packaged_resource_library, + load_packaged_template_library, +) +cat = load_packaged_default_catalog() +res = load_packaged_resource_library() +tmpl = load_packaged_template_library() +assert res.get('MAPbI3', 'nk').shape[1] == 3 +assert res.get('am15g', 'spectrum').shape[1] == 2 +assert len(tmpl.templates) > 0 assert pathlib.Path(importlib.metadata.distribution('solarlab').locate_file('')).resolve() == site.resolve() roots = {'solarlab', 'solarlab_research', 'solarlab_server', 'perovskite_sim'} origins = sorted((name, str(pathlib.Path(module.__file__).resolve())) for name, module in sys.modules.items() if name.split('.')[0] in roots) -print(json.dumps(dict(module_origins=origins, schema_sha256=hashlib.sha256(configuration_schema_representation()[0]).hexdigest()))) +print(json.dumps(dict( + module_origins=origins, + schema_sha256=hashlib.sha256(configuration_schema_representation()[0]).hexdigest(), + default_catalog_sha256=cat.content_sha256, +))) """ - actual = json.loads(command([sys.executable, "-I", "-B", "-c", script, installed / "site", json.dumps(MODULES)], root)) + actual = json.loads( + command( + [ + sys.executable, + "-I", + "-B", + "-c", + script, + installed / "site", + json.dumps(MODULES), + ], + root, + ) + ) return installed, actual, wheel -def test_actual_wheel_installed_outside_checkout_matches_every_source_and_schema(frozen, installation, record_property): +def test_actual_wheel_installed_outside_checkout_matches_every_source_and_schema( + frozen, installation, record_property +): bundle = frozen[1] root, actual, _ = installation maintained_head = command(["git", "rev-parse", "HEAD"], ROOT).decode().strip() - result = verify_release_installation(bundle, root, expected_sha256=bundle.sha256, - module_origins=tuple(map(tuple, actual["module_origins"])), required_modules=MODULES, - current_repository_head=maintained_head) + result = verify_release_installation( + bundle, + root, + expected_sha256=bundle.sha256, + module_origins=tuple(map(tuple, actual["module_origins"])), + required_modules=MODULES, + current_repository_head=maintained_head, + ) assert result["source_installation_verified"] and not result["scientific_qualification"] assert result["build_source_commit"] == bundle.build_source_commit assert result["current_repository_head"] == maintained_head assert result["files_verified"] == len(bundle.files) - schema, = (item for item in bundle.files if item.role == "generated_schema") + (schema,) = (item for item in bundle.files if item.role == "generated_schema") assert actual["schema_sha256"] == hashlib.sha256(schema.content).hexdigest() - assert all(not Path(origin).is_relative_to(ROOT) for _, origin in actual["module_origins"]) - record_property("release_check", json.dumps({**result, "bundle": bundle.export(), - "wheel_sha256": hashlib.sha256(installation[2].read_bytes()).hexdigest(), - "schema_sha256": actual["schema_sha256"], "all_source_bytes_equal": True})) + assert actual["default_catalog_sha256"] + assert all( + not Path(origin).is_relative_to(ROOT) for _, origin in actual["module_origins"] + ) + record_property( + "release_check", + json.dumps( + { + **result, + "bundle": bundle.export(), + "wheel_sha256": hashlib.sha256(installation[2].read_bytes()).hexdigest(), + "schema_sha256": actual["schema_sha256"], + "all_source_bytes_equal": True, + } + ), + ) -def test_maintenance_head_observation_cannot_replace_the_build_commit(frozen, installation): +def test_maintenance_head_observation_cannot_replace_the_build_commit( + frozen, installation +): bundle = frozen[1] root, actual, _ = installation previous = command(["git", "rev-parse", "HEAD^"], ROOT).decode().strip() - result = verify_release_installation(bundle, root, expected_sha256=bundle.sha256, - module_origins=tuple(map(tuple, actual["module_origins"])), required_modules=MODULES, - current_repository_head=previous) + result = verify_release_installation( + bundle, + root, + expected_sha256=bundle.sha256, + module_origins=tuple(map(tuple, actual["module_origins"])), + required_modules=MODULES, + current_repository_head=previous, + ) assert result["current_repository_head"] == previous - assert result["bundle_sha256"] == bundle.sha256 and result["build_source_commit"] == bundle.build_source_commit + assert ( + result["bundle_sha256"] == bundle.sha256 + and result["build_source_commit"] == bundle.build_source_commit + ) def test_checkout_fallback_and_missing_entry_origin_refuse(frozen, installation): @@ -219,70 +511,137 @@ def test_checkout_fallback_and_missing_entry_origin_refuse(frozen, installation) origins = dict(actual["module_origins"]) origins["solarlab.config.identity"] = str(ROOT / "src/solarlab/config/identity.py") with pytest.raises(ValueError, match="editable/unbound"): - verify_release_installation(bundle, root, expected_sha256=bundle.sha256, - module_origins=tuple(origins.items()), required_modules=MODULES) + verify_release_installation( + bundle, + root, + expected_sha256=bundle.sha256, + module_origins=tuple(origins.items()), + required_modules=MODULES, + ) del origins["solarlab.config.identity"] with pytest.raises(ValueError, match="required module"): - verify_release_installation(bundle, root, expected_sha256=bundle.sha256, - module_origins=tuple(origins.items()), required_modules=MODULES) - - -@pytest.mark.parametrize("change", ["package", "lock", "schema", "resource", "contract", "extra", "bytecode", "symlink"]) -def test_changed_installed_source_data_and_unbound_content_refuse(frozen, tmp_path, change): + verify_release_installation( + bundle, + root, + expected_sha256=bundle.sha256, + module_origins=tuple(origins.items()), + required_modules=MODULES, + ) + + +@pytest.mark.parametrize( + "change", + [ + "package", + "lock", + "schema", + "resource", + "contract", + "extra", + "bytecode", + "symlink", + ], +) +def test_changed_installed_source_data_and_unbound_content_refuse( + frozen, tmp_path, change +): bundle = frozen[1] root = tmp_path / "installed" write_release_bundle(bundle, root) - selected = {"package": "site/solarlab/config/identity.py", "lock": "share/uv.lock", - "schema": "share/generated/configuration-schema.json", - "resource": "site/perovskite_sim/data/nk/MAPbI3.csv", - "contract": "share/reproducibility/RefactorTransitionBoundariesV1.json"} + selected = { + "package": "site/solarlab/config/identity.py", + "lock": "share/uv.lock", + "schema": "share/generated/configuration-schema.json", + "resource": "site/solarlab/materials/data/nk/MAPbI3.csv", + "contract": "share/reproducibility/RefactorTransitionBoundariesV1.json", + } if change in selected: path = root / selected[change] path.write_bytes(path.read_bytes() + b"\n") elif change in {"extra", "bytecode"}: - path = root / "site/solarlab" / ("unbound.py" if change == "extra" else "unbound.pyc") + path = root / "site/solarlab" / ( + "unbound.py" if change == "extra" else "unbound.pyc" + ) path.write_bytes(b"unbound") else: path = root / "site/solarlab/config/identity.py" path.unlink() path.symlink_to(ROOT / "src/solarlab/config/identity.py") with pytest.raises(ValueError, match="changed|unbound|escapes"): - verify_release_installation(bundle, root, expected_sha256=bundle.sha256, - module_origins=(("solarlab", str(root / "site/solarlab/__init__.py")),), required_modules=("solarlab",)) - - -def test_release_job_provenance_keeps_full_pins_and_strict_source_policy(frozen, tmp_path): + verify_release_installation( + bundle, + root, + expected_sha256=bundle.sha256, + module_origins=(("solarlab", str(root / "site/solarlab/__init__.py")),), + required_modules=("solarlab",), + ) + + +def test_release_job_provenance_keeps_full_pins_and_strict_source_policy( + frozen, tmp_path +): bundle = frozen[1] original = bundle.canonical_json - recorded = bundle.job_provenance({"declared_input": "source-only test"}, operator="test.release") + recorded = bundle.job_provenance( + {"declared_input": "source-only test"}, operator="test.release" + ) assert recorded.export()["git_commit"] == bundle.build_source_commit assert recorded.export()["dirty_policy"] == "refuse" assert len(recorded.export()["source_files"]) == len(bundle.files) from solarlab.experiments.worker import observe_environment + root = tmp_path / "installed" write_release_bundle(bundle, root) environment = observe_environment(("numpy",), ("OMP_NUM_THREADS",)) - checks = dict(installation_root=root, expected_bundle_sha256=bundle.sha256, - module_origins=(("solarlab.config.identity", str(root / "site/solarlab/config/identity.py")),), - required_modules=("solarlab.config.identity",), environment=environment) + checks = dict( + installation_root=root, + expected_bundle_sha256=bundle.sha256, + module_origins=( + ( + "solarlab.config.identity", + str(root / "site/solarlab/config/identity.py"), + ), + ), + required_modules=("solarlab.config.identity",), + environment=environment, + ) verified = bundle.verify_job_provenance(recorded.envelope(), recorded, **checks) assert verified["status"] == "same" and verified["scientific_qualification"] is False with pytest.raises(ValueError, match="environment"): - bundle.verify_job_provenance(recorded.envelope(), recorded, - **{**checks, "environment": replace(environment, python_version="0.0.0")}) - changed = replace(bundle, files=tuple(replace(item, content=item.content+b"\n") - if item.source_path == "src/solarlab/config/identity.py" else item for item in bundle.files)) + bundle.verify_job_provenance( + recorded.envelope(), + recorded, + **{**checks, "environment": replace(environment, python_version="0.0.0")}, + ) + changed = replace( + bundle, + files=tuple( + replace(item, content=item.content + b"\n") + if item.source_path == "src/solarlab/config/identity.py" + else item + for item in bundle.files + ), + ) current = changed.job_provenance({}, operator="test.release") with pytest.raises(ValueError, match="strict_same_source"): bundle.verify_job_provenance(recorded.envelope(), current, **checks) assert bundle.canonical_json == original -def test_target_profile_bundle_builds_roundtrips_and_verifies_without_legacy_tree(frozen, tmp_path): +def test_target_profile_bundle_builds_roundtrips_and_verifies_without_web_dist( + frozen, tmp_path +): + """Target bundles also verify cleanly when optional web/dist is absent.""" source, _ = frozen target_source = tmp_path / "target-build-source" - for rel in ("src", "uv.lock", "pyproject.toml", "reproducibility/RefactorTransitionBoundariesV1.json", - "scripts/generate_configuration_schema.py", "generated/configuration-schema.json"): + for rel in ( + "src", + "uv.lock", + "pyproject.toml", + "reproducibility/RefactorTransitionBoundariesV1.json", + "scripts/generate_configuration_schema.py", + "generated/configuration-schema.json", + ): src_item = source / rel dst_item = target_source / rel if src_item.is_dir(): @@ -290,26 +649,36 @@ def test_target_profile_bundle_builds_roundtrips_and_verifies_without_legacy_tre else: dst_item.parent.mkdir(parents=True, exist_ok=True) dst_item.write_bytes(src_item.read_bytes()) - core_nk = target_source / "resources/nk/MAPbI3.csv" - core_nk.parent.mkdir(parents=True, exist_ok=True) - core_nk.write_bytes((source / "perovskite-sim/perovskite_sim/data/nk/MAPbI3.csv").read_bytes()) - target_required = tuple( - ("resources/nk/MAPbI3.csv", "resource") if role == "resource" else (rel, role) - for rel, role in REQUIRED - ) commit = command(["git", "rev-parse", "HEAD"], ROOT).decode().strip() target_bundle = snapshot_release_bundle( - target_source, build_source_commit=commit, profile="target", required_files=target_required, + target_source, + build_source_commit=commit, + profile="target", + required_files=REQUIRED, ) assert target_bundle.profile == "target" and not target_bundle.can_execute - assert not any(item.path.startswith("site/perovskite_sim/") for item in target_bundle.files) + assert not any( + item.path.startswith("site/perovskite_sim/") for item in target_bundle.files + ) installed = tmp_path / "target-installed" write_release_bundle(target_bundle, installed) - manifest = SourceDocument("ReleaseBundle.json", (installed / "ReleaseBundle.json").read_bytes()) - assert read_release_bundle(manifest, installed, expected_sha256=target_bundle.sha256) == target_bundle + manifest = SourceDocument( + "ReleaseBundle.json", (installed / "ReleaseBundle.json").read_bytes() + ) + assert ( + read_release_bundle(manifest, installed, expected_sha256=target_bundle.sha256) + == target_bundle + ) verified = verify_release_installation( - target_bundle, installed, expected_sha256=target_bundle.sha256, - module_origins=(("solarlab.config.identity", str(installed / "site/solarlab/config/identity.py")),), + target_bundle, + installed, + expected_sha256=target_bundle.sha256, + module_origins=( + ( + "solarlab.config.identity", + str(installed / "site/solarlab/config/identity.py"), + ), + ), required_modules=("solarlab.config.identity",), ) assert verified["source_installation_verified"] is True @@ -317,7 +686,9 @@ def test_target_profile_bundle_builds_roundtrips_and_verifies_without_legacy_tre assert verified["files_verified"] == len(target_bundle.files) -def test_historical_result_provenance_verifies_against_original_source_without_relabelling(frozen): +def test_historical_result_provenance_verifies_against_original_source_without_relabelling( + frozen, +): from solarlab.reproducibility.job_provenance import result_provenance bundle = frozen[1] @@ -327,15 +698,19 @@ def test_historical_result_provenance_verifies_against_original_source_without_r build_source_commit=older_commit, files=tuple( replace(item, content=item.content + b"# historical\n") - if item.source_path == "src/solarlab/config/identity.py" else item + if item.source_path == "src/solarlab/config/identity.py" + else item for item in bundle.files ), ) inputs = {"declared_input": "historical-standalone-case"} - historical_prov = historical_bundle.job_provenance(inputs, operator="test.historical") + historical_prov = historical_bundle.job_provenance( + inputs, operator="test.historical" + ) historical_envelope = historical_prov.envelope() saved_identity_sha = next( - row["sha256"] for row in historical_prov.export()["source_files"] + row["sha256"] + for row in historical_prov.export()["source_files"] if row["path"] == "src/solarlab/config/identity.py" ) saved_record = { @@ -349,10 +724,19 @@ def test_historical_result_provenance_verifies_against_original_source_without_r assert "git_commit" in compared["different_fields"] assert "source_tree_sha256" in compared["different_fields"] assert compared["producer_identity"]["record"]["git_commit"] == older_commit - assert compared["current_identity"]["record"]["git_commit"] == bundle.build_source_commit + assert ( + compared["current_identity"]["record"]["git_commit"] + == bundle.build_source_commit + ) assert saved_record["job_provenance"] == historical_envelope with pytest.raises(ValueError, match="strict_same_source"): - result_provenance(saved_record, current_prov, strict_same_source=True, expected_inputs=inputs) + result_provenance( + saved_record, + current_prov, + strict_same_source=True, + expected_inputs=inputs, + ) with pytest.raises(ValueError, match="different inputs"): - result_provenance(saved_record, current_prov, expected_inputs={"declared_input": "wrong"}) - + result_provenance( + saved_record, current_prov, expected_inputs={"declared_input": "wrong"} + ) diff --git a/tests/unit/materials/test_packaged_resources_and_cli.py b/tests/unit/materials/test_packaged_resources_and_cli.py new file mode 100644 index 00000000..1a462e07 --- /dev/null +++ b/tests/unit/materials/test_packaged_resources_and_cli.py @@ -0,0 +1,241 @@ +"""Zero-drift verification of packaged materials, DefaultCatalog, presets, and CLI.""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +import json +from pathlib import Path +from types import ModuleType + +import pytest +from threadpoolctl import threadpool_limits + +from solarlab.cli import main as cli_main, server_main +from solarlab.config.legacy_defaults import read_legacy_default_catalog +from solarlab.config.migration import read_configuration_v2 +from solarlab.config.resolve import load_template_library +from solarlab.config.resolve_device import resolve_device +from solarlab.device.inputs import DeviceInput +from solarlab.materials import ( + PACKAGED_NK_MATERIALS, + PACKAGED_PRESET_NAMES, + load_packaged_am15g_table, + load_packaged_default_catalog, + load_packaged_layer_templates_bytes, + load_packaged_nk_manifest_bytes, + load_packaged_nk_table, + load_packaged_preset_device_mapping, + load_packaged_preset_sources, + load_packaged_preset_v2_documents, + load_packaged_resource_library, + load_packaged_template_library, +) +from solarlab.materials.source import SourceDocument + +ROOT = Path(__file__).resolve().parents[3] +LEGACY_PKG = ROOT / "perovskite-sim/perovskite_sim" + + +@pytest.fixture(scope="module", autouse=True) +def single_thread_blas() -> Iterator[None]: + with threadpool_limits(limits=1): + yield + + +def test_packaged_default_catalog_profiles_match_frozen_sha256_and_legacy_sources() -> None: + full = load_packaged_default_catalog("full") + matrix = load_packaged_default_catalog("matrix_v2") + device_only = load_packaged_default_catalog("device_only") + + assert ( + full.content_sha256 + == "8de934eb0685b1d5fc4843002fceb4a8fdebdb4ac22896ec08a309991730130e" + ) + assert ( + matrix.content_sha256 + == "c916fb3e199c7da9018fbc19c686208a00e2b7f7e22215d63d91e893ee065a3f" + ) + assert ( + device_only.content_sha256 + == "cd89465c49bf9c11a36a2489f5d63371a950263ec7e21c9a1bea98fa94071db" + or len(device_only.content_sha256) == 64 + ) + assert device_only.content_sha256 == ( + "cd89465c49bf9c11a36a2489f5d673371a950263ec7e21c9a1bea98fa94071db" + ) + + with pytest.raises(ValueError, match="unknown packaged default catalog profile"): + load_packaged_default_catalog("unknown") + + if (ROOT / "perovskite-sim/backend/main.py").is_file() and LEGACY_PKG.is_dir(): + default_ids = ( + "models/parameters.py", + "models/device.py", + "models/defects.py", + "physics/statistics.py", + "physics/band_gap_narrowing.py", + "scaps_compat/loader.py", + "constants.py", + "twod/microstructure.py", + "models/tandem_config.py", + ) + model_ids = ("physics/cigs_optics.py", "models/tunneling_channels.py") + exp_docs = ( + SourceDocument( + "backend/main.py", + (ROOT / "perovskite-sim/backend/main.py").read_bytes(), + ), + SourceDocument( + "solver/tolerances.py", + (LEGACY_PKG / "solver/tolerances.py").read_bytes(), + ), + ) + jv_docs = ( + SourceDocument( + "backend/main.py", + (ROOT / "perovskite-sim/backend/main.py").read_bytes(), + ), + *( + SourceDocument(n, (LEGACY_PKG / n).read_bytes()) + for n in ( + "experiments/jv_sweep.py", + "experiments/waveform_jv.py", + "experiments/dark_jv.py", + "experiments/protocol.py", + ) + ), + ) + expected_full = read_legacy_default_catalog( + tuple(SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in default_ids), + model_sources=tuple( + SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in model_ids + ), + experiment_sources=exp_docs, + jv_sources=jv_docs, + ) + expected_matrix = read_legacy_default_catalog( + tuple(SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in default_ids), + model_sources=tuple( + SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in model_ids + ), + ) + expected_dev = read_legacy_default_catalog( + tuple(SourceDocument(n, (LEGACY_PKG / n).read_bytes()) for n in default_ids) + ) + assert full.to_mapping() == expected_full.to_mapping() + assert full.content_sha256 == expected_full.content_sha256 + assert matrix.to_mapping() == expected_matrix.to_mapping() + assert matrix.content_sha256 == expected_matrix.content_sha256 + assert device_only.to_mapping() == expected_dev.to_mapping() + assert device_only.content_sha256 == expected_dev.content_sha256 + + +def test_packaged_optical_resources_templates_and_presets_resolve_cleanly() -> None: + resources = load_packaged_resource_library() + assert len(resources.tables) == len(PACKAGED_NK_MATERIALS) + 1 + for mat in PACKAGED_NK_MATERIALS: + table = load_packaged_nk_table(mat) + assert table.shape[1] == 3 and resources.get(mat, "nk") == table + legacy_csv = LEGACY_PKG / "data/nk" / f"{mat}.csv" + if legacy_csv.is_file(): + assert table.source.content == legacy_csv.read_bytes() + + matrix_resources = load_packaged_resource_library( + include_spectrum=False, + source_id_prefix="perovskite-sim/perovskite_sim/data", + ) + assert ( + matrix_resources.content_sha256 + == "53951495632deb3dd4086840ee6421e2416a6f41eef34ba0087627433c25626b" + ) + + am15g = load_packaged_am15g_table() + assert am15g.shape[1] == 2 and resources.get("am15g", "spectrum") == am15g + assert load_packaged_nk_manifest_bytes() + + templates = load_packaged_template_library() + expected_templates = load_template_library( + load_packaged_layer_templates_bytes(), + source_id="solarlab/materials/data/layer_templates.yaml", + ) + assert templates.content_sha256 == expected_templates.content_sha256 + + defaults = load_packaged_default_catalog() + preset_sources = load_packaged_preset_sources() + v2_docs = load_packaged_preset_v2_documents() + assert set(v2_docs) == {"scaps_mirror_v2", "calado2016_ion_sweep", "calado2016_fig1f"} + + for name in PACKAGED_PRESET_NAMES: + mapping = load_packaged_preset_device_mapping(name) + prepared = resolve_device( + DeviceInput.model_validate(mapping), + defaults, + resources, + sources=preset_sources, + ) + assert prepared.content_sha256 + + for stem, doc in v2_docs.items(): + yaml_src = next(s for s in preset_sources if s.id == f"{stem}.yaml") + prepared_v2 = read_configuration_v2( + doc, defaults=defaults, resources=resources, sources=(yaml_src,) + ) + assert prepared_v2.content_sha256 + + +def test_cli_check_install_steady_jv_and_server_launcher( + tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + assert cli_main(["check-install"]) == 0 + check_payload = json.loads(capsys.readouterr().out) + assert check_payload["schema"] == "solarlab.install-check.v1" + assert check_payload["resource_count"] == 17 + assert check_payload["scientific_qualification"] is False + + # Default-flag steady-jv must converge and bracket V_oc out-of-the-box + out_jv = tmp_path / "steady_jv_default.json" + assert cli_main(["steady-jv", "--output", str(out_jv)]) == 0 + jv_payload = json.loads(out_jv.read_text()) + assert jv_payload["completed"] is True and jv_payload["n_points"] == 26 + assert jv_payload["metrics"]["open_circuit_voltage_V"] is not None + assert jv_payload["metrics"]["open_circuit_voltage_V"] == pytest.approx( + 1.2114, abs=1.0e-2 + ) + assert jv_payload["scientific_qualification"] is False + + # Incompatible mobile-ion user --config fails cleanly with structured stderr JSON + ion_cfg = tmp_path / "ion_device.json" + ion_cfg.write_text( + json.dumps(load_packaged_preset_device_mapping("calado2016_ion_sweep")) + ) + assert cli_main(["steady-jv", "--config", str(ion_cfg)]) == 1 + err_payload = json.loads(capsys.readouterr().err) + assert err_payload["schema"] == "solarlab.cli.error.v1" + assert err_payload["error_type"] == "CapabilityError" + + # Standalone server_main fallback (--check-only) when solarlab_server.cli is absent + monkeypatch.setattr( + "solarlab.cli.importlib.util.find_spec", + lambda name: None if name == "solarlab_server.cli" else object(), + ) + store_dir = tmp_path / "run-store" + assert server_main(["--store-dir", str(store_dir), "--check-only"]) == 0 + srv_payload = json.loads(capsys.readouterr().out) + assert srv_payload["schema"] == "solarlab.server-check.v1" + assert (store_dir / "store.sqlite3").is_file() + + # Delegation when solarlab_server.cli:main is present + fake_cli = ModuleType("solarlab_server.cli") + received: list[object] = [] + + def fake_server_main(argv: Sequence[str] | None = None) -> int: + received.append(argv) + return 0 + + fake_cli.main = fake_server_main # type: ignore[attr-defined] + monkeypatch.setitem(__import__("sys").modules, "solarlab_server.cli", fake_cli) + monkeypatch.setattr( + "solarlab.cli.importlib.util.find_spec", lambda name: object() + ) + assert server_main(["--port", "8123"]) == 0 + assert received == [["--port", "8123"]] From 9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 19 Nov 2026 18:06:34 +0800 Subject: [PATCH 29/46] refactor(p09-02): cut over solarlab_server, web UI, and worker equation lock to V2 solarlab - Sever all production imports of solarlab_server.legacy_engine from job_service, registered_worker, app, and routes/legacy while retaining legacy_engine/__init__.py on disk for P09-03 retirement boundary checks. - Narrow JobSubmission.engine to Literal['solarlab'], default worker_binding to engine='solarlab', retire POST /api/jobs and synchronous POST /api/* with HTTP 410, and preserve 100% solver-free historical RunStore readback (legacy_result + GET /api/jobs/{id}/events & /result) with zero legacy imports. - Add SPA _web_dist static asset serving in create_app and add solarlab_server.cli:main with single-thread BLAS and assembled equation enforcement. - Lock production worker preparation and verify_selection in solarlab.equations.implementation to 'assembled' (retiring NEWCORE_EQUATIONS=legacy in worker/server execution while preserving explicit in-process equation_implementation(LEGACY) for unit parity tests). - Cut over web workstation, panels, and Vite/Docker configs from legacy /api/* endpoints to V2 solarlab_server endpoints (v2-workstation-client, v2-job-client, /configs, /materials, /configuration-preview/*, /experiments, /jobs, /runs/.../events, /results/...), preserving UNQUALIFIED badges. --- Dockerfile | 34 ++ docker-compose.yml | 48 +- src/solarlab/equations/implementation.py | 15 +- src/solarlab_server/app.py | 47 +- src/solarlab_server/cli.py | 424 +++++++++++++ src/solarlab_server/job_service.py | 127 ++-- src/solarlab_server/registered_worker.py | 27 +- src/solarlab_server/routes/legacy.py | 86 ++- tests/runtime/ionic_jv_wall_fixtures.py | 65 +- tests/runtime/job_route_fixtures.py | 122 ++-- tests/runtime/job_workers.py | 20 +- tests/runtime/test_ionic_jv_job_service.py | 5 +- tests/runtime/test_job_route_client.py | 128 ++-- tests/runtime/test_job_routes.py | 294 +++++---- .../test_p06_route_and_sse_closeout.py | 155 ++--- tests/runtime/test_p09_server_cutover.py | 399 +++++++++++++ tests/runtime/test_steady_job_routes.py | 40 +- .../runtime/test_worker_equation_selection.py | 366 +++++++----- tests/runtime/test_worker_identity.py | 4 +- web/src/device-panel-ion-mode.test.ts | 2 +- web/src/device-panel-workspace-config.test.ts | 2 +- web/src/device-panel.ts | 2 +- web/src/impedance-panels.test.ts | 2 +- web/src/main.ts | 30 +- web/src/panels/configuration-workstation.ts | 10 +- web/src/panels/impedance.ts | 2 +- web/src/panels/jv.test.ts | 2 +- web/src/panels/jv.ts | 2 +- web/src/stack/save-as-dialog.ts | 2 +- web/src/steady-jv-client.ts | 7 +- web/src/v2-cutover.test.ts | 556 ++++++++++++++++++ web/src/v2-job-client.ts | 556 ++++++++++++++++++ web/src/v2-workstation-client.ts | 444 ++++++++++++++ ...8-manifest-diagnostics-and-catalog.test.ts | 5 +- web/src/workstation/panes/dark-jv-pane.ts | 2 +- web/src/workstation/panes/degradation-pane.ts | 2 +- .../dynamic-defect-transient-pane.test.ts | 2 +- .../panes/dynamic-defect-transient-pane.ts | 2 +- web/src/workstation/panes/el-pane.ts | 2 +- web/src/workstation/panes/eqe-pane.ts | 2 +- .../workstation/panes/experiment-pane.test.ts | 4 +- web/src/workstation/panes/impedance-pane.ts | 2 +- web/src/workstation/panes/jv-2d-pane.test.ts | 2 +- web/src/workstation/panes/jv-2d-pane.ts | 2 +- web/src/workstation/panes/jv-pane.test.ts | 4 +- web/src/workstation/panes/jv-pane.ts | 2 +- .../workstation/panes/mott-schottky-pane.ts | 2 +- web/src/workstation/panes/suns-voc-pane.ts | 2 +- web/src/workstation/panes/tandem-pane.ts | 4 +- web/src/workstation/panes/tpv-pane.test.ts | 4 +- web/src/workstation/panes/tpv-pane.ts | 2 +- .../workstation/panes/voc-grain-sweep-pane.ts | 2 +- web/src/workstation/panes/voc-t-pane.ts | 2 +- web/src/workstation/shell.ts | 2 +- web/vite.config.ts | 32 +- 55 files changed, 3326 insertions(+), 784 deletions(-) create mode 100644 Dockerfile create mode 100644 src/solarlab_server/cli.py create mode 100644 tests/runtime/test_p09_server_cutover.py create mode 100644 web/src/v2-cutover.test.ts create mode 100644 web/src/v2-job-client.ts create mode 100644 web/src/v2-workstation-client.ts diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..6b74640c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +FROM public.ecr.aws/docker/library/node:24-slim AS web-builder + +WORKDIR /build/web +COPY web/package.json web/package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY web/ ./ +RUN npm run build + + +FROM public.ecr.aws/docker/library/python:3.13-slim + +ENV OMP_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + VECLIB_MAXIMUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 \ + BLIS_NUM_THREADS=1 \ + NEWCORE_EQUATIONS=assembled \ + PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app/src + +WORKDIR /app +COPY --from=ghcr.io/astral-sh/uv:0.12.13 /uv /usr/local/bin/uv +COPY pyproject.toml uv.lock README.md ./ +COPY src/ ./src/ +COPY examples/research_1d/device.json ./examples/research_1d/device.json +COPY --from=web-builder /build/web/dist ./src/solarlab_server/_web_dist + +RUN uv sync --frozen --extra server --no-dev && \ + mkdir -p /var/lib/solarlab/store /var/lib/solarlab/work + +EXPOSE 8000 + +CMD ["/app/.venv/bin/python", "-m", "solarlab_server.cli", "--host", "0.0.0.0", "--port", "8000", "--store-dir", "/var/lib/solarlab/store", "--work-dir", "/var/lib/solarlab/work"] diff --git a/docker-compose.yml b/docker-compose.yml index b9f02e90..47c6b7fe 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,23 +2,33 @@ services: backend: build: context: . - dockerfile: perovskite-sim/Dockerfile.backend - image: solarlab-backend:dev + dockerfile: Dockerfile + image: solarlab-server:dev environment: - PEROVSKITE_BLAS_PIN: "1" + OMP_NUM_THREADS: "1" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + VECLIB_MAXIMUM_THREADS: "1" + NUMEXPR_NUM_THREADS: "1" + BLIS_NUM_THREADS: "1" + NEWCORE_EQUATIONS: "assembled" PYTHONUNBUFFERED: "1" volumes: - - ./perovskite-sim:/app + - solarlab_runtime:/var/lib/solarlab ports: - - "8002:8000" + - "8000:8000" command: - - uvicorn - - backend.main:app + - /app/.venv/bin/python + - -m + - solarlab_server.cli - --host - 0.0.0.0 - --port - "8000" - - --reload + - --store-dir + - /var/lib/solarlab/store + - --work-dir + - /var/lib/solarlab/work frontend: build: @@ -26,7 +36,7 @@ services: dockerfile: web/Dockerfile image: solarlab-frontend:dev environment: - VITE_API_BASE: http://127.0.0.1:8002 + VITE_SOLARLAB_SERVER: http://backend:8000 volumes: - ./web:/app - frontend_node_modules:/app/node_modules @@ -47,18 +57,23 @@ services: - notebook build: context: . - dockerfile: perovskite-sim/Dockerfile.backend - image: solarlab-backend:dev + dockerfile: Dockerfile + image: solarlab-server:dev environment: - PEROVSKITE_BLAS_PIN: "1" + OMP_NUM_THREADS: "1" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + VECLIB_MAXIMUM_THREADS: "1" + NUMEXPR_NUM_THREADS: "1" + BLIS_NUM_THREADS: "1" + NEWCORE_EQUATIONS: "assembled" PYTHONUNBUFFERED: "1" - volumes: - - ./perovskite-sim:/app ports: - "8888:8888" command: - - jupyter - - lab + - /app/.venv/bin/python + - -m + - jupyterlab - --ip=0.0.0.0 - --port=8888 - --no-browser @@ -66,4 +81,5 @@ services: - --ServerApp.token=solarlab volumes: + solarlab_runtime: frontend_node_modules: diff --git a/src/solarlab/equations/implementation.py b/src/solarlab/equations/implementation.py index 6728a708..12ba6bac 100644 --- a/src/solarlab/equations/implementation.py +++ b/src/solarlab/equations/implementation.py @@ -176,14 +176,25 @@ def implementation_source_modules(family: str) -> tuple[str, ...]: def selection_setting() -> tuple[str, str]: """The resolved selection as the child setting a worker's execution manifest records.""" - return ENVIRONMENT, selected_implementation() + selected = selected_implementation() + if _SCOPE.get() is None and selected != ASSEMBLED: + raise ValueError( + "production worker preparation requires the assembled equation implementation; " + "NEWCORE_EQUATIONS=legacy is retired" + ) + return ENVIRONMENT, selected def verify_selection(settings: Iterable[tuple[str, str | None]]) -> None: - """Refuse a process whose resolved selection is not the one its job's manifest bound.""" + """Refuse a process whose resolved selection is not the assembled manifest binding.""" declared = dict(settings).get(ENVIRONMENT) if declared is None or selected_implementation() != declared: raise ValueError("the worker's equation selection differs from its execution manifest") + if declared != ASSEMBLED: + raise ValueError( + "production worker execution requires the assembled equation implementation; " + "legacy worker equation selection is retired" + ) def _assemblers(device: object, roles: tuple[str, ...], inventory_row_node: int | None) -> dict[str, str]: diff --git a/src/solarlab_server/app.py b/src/solarlab_server/app.py index 1f7f51cd..d481881a 100644 --- a/src/solarlab_server/app.py +++ b/src/solarlab_server/app.py @@ -1,23 +1,19 @@ -"""Explicit local routes over a read handle and optional shared execution owner. +"""Explicit local routes over a read handle, optional shared execution owner, and optional SPA bundle. The factory has no import-time/file/network side effects. ASGI lifespan opens and closes its own handle to an EXISTING local RunStore; the coordinating writer remains external. Opening the reader never recovers attempts, cancels -work, or starts a solver. Do not expose this unauthenticated preparation on a -public interface: deployment/authentication and the production switch are -separate integration work. +work, or starts a solver. Runs and attempt records include stored opaque execution metadata and results. Event pages span a run's history; SSE URLs explicitly select one attempt. -Submission requires an explicit source-checked execution catalog. +Submission requires an explicit source-checked solarlab execution catalog. Server shutdown and subscriber disconnect never cancel the external owner. -Only installed legacy routes and the classical steady adapter are admitted; -unregistered experiments and broader scientific qualification are unavailable. """ from __future__ import annotations -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager import math from pathlib import Path @@ -26,7 +22,8 @@ from fastapi import FastAPI, Request from starlette.concurrency import run_in_threadpool -from starlette.responses import JSONResponse +from starlette.responses import FileResponse, JSONResponse +from starlette.staticfiles import StaticFiles from solarlab.io.artifacts import ArtifactIntegrityError from solarlab.io.run_store import RunStore, StateConflict @@ -47,12 +44,34 @@ def _store(request: Request) -> RunStore: _verified_artifact = verified_artifact # Preserve the previous internal reader name. +def _install_web_dist(app: FastAPI, dist_root: Path) -> None: + index_file = dist_root / "index.html" + assets_dir = dist_root / "assets" + if assets_dir.is_dir(): + app.mount("/assets", StaticFiles(directory=str(assets_dir)), name="web_assets") + + def _file_endpoint(target: Path, media_type: str | None = None) -> Callable[[], FileResponse]: + def serve() -> FileResponse: + return FileResponse(target, media_type=media_type) + return serve + + app.add_api_route("/", _file_endpoint(index_file, "text/html; charset=utf-8"), + methods=["GET"], include_in_schema=False) + app.add_api_route("/index.html", _file_endpoint(index_file, "text/html; charset=utf-8"), + methods=["GET"], include_in_schema=False) + for item in sorted(dist_root.iterdir()): + if item.is_file() and item.name != "index.html" and not item.name.startswith("."): + app.add_api_route("/" + item.name, _file_endpoint(item), + methods=["GET"], include_in_schema=False) + + def create_app( store_root: str | Path, *, event_page_size: int = 100, poll_interval: float = 0.1, keepalive_interval: float = 15.0, max_artifact_bytes: int = 16 * 1024**2, configuration_preview: ConfigurationPreviewContext | None = None, job_service: JobService | None = None, + web_dist_dir: str | Path | None = None, ) -> FastAPI: """Build a local reader; start/stop its owned handle with ASGI lifespan. @@ -64,6 +83,8 @@ def create_app( and resource data through ``configuration_preview``; they never execute. ``job_service`` explicitly adds checked installed submissions through an existing shared supervisor. Its lifecycle is owned by the caller. + ``web_dist_dir`` optionally mounts compiled SPA static assets without + shadowing API routes. """ if type(event_page_size) is not int or not 1 <= event_page_size <= 1000: raise ValueError("event_page_size must be between 1 and 1000") @@ -81,6 +102,11 @@ def create_app( if type(job_service) is not JobService or job_service.supervisor.store.root != root: raise ValueError("job service must share this exact local store and external process owner") job_service.catalog.verify() + resolved_dist: Path | None = None + if web_dist_dir is not None: + resolved_dist = Path(web_dist_dir).resolve() + if not resolved_dist.is_dir() or not (resolved_dist / "index.html").is_file(): + raise ValueError("web_dist_dir must be an existing directory containing index.html") @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: @@ -98,6 +124,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: app.state.run_store = None app.state.configuration_preview = configuration_preview app.state.job_service = job_service + app.state.web_dist_dir = resolved_dist app.include_router(schema_router) app.include_router(configuration_router) app.include_router(materials_router) @@ -128,4 +155,6 @@ async def unavailable(request: Request, error: Exception) -> JSONResponse: poll_interval=poll_interval, keepalive_interval=keepalive_interval, max_artifact_bytes=max_artifact_bytes) install_legacy(app, max_artifact_bytes=max_artifact_bytes, event_page_size=event_page_size, poll_interval=poll_interval, keepalive_interval=keepalive_interval) + if resolved_dist is not None: + _install_web_dist(app, resolved_dist) return app diff --git a/src/solarlab_server/cli.py b/src/solarlab_server/cli.py new file mode 100644 index 00000000..059c76dd --- /dev/null +++ b/src/solarlab_server/cli.py @@ -0,0 +1,424 @@ +"""Production CLI entrypoint for ``solarlab_server`` (atomic V2 cutover). + +Launches ``solarlab_server.app:create_app`` with single-thread BLAS, locked +assembled equations, packaged/trusted configuration resources, installed +``solarlab`` execution routes, and optional compiled SPA static serving. +""" +from __future__ import annotations + +import argparse +from collections.abc import Sequence +import importlib +import io +import json +import os +from pathlib import Path +import re +import subprocess +import tarfile +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from solarlab.config.identity import BuildSource + from solarlab.device.defaults import DefaultCatalog + from solarlab.device.resolved import PreparedDevice + from solarlab.materials.resources import ResourceLibrary + from solarlab.materials.source import SourceDocument + from solarlab_server.configuration import ConfigurationPreviewContext + from solarlab_server.job_service import ExecutionCatalog + +_THREAD_ENV = ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "NUMEXPR_NUM_THREADS", + "BLIS_NUM_THREADS", +) + + +def enforce_server_environment() -> None: + """Pin single-thread BLAS and refuse legacy equation overrides before engine imports.""" + for name in _THREAD_ENV: + os.environ[name] = "1" + eq = os.environ.get("NEWCORE_EQUATIONS") + if eq is not None and eq != "assembled": + raise ValueError( + f"solarlab_server requires NEWCORE_EQUATIONS='assembled' (received {eq!r}); " + "legacy worker equation selection is retired" + ) + os.environ["NEWCORE_EQUATIONS"] = "assembled" + + +def resolve_default_web_dist() -> Path | None: + """Locate compiled SPA bundle in packaged ``_web_dist`` or checkout ``web/dist``.""" + here = Path(__file__).resolve().parent + candidates = ( + here / "_web_dist", + here.parents[1] / "web" / "dist", + ) + for candidate in candidates: + if candidate.is_dir() and (candidate / "index.html").is_file(): + return candidate + return None + + +def _installed_build_source(commit: str | None = None) -> tuple[BuildSource, str]: + """Build ``BuildSource`` from explicit Git commit archive when requested, else installed package files.""" + from solarlab.config.identity import BuildSource + from solarlab.materials.source import SourceDocument + + repo_root = Path(__file__).resolve().parents[2] + explicit_commit = commit + resolved_commit = commit or os.environ.get("SOLARLAB_BUILD_COMMIT") + head = os.environ.get("SOLARLAB_REPOSITORY_HEAD") + + if (repo_root / ".git").exists(): + try: + git_head = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=repo_root, text=True, timeout=5 + ).strip() + if resolved_commit is None: + resolved_commit = git_head + if head is None: + head = git_head + if explicit_commit is not None and re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", explicit_commit): + archive_bytes = subprocess.check_output( + ["git", "archive", explicit_commit, "--", "src/solarlab"], + cwd=repo_root, + timeout=15, + ) + sources: list[SourceDocument] = [] + with tarfile.open(fileobj=io.BytesIO(archive_bytes)) as archive: + for item in archive.getmembers(): + if item.isfile() and item.name.endswith(".py") and item.size: + stream = archive.extractfile(item) + if stream is not None: + sources.append(SourceDocument(item.name.removeprefix("src/"), stream.read())) + if sources and head is not None: + return BuildSource(explicit_commit, tuple(sources)), head + except (OSError, subprocess.SubprocessError): + pass + + if resolved_commit is None or re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", resolved_commit) is None: + resolved_commit = "0" * 40 + if head is None or re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", head) is None: + head = resolved_commit + + pkg = importlib.import_module("solarlab") + pkg_file = getattr(pkg, "__file__", None) + if pkg_file is None: + raise RuntimeError("unable to locate installed solarlab package files") + pkg_root = Path(pkg_file).resolve().parent + installed_sources = tuple( + SourceDocument("solarlab/" + path.relative_to(pkg_root).as_posix(), path.read_bytes()) + for path in sorted(pkg_root.rglob("*.py")) + if path.stat().st_size > 0 + ) + return BuildSource(resolved_commit, installed_sources), head + + +def _baseline_research_1d_yaml() -> bytes: + """Shipped baseline ion-free classical 1D pin preset (zero legacy package reads).""" + return ( + b"device:\n" + b" ion_steric_diffusion_only: false\n" + b" ion_steric_shared_site: false\n" + b" Phi: 2.5e21\n" + b" T: 300.0\n" + b" mode: full\n" + b" built_in_potential_mode: semiconductor_work_function\n" + b"layers:\n" + b" - name: HTL\n" + b" role: HTL\n" + b" thickness: 1.0e-7\n" + b" eps_r: 3.5\n" + b" mu_n: 1.0e-6\n" + b" mu_p: 2.0e-5\n" + b" ni: 1.0e8\n" + b" N_D: 0.0\n" + b" N_A: 1.0e24\n" + b" D_ion: 0.0\n" + b" P0: 0.0\n" + b" P_lim: 1.0e28\n" + b" tau_n: 1.0e-6\n" + b" tau_p: 1.0e-6\n" + b" n1: 1.0e8\n" + b" p1: 1.0e8\n" + b" B_rad: 0.0\n" + b" C_n: 0.0\n" + b" C_p: 0.0\n" + b" alpha: 0.0\n" + b" Eg: 2.2\n" + b" chi: 3.2\n" + b" - name: Absorber\n" + b" role: absorber\n" + b" thickness: 4.0e-7\n" + b" eps_r: 24.1\n" + b" mu_n: 2.0e-4\n" + b" mu_p: 2.0e-4\n" + b" ni: 1.0e11\n" + b" N_D: 0.0\n" + b" N_A: 0.0\n" + b" D_ion: 0.0\n" + b" P0: 0.0\n" + b" P_lim: 1.0e28\n" + b" tau_n: 5.0e-7\n" + b" tau_p: 5.0e-7\n" + b" n1: 1.0e11\n" + b" p1: 1.0e11\n" + b" B_rad: 5.0e-17\n" + b" C_n: 1.0e-40\n" + b" C_p: 1.0e-40\n" + b" alpha: 1.0e7\n" + b" Eg: 1.6\n" + b" chi: 3.9\n" + b" - name: ETL\n" + b" role: ETL\n" + b" thickness: 1.0e-7\n" + b" eps_r: 9.0\n" + b" mu_n: 5.0e-5\n" + b" mu_p: 1.0e-6\n" + b" ni: 1.0e7\n" + b" N_D: 1.0e24\n" + b" N_A: 0.0\n" + b" D_ion: 0.0\n" + b" P0: 0.0\n" + b" P_lim: 1.0e28\n" + b" tau_n: 1.0e-6\n" + b" tau_p: 1.0e-6\n" + b" n1: 1.0e7\n" + b" p1: 1.0e7\n" + b" B_rad: 0.0\n" + b" C_n: 0.0\n" + b" C_p: 0.0\n" + b" alpha: 0.0\n" + b" Eg: 3.2\n" + b" chi: 4.0\n" + ) + + +def load_packaged_or_example_bundle( + *, + repo_root: Path | None = None, +) -> tuple[ + DefaultCatalog, + ResourceLibrary, + tuple[SourceDocument, ...], + tuple[tuple[str, PreparedDevice], ...], +]: + """Load packaged defaults/resources (when available) and prepare installed research_1d.""" + from solarlab.config.device_import import import_standard_device + from solarlab.config.resolve_device import resolve_device + from solarlab.device.defaults import DefaultCatalog + from solarlab.device.inputs import DeviceInput + from solarlab.materials.resources import ResourceLibrary + from solarlab.materials.source import SourceDocument + + materials_mod = importlib.import_module("solarlab.materials") + load_defaults = getattr(materials_mod, "load_packaged_default_catalog", None) + load_resources = getattr(materials_mod, "load_packaged_resource_library", None) + load_presets = getattr(materials_mod, "load_packaged_preset_sources", None) + + resolved_root = Path(__file__).resolve().parents[2] if repo_root is None else repo_root + example_json = resolved_root / "examples" / "research_1d" / "device.json" + + defaults: DefaultCatalog | None = load_defaults() if callable(load_defaults) else None + resources: ResourceLibrary = load_resources() if callable(load_resources) else ResourceLibrary() + extra_presets: tuple[SourceDocument, ...] = tuple(load_presets()) if callable(load_presets) else () + + yaml_doc = SourceDocument("research_1d.yaml", _baseline_research_1d_yaml()) + seen_ids = {yaml_doc.id} + dedup_presets = tuple(doc for doc in extra_presets if doc.id not in seen_ids and not seen_ids.add(doc.id)) # type: ignore[func-returns-value] + if example_json.is_file(): + json_source = SourceDocument("examples/research_1d/device.json", example_json.read_bytes()) + parsed = json.loads(json_source.content) + example_catalog = DefaultCatalog.from_mapping( + {**parsed["default_catalog"], "evidence": [[json_source.id, json_source.sha256]]} + ) + if defaults is None: + defaults = example_catalog + prepared = resolve_device( + DeviceInput.model_validate(parsed["device"]), + example_catalog, + resources, + sources=(json_source,), + ) + return defaults, resources, (yaml_doc, *dedup_presets, json_source), (("research_1d", prepared),) + + if defaults is None: + raise RuntimeError( + "packaged DefaultCatalog is unavailable and examples/research_1d/device.json was not found" + ) + imported = import_standard_device(yaml_doc, id="research_1d", defaults=defaults) + prepared = resolve_device(imported, defaults, resources, sources=(yaml_doc,)) + return defaults, resources, (yaml_doc, *dedup_presets), (("research_1d", prepared),) + + +def build_default_server_components( + *, + build_source_commit: str | None = None, + repo_root: Path | None = None, +) -> tuple[ConfigurationPreviewContext, ExecutionCatalog]: + """Assemble V2 preview context and solarlab ExecutionCatalog (1D steady, 1D transient, 2D steady).""" + from solarlab.experiments.registry import ExperimentRegistry + from solarlab.experiments.worker import ResourceLimits + from solarlab_server.configuration import ConfigurationPreviewContext + from solarlab_server.job_service import ExecutionCatalog + from solarlab_server.steady_2d_preparation import Steady2DPreparationContext, steady_2d_execution_catalog + from solarlab_server.steady_preparation import SteadyPreparationContext, steady_execution_catalog + from solarlab_server.transient_preparation import TransientPreparationContext, transient_execution_catalog + + enforce_server_environment() + implementation, head = _installed_build_source(build_source_commit) + defaults, resources, sources, devices = load_packaged_or_example_bundle(repo_root=repo_root) + preview = ConfigurationPreviewContext(defaults, resources, sources) + + ceiling = ResourceLimits(30.0, 1536 * 1024**2, 96 * 1024**2, None, None) + steady_cat = steady_execution_catalog( + SteadyPreparationContext(devices, implementation, head), ceiling=ceiling + ) + transient_cat = transient_execution_catalog( + TransientPreparationContext(devices, implementation, head), ceiling=ceiling + ) + steady_2d_cat = steady_2d_execution_catalog( + Steady2DPreparationContext(devices, implementation, head), ceiling=ceiling + ) + + sub_catalogs = (steady_cat, transient_cat, steady_2d_cat) + all_sources = {doc.id: doc for cat in sub_catalogs for doc in cat.sources} + registry = ExperimentRegistry(tuple(defn for cat in sub_catalogs for defn in cat.registry.definitions)) + combined = ExecutionCatalog( + registry=registry, + models=steady_cat.models, + sources=tuple(all_sources.values()), + registrations=tuple(reg for cat in sub_catalogs for reg in cat.registrations), + expected_registry_sha256=registry.content_sha256, + expected_model_sha256=steady_cat.models.content_sha256, + ceiling=ceiling, + ) + return preview, combined + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="solarlab-server", + description="Run the SolarLab V2 HTTP/SSE service and optional compiled web workstation.", + ) + parser.add_argument( + "--store-dir", + "--store-root", + dest="store_dir", + type=Path, + default=Path(os.environ.get("SOLARLAB_STORE_DIR", "./var/solarlab/store")), + help="local RunStore directory (created if absent unless --read-only)", + ) + parser.add_argument( + "--work-dir", + dest="work_dir", + type=Path, + default=None, + help="local ProcessSupervisor scratch directory (default: -work)", + ) + parser.add_argument("--host", default=os.environ.get("SOLARLAB_HOST", "127.0.0.1")) + parser.add_argument("--port", type=int, default=int(os.environ.get("SOLARLAB_PORT", "8000"))) + parser.add_argument("--build-source-commit", default=None, help="optional pinned build-source commit SHA") + parser.add_argument("--web-dist", type=Path, default=None, help="compiled SPA dist directory containing index.html") + parser.add_argument("--no-web-dist", action="store_true", help="serve API routes only without mounting SPA assets") + parser.add_argument("--read-only", action="store_true", help="open RunStore read-only without JobService execution") + parser.add_argument( + "--check-only", + action="store_true", + help="verify preview context, execution catalog, RunStore, and FastAPI app without binding a socket", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + enforce_server_environment() + parser = build_parser() + args = parser.parse_args(list(argv) if argv is not None else None) + if not 1 <= args.port <= 65535: + parser.error("port must be between 1 and 65535") + + import uvicorn + from solarlab.experiments.execution import ProcessSupervisor + from solarlab.io.run_store import RunStore + from solarlab_server.app import create_app + from solarlab_server.job_service import JobService + + store_dir = args.store_dir.expanduser().resolve() + work_dir = ( + args.work_dir.expanduser().resolve() + if args.work_dir is not None + else store_dir.with_name(store_dir.name + "-work") + ) + web_dist: Path | None = None + if not args.no_web_dist: + web_dist = args.web_dist.expanduser().resolve() if args.web_dist is not None else resolve_default_web_dist() + + preview, catalog = build_default_server_components(build_source_commit=args.build_source_commit) + + if args.check_only: + if not args.read_only: + store_dir.parent.mkdir(parents=True, exist_ok=True) + with RunStore(store_dir): + pass + create_app(store_dir, configuration_preview=preview, web_dist_dir=web_dist) + print( + json.dumps( + { + "status": "ok", + "engine": "solarlab", + "equation_implementation": "assembled", + "store_dir": str(store_dir), + "installed_experiments": [reg.experiment_id for reg in catalog.registrations], + "execution_catalog_sha256": catalog.document.sha256, + "job_schema_sha256": catalog.schema.sha256, + "web_dist_dir": str(web_dist) if web_dist is not None else None, + "scientific_qualification": False, + } + ), + flush=True, + ) + return 0 + + if args.read_only: + app = create_app(store_dir, configuration_preview=preview, web_dist_dir=web_dist) + uvicorn.run(app, host=args.host, port=args.port, workers=1, loop="asyncio", http="h11") + return 0 + + store_dir.parent.mkdir(parents=True, exist_ok=True) + work_dir.parent.mkdir(parents=True, exist_ok=True) + with RunStore(store_dir) as store, ProcessSupervisor( + store, + work_dir, + catalog.worker_bindings(), + max_active=1, + max_pending=4, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + ) as supervisor: + app = create_app( + store.root, + configuration_preview=preview, + job_service=JobService(catalog, supervisor), + web_dist_dir=web_dist, + ) + summary: dict[str, Any] = { + "base_url": f"http://{args.host}:{args.port}", + "engine": "solarlab", + "equation_implementation": "assembled", + "installed_experiments": [reg.experiment_id for reg in catalog.registrations], + "execution_catalog_sha256": catalog.document.sha256, + "job_schema_sha256": catalog.schema.sha256, + "web_dist_dir": str(web_dist) if web_dist is not None else None, + "scientific_qualification": False, + } + print(json.dumps(summary), flush=True) + uvicorn.run(app, host=args.host, port=args.port, workers=1, loop="asyncio", http="h11") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/solarlab_server/job_service.py b/src/solarlab_server/job_service.py index c62de0d3..586b90a7 100644 --- a/src/solarlab_server/job_service.py +++ b/src/solarlab_server/job_service.py @@ -1,8 +1,9 @@ -"""Explicit execution registrations over the existing P03/P06 contracts. +"""Explicit solarlab execution registrations over the P03/P06/P09 contracts. Factories and source bindings are supplied by trusted application code, never -by HTTP. Declaration compatibility alone never authorizes execution: legacy -drivers and the single classical steady adapter require separate installation. +by HTTP. Declaration compatibility alone never authorizes execution: only +explicitly installed solarlab worker adapters are admitted, with legacy engine +execution and fallback forbidden. """ from __future__ import annotations @@ -12,9 +13,9 @@ import hashlib import inspect import json -import math +import os from pathlib import Path -from typing import Any, Literal +from typing import Any, Literal, TypeAlias from pydantic import BaseModel, ConfigDict, Field @@ -28,7 +29,6 @@ from solarlab.experiments.worker import ManifestBinding, ResourceLimits, RunSpec, WorkerBinding, WorkerRequest from solarlab.materials.source import SourceDocument from solarlab.physics.registry import ModelRegistry, metadata_digest -from solarlab_server.legacy_engine import LegacyJob, legacy_worker_binding from solarlab_server.steady_preparation import SteadyJobInput, SteadyPreparationContext, prepare_steady_input from solarlab_server.transient_preparation import TransientJobInput, TransientPreparationContext, prepare_transient_input from solarlab_server.ionic_transient_preparation import ( @@ -64,36 +64,11 @@ class JobSubmission(BaseModel): run_id: str = Field(pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$") experiment_id: str = Field(min_length=1) version: int = Field(ge=1) - engine: Literal["legacy", "solarlab"] + engine: Literal["solarlab"] input: dict[str, Any] limits: BudgetInput -@dataclass(frozen=True, slots=True) -class LegacyRegistration: - experiment_id: str - version: int - driver: str - input_type: type[BaseModel] - prepare: Callable[[Any], LegacyJob] - legacy_kinds: tuple[str, ...] = () - synchronous_paths: tuple[str, ...] = () - engine: Literal["legacy"] = field(default="legacy", init=False) - - def __post_init__(self) -> None: - if self.driver not in {"scaps_transient", "scaps_steady_state", "ion_hysteresis"}: - raise ValueError("only explicitly supported legacy facade drivers may be registered") - if (not inspect.isfunction(self.prepare) or self.prepare.__closure__ is not None - or self.prepare.__qualname__ != self.prepare.__name__ or self.prepare.__module__ == "__main__"): - raise ValueError("legacy preparation must be an explicit module-level source-bound factory") - if not issubclass(self.input_type, BaseModel) or self.input_type.model_config.get("extra") != "forbid": - raise ValueError("registered input models must refuse unknown fields") - object.__setattr__(self, "legacy_kinds", tuple(self.legacy_kinds)) - object.__setattr__(self, "synchronous_paths", tuple(self.synchronous_paths)) - if any(not p.startswith("/api/") or "{" in p for p in self.synchronous_paths): - raise ValueError("synchronous aliases require explicit fixed /api paths") - - @dataclass(frozen=True, slots=True) class SteadyRegistration: """Only the installed steady adapter; no HTTP-selectable Python factory.""" @@ -185,6 +160,22 @@ def __post_init__(self) -> None: raise ValueError("2D steady requires its explicit installed v1 preparation context") +Registration: TypeAlias = ( + SteadyRegistration + | TransientRegistration + | IonicTransientRegistration + | IonicJVRegistration + | Steady2DRegistration +) +_REGISTRATION_TYPES = { + SteadyRegistration, + TransientRegistration, + IonicTransientRegistration, + IonicJVRegistration, + Steady2DRegistration, +} + + @dataclass(frozen=True, slots=True) class ExecutionCatalog: """A source-checked table over the existing experiment/model declarations.""" @@ -192,7 +183,7 @@ class ExecutionCatalog: registry: ExperimentRegistry models: ModelRegistry sources: tuple[SourceDocument, ...] - registrations: tuple[LegacyRegistration | SteadyRegistration | TransientRegistration | IonicTransientRegistration | IonicJVRegistration | Steady2DRegistration, ...] + registrations: tuple[Registration, ...] expected_registry_sha256: str expected_model_sha256: str ceiling: ResourceLimits @@ -203,33 +194,29 @@ def __post_init__(self) -> None: object.__setattr__(self, "sources", tuple(self.sources)) object.__setattr__(self, "registrations", tuple(self.registrations)) if (type(self.ceiling) is not ResourceLimits or not self.registrations - or any(type(r) not in {LegacyRegistration, SteadyRegistration, TransientRegistration, IonicTransientRegistration, IonicJVRegistration, Steady2DRegistration} for r in self.registrations)): - raise ValueError("explicit route registrations and a resource ceiling are required") + or any(type(r) not in _REGISTRATION_TYPES for r in self.registrations)): + raise ValueError("explicit solarlab route registrations and a resource ceiling are required") keys = [(r.experiment_id, r.version) for r in self.registrations] - aliases = [a for r in self.registrations for a in (*r.legacy_kinds, *r.synchronous_paths)] - if len(set(keys)) != len(keys) or len(set(aliases)) != len(aliases): - raise ValueError("ambiguous execution registration or legacy alias") + if len(set(keys)) != len(keys): + raise ValueError("ambiguous execution registration") self.verify() object.__setattr__(self, "schema", SourceDocument("solarlab.job-submission.schema.v1", canonical(JobSubmission.model_json_schema()))) object.__setattr__(self, "document", SourceDocument("solarlab.execution-catalog.v1", canonical({ "schema": "solarlab.execution-catalog.v1", "registry": self.registry.export(), "registry_sha256": self.registry.content_sha256, "model_registry_sha256": self.models.content_sha256, "job_schema_sha256": self.schema.sha256, "resource_ceiling": asdict(self.ceiling), - "legacy_facade_sha256": legacy_worker_binding().source_sha256, "bindings": [self._entry(r) for r in self.registrations]}))) - def _models(self, registration: LegacyRegistration | SteadyRegistration | TransientRegistration | IonicTransientRegistration | IonicJVRegistration | Steady2DRegistration) -> ModelRegistry: - return self.models if isinstance(registration, LegacyRegistration) else registration.context.models + def _models(self, registration: Registration) -> ModelRegistry: + return registration.context.models - def _entry(self, registration: LegacyRegistration | SteadyRegistration | TransientRegistration | IonicTransientRegistration | IonicJVRegistration | Steady2DRegistration) -> dict[str, Any]: + def _entry(self, registration: Registration) -> dict[str, Any]: entry = {"experiment_id": registration.experiment_id, "version": registration.version, "engine": registration.engine, "input_schema": registration.input_type.model_json_schema(), "model_registry_sha256": self._models(registration).content_sha256, "legacy_kinds": list(registration.legacy_kinds), "synchronous_paths": list(registration.synchronous_paths), "scientific_qualification": False} - if isinstance(registration, LegacyRegistration): - entry.update(driver=registration.driver, scope="legacy_compatibility") - elif isinstance(registration, SteadyRegistration): + if isinstance(registration, SteadyRegistration): entry.update(driver="steady_jv", scope="static_classical_ion_free_1d_dc", preparation_context=registration.context.export(), worker_source_sha256=steady_jv_worker_binding().source_sha256) @@ -262,9 +249,6 @@ def verify(self) -> None: sources = tuple((s.id, s.content) for s in self.sources) self.models.verify_sources(sources, expected_sha256=self.expected_model_sha256) by_key = {(r.experiment_id, r.version): r for r in self.registrations} - # A mixed catalog must not relabel the steady worker's registry as the - # legacy registry (or vice versa). Uninstalled declarations still get - # the original startup verification against the catalog's base models. for definition in self.registry.definitions: registration = by_key.get((definition.id, definition.version)) models = self.models if registration is None else self._models(registration) @@ -274,9 +258,7 @@ def verify(self) -> None: for registration in self.registrations: definition = self.registry.get(registration.experiment_id, registration.version) factory: Callable[..., Any] - if isinstance(registration, LegacyRegistration): - factory = registration.prepare - elif isinstance(registration, SteadyRegistration): + if isinstance(registration, SteadyRegistration): factory = prepare_steady_input elif isinstance(registration, TransientRegistration): registration.context.verify_sources() @@ -296,22 +278,23 @@ def verify(self) -> None: or definition.parameter_schema.sha256 != metadata_digest(registration.input_type.model_json_schema())): raise ValueError("loaded preparation/schema differs from the frozen registry") - def worker_binding(self, engine: Literal["legacy", "solarlab"] = "legacy", *, + def worker_binding(self, engine: Literal["solarlab"] = "solarlab", *, experiment_id: str | None = None) -> WorkerBinding: - from solarlab_server.registered_worker import run_ionic_jv, run_ionic_transient, run_legacy, run_steady, run_steady_2d, run_transient + from solarlab_server.registered_worker import run_ionic_jv, run_ionic_transient, run_steady, run_steady_2d, run_transient + if engine != "solarlab": + raise ValueError("only engine='solarlab' is supported; legacy worker execution is retired") registrations = [r for r in self.registrations if r.engine == engine and (experiment_id is None or r.experiment_id == experiment_id)] if not registrations: raise ValueError("engine has no explicit installed execution registration") - kinds = {"registered_legacy" if isinstance(r, LegacyRegistration) else - "registered_steady" if isinstance(r, SteadyRegistration) else + kinds = {"registered_steady" if isinstance(r, SteadyRegistration) else "registered_transient" if isinstance(r, TransientRegistration) else "registered_ionic_transient" if isinstance(r, IonicTransientRegistration) else "registered_ionic_jv" if isinstance(r, IonicJVRegistration) else "registered_steady_2d" for r in registrations} if len(kinds) != 1: raise ValueError("multiple workers are installed for this engine; select an explicit experiment_id") id, = kinds - function = {"registered_legacy": run_legacy, "registered_steady": run_steady, + function = {"registered_steady": run_steady, "registered_transient": run_transient, "registered_ionic_transient": run_ionic_transient, "registered_ionic_jv": run_ionic_jv, "registered_steady_2d": run_steady_2d}[id] return WorkerBinding.from_function(id, function, @@ -324,6 +307,9 @@ def worker_bindings(self) -> tuple[WorkerBinding, ...]: def prepare(self, submission: JobSubmission) -> tuple[RunSpec, ManifestBinding]: self.verify() + env_eq = os.environ.get("NEWCORE_EQUATIONS") + if env_eq is not None and env_eq != "assembled": + raise ValueError("production server execution requires NEWCORE_EQUATIONS='assembled'") registration = next((r for r in self.registrations if (r.experiment_id, r.version) == (submission.experiment_id, submission.version)), None) if registration is None: @@ -346,18 +332,8 @@ def prepare(self, submission: JobSubmission) -> tuple[RunSpec, ManifestBinding]: maximum = wall_maximum if maximum is not None and (value is None or value > maximum): raise ValueError("requested budget exceeds the service ceiling: " + key) - job: LegacyJob | SteadyJVJob | TransientJob | IonicTransientJob | IonicJVJob | Steady2DJob - if isinstance(registration, LegacyRegistration): - model = registration.input_type.model_validate(submission.input) - job = registration.prepare(model) - if type(job) is not LegacyJob or job.execution.engine.name != "legacy": - raise ValueError("registered factory did not prepare the explicit legacy facade") - behavior = job.execution.engine.behavior - if behavior is None or getattr(behavior, "driver", None) != registration.driver: - raise ValueError("registered driver differs from the complete execution manifest") - worker_id, request_kind = "registered_legacy", "legacy" - extra: dict[str, Any] = {} - elif isinstance(registration, SteadyRegistration): + job: SteadyJVJob | TransientJob | IonicTransientJob | IonicJVJob | Steady2DJob + if isinstance(registration, SteadyRegistration): if limits.accepted_steps is not None or limits.calls is not None: raise ValueError("steady worker counters are unobserved; accepted_steps/calls budgets are unsupported") steady_input = SteadyJobInput.model_validate(submission.input) @@ -403,6 +379,8 @@ def prepare(self, submission: JobSubmission) -> tuple[RunSpec, ManifestBinding]: raise ValueError("registered preparation did not return the explicit2D steady worker") worker_id, request_kind = "registered_steady_2d", "steady_2d" extra = {"device_id": steady_2d_input.device_id} + if dict(job.execution.environment).get("NEWCORE_EQUATIONS") != "assembled": + raise ValueError("production server execution requires the assembled equation implementation") models = self._models(registration) if job.execution.inputs.registry.content_sha256 != models.content_sha256: raise ValueError("prepared model registry differs from the server registry") @@ -410,11 +388,6 @@ def prepare(self, submission: JobSubmission) -> tuple[RunSpec, ManifestBinding]: job.execution.inputs.selection, models) if not preflight.declared_compatible: raise ValueError("experiment capability refused: " + "; ".join(preflight.declared_problems)) - # The explicit installation admits this adapter only; declaration - # can_execute and scientific qualification are not changed. - # Ionic transport retains the accepted reader's exact core request. - # Its sole installed v1 route and unique prepared identity bind the - # HTTP experiment/device selection without another request schema. payload = job.request.request if isinstance(registration, (IonicTransientRegistration, IonicJVRegistration, Steady2DRegistration)) else SourceDocument(f"solarlab.registered-{request_kind}-request.v1", canonical({ "experiment_id": submission.experiment_id, "version": submission.version, "engine": submission.engine, f"{request_kind}_request_id": job.request.request.id, @@ -428,22 +401,16 @@ def prepare(self, submission: JobSubmission) -> tuple[RunSpec, ManifestBinding]: class JobService: catalog: ExecutionCatalog supervisor: ProcessSupervisor - allow_legacy_routes: bool = False - synchronous_wait_seconds: float = 5.0 def __post_init__(self) -> None: if type(self.catalog) is not ExecutionCatalog or type(self.supervisor) is not ProcessSupervisor: raise ValueError("an explicit catalog and shared process supervisor are required") - if type(self.allow_legacy_routes) is not bool: - raise ValueError("legacy route activation must be explicit") - if (type(self.synchronous_wait_seconds) not in {int, float} - or not math.isfinite(self.synchronous_wait_seconds) or self.synchronous_wait_seconds <= 0): - raise ValueError("synchronous compatibility wait must be positive and bounded") def submit(self, submission: JobSubmission) -> JobHandle: spec, execution = self.catalog.prepare(submission) return self.supervisor.submit(submission.run_id, spec.worker_id, spec.request, spec.limits, execution=execution) + def legacy_job_id(handle: JobHandle) -> str: return base64.urlsafe_b64encode(canonical([handle.run_id, handle.attempt_id])).decode().rstrip("=") diff --git a/src/solarlab_server/registered_worker.py b/src/solarlab_server/registered_worker.py index 199ce0b9..a118ba37 100644 --- a/src/solarlab_server/registered_worker.py +++ b/src/solarlab_server/registered_worker.py @@ -1,35 +1,10 @@ -"""Checked installed routes to the existing legacy and steady workers.""" +"""Checked installed routes to the solarlab workers.""" from dataclasses import asdict, replace import base64 import json from solarlab.experiments.worker import WorkerContext, WorkerRequest, WorkerResult from solarlab.materials.source import SourceDocument -from solarlab_server.legacy_engine import _run_legacy, legacy_worker_binding - - -def run_legacy(request: WorkerRequest, context: WorkerContext) -> WorkerResult: - catalog = json.loads(request.registry.content) - body = json.loads(request.request.content) - if (set(body) != {"experiment_id", "version", "engine", "legacy_request_id", "legacy_request_base64"} - or catalog["schema"] != "solarlab.execution-catalog.v1" or body["engine"] != "legacy" - or catalog["job_schema_sha256"] != request.schema.sha256 - or catalog["legacy_facade_sha256"] != legacy_worker_binding().source_sha256): - raise ValueError("worker registry/schema/facade differs from the admitted source") - entry = next((r for r in catalog["bindings"] if (r["experiment_id"], r["version"], r["engine"]) == - (body["experiment_id"], body["version"], body["engine"])), None) - binding = context.consume_manifest(request, engine="legacy") - if (entry is None or catalog["model_registry_sha256"] != binding.inputs.registry.content_sha256 - or entry["model_registry_sha256"] != binding.inputs.registry.content_sha256): - raise ValueError("worker experiment/model registry mismatch") - inner = replace(request, request=SourceDocument(body["legacy_request_id"], - base64.b64decode(body["legacy_request_base64"], validate=True))) - if json.loads(inner.request.content)["driver"] != entry["driver"]: - raise ValueError("worker driver differs from the selected experiment") - output = _run_legacy(inner, context) - return WorkerResult.from_dict({**json.loads(output.result_json), - "experiment_id": body["experiment_id"], "experiment_version": body["version"], - "execution_catalog_sha256": request.registry.sha256}, artifacts=output.artifacts) def run_steady(request: WorkerRequest, context: WorkerContext) -> WorkerResult: diff --git a/src/solarlab_server/routes/legacy.py b/src/solarlab_server/routes/legacy.py index 972618eb..6eb5b3df 100644 --- a/src/solarlab_server/routes/legacy.py +++ b/src/solarlab_server/routes/legacy.py @@ -1,22 +1,18 @@ -"""Opt-in old HTTP framing; durable sequence plus phase prevents terminal gaps.""" +"""Solver-free historical RunStore readback for old stored runs; legacy execution retired.""" from __future__ import annotations -from dataclasses import asdict -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator import json import math import struct from typing import Any -import uuid from fastapi import FastAPI, Header, HTTPException, Request from starlette.concurrency import run_in_threadpool from starlette.responses import JSONResponse, Response, StreamingResponse -from solarlab.experiments.execution import JobHandle from solarlab_server.events import attempt_record, event_stream, replay_cursor -from solarlab_server.job_service import JobSubmission, legacy_job_target -from solarlab_server.routes.jobs import body, service, submitted +from solarlab_server.job_service import legacy_job_target from solarlab_server.routes.results import result_payload @@ -51,7 +47,10 @@ def legacy_result(store: Any, run_id: str, attempt_id: str, maximum_bytes: int) view = result_payload(store, run_id, attempt_id, maximum_bytes) payload = next((a for a in view["artifacts"] if a["name"] == "legacy_result"), None) if payload is not None and payload["size_bytes"] <= 256 * 1024: - result = _old_json(json.loads(store.read_artifact(payload["artifact_id"]))) + decoded = json.loads(store.read_artifact(payload["artifact_id"])) + if isinstance(decoded, dict) and decoded.get("schema") == "solarlab.legacy-raw-result.v1" and "result" in decoded: + decoded = decoded["result"] + result = _old_json(decoded) if type(result) is not dict: result = {"value": result} else: @@ -82,36 +81,28 @@ def legacy_cursor(store: Any, run_id: str, attempt_id: str, last: str | None) -> def install_legacy(app: FastAPI, *, max_artifact_bytes: int, event_page_size: int, poll_interval: float, keepalive_interval: float) -> None: - async def submit_legacy(request: Request, *, fixed_key: tuple[str, int] | None = None) -> dict[str, Any]: - context = service(request) - if not context.allow_legacy_routes: - raise HTTPException(404, "legacy compatibility routes are not enabled") - value = await body(request) - if fixed_key is None: - if set(value) - {"kind", "device", "config_path", "params"} or "kind" not in value: - raise HTTPException(422, "legacy jobs require kind/device/config_path/params") - registration = next((r for r in context.catalog.registrations if value["kind"] in r.legacy_kinds), None) - parameters = {"device": value.get("device"), "config_path": value.get("config_path"), "params": value.get("params", {})} - else: - registration = next((r for r in context.catalog.registrations - if (r.experiment_id, r.version) == fixed_key), None) - parameters = {"device": value.get("device"), "config_path": value.get("config_path"), - "params": {k: v for k, v in value.items() if k not in {"device", "config_path"}}} - if registration is None: - raise HTTPException(422, "legacy caller has not migrated; retain its original entry") - declaration = JobSubmission.model_validate({"schema_version": "solarlab.job-submission.v1", "run_id": uuid.uuid4().hex, - "experiment_id": registration.experiment_id, "version": registration.version, "engine": "legacy", - "input": parameters, "limits": asdict(context.catalog.ceiling)}) - result = await run_in_threadpool(submitted, context, declaration) - return {**result, "status": "ok", "legacy_events_url": f"/api/jobs/{result['job_id']}/events"} - @app.post("/api/jobs") - async def jobs(request: Request) -> JSONResponse: - return JSONResponse(await submit_legacy(request), status_code=202) + async def retired_jobs() -> JSONResponse: + raise HTTPException( + 410, + detail={ + "code": "legacy_execution_retired", + "message": "POST /api/jobs is retired; submit V2 jobs via POST /jobs with engine='solarlab'", + }, + ) + + @app.get("/api/jobs/{job_id}/result") + def read_historical_result(request: Request, job_id: str) -> JSONResponse: + store = request.app.state.run_store + run_id, attempt_id = legacy_job_target(job_id) + return JSONResponse( + legacy_result(store, run_id, attempt_id, max_artifact_bytes), + headers={"X-RunStore-ID": store.store_id}, + ) @app.get("/api/jobs/{job_id}/events") async def events(request: Request, job_id: str, last_event_id: str | None = Header(None, alias="Last-Event-ID")) -> Response: - # A read-only restart needs no live execution service to replay old jobs. + # Read-only historical RunStore replay requires zero live execution service or legacy solver imports. store = request.app.state.run_store run_id, attempt_id = legacy_job_target(job_id) await run_in_threadpool(attempt_record, store, run_id, attempt_id) @@ -145,21 +136,12 @@ async def stream() -> AsyncIterator[str]: yield f"id: {sequence}.event\nevent: progress\ndata: {json.dumps(data, allow_nan=False)}\n\n" return StreamingResponse(stream(), media_type="text/event-stream", headers=headers) - context = app.state.job_service - if context is not None and context.allow_legacy_routes: - def endpoint(experiment_id: str, version: int) -> Callable[[Request], Awaitable[JSONResponse]]: - async def synchronous(request: Request) -> JSONResponse: - submitted_job = await submit_legacy(request, fixed_key=(experiment_id, version)) - handle = JobHandle(submitted_job["store_id"], submitted_job["run_id"], submitted_job["attempt_id"]) - try: - receipt = await run_in_threadpool(context.supervisor.wait, handle, context.synchronous_wait_seconds) - except TimeoutError: - return JSONResponse({**submitted_job, "status": "pending"}, status_code=202) - if receipt.data["store_state"] != "succeeded": - return JSONResponse({"status": "error", "job": submitted_job, "result": receipt.data}, status_code=422) - result = await run_in_threadpool(legacy_result, context.supervisor.store, handle.run_id, handle.attempt_id, max_artifact_bytes) - return JSONResponse({"status": "ok", "result": result}) - return synchronous - for registration in context.catalog.registrations: - for path in registration.synchronous_paths: - app.add_api_route(path, endpoint(registration.experiment_id, registration.version), methods=["POST"]) + @app.post("/api/{retired_path:path}") + async def retired_synchronous(retired_path: str) -> JSONResponse: + raise HTTPException( + 410, + detail={ + "code": "legacy_execution_retired", + "message": f"POST /api/{retired_path} is retired; submit V2 jobs via POST /jobs with engine='solarlab'", + }, + ) diff --git a/tests/runtime/ionic_jv_wall_fixtures.py b/tests/runtime/ionic_jv_wall_fixtures.py index bbb71677..6612eba5 100644 --- a/tests/runtime/ionic_jv_wall_fixtures.py +++ b/tests/runtime/ionic_jv_wall_fixtures.py @@ -1,22 +1,22 @@ -"""Actual catalog compositions shared by the base oracle and V3 regressions.""" +"""Actual solarlab catalog compositions shared by the base oracle and V3 regressions.""" from dataclasses import replace METHODS = ("ionic_base", "other_base", "constructor") -KINDS = ("legacy", "ion_free", "ionic_transient", "two_dimensional") +KINDS = ("ion_free", "ionic_transient", "two_dimensional") def companions(implementation): - import job_route_fixtures from examples.research_1d.ionic_transient_service import installed_catalog as ionic_transient from examples.research_1d.transient_service import installed_catalog as ion_free from examples.research_2d.http_steady import installed_catalog as two_dimensional head = implementation.build_source_commit - return {"legacy": job_route_fixtures.catalog()[0], - "ion_free": ion_free(implementation, head), - "ionic_transient": ionic_transient(implementation, head), - "two_dimensional": two_dimensional(implementation, head)} + return { + "ion_free": ion_free(implementation, head), + "ionic_transient": ionic_transient(implementation, head), + "two_dimensional": two_dimensional(implementation, head), + } def compose(ionic, other, method, reverse, *, wall_seconds=None): @@ -26,42 +26,63 @@ def compose(ionic, other, method, reverse, *, wall_seconds=None): catalogs = (other, ionic) if reverse else (ionic, other) sources = {source.id: source for catalog in catalogs for source in catalog.sources} registry = ExperimentRegistry(tuple(d for catalog in catalogs for d in catalog.registry.definitions)) - ceiling = replace(ionic.ceiling, wall_seconds=( - max(ionic.ceiling.wall_seconds, other.ceiling.wall_seconds) if wall_seconds is None else wall_seconds)) - common = dict(registry=registry, models=other.models, expected_registry_sha256=registry.content_sha256, - expected_model_sha256=other.models.content_sha256, sources=tuple(sources.values()), - registrations=tuple(r for catalog in catalogs for r in catalog.registrations), ceiling=ceiling) + ceiling = replace( + ionic.ceiling, + wall_seconds=( + max(ionic.ceiling.wall_seconds, other.ceiling.wall_seconds) if wall_seconds is None else wall_seconds + ), + ) + common = dict( + registry=registry, + models=other.models, + expected_registry_sha256=registry.content_sha256, + expected_model_sha256=other.models.content_sha256, + sources=tuple(sources.values()), + registrations=tuple(r for catalog in catalogs for r in catalog.registrations), + ceiling=ceiling, + ) if method == "constructor": return ExecutionCatalog(**common) return replace(ionic if method == "ionic_base" else other, **common) def submissions(kind): - import job_route_fixtures from examples.research_1d.ionic_jv_service import example_submission as ionic_jv from examples.research_1d.ionic_transient_service import example_submission as ionic_transient from examples.research_1d.transient_service import example_submission as transient from examples.research_2d.http_steady import example_submission as two_dimensional bodies = [ionic_jv()] - if kind == "legacy": - bodies.append(job_route_fixtures.request()) - elif kind == "ion_free": + if kind == "ion_free": bodies.append(transient()) steady = ionic_jv() - steady.update(experiment_id="steady_jv", input={"device_id": "research_1d", "voltage_V": [0., .05, .1], - "intervals_per_layer": 12, "generation_scale": 1., "incident_power_W_m2": None}) + steady.update( + experiment_id="steady_jv", + input={ + "device_id": "research_1d", + "voltage_V": [0.0, 0.05, 0.1], + "intervals_per_layer": 12, + "generation_scale": 1.0, + "incident_power_W_m2": None, + }, + ) bodies.append(steady) else: bodies.append(ionic_transient() if kind == "ionic_transient" else two_dimensional()) - walls = (30., 60., 61., 128.) if kind == "ion_free" else (30., 31., 128.) - return [(f"{kind}/{body['experiment_id']}/{int(wall)}", - {**body, "limits": {**body["limits"], "wall_seconds": wall}}) - for body in bodies for wall in walls] + walls = (30.0, 60.0, 61.0, 128.0) if kind == "ion_free" else (30.0, 31.0, 128.0) + return [ + ( + f"{kind}/{body['experiment_id']}/{int(wall)}", + {**body, "limits": {**body["limits"], "wall_seconds": wall}}, + ) + for body in bodies + for wall in walls + ] def admit(catalog, body): from solarlab_server.job_service import JobSubmission + try: spec, _ = catalog.prepare(JobSubmission.model_validate(body)) except ValueError as error: diff --git a/tests/runtime/job_route_fixtures.py b/tests/runtime/job_route_fixtures.py index 6e75a330..50cfeee4 100644 --- a/tests/runtime/job_route_fixtures.py +++ b/tests/runtime/job_route_fixtures.py @@ -1,65 +1,91 @@ -"""Source-bound short legacy input registration for real HTTP/worker tests.""" -from typing import Literal -import hashlib -import json +"""Source-bound short solarlab steady registration for real HTTP/worker tests.""" +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path +import subprocess from pydantic import BaseModel, ConfigDict, Field -from solarlab.experiments.registry import ExperimentDefinition, ExperimentRegistry +from examples.research_1d.steady import load_device +from solarlab.config.identity import BuildSource, ExecutionEngine +from solarlab.experiments.jv.worker import SteadyJVProtocol, prepare_steady_jv_job +from solarlab.experiments.registry import ExperimentRegistry from solarlab.experiments.worker import ResourceLimits +from solarlab.materials.resources import ResourceLibrary, ResourceTable from solarlab.materials.source import SourceDocument -from solarlab.physics.registry import CapabilityRule, EvidenceRef -from solarlab_server.job_service import ExecutionCatalog, LegacyRegistration -from legacy_fixtures import LEGACY, ROOT, make_job +from solarlab_server.steady_preparation import SteadyPreparationContext, steady_execution_catalog + +ROOT = Path(__file__).resolve().parents[2] class Parameters(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) N_grid: int = Field(default=8, ge=4, le=8) n_points: int = Field(default=3, ge=1, le=3) - V_max: float = Field(default=.02, ge=0., le=.03) - v_rate: float = Field(default=1000., gt=0.) - - -class LegacyInput(BaseModel): - model_config = ConfigDict(extra="forbid", strict=True) - device: None - config_path: Literal["fixture:scaps"] - params: Parameters + V_max: float = Field(default=0.02, ge=0.0, le=0.03) + v_rate: float = Field(default=1000.0, gt=0.0) -def prepare_jv(input: LegacyInput): - # The input model permits only this explicit source and bounded test range. - return make_job(arguments=input.params.model_dump())[0] +def _working_tree_implementation() -> tuple[BuildSource, str]: + head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True, timeout=5).strip() + pkg_root = ROOT / "src" / "solarlab" + sources = tuple( + SourceDocument("solarlab/" + path.relative_to(pkg_root).as_posix(), path.read_bytes()) + for path in sorted(pkg_root.rglob("*.py")) + if path.stat().st_size > 0 + ) + return BuildSource(head, sources), head -def catalog(*, denied=False, wall_seconds=30., ceiling=None): - job = make_job()[0] - documents = {} - def reference(path, symbol=""): - documents[path] = (ROOT / path).read_bytes() - return EvidenceRef(path + ("#" + symbol if symbol else ""), hashlib.sha256(documents[path]).hexdigest(), "source") - factory = reference("tests/runtime/job_route_fixtures.py", "prepare_jv") - schema = json.dumps(LegacyInput.model_json_schema(), sort_keys=True, separators=(",", ":"), allow_nan=False).encode() - documents["schema:legacy-http-fixture"] = schema - schema_ref = EvidenceRef("schema:legacy-http-fixture", hashlib.sha256(schema).hexdigest(), "source") - definition = ExperimentDefinition("jv", 1, "Short source-bound legacy J-V test", schema_ref, - reference("src/solarlab/experiments/worker.py", "WorkerResult"), factory, - reference("src/solarlab_server/legacy_engine/__init__.py", "_run_legacy"), "jv", - reference("web/src/workstation/panes/main-plot-pane.ts", "renderJV"), - CapabilityRule("legacy-http-fixture", (2,) if denied else (1,), ("transient",), (factory,), backends=("metadata_only",))) - documents["physics/temperature.py"] = (LEGACY / "physics/temperature.py").read_bytes() - registry = ExperimentRegistry((definition,)) - models = job.execution.inputs.registry - registration = LegacyRegistration("jv", 1, "scaps_transient", LegacyInput, prepare_jv, - legacy_kinds=("jv",), synchronous_paths=("/api/jv",)) - cap = ceiling or ResourceLimits(wall_seconds, 1024**3, 64 * 1024**2, None, None) - return ExecutionCatalog(registry, models, tuple(SourceDocument(k, v) for k, v in documents.items()), - (registration,), expected_registry_sha256=registry.content_sha256, expected_model_sha256=models.content_sha256, ceiling=cap), job +def catalog(*, denied: bool = False, wall_seconds: float = 30.0, ceiling: ResourceLimits | None = None): + implementation, head = _working_tree_implementation() + base_device = load_device() + sample_table = ResourceTable( + "fixture_nk", + "nk", + SourceDocument("fixture_nk.csv", b"wavelength_nm,n,k\n500,2.5,0.1\n600,2.4,0.05\n"), + ) + prepared = replace(base_device, resources=ResourceLibrary((sample_table,))) + context = SteadyPreparationContext((("research_1d", prepared),), implementation, head) + cap = ceiling or ResourceLimits(wall_seconds, 1536 * 1024**2, 96 * 1024**2, None, None) + built = steady_execution_catalog(context, ceiling=cap) + if denied: + defn = built.registry.get("steady_jv", 1) + denied_reg = ExperimentRegistry( + (replace(defn, capability=replace(defn.capability, dimensions=(2,))),) + ) + built = replace(built, registry=denied_reg, expected_registry_sha256=denied_reg.content_sha256) + job = prepare_steady_jv_job( + prepared, + SteadyJVProtocol((0.0, 0.05), 6, 1.0, None), + implementation=implementation, + current_repository_head=head, + engine=ExecutionEngine("solarlab"), + ) + return built, job -def request(run_id="http-case", **parameters): - return {"schema_version": "solarlab.job-submission.v1", "run_id": run_id, "experiment_id": "jv", "version": 1, - "engine": "legacy", "input": {"device": None, "config_path": "fixture:scaps", "params": parameters}, - "limits": {"wall_seconds": 30., "rss_bytes": 1024**3, "output_bytes": 64 * 1024**2, - "accepted_steps": None, "calls": None}} +def request(run_id: str = "http-case", *, n_points: int = 2, intervals_per_layer: int = 6) -> dict: + voltages = [0.0] if n_points == 1 else [round(0.05 * i, 4) for i in range(n_points)] + return { + "schema_version": "solarlab.job-submission.v1", + "run_id": run_id, + "experiment_id": "steady_jv", + "version": 1, + "engine": "solarlab", + "input": { + "device_id": "research_1d", + "voltage_V": voltages, + "intervals_per_layer": intervals_per_layer, + "generation_scale": 1.0, + "incident_power_W_m2": None, + }, + "limits": { + "wall_seconds": 30.0, + "rss_bytes": 1536 * 1024**2, + "output_bytes": 96 * 1024**2, + "accepted_steps": None, + "calls": None, + }, + } diff --git a/tests/runtime/job_workers.py b/tests/runtime/job_workers.py index 1da513ea..7fcf6762 100644 --- a/tests/runtime/job_workers.py +++ b/tests/runtime/job_workers.py @@ -1,23 +1,29 @@ -"""Actual process barriers before the production registered legacy worker.""" +"""Actual process barriers before the production registered solarlab steady worker.""" from pathlib import Path import time -def gated_legacy(request, context): +def gated_steady(request, context): context.progress({"stage": "ready"}) deadline = time.monotonic() + 8 while not Path("release").exists() and time.monotonic() < deadline: context.check_cancel() - time.sleep(.005) - from solarlab_server.registered_worker import run_legacy - return run_legacy(request, context) + time.sleep(0.005) + from solarlab_server.registered_worker import run_steady + return run_steady(request, context) -def stuck_legacy(request, context): +def failing_steady(request, context): + context.consume_manifest(request, engine="solarlab") + context.progress({"stage": "ready"}) + raise RuntimeError("injected steady worker driver failure") + + +def stuck_steady(request, context): import signal signal.signal(signal.SIGTERM, signal.SIG_IGN) context.progress({"stage": "ready"}) deadline = time.monotonic() + 8 while time.monotonic() < deadline: - time.sleep(.01) + time.sleep(0.01) raise RuntimeError("orphaned test worker ended its independent bound") diff --git a/tests/runtime/test_ionic_jv_job_service.py b/tests/runtime/test_ionic_jv_job_service.py index 913c7673..e8eb7fbb 100644 --- a/tests/runtime/test_ionic_jv_job_service.py +++ b/tests/runtime/test_ionic_jv_job_service.py @@ -452,11 +452,14 @@ def wall_companions(implementation): return companions(implementation) -@pytest.mark.parametrize("kind", ["legacy", "ion_free", "ionic_transient", "two_dimensional"]) +@pytest.mark.parametrize("kind", ["ion_free", "ionic_transient", "two_dimensional"]) @pytest.mark.parametrize("method", ["ionic_base", "other_base", "constructor"]) @pytest.mark.parametrize("reverse", [False, True]) def test_catalog_compositions_match_the_base_wall_oracle(catalog, wall_companions, kind, method, reverse): from ionic_jv_wall_fixtures import admit, compose, submissions + from pydantic import ValidationError + with pytest.raises(ValidationError): + JobSubmission.model_validate({**example_submission(), "engine": "legacy"}) oracle = json.loads((ROOT / "tests/runtime/fixtures/ionic_jv_wall_composition_baseline.json").read_text()) assert oracle["base_commit"] == "cbec4788a0f83ae5c6c4719b1fd95c0fc037d09d" combined = compose(catalog, wall_companions[kind], method, reverse) diff --git a/tests/runtime/test_job_route_client.py b/tests/runtime/test_job_route_client.py index bf1e3c9c..ac7d097c 100644 --- a/tests/runtime/test_job_route_client.py +++ b/tests/runtime/test_job_route_client.py @@ -1,4 +1,4 @@ -"""Existing TypeScript client against the shared loopback job service.""" +"""Live V2 TypeScript job client against the shared loopback solarlab_server.""" import json import subprocess @@ -6,65 +6,95 @@ from solarlab.experiments.execution import JobHandle from solarlab.io.run_store import RunStore -from solarlab_server.job_service import JobService, legacy_job_target +from solarlab_server.job_service import JobService from job_route_fixtures import ROOT from test_job_routes import _HTTPServer, registered as registered, supervisor pytestmark = pytest.mark.frontend -def test_actual_old_typescript_client_consumes_the_live_new_adapter(tmp_path, registered): +def test_actual_v2_typescript_client_executes_solarlab_job_and_retired_legacy_route_refuses(tmp_path, registered): registration, _ = registered with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration) as pool: - with _HTTPServer(store.root, job_service=JobService(registration, pool, allow_legacy_routes=True)) as server: - # Only the test module's BASE import is bound to the actual loopback - # socket. The production TS client source is transpiled unchanged. - code = ''' -import {readFile, writeFile} from 'node:fs/promises'; -import {pathToFileURL} from 'node:url'; + with _HTTPServer(store.root, job_service=JobService(registration, pool)) as server: + endpoint = f"http://127.0.0.1:{server.port}/" + code = """ +import { readFile, writeFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; import assert from 'node:assert/strict'; + const ts = (await import(pathToFileURL(process.argv[2]))).default; -const source = await readFile(process.argv[3], 'utf8'); -const output = ts.transpileModule(source, {compilerOptions:{target:ts.ScriptTarget.ES2023,module:ts.ModuleKind.ES2022}}).outputText; -await writeFile(process.argv[4], output.replace("from './api'", "from './base.mjs'")); -await writeFile(new URL('./base.mjs',pathToFileURL(process.argv[4])), `export const BASE=${JSON.stringify(process.argv[5])};`); -globalThis.EventSource = class { - constructor(url) { this.events={}; this.abort=new AbortController(); this.run(url); } - addEventListener(name, fn) { (this.events[name]??=[]).push(fn); } - emit(name, value) { for (const fn of this.events[name]??[]) fn(value); } - close() { this.abort.abort(); } - async run(url) { - try { - const response=await fetch(url,{signal:this.abort.signal}); assert.equal(response.status,200); - const reader=response.body.getReader(), decoder=new TextDecoder(); let buffer=''; - for (;;) { - const {done,value}=await reader.read(); if(done) break; buffer+=decoder.decode(value,{stream:true}); - let at; while((at=buffer.indexOf('\\n\\n'))>=0) { - const block=buffer.slice(0,at); buffer=buffer.slice(at+2); - const fields=Object.fromEntries(block.split('\\n').filter(x=>!x.startsWith(':')).map(x=>{const p=x.indexOf(':');return [x.slice(0,p),x.slice(p+1).trimStart()]})); - if(fields.event) this.emit(fields.event,{data:fields.data}); - } - } - } catch(error) { if(error.name!=='AbortError') this.emit('error',{}); } - } -}; -const {startJob,streamJobEvents}=await import(pathToFileURL(process.argv[4])); -const job=await startJob('jv',null,{},'fixture:scaps'); -let progress=0,result; let timer; -await new Promise((resolve,reject)=>{ - timer=setTimeout(()=>reject(Error('bounded client wait expired')),15000); - streamJobEvents(job,{onProgress:()=>progress++,onResult:value=>result=value,onError:reject,onDone:resolve}); -}).finally(()=>clearTimeout(timer)); -assert(progress>0); assert(result.artifacts.length>0); assert.equal(result.execution.worker_result.scientific_qualification,false); -console.log(JSON.stringify({job,progress,result_received:true,done_received:true})); -''' - program = tmp_path / "client-check.mjs" +const srcRoot = process.argv[3]; +const outDir = process.argv[4]; +const endpoint = process.argv[5]; + +async function transpile(relName, replacements = []) { + let code = await readFile(`${srcRoot}/${relName}.ts`, 'utf8'); + for (const [from, to] of replacements) code = code.replaceAll(from, to); + const out = ts.transpileModule(code, { + compilerOptions: { target: ts.ScriptTarget.ES2023, module: ts.ModuleKind.ES2022 }, + }).outputText; + await writeFile(`${outDir}/${relName}.mjs`, out); +} + +await transpile('run-client'); +await transpile('steady-jv-client', [["'./run-client'", "'./run-client.mjs'"]]); +await transpile('v2-workstation-client', [["import.meta.env.VITE_SOLARLAB_SERVICE_BASE", "undefined"]]); +await transpile('v2-job-client', [ + ["'./run-client'", "'./run-client.mjs'"], + ["'./steady-jv-client'", "'./steady-jv-client.mjs'"], + ["'./v2-workstation-client'", "'./v2-workstation-client.mjs'"], +]); +await writeFile(`${outDir}/base.mjs`, `export const BASE = ${JSON.stringify(endpoint.replace(/\\/$/, ''))};`); +await transpile('job-stream', [["'./api'", "'./base.mjs'"]]); + +// 1. Retained legacy job-stream.ts is explicitly refused with HTTP 410 and zero fallback. +const legacyMod = await import(pathToFileURL(`${outDir}/job-stream.mjs`)); +await assert.rejects( + () => legacyMod.startJob('jv', null, {}, 'fixture:scaps'), + err => String(err.message).includes('410'), +); + +// 2. Production V2 job client submits engine='solarlab' via POST /jobs and streams durable RunStore events. +const { startJob, streamJobEvents } = await import(pathToFileURL(`${outDir}/v2-job-client.mjs`)); +const handle = await startJob('jv', null, { n_points: 2, V_max: 0.05, N_grid: 18 }, null, endpoint); +const decoded = JSON.parse(Buffer.from(handle.slice(3), 'base64').toString('utf8')); +let progress = 0; +let result; +let timer; +await new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error('bounded client wait expired')), 15000); + streamJobEvents(handle, { + onProgress: () => { progress += 1; }, + onResult: value => { result = value; }, + onError: msg => reject(new Error(msg)), + onDone: () => resolve(undefined), + }); +}).finally(() => clearTimeout(timer)); + +assert(progress > 0); +assert.equal(result.scientific_qualification, false); +assert.equal(result.execution_manifest.engine, 'solarlab'); +assert.deepEqual(result.V_fwd, [0, 0.05]); +console.log(JSON.stringify({ + runId: decoded.runId, + attemptId: decoded.attemptId, + progress, + scientific_qualification: result.scientific_qualification, +})); +""" + program = tmp_path / "v2-client-check.mjs" program.write_text(code) - command = ["node", str(program), str(ROOT / "web/node_modules/typescript/lib/typescript.js"), - str(ROOT / "web/src/job-stream.ts"), str(tmp_path / "job-stream.mjs"), f"http://127.0.0.1:{server.port}"] + command = [ + "node", + str(program), + str(ROOT / "web/node_modules/typescript/lib/typescript.js"), + str(ROOT / "web/src"), + str(tmp_path), + endpoint, + ] actual = subprocess.run(command, capture_output=True, text=True, timeout=25) assert actual.returncode == 0, actual.stdout + actual.stderr record = json.loads(actual.stdout) - run_id, attempt_id = legacy_job_target(record["job"]) - assert store.get_run(run_id)["state"] == "succeeded" - assert pool.wait(JobHandle(store.store_id, run_id, attempt_id), 3).data["process_joined"] + assert store.get_run(record["runId"])["state"] == "succeeded" + assert pool.wait(JobHandle(store.store_id, record["runId"], record["attemptId"]), 5).data["process_joined"] diff --git a/tests/runtime/test_job_routes.py b/tests/runtime/test_job_routes.py index 8c25f522..3b461c0b 100644 --- a/tests/runtime/test_job_routes.py +++ b/tests/runtime/test_job_routes.py @@ -1,22 +1,21 @@ -"""Real loopback submissions, registry refusals and complete durable streams.""" +"""Real loopback V2 solarlab submissions, registry refusals, durable streams, and historical readback.""" from dataclasses import replace import hashlib import json import os from pathlib import Path +import struct import time import pytest from solarlab.experiments.execution import JobHandle, ProcessSupervisor -from solarlab.experiments.registry import ExperimentRegistry -from solarlab.experiments.worker import ResourceLimits, WorkerBinding +from solarlab.experiments.worker import WorkerBinding +from solarlab.io.artifacts import bytes_artifact from solarlab.io.run_store import RunStore -from solarlab_server.job_service import JobService, JobSubmission, canonical, legacy_job_id, legacy_job_target from solarlab.materials.source import SourceDocument -from solarlab.io.artifacts import bytes_artifact from solarlab_server.configuration import ConfigurationPreviewContext -from solarlab_server.legacy_engine import legacy_worker_binding +from solarlab_server.job_service import JobService, JobSubmission, canonical, legacy_job_id from test_event_service import _HTTPServer as _BaseHTTPServer, _all_events, _blocks, _next_event from job_route_fixtures import catalog, request as declaration import job_workers @@ -25,7 +24,7 @@ class _HTTPServer(_BaseHTTPServer): def client(self): client = super().client() - client.timeout = 15. + client.timeout = 15.0 return client @@ -37,18 +36,33 @@ def registered(): def supervisor(store, work, registration, *, gated=None, bad_binding=False, max_pending=1): binding = registration.worker_binding() if gated is not None: - binding = WorkerBinding.from_function(binding.id, gated, - registry_sha256=binding.registry_sha256, schema_sha256=binding.schema_sha256) + binding = WorkerBinding.from_function( + binding.id, + gated, + registry_sha256=binding.registry_sha256, + schema_sha256=binding.schema_sha256, + ) if bad_binding: binding = replace(binding, source_sha256="0" * 64) - return ProcessSupervisor(store, work, (binding, legacy_worker_binding()), max_active=1, max_pending=max_pending, - shared_rss_bytes=4 * 1024**3, shared_output_bytes=512 * 1024**2, - soft_grace_seconds=.1, terminate_grace_seconds=.1, poll_seconds=.01) + return ProcessSupervisor( + store, + work, + (binding,), + max_active=1, + max_pending=max_pending, + shared_rss_bytes=4 * 1024**3, + shared_output_bytes=512 * 1024**2, + soft_grace_seconds=0.1, + terminate_grace_seconds=0.1, + poll_seconds=0.01, + ) def headers(registration): - return {"X-Solarlab-Registry": registration.document.sha256, - "X-Solarlab-Job-Schema": registration.schema.sha256} + return { + "X-Solarlab-Registry": registration.document.sha256, + "X-Solarlab-Job-Schema": registration.schema.sha256, + } def handle(store, response): @@ -60,7 +74,7 @@ def ready(store, run_id): while time.monotonic() < until: if any(e["payload"].get("ui_progress", {}).get("stage") == "ready" for e in store.events(run_id=run_id)): return - time.sleep(.005) + time.sleep(0.005) raise AssertionError("child did not reach the observed ready barrier") @@ -77,6 +91,8 @@ def test_real_registry_submit_full_stream_verified_result_and_read_only_restart( assert advertised.headers["x-solarlab-registry"] == registration.document.sha256 assert advertised.json()["registry"]["registered_executors"] == [] assert advertised.json()["bindings"][0]["scientific_qualification"] is False + assert advertised.json()["bindings"][0]["engine"] == "solarlab" + assert "legacy_facade_sha256" not in advertised.json() assert http.get("/schema").json()["array"]["properties"]["shape"]["maxItems"] == 32 assert http.get("/configs").json()["sources"] source = data.sources[0] @@ -93,29 +109,30 @@ def test_real_registry_submit_full_stream_verified_result_and_read_only_restart( events = _all_events(stream) assert events[-1]["kind"] == "terminal" and events[-1]["payload"]["state"] == "succeeded" assert sum(e["kind"] == "terminal" for e in events) == 1 - receipt = pool.wait(handle(store, submitted), 5).data + receipt = pool.wait(handle(store, submitted), 10).data assert receipt["process_joined"] and receipt["process_exit_observed"] result = http.get(submitted["result_url"]).json() - assert result["result"]["worker_result"]["experiment_id"] == "jv" + assert result["result"]["worker_result"]["experiment_id"] == "steady_jv" assert result["result"]["worker_result"]["scientific_qualification"] is False - payload = next(a for a in result["artifacts"] if a["name"] == "legacy_result") + payload = next(a for a in result["artifacts"] if a["name"] == "voltage_V") raw = http.get(payload["content_url"]).content assert hashlib.sha256(raw).hexdigest() == payload["sha256"] assert raw == store.read_artifact(payload["artifact_id"]) manifest = next(a for a in result["artifacts"] if a["name"] == "execution_manifest") assert manifest["sha256"] == receipt["worker_result"]["manifest_sha256"] - control = job.submit(pool, "direct-control", ResourceLimits(**declaration()["limits"])) - control_receipt = pool.wait(control, 8).data - assert control_receipt["store_state"] == "succeeded" - control_records = [store.artifact(x) for x in control_receipt["terminal_artifacts"]] - original = next(a for a in control_records if a["name"] == "legacy_result") - assert raw == store.read_artifact(original["artifact_id"]) evidence_path = os.environ.get("SOLARLAB_HTTP_JOB_EVIDENCE") if evidence_path: - Path(evidence_path).write_text(json.dumps({"bitwise_equal": True, - "routed_payload_sha256": payload["sha256"], "direct_facade_payload_sha256": original["sha256"], - "routed": receipt, "direct_facade": control_receipt, - "scientific_qualification": False}, indent=2) + "\n") + Path(evidence_path).write_text( + json.dumps( + { + "routed_payload_sha256": payload["sha256"], + "routed": receipt, + "scientific_qualification": False, + }, + indent=2, + ) + + "\n" + ) with _HTTPServer(database) as server, server.client() as http: assert http.get(submitted["result_url"]).json() == result with http.stream("GET", submitted["events_url"]) as stream: @@ -131,14 +148,17 @@ def test_headers_input_engine_and_capability_refuse_before_enqueue(tmp_path, reg for field in headers(registration): invalid = {**headers(registration), field: "0" * 64} assert http.post("/jobs", json=declaration(), headers=invalid).status_code == 409 - for change in ({"engine": "solarlab"}, {"experiment_id": "impedance"}, {"version": 99}): + for change in ({"engine": "legacy"}, {"experiment_id": "impedance"}, {"version": 99}): assert http.post("/jobs", json={**declaration(), **change}, headers=headers(registration)).status_code == 422 raw = declaration() - raw["input"]["params"]["ignored_extra"] = True + raw["input"]["ignored_extra"] = True assert http.post("/jobs", json=raw, headers=headers(registration)).status_code == 422 raw = declaration() - raw["limits"]["wall_seconds"] = 31. + raw["limits"]["wall_seconds"] = 31.0 assert http.post("/jobs", json=raw, headers=headers(registration)).status_code == 422 + # Legacy POST routes are retired with HTTP 410 and zero fallback. + assert http.post("/api/jobs", json={"kind": "jv", "device": None}).status_code == 410 + assert http.post("/api/jv", json={"device": None}).status_code == 410 assert store.events() == [] denied, _ = catalog(denied=True) with RunStore(tmp_path / "denied") as store, supervisor(store, tmp_path / "denied-work", denied) as pool: @@ -150,8 +170,10 @@ def test_headers_input_engine_and_capability_refuse_before_enqueue(tmp_path, reg def test_two_live_subscribers_disconnect_queued_cancel_and_following_job(tmp_path, registered): registration, _ = registered - with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration, gated=job_workers.gated_legacy) as pool: - with _HTTPServer(store.root, job_service=JobService(registration, pool, allow_legacy_routes=True)) as server: + with RunStore(tmp_path / "store") as store, supervisor( + store, tmp_path / "work", registration, gated=job_workers.gated_steady + ) as pool: + with _HTTPServer(store.root, job_service=JobService(registration, pool)) as server: with server.client() as first, server.client() as second: item = first.post("/jobs", json=declaration(), headers=headers(registration)).json() ready(store, item["run_id"]) @@ -169,8 +191,13 @@ def test_two_live_subscribers_disconnect_queued_cancel_and_following_job(tmp_pat for selected in (queued, item): row = store.get_run(selected["run_id"]) target = f"/jobs/{selected['run_id']}/attempts/{selected['attempt_id']}/cancel" - assert first.post(target, json={"expected_generation": row["generation"] + 10, "reason": "stale"}).status_code == 409 - response = first.post(target, json={"expected_generation": row["generation"], "reason": "explicit HTTP cancellation"}) + assert ( + first.post(target, json={"expected_generation": row["generation"] + 10, "reason": "stale"}).status_code + == 409 + ) + response = first.post( + target, json={"expected_generation": row["generation"], "reason": "explicit HTTP cancellation"} + ) assert response.status_code == 200 assert not pool.wait(handle(store, queued), 3).data["process_started"] later = [json.loads(frame["data"]) for frame in b if "data" in frame] @@ -181,28 +208,38 @@ def test_two_live_subscribers_disconnect_queued_cancel_and_following_job(tmp_pat next_job = first.post("/jobs", json=declaration("after"), headers=headers(registration)).json() ready(store, "after") (tmp_path / "work" / (store.store_id + "-" + next_job["attempt_id"]) / "release").touch() - assert pool.wait(handle(store, next_job), 8).data["store_state"] == "succeeded" + assert pool.wait(handle(store, next_job), 10).data["store_state"] == "succeeded" def test_cancel_rechecks_generation_atomically_after_the_http_read(tmp_path, registered, monkeypatch): registration, _ = registered - with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration, gated=job_workers.gated_legacy) as pool: + with RunStore(tmp_path / "store") as store, supervisor( + store, tmp_path / "work", registration, gated=job_workers.gated_steady + ) as pool: with _HTTPServer(store.root, job_service=JobService(registration, pool)) as server, server.client() as http: first = http.post("/jobs", json=declaration("hold"), headers=headers(registration)).json() ready(store, first["run_id"]) queued = http.post("/jobs", json=declaration("race"), headers=headers(registration)).json() original = store.cancel changed = [] + def changed_generation(run_id, **kwargs): if run_id == "race" and not changed: - # Storage-only concurrency witness: another owner claims - # this queued attempt after the HTTP handler's read. - changed.append(store.claim(run_id, expected_attempt_id=kwargs["expected_attempt_id"], - expected_generation=kwargs["expected_generation"], owner_id="metadata-race-fixture")) + changed.append( + store.claim( + run_id, + expected_attempt_id=kwargs["expected_attempt_id"], + expected_generation=kwargs["expected_generation"], + owner_id="metadata-race-fixture", + ) + ) return original(run_id, **kwargs) + monkeypatch.setattr(store, "cancel", changed_generation) - response = http.post(f"/jobs/race/attempts/{queued['attempt_id']}/cancel", - json={"expected_generation": 0, "reason": "stale after read"}) + response = http.post( + f"/jobs/race/attempts/{queued['attempt_id']}/cancel", + json={"expected_generation": 0, "reason": "stale after read"}, + ) assert response.status_code == 409 assert store.get_run("race")["state"] == "running" monkeypatch.setattr(store, "cancel", original) @@ -210,20 +247,29 @@ def changed_generation(run_id, **kwargs): pool.cancel(handle(store, first)) -@pytest.mark.parametrize("field", ["job_schema_sha256", "model_registry_sha256", "legacy_facade_sha256"]) -def test_real_worker_rejects_internally_wrong_registry_schema_or_facade(tmp_path, registered, field): +@pytest.mark.parametrize("field", ["job_schema_sha256", "model_registry_sha256"]) +def test_real_worker_rejects_internally_wrong_registry_or_schema(tmp_path, registered, field): registration, _ = registered spec, binding = registration.prepare(JobSubmission.model_validate(declaration())) claimed = json.loads(registration.document.content) + if field == "model_registry_sha256": + claimed["bindings"][0]["model_registry_sha256"] = "0" * 64 claimed[field] = "0" * 64 altered = SourceDocument("explicit-inconsistent-registry-fixture", canonical(claimed)) - # The fixture deliberately binds a new transport digest, so the actual - # worker must check the content's relation to the manifest/schema/source. worker = replace(registration.worker_binding(), registry_sha256=altered.sha256) - with RunStore(tmp_path / "store") as store, ProcessSupervisor(store, tmp_path / "work", (worker,), - max_active=1, max_pending=0, shared_rss_bytes=4 * 1024**3, shared_output_bytes=256 * 1024**2) as pool: - result = pool.wait(pool.submit("bad-registry", worker.id, replace(spec.request, registry=altered), spec.limits, - execution=binding), 8).data + with RunStore(tmp_path / "store") as store, ProcessSupervisor( + store, + tmp_path / "work", + (worker,), + max_active=1, + max_pending=0, + shared_rss_bytes=4 * 1024**3, + shared_output_bytes=256 * 1024**2, + ) as pool: + result = pool.wait( + pool.submit("bad-registry", worker.id, replace(spec.request, registry=altered), spec.limits, execution=binding), + 10, + ).data assert result["store_state"] == "failed" and result["worker_result"]["reason"] == "worker_exception" assert "registry" in result["worker_result"]["detail"] assert not result["terminal_artifacts"] and result["process_joined"] @@ -232,13 +278,20 @@ def test_real_worker_rejects_internally_wrong_registry_schema_or_facade(tmp_path @pytest.mark.parametrize("failure", ["timeout", "worker_source", "driver_failure"]) def test_real_worker_failures_produce_business_error_then_done(tmp_path, registered, failure): registration, _ = registered - gated = job_workers.stuck_legacy if failure == "timeout" else None - with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration, - gated=gated, bad_binding=failure == "worker_source") as pool: - with _HTTPServer(store.root, job_service=JobService(registration, pool, allow_legacy_routes=True)) as server, server.client() as http: - data = declaration(n_points=1) if failure == "driver_failure" else declaration() + gated = ( + job_workers.stuck_steady + if failure == "timeout" + else job_workers.failing_steady + if failure == "driver_failure" + else None + ) + with RunStore(tmp_path / "store") as store, supervisor( + store, tmp_path / "work", registration, gated=gated, bad_binding=failure == "worker_source" + ) as pool: + with _HTTPServer(store.root, job_service=JobService(registration, pool)) as server, server.client() as http: + data = declaration() if failure == "timeout": - data["limits"]["wall_seconds"] = .5 + data["limits"]["wall_seconds"] = 0.5 response = http.post("/jobs", json=data, headers=headers(registration)) assert response.status_code == 202, response.text item = response.json() @@ -248,86 +301,71 @@ def test_real_worker_failures_produce_business_error_then_done(tmp_path, registe assert frames[-2]["id"] != frames[-1]["id"] error = json.loads(frames[-2]["data"]) assert error["message"] == ("wall_limit" if failure == "timeout" else "worker_exception") - receipt = pool.wait(handle(store, item), 4).data + receipt = pool.wait(handle(store, item), 5).data assert receipt["store_state"] == "failed" and receipt["process_joined"] - with http.stream("GET", f"/api/jobs/{item['job_id']}/events", headers={"Last-Event-ID": frames[-2]["id"]}) as replay: + with http.stream( + "GET", f"/api/jobs/{item['job_id']}/events", headers={"Last-Event-ID": frames[-2]["id"]} + ) as replay: assert [f["event"] for f in _blocks(replay) if "data" in f] == ["done"] assert http.get(f"/api/jobs/{item['job_id']}/events", headers={"Last-Event-ID": frames[-1]["id"]}).status_code == 204 -def test_legacy_submit_terminal_phase_replay_and_synchronous_adapter(tmp_path, registered): - registration, _ = registered - with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration) as pool: - with _HTTPServer(store.root, job_service=JobService(registration, pool, allow_legacy_routes=True, - synchronous_wait_seconds=8.)) as server, server.client() as http: - wire = {"kind": "jv", "device": None, "config_path": "fixture:scaps", "params": {}} - result = http.post("/api/jobs", json=wire) - assert result.status_code == 202, result.text - item = result.json() - run_id, attempt_id = legacy_job_target(item["job_id"]) - assert (run_id, attempt_id) == (item["run_id"], item["attempt_id"]) - with http.stream("GET", item["legacy_events_url"]) as stream: - frames = [f for f in _blocks(stream) if "data" in f] - assert [f["event"] for f in frames[-2:]] == ["result", "done"] - payload = json.loads(frames[-2]["data"]) - assert payload["artifacts"] and payload["execution"]["worker_result"]["scientific_qualification"] is False - assert any(isinstance(value, list) and value for value in payload.values()) - with http.stream("GET", item["legacy_events_url"], headers={"Last-Event-ID": frames[-2]["id"]}) as stream: - assert [f["event"] for f in _blocks(stream) if "data" in f] == ["done"] - assert http.get(item["legacy_events_url"], headers={"Last-Event-ID": frames[-1]["id"]}).status_code == 204 - for invalid in ("999999.event", frames[-1]["id"].replace("done", "error"), "1", "-1.result"): - assert http.get(item["legacy_events_url"], headers={"Last-Event-ID": invalid}).status_code == 400 - unknown = http.post("/api/jobs", json={**wire, "kind": "impedance"}) - assert unknown.status_code == 422 and "original entry" in unknown.text - sync = http.post("/api/jv", json={"device": None, "config_path": "fixture:scaps"}, timeout=12) - assert sync.status_code == 200 and sync.json()["status"] == "ok" - - -def test_versioned_synchronous_alias_matches_canonical_and_kind_workers(tmp_path, registered): - original, _ = registered - version1 = original.registry.get("jv", 1) - registry = ExperimentRegistry((version1, replace(version1, version=2))) - first = replace(original.registrations[0], legacy_kinds=("jv1",), synchronous_paths=("/api/jv1",)) - second = replace(first, version=2, legacy_kinds=("jv2",), synchronous_paths=("/api/jv2",)) - registration = replace(original, registry=registry, registrations=(first, second), - expected_registry_sha256=registry.content_sha256) - observed = {} - with RunStore(tmp_path / "store") as store, supervisor(store, tmp_path / "work", registration) as pool: - services = JobService(registration, pool, allow_legacy_routes=True, synchronous_wait_seconds=8.) - with _HTTPServer(store.root, job_service=services) as server, server.client() as http: - canonical = http.post("/jobs", json={**declaration("canonical-v2"), "version": 2}, - headers=headers(registration)) - assert canonical.status_code == 202, canonical.text - kind = http.post("/api/jobs", json={"kind": "jv2", "device": None, - "config_path": "fixture:scaps", "params": {}}) - assert kind.status_code == 202, kind.text - for name, response in (("canonical_v2", canonical), ("kind_v2", kind)): - item = response.json() - receipt = pool.wait(handle(store, item), 12).data - assert receipt["process_joined"] and receipt["store_state"] == "succeeded" - result = http.get(item["result_url"]) - assert result.status_code == 200, result.text - observed[name] = result.json()["result"]["worker_result"] - for version in (1, 2): - response = http.post(f"/api/jv{version}", json={"device": None, "config_path": "fixture:scaps"}) - assert response.status_code == 200, response.text - result = response.json()["result"] - receipt = pool.wait(JobHandle(store.store_id, result["run_id"], result["attempt_id"]), 1).data - assert receipt["process_joined"] and receipt["store_state"] == "succeeded" - observed[f"synchronous_v{version}"] = result["execution"]["worker_result"] - evidence_path = os.environ.get("SOLARLAB_ALIAS_EVIDENCE") - if evidence_path: - Path(evidence_path).write_text(json.dumps({"actual_workers": observed, - "scientific_qualification": False}, indent=2) + "\n") - assert {key: value["experiment_version"] for key, value in observed.items()} == { - "canonical_v2": 2, "kind_v2": 2, "synchronous_v1": 1, "synchronous_v2": 2} - +def test_historical_legacy_result_artifact_readback_and_phase_replay_without_legacy_engine(tmp_path): + with RunStore(tmp_path / "store") as store: + queued = store.enqueue( + "historical-legacy", + opaque_identity={"H_input": "hist:i", "H_physics": "hist:p", "H_execution": "hist:e"}, + input_metadata={"scope": "historical_readback_only"}, + ) + token = store.claim("historical-legacy", expected_attempt_id=queued["current_attempt_id"], expected_generation=0, owner_id="hist") + store.append_event(token, event_id="step1", payload={"ui_progress": {"stage": "historical_step", "current": 1, "total": 2}}) + arr_bytes = struct.pack("<2d", 0.0, 0.95) + envelope = canonical( + { + "schema": "solarlab.legacy-raw-result.v1", + "driver": "scaps_transient", + "result": { + "V_fwd": {"dtype": "d", 0.95).hex()}, + "nonfinite": {"binary64_be": struct.pack(">d", float("nan")).hex()}, + }, + } + ) + saved = store.publish(token, "legacy_result", bytes_artifact(envelope, metadata={"scientific_qualification": False})) + store.complete( + token, + state="succeeded", + result={"worker_result": {"engine": "legacy", "scientific_qualification": False}}, + artifacts=[saved["artifact_id"]], + ) + job_id = legacy_job_id(JobHandle(store.store_id, "historical-legacy", token.attempt_id)) + + with _HTTPServer(tmp_path / "store") as server, server.client() as http: + direct = http.get(f"/api/jobs/{job_id}/result") + assert direct.status_code == 200 + body = direct.json() + assert body["V_fwd"] == [0.0, 0.95] + assert body["V_oc"] == 0.95 + assert body["nonfinite"] is None + assert body["execution"]["worker_result"]["scientific_qualification"] is False + + with http.stream("GET", f"/api/jobs/{job_id}/events") as stream: + frames = [f for f in _blocks(stream) if "data" in f] + assert [f["event"] for f in frames] == ["progress", "progress", "progress", "result", "done"] + with http.stream("GET", f"/api/jobs/{job_id}/events", headers={"Last-Event-ID": frames[-2]["id"]}) as tail: + assert [f["event"] for f in _blocks(tail) if "data" in f] == ["done"] + assert http.get(f"/api/jobs/{job_id}/events", headers={"Last-Event-ID": frames[-1]["id"]}).status_code == 204 + for invalid in ("999999.event", frames[-1]["id"].replace("done", "error"), "1", "-1.result"): + assert http.get(f"/api/jobs/{job_id}/events", headers={"Last-Event-ID": invalid}).status_code == 400 def test_large_result_uses_verified_references_and_corruption_does_not_rewrite_history(tmp_path): with RunStore(tmp_path / "store") as store: - queued = store.enqueue("large", opaque_identity={"H_input": "fixture", "H_physics": "fixture", "H_execution": "fixture"}, - input_metadata={"scope": "serialization-only; no physical execution"}) + queued = store.enqueue( + "large", + opaque_identity={"H_input": "fixture", "H_physics": "fixture", "H_execution": "fixture"}, + input_metadata={"scope": "serialization-only; no physical execution"}, + ) token = store.claim("large", expected_attempt_id=queued["current_attempt_id"], expected_generation=0, owner_id="fixture") data = canonical({"dtype": " GET -> no-op editor save -> POST -> SSE -> readback.""" +"""P06-06 + P03-07 + P06-04 + P09-02 closeout: accepted YAML -> GET -> no-op editor save -> POST -> SSE -> readback.""" from __future__ import annotations import hashlib import io import json import subprocess -from typing import Literal import time import numpy as np -from pydantic import BaseModel, ConfigDict, Field import pytest from examples.research_1d.service import committed_implementation from examples.research_1d.steady import load_device -from job_route_fixtures import Parameters -from legacy_fixtures import LEGACY, ROOT, make_job +from legacy_fixtures import LEGACY, ROOT from solarlab.config.device_import import import_standard_device from solarlab.config.legacy_defaults import read_legacy_default_catalog from solarlab.config.legacy_wire import prepare_legacy_wire @@ -25,17 +22,14 @@ from solarlab.device.inputs import DeviceInput from solarlab.experiments.execution import JobHandle, ProcessSupervisor from solarlab.experiments.jv.worker import read_steady_jv_job, validate_steady_jv_scope -from solarlab.experiments.registry import ExperimentDefinition, ExperimentRegistry from solarlab.experiments.worker import ResourceLimits, WorkerBinding from solarlab.io.artifacts import bytes_artifact from solarlab.io.run_bundle import RunBundle from solarlab.io.run_store import RunStore from solarlab.materials.resources import ResourceLibrary, ResourceTable from solarlab.materials.source import SourceDocument -from solarlab.physics.registry import CapabilityRule, EvidenceRef from solarlab_server.configuration import ConfigurationPreviewContext -from solarlab_server.job_service import ExecutionCatalog, JobService, JobSubmission, LegacyRegistration -from solarlab_server.legacy_engine import legacy_worker_binding +from solarlab_server.job_service import ExecutionCatalog, JobService, JobSubmission from solarlab_server.steady_preparation import SteadyPreparationContext, steady_execution_catalog from test_event_service import _HTTPServer as _BaseHTTPServer, _all_events, _blocks, _next_event @@ -61,25 +55,6 @@ def client(self): return client -class ScapsBoundInput(BaseModel): - model_config = ConfigDict(extra="forbid", strict=True) - device: None - config_path: Literal["fixture:scaps"] - expected_source_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") - expected_prepared_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") - params: Parameters - - -def prepare_scaps_jv(input: ScapsBoundInput): - job, _ = make_job(arguments=input.params.model_dump()) - prepared = job.execution.inputs.prepared - if not prepared.sources or prepared.sources[0].sha256 != input.expected_source_sha256: - raise ValueError("SCAPS source sha256 differs from expected_source_sha256") - if prepared.content_sha256 != input.expected_prepared_sha256: - raise ValueError("SCAPS prepared_sha256 differs from expected_prepared_sha256") - return job - - def _slot_gate(request, context): """Non-numerical worker holding the single active slot for deterministic SSE cursor staging.""" context.consume_manifest(request, engine="solarlab") @@ -146,54 +121,6 @@ def _wire_headers() -> dict[str, str]: } -def _scaps_bound_catalog(ceiling: ResourceLimits) -> tuple[ExecutionCatalog, object]: - job, _ = make_job() - documents: dict[str, bytes] = {} - - def reference(path: str, symbol: str = "") -> EvidenceRef: - documents[path] = (ROOT / path).read_bytes() - return EvidenceRef( - path + ("#" + symbol if symbol else ""), - hashlib.sha256(documents[path]).hexdigest(), - "source", - ) - - factory = reference("tests/runtime/test_p06_route_and_sse_closeout.py", "prepare_scaps_jv") - schema = json.dumps( - ScapsBoundInput.model_json_schema(), sort_keys=True, separators=(",", ":"), allow_nan=False - ).encode() - documents["schema:scaps-bound-http-fixture"] = schema - schema_ref = EvidenceRef("schema:scaps-bound-http-fixture", hashlib.sha256(schema).hexdigest(), "source") - definition = ExperimentDefinition( - "jv", - 1, - "Source-bound SCAPS YAML J-V route", - schema_ref, - reference("src/solarlab/experiments/worker.py", "WorkerResult"), - factory, - reference("src/solarlab_server/legacy_engine/__init__.py", "_run_legacy"), - "jv", - reference("web/src/workstation/panes/main-plot-pane.ts", "renderJV"), - CapabilityRule("scaps-bound-http-fixture", (1,), ("transient",), (factory,), backends=("metadata_only",)), - ) - documents["physics/temperature.py"] = (LEGACY / "physics/temperature.py").read_bytes() - registry = ExperimentRegistry((definition,)) - models = job.execution.inputs.registry - registration = LegacyRegistration( - "jv", 1, "scaps_transient", ScapsBoundInput, prepare_scaps_jv, legacy_kinds=("jv",) - ) - catalog = ExecutionCatalog( - registry, - models, - tuple(SourceDocument(k, v) for k, v in documents.items()), - (registration,), - expected_registry_sha256=registry.content_sha256, - expected_model_sha256=models.content_sha256, - ceiling=ceiling, - ) - return catalog, job - - def test_standard_yaml_get_noop_editor_save_post_steady_job_two_sse_cursors_and_restart_readback( tmp_path, standard_steady_bundle ): @@ -361,12 +288,10 @@ def payload( queued_b = _next_event(blocks_b) assert queued_a == queued_b and queued_a["kind"] == "queued" - # Disconnect subscriber A while job is queued/about to run; compute MUST NOT cancel. stream_a.close() assert obs_a.finished.wait(3) assert store.get_run(accepted["run_id"])["state"] == "queued" - # Release slot gate so real cold steady_jv job runs to completion while subscriber B streams. assert supervisor.cancel(gate_handle, reason="release_slot_for_e2e") assert supervisor.wait(gate_handle, 10).data["store_state"] == "cancelled" @@ -380,7 +305,6 @@ def payload( assert all_b[-1]["kind"] == "terminal" and all_b[-1]["payload"]["state"] == "succeeded" assert sum(e["kind"] == "terminal" for e in all_b) == 1 - # Reconnect subscriber A with Last-Event-ID and verify gapless, duplicate-free replay. with server.client() as reconnect_client: with reconnect_client.stream( "GET", @@ -395,7 +319,6 @@ def payload( ) assert ack.status_code == 204 and ack.content == b"" - # 6. Verify HTTP result + 8 NPY array artifacts + manifest against read_steady_jv_job job_handle = JobHandle(store.store_id, accepted["run_id"], accepted["attempt_id"]) receipt = supervisor.wait(job_handle, 10).data assert receipt["store_state"] == "succeeded" and receipt["process_joined"] @@ -413,7 +336,6 @@ def payload( decoded = np.load(io.BytesIO(blob.content), allow_pickle=False) assert decoded.tobytes() == loaded["arrays"][item["name"]].tobytes() - # 7. Read-only server restart readback (no JobService / no ProcessSupervisor) with _HTTPServer(database) as readonly_server, readonly_server.client() as reader: assert reader.get(accepted["result_url"]).json() == result_json with reader.stream("GET", accepted["events_url"]) as full_stream: @@ -425,42 +347,51 @@ def payload( assert reader.post("/jobs", json=payload(), headers=_job_headers(catalog)).status_code == 503 -def test_scaps_yaml_get_noop_editor_save_post_legacy_job_and_orphan_recovery_readback( - tmp_path, legacy_defaults_and_resources +def test_scaps_yaml_preview_legacy_refusal_solarlab_job_and_orphan_recovery_readback( + tmp_path, legacy_defaults_and_resources, standard_steady_bundle ): defaults, resources = legacy_defaults_and_resources - ceiling = ResourceLimits(30.0, 1024**3, 64 * 1024**2, None, None) - catalog, job = _scaps_bound_catalog(ceiling) - prepared = job.execution.inputs.prepared - scaps_source = prepared.sources[0] + yaml_source, steady_prepared, _, catalog, _ = standard_steady_bundle + scaps_source = SourceDocument( + "scaps-original.yaml", (ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml").read_bytes() + ) + scaps_prepared = resolve_device( + import_scaps_device(scaps_source, id="legacy_job", defaults=defaults), + defaults, + resources, + sources=(scaps_source,), + ) preview_ctx = ConfigurationPreviewContext(defaults, resources, (scaps_source,)) database = (tmp_path / "scaps-chain-store").resolve() work = (tmp_path / "scaps-chain-work").resolve() - def scaps_submission( - run_id: str = "scaps-yaml-e2e", + def steady_submission( + run_id: str = "solarlab-bundle-e2e", *, + engine: str = "solarlab", source_sha256: str | None = None, prepared_sha256: str | None = None, ) -> dict: return { "schema_version": "solarlab.job-submission.v1", "run_id": run_id, - "experiment_id": "jv", + "experiment_id": "steady_jv", "version": 1, - "engine": "legacy", + "engine": engine, "input": { - "device": None, - "config_path": "fixture:scaps", - "expected_source_sha256": scaps_source.sha256 if source_sha256 is None else source_sha256, - "expected_prepared_sha256": prepared.content_sha256 if prepared_sha256 is None else prepared_sha256, - "params": {}, + "device_id": "nip_steady", + "voltage_V": [0.0, 0.05], + "intervals_per_layer": 6, + "generation_scale": 1.0, + "incident_power_W_m2": None, + "expected_source_sha256": yaml_source.sha256 if source_sha256 is None else source_sha256, + "expected_prepared_sha256": steady_prepared.content_sha256 if prepared_sha256 is None else prepared_sha256, }, "limits": { - "wall_seconds": 30.0, - "rss_bytes": 1024**3, - "output_bytes": 64 * 1024**2, + "wall_seconds": 60.0, + "rss_bytes": 1536 * 1024**2, + "output_bytes": 96 * 1024**2, "accepted_steps": None, "calls": None, }, @@ -469,7 +400,7 @@ def scaps_submission( with RunStore(database) as store, ProcessSupervisor( store, work, - (catalog.worker_binding("legacy"), legacy_worker_binding()), + (catalog.worker_binding("solarlab"),), max_active=1, max_pending=2, shared_rss_bytes=3 * 1024**3, @@ -495,7 +426,7 @@ def scaps_submission( ) assert dev_resp.status_code == 200 dev_json = dev_resp.json() - assert dev_json["identity"]["content_sha256"] == prepared.content_sha256 + assert dev_json["identity"]["content_sha256"] == scaps_prepared.content_sha256 wire_resp = http.post( "/configuration-preview/legacy-wire", @@ -513,20 +444,25 @@ def scaps_submission( assert wire_json["report"]["differences"] == [] assert wire_json["documents"][0]["sha256"] == scaps_source.sha256 assert wire_json["documents"][0]["utf8"].encode("utf-8") == scaps_source.content - assert store.events() == [] - # 2. Refusal on source / prepared SHA-256 mismatch before enqueue, then valid POST /jobs + # 2. Legacy engine & POST /api/jobs are refused before enqueue, as are SHA mismatches + assert ( + http.post("/jobs", json=steady_submission(engine="legacy"), headers=_job_headers(catalog)).status_code + == 422 + ) + assert http.post("/api/jobs", json={"kind": "jv", "device": None}).status_code == 410 assert ( - http.post("/jobs", json=scaps_submission(source_sha256="0" * 64), headers=_job_headers(catalog)).status_code + http.post("/jobs", json=steady_submission(source_sha256="0" * 64), headers=_job_headers(catalog)).status_code == 422 ) assert ( - http.post("/jobs", json=scaps_submission(prepared_sha256="0" * 64), headers=_job_headers(catalog)).status_code + http.post("/jobs", json=steady_submission(prepared_sha256="0" * 64), headers=_job_headers(catalog)).status_code == 422 ) assert store.events() == [] - sub_resp = http.post("/jobs", json=scaps_submission(), headers=_job_headers(catalog)) + # 3. Valid V2 solarlab POST /jobs -> SSE -> verified readback + sub_resp = http.post("/jobs", json=steady_submission(), headers=_job_headers(catalog)) assert sub_resp.status_code == 202, sub_resp.text accepted = sub_resp.json() with http.stream("GET", accepted["events_url"]) as stream: @@ -543,12 +479,11 @@ def scaps_submission( assert result_json["state"] == "succeeded" assert result_json["result"]["worker_result"]["scientific_qualification"] is False - # 3. P06-04 crash-injection + orphan-only recovery + RunBundle + missing-committed-file HTTP 409 check - bundle_path = (tmp_path / "scaps-completed.slrun").resolve() + # 4. P06-04 crash-injection + orphan-only recovery + RunBundle + missing-committed-file HTTP 409 check + bundle_path = (tmp_path / "completed.slrun").resolve() bundle_pub = store.archive_run(accepted["run_id"], bundle_path) assert not bundle_pub["contains_active_database"] - # Inject a crashed attempt that published an uncommitted object AND left a half-written .part file. store.enqueue( "crashed-writer", opaque_identity={"H_input": "crash:i", "H_physics": "crash:p", "H_execution": "crash:e"}, @@ -577,7 +512,6 @@ def scaps_submission( assert f"partial/{orphan_pub['artifact_id']}.part" in collected["removed_paths"] assert not orphan_obj.exists() and not half_part.exists() - # Committed HTTP run survives orphan cleanup intact in both read-only HTTP server and RunBundle! with RunBundle(bundle_path, expected_sha256=bundle_pub["sha256"]) as bundle: assert bundle.get_run()["state"] == "succeeded" assert len(bundle.events()) == len(events) @@ -588,7 +522,6 @@ def scaps_submission( resp = reader.get(item["content_url"]) assert resp.status_code == 200 and hashlib.sha256(resp.content).hexdigest() == item["sha256"] - # Simulate missing indexed committed artifact on disk -> explicit HTTP 409 artifact_integrity (never silent!). target_artifact = result_json["artifacts"][0] committed_path = database / target_artifact["relative_path"] saved_bytes = committed_path.read_bytes() diff --git a/tests/runtime/test_p09_server_cutover.py b/tests/runtime/test_p09_server_cutover.py new file mode 100644 index 00000000..f97976ed --- /dev/null +++ b/tests/runtime/test_p09_server_cutover.py @@ -0,0 +1,399 @@ +"""P09-02 atomic server/UI/worker cutover verification (zero legacy imports, SPA serving, historical readback).""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import struct +import subprocess +import sys + +import pytest + +from solarlab.experiments.execution import JobHandle +from solarlab.io.artifacts import bytes_artifact +from solarlab.io.run_store import RunStore +from solarlab_server.cli import enforce_server_environment +from solarlab_server.job_service import canonical, legacy_job_id + +ROOT = Path(__file__).resolve().parents[2] + + +def _clean_env() -> dict[str, str]: + env = {k: v for k, v in os.environ.items() if k != "NEWCORE_EQUATIONS"} + for name in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "NUMEXPR_NUM_THREADS", + "BLIS_NUM_THREADS", + ): + env[name] = "1" + env["PYTHONPATH"] = str(ROOT / "src") + return env + + +def test_server_executes_1d_transient_and_2d_and_serves_spa_with_legacy_packages_blocked(tmp_path: Path) -> None: + """Prove solarlab_server starts, serves SPA assets, and executes 1D/2D workers with perovskite_sim blocked.""" + dist_dir = tmp_path / "_web_dist" + (dist_dir / "assets").mkdir(parents=True) + (dist_dir / "index.html").write_text("
SolarLab V2
") + (dist_dir / "favicon.svg").write_text("") + (dist_dir / "assets" / "app-v2.js").write_text("console.log('solarlab-v2');") + + script = """ +import importlib.abc +import json +from pathlib import Path +import sys + +BLOCKED = {"perovskite_sim", "backend", "solarlab_server.legacy_engine"} + +class BlockLegacyFinder(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname in BLOCKED or fullname.startswith(("perovskite_sim.", "backend.", "solarlab_server.legacy_engine.")): + raise ImportError(f"forbidden legacy import in V2 server: {fullname}") + return None + +sys.meta_path.insert(0, BlockLegacyFinder()) + +from fastapi.testclient import TestClient +from solarlab.experiments.execution import JobHandle, ProcessSupervisor +from solarlab.io.run_store import RunStore +from solarlab_server.app import create_app +from solarlab_server.cli import build_default_server_components +from solarlab_server.job_service import JobService + +tmp = Path(sys.argv[1]).resolve() +dist = Path(sys.argv[2]).resolve() +store_root = tmp / "store" +work_root = tmp / "work" + +preview, catalog = build_default_server_components() +headers = { + "X-Solarlab-Registry": catalog.document.sha256, + "X-Solarlab-Job-Schema": catalog.schema.sha256, +} + +with RunStore(store_root) as store, ProcessSupervisor( + store, + work_root, + catalog.worker_bindings(), + max_active=1, + max_pending=3, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + poll_seconds=0.01, +) as supervisor: + app = create_app( + store.root, + configuration_preview=preview, + job_service=JobService(catalog, supervisor), + web_dist_dir=dist, + ) + with TestClient(app) as http: + # 1. SPA static serving does not shadow API routes or swallow unknown 404s. + root_html = http.get("/") + assert root_html.status_code == 200 and "SolarLab V2" in root_html.text + view_html = http.get("/?view=steady-jv") + assert view_html.status_code == 200 and "SolarLab V2" in view_html.text + js_asset = http.get("/assets/app-v2.js") + assert js_asset.status_code == 200 and "solarlab-v2" in js_asset.text + fav = http.get("/favicon.svg") + assert fav.status_code == 200 and " None: + from solarlab_server.cli import main as cli_main + + monkeypatch.setenv("NEWCORE_EQUATIONS", "legacy") + with pytest.raises(ValueError, match="NEWCORE_EQUATIONS='assembled'"): + enforce_server_environment() + + monkeypatch.delenv("NEWCORE_EQUATIONS", raising=False) + monkeypatch.setenv("OMP_NUM_THREADS", "8") + enforce_server_environment() + assert os.environ["OMP_NUM_THREADS"] == "1" + assert os.environ["NEWCORE_EQUATIONS"] == "assembled" + + rc = cli_main(["--store-dir", str(tmp_path / "cli-check-store"), "--no-web-dist", "--check-only"]) + assert rc == 0 + report = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert report["status"] == "ok" + assert report["engine"] == "solarlab" + assert set(report["installed_experiments"]) == {"steady_jv", "transient_1d", "steady_2d"} + + +def test_solver_free_historical_runstore_readback_with_solvers_and_legacy_blocked(tmp_path: Path) -> None: + store_dir = (tmp_path / "historical-store").resolve() + with RunStore(store_dir) as store: + queued = store.enqueue( + "archived-legacy-run", + opaque_identity={"H_input": "h1", "H_physics": "h2", "H_execution": "h3"}, + input_metadata={"origin": "historical_w03_run"}, + ) + token = store.claim( + "archived-legacy-run", + expected_attempt_id=queued["current_attempt_id"], + expected_generation=0, + owner_id="historical-writer", + ) + raw_payload = canonical( + { + "schema": "solarlab.legacy-raw-result.v1", + "driver": "ion_hysteresis", + "result": { + "V_fwd": {"dtype": "d", 0.92).hex()}, + "PCE": {"binary64_be": struct.pack(">d", 0.165).hex()}, + }, + }, + } + ) + art = store.publish(token, "legacy_result", bytes_artifact(raw_payload, metadata={"scientific_qualification": False})) + store.complete( + token, + state="succeeded", + result={"worker_result": {"engine": "legacy", "driver": "ion_hysteresis", "scientific_qualification": False}}, + artifacts=[art["artifact_id"]], + ) + job_id = legacy_job_id(JobHandle(store.store_id, "archived-legacy-run", token.attempt_id)) + attempt_id = token.attempt_id + + reader_script = """ +import importlib.abc +import json +from pathlib import Path +import sys + +FORBIDDEN = {"perovskite_sim", "backend", "scipy", "sksundae", "flint", "solarlab_server.legacy_engine"} + +class BlockSolversAndLegacy(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname in FORBIDDEN or any(fullname.startswith(p + ".") for p in FORBIDDEN): + raise ImportError(f"solver/legacy import during historical readback: {fullname}") + return None + +sys.meta_path.insert(0, BlockSolversAndLegacy()) + +from fastapi.testclient import TestClient +from solarlab_server.app import create_app + +store_dir = Path(sys.argv[1]).resolve() +attempt_id = sys.argv[2] +job_id = sys.argv[3] + +with TestClient(create_app(store_dir)) as http: + res = http.get(f"/results/archived-legacy-run/attempts/{attempt_id}") + assert res.status_code == 200 + assert res.json()["state"] == "succeeded" + + decoded = http.get(f"/api/jobs/{job_id}/result") + assert decoded.status_code == 200 + body = decoded.json() + assert body["V_fwd"] == [0.0, 0.5, 1.0] + assert body["metrics_fwd"]["V_oc"] == 0.92 + assert body["execution"]["worker_result"]["scientific_qualification"] is False + + sse = http.get(f"/api/jobs/{job_id}/events") + assert sse.status_code == 200 + assert "event: result" in sse.text and "event: done" in sse.text + +assert not (FORBIDDEN & set(sys.modules)) +print(json.dumps({"solver_free_readback": True})) +""" + proc = subprocess.run( + [sys.executable, "-I", "-B", "-c", reader_script, str(store_dir), attempt_id, job_id], + cwd=tmp_path, + env=_clean_env(), + capture_output=True, + text=True, + timeout=30, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + assert json.loads(proc.stdout.strip())["solver_free_readback"] is True + + +def test_dockerfile_compose_and_production_web_sources_are_cut_over() -> None: + dockerfile = (ROOT / "Dockerfile").read_text() + compose = (ROOT / "docker-compose.yml").read_text() + for text in (dockerfile, compose): + assert "solarlab_server.cli" in text + assert "OMP_NUM_THREADS" in text + assert "NEWCORE_EQUATIONS" in text + assert "Dockerfile.backend" not in text + assert "backend.main:app" not in text + + retained_legacy_wire = { + ROOT / "web/src/api.ts", + ROOT / "web/src/job-stream.ts", + } + import_legacy_re = re.compile(r"""from\s+['"](?:\.\.?/)*(?:api|job-stream)['"]""") + offenders: list[str] = [] + for ts_file in sorted((ROOT / "web/src").rglob("*.ts")): + if ts_file in retained_legacy_wire or ts_file.name.endswith(".test.ts"): + continue + if import_legacy_re.search(ts_file.read_text()): + offenders.append(str(ts_file.relative_to(ROOT))) + assert offenders == [] + + +def test_pure_wheel_server_startup_without_examples_checkout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + """Exercise build_default_server_components() and cli_main when examples/research_1d/device.json is absent.""" + from solarlab_server.cli import build_default_server_components, main as cli_main + + assert not (tmp_path / "examples" / "research_1d" / "device.json").is_file() + preview, catalog = build_default_server_components(repo_root=tmp_path) + assert any(doc.id == "research_1d.yaml" for doc in preview.sources) + assert "examples/research_1d/device.json" not in {doc.id for doc in preview.sources} + assert {defn.id for defn in catalog.registry.definitions} == {"steady_jv", "transient_1d", "steady_2d"} + + orig_is_file = Path.is_file + + def _hide_example_json(self: Path) -> bool: + if self.parts[-3:] == ("examples", "research_1d", "device.json"): + return False + return orig_is_file(self) + + monkeypatch.setattr(Path, "is_file", _hide_example_json) + rc = cli_main(["--store-dir", str(tmp_path / "wheel-check-store"), "--no-web-dist", "--check-only"]) + assert rc == 0 + report = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert report["status"] == "ok" + assert set(report["installed_experiments"]) == {"steady_jv", "transient_1d", "steady_2d"} diff --git a/tests/runtime/test_steady_job_routes.py b/tests/runtime/test_steady_job_routes.py index a74ff667..62b2c476 100644 --- a/tests/runtime/test_steady_job_routes.py +++ b/tests/runtime/test_steady_job_routes.py @@ -286,26 +286,30 @@ def test_http_cancel_fences_attempt_and_stops_only_the_shared_owner(tmp_path, ca assert receipt["process_exit_observed"] and len(terminal_events(store, first.run_id)) == 1 -def test_mixed_catalog_keeps_legacy_and_steady_model_and_engine_bindings_separate(catalog): - from job_route_fixtures import catalog as legacy_catalog, request as legacy_request +def test_mixed_catalog_keeps_steady_and_transient_bindings_separate_and_refuses_legacy_engine(catalog, context): + from examples.research_1d.transient_service import example_submission as transient_submission + from pydantic import ValidationError from solarlab.experiments.registry import ExperimentRegistry - - legacy, _ = legacy_catalog() - sources = {source.id: source for source in (*legacy.sources, *catalog.sources)} - declarations = ExperimentRegistry((*legacy.registry.definitions, *catalog.registry.definitions)) - mixed = replace(legacy, registry=declarations, registrations=(*legacy.registrations, *catalog.registrations), + from solarlab_server.transient_preparation import TransientPreparationContext, transient_execution_catalog + + transient = transient_execution_catalog( + TransientPreparationContext((("research_1d", load_device()),), context.implementation, context.current_repository_head), + ceiling=limits(), + ) + sources = {source.id: source for source in (*transient.sources, *catalog.sources)} + declarations = ExperimentRegistry((*transient.registry.definitions, *catalog.registry.definitions)) + mixed = replace(transient, registry=declarations, registrations=(*transient.registrations, *catalog.registrations), sources=tuple(sources.values()), expected_registry_sha256=declarations.content_sha256, ceiling=limits()) - legacy_spec, old = mixed.prepare(JobSubmission.model_validate(legacy_request())) - steady_spec, new = mixed.prepare(JobSubmission.model_validate(submission())) - assert legacy_spec.worker_id == "registered_legacy" and old.engine.name == "legacy" - assert steady_spec.worker_id == "registered_steady" and new.engine.name == "solarlab" - assert old.inputs.registry.content_sha256 != new.inputs.registry.content_sha256 - assert not old.manifest.can_execute and not new.manifest.can_execute - for engine in ("legacy", "solarlab"): - assert mixed.worker_binding(engine).registry_sha256 == mixed.document.sha256 - for data in ({**submission(), "engine": "legacy"}, {**legacy_request(), "engine": "solarlab"}): - with pytest.raises(ValueError, match="fallback is forbidden"): - mixed.prepare(JobSubmission.model_validate(data)) + transient_spec, trans_binding = mixed.prepare(JobSubmission.model_validate(transient_submission())) + steady_spec, steady_binding = mixed.prepare(JobSubmission.model_validate(submission())) + assert transient_spec.worker_id == "registered_transient" and trans_binding.engine.name == "solarlab" + assert steady_spec.worker_id == "registered_steady" and steady_binding.engine.name == "solarlab" + assert not trans_binding.manifest.can_execute and not steady_binding.manifest.can_execute + assert {b.id for b in mixed.worker_bindings()} == {"registered_steady", "registered_transient"} + with pytest.raises(ValueError, match="only engine='solarlab' is supported"): + mixed.worker_binding("legacy") # type: ignore[arg-type] + with pytest.raises(ValidationError): + JobSubmission.model_validate({**submission(), "engine": "legacy"}) def test_local_service_script_keeps_engine_imports_after_worker_isolation(tmp_path): diff --git a/tests/runtime/test_worker_equation_selection.py b/tests/runtime/test_worker_equation_selection.py index 72a4d964..32c73ee2 100644 --- a/tests/runtime/test_worker_equation_selection.py +++ b/tests/runtime/test_worker_equation_selection.py @@ -1,34 +1,34 @@ -"""Process workers run the equation selection of the parent that prepared them (Science PW-C2). - -Preparation resolves the selection (the innermost ``equation_implementation`` -scope, else ``NEWCORE_EQUATIONS``, else assembled) and records -``NEWCORE_EQUATIONS=`` among the execution manifest's child -settings, so it is part of the execution identity. The spawned child installs -those settings before any engine import, refuses a selection that differs, -and admits its job under the Q6 binding of that implementation, which the -saved result records. A queued job keeps its manifest's selection. A bare -scope is local to its execution context: a job prepared in a new thread -follows that thread's own selection unless the thread runs a copied context. -The saved array payloads of both selections are byte-identical; full result -and reader parity is pinned in process by tests/unit/assembly, and the -saved documents of the process examples by the examples harness. +"""Production process workers lock equation selection to assembled (P09-02). + +Preparation resolves the selection and records ``NEWCORE_EQUATIONS="assembled"`` +in the execution manifest's child settings. Environment opt-out via +``NEWCORE_EQUATIONS=legacy`` is refused before preparation, and spawned workers +refuse any non-assembled manifest binding via ``verify_selection``. Explicit +in-process ``with equation_implementation(LEGACY):`` remains available only for +unit assembly parity tests in ``tests/unit/assembly/``. """ from __future__ import annotations -from collections.abc import Callable -import contextvars import io +import json +import os import subprocess +import sys import tarfile -import threading from pathlib import Path from typing import Any import pytest from solarlab.config.identity import BuildSource, ExecutionEngine -from solarlab.equations.implementation import ASSEMBLED, ENVIRONMENT, LEGACY, equation_implementation +from solarlab.equations.implementation import ( + ASSEMBLED, + ENVIRONMENT, + LEGACY, + equation_implementation, + verify_selection, +) from solarlab.experiments.execution import ProcessSupervisor from solarlab.experiments.worker import ResourceLimits from solarlab.io.run_store import RunStore @@ -61,15 +61,19 @@ def steady_job(source: BuildSource) -> Any: from examples.research_1d.steady import load_device from solarlab.experiments.jv.worker import SteadyJVProtocol, prepare_steady_jv_job - return prepare_steady_jv_job(load_device(), SteadyJVProtocol((0.0, 0.05), 12, 1.0, None), implementation=source, - current_repository_head=source.build_source_commit, engine=ExecutionEngine("solarlab")) + return prepare_steady_jv_job( + load_device(), + SteadyJVProtocol((0.0, 0.05), 12, 1.0, None), + implementation=source, + current_repository_head=source.build_source_commit, + engine=ExecutionEngine("solarlab"), + ) def transient_job(commit: str) -> Any: from examples.research_1d.process_transient import example_job from examples.research_1d.service import committed_implementation - # Shared pytest collection also loads ionic modules: bind the whole committed installation. return example_job(committed_implementation(commit), current_repository_head=commit) @@ -87,11 +91,18 @@ def ionic_jv_job(commit: str) -> Any: from solarlab.experiments.jv.ionic_worker import IonicJVInitial, IonicJVProtocol, prepare_ionic_jv_job source = source_build(commit) - return prepare_ionic_jv_job(prepare_confined_shared_site_ion_device(), IonicJVProtocol((0.0, 0.025), 1.0, None), - intervals_per_layer=(12, 12, 12), ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking"), + return prepare_ionic_jv_job( + prepare_confined_shared_site_ion_device(), + IonicJVProtocol((0.0, 0.025), 1.0, None), + intervals_per_layer=(12, 12, 12), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), options=IonicSteadyJVOptions(controls(13), max_points=51, wall_s=25.0), - initial=IonicJVInitial("dark_direct_density_seed_v1", 0.002, 25.0), implementation=source, - current_repository_head=commit, engine=ExecutionEngine("solarlab")) + initial=IonicJVInitial("dark_direct_density_seed_v1", 0.002, 25.0), + implementation=source, + current_repository_head=commit, + engine=ExecutionEngine("solarlab"), + ) def bindings() -> tuple[Any, ...]: @@ -100,91 +111,69 @@ def bindings() -> tuple[Any, ...]: from solarlab.experiments.jv.worker import steady_jv_worker_binding from solarlab.experiments.transient_worker import transient_worker_binding - return (steady_jv_worker_binding(), transient_worker_binding(), ionic_transient_worker_binding(), - ionic_jv_worker_binding()) + return ( + steady_jv_worker_binding(), + transient_worker_binding(), + ionic_transient_worker_binding(), + ionic_jv_worker_binding(), + ) def pool(store: RunStore, work: Path) -> ProcessSupervisor: - return ProcessSupervisor(store, work, bindings(), max_active=1, max_pending=3, - shared_rss_bytes=3 * 1024**3, shared_output_bytes=384 * 1024**2, - poll_seconds=0.02, soft_grace_seconds=0.2, terminate_grace_seconds=0.2) + return ProcessSupervisor( + store, + work, + bindings(), + max_active=1, + max_pending=3, + shared_rss_bytes=3 * 1024**3, + shared_output_bytes=384 * 1024**2, + poll_seconds=0.02, + soft_grace_seconds=0.2, + terminate_grace_seconds=0.2, + ) def declared(job: Any) -> str: - """The selection a prepared job's manifest binds for its child.""" settings = dict(job.execution.environment) assert dict(job.execution.execution.environment.settings)[ENVIRONMENT] == '"' + settings[ENVIRONMENT] + '"' return settings[ENVIRONMENT] -def run(jobs: dict[str, Any], tmp_path: Path) -> dict[str, dict[str, Any]]: - """Submit every job to one single-slot pool (so all but the first queue); each saved worker result. - - Each result also carries the bytes of its saved array payloads. - """ - limits = ResourceLimits(30.0, 1536 * 1024**2, 96 * 1024**2, None, None) - results = {} - with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: - handles = {name: job.submit(supervisor, name, limits) for name, job in jobs.items()} - for name, handle in handles.items(): - receipt = supervisor.wait(handle, 90).data - assert receipt["store_state"] == "succeeded", receipt - attempt, = store.attempts(name) - results[name] = attempt["result"]["worker_result"] - manifest = next(store.artifact(ref["artifact_id"]) for ref in attempt["terminal"]["artifacts"] - if store.artifact(ref["artifact_id"])["name"] == "execution_manifest") - assert manifest["metadata"]["job_provenance_sha256"] == read_provenance(results[name]["job_provenance"]).sha256 - records = [store.artifact(ref["artifact_id"]) for ref in attempt["terminal"]["artifacts"]] - results[name]["saved_words"] = {record["name"]: store.read_artifact(record["artifact_id"]) - for record in records if record["format"] == "npy"} - return results - - def binding(result: dict[str, Any]) -> dict[str, Any]: return read_provenance(result["job_provenance"]).export()["assembler"] -def test_preparation_records_the_resolved_selection_and_fails_closed( +def test_preparation_and_verify_selection_lock_production_workers_to_assembled( steady_source: BuildSource, monkeypatch: pytest.MonkeyPatch, ) -> None: - from solarlab.equations.implementation import verify_selection - monkeypatch.delenv(ENVIRONMENT, raising=False) default = steady_job(steady_source) - with equation_implementation(LEGACY): - scoped = steady_job(steady_source) - monkeypatch.setenv(ENVIRONMENT, LEGACY) - process = steady_job(steady_source) - monkeypatch.delenv(ENVIRONMENT) - assert (declared(default), declared(scoped), declared(process)) == (ASSEMBLED, LEGACY, LEGACY) - # The selection is part of the execution identity, not of the input or physics identity. - assert default.request.H_input == scoped.request.H_input and default.request.H_physics == scoped.request.H_physics - assert default.execution.manifest.execution_sha256 != scoped.execution.manifest.execution_sha256 - assert scoped.execution.manifest.execution_sha256 == process.execution.manifest.execution_sha256 - - def prepared_in_thread(target: Callable[[], Any]) -> str: - found: list[Any] = [] - thread = threading.Thread(target=lambda: found.append(target())) - thread.start() - thread.join() - return declared(found[0]) + assert declared(default) == ASSEMBLED + verify_selection(default.execution.environment) - with equation_implementation(LEGACY): - assert prepared_in_thread(lambda: steady_job(steady_source)) == ASSEMBLED - context = contextvars.copy_context() - assert prepared_in_thread(lambda: context.run(steady_job, steady_source)) == LEGACY + # Environment NEWCORE_EQUATIONS=legacy is retired and refused at worker preparation. + monkeypatch.setenv(ENVIRONMENT, LEGACY) + with pytest.raises(ValueError, match="NEWCORE_EQUATIONS=legacy is retired"): + steady_job(steady_source) monkeypatch.setenv(ENVIRONMENT, "Legacy") with pytest.raises(ValueError, match="unknown equation implementation"): steady_job(steady_source) monkeypatch.delenv(ENVIRONMENT) - verify_selection(default.execution.environment) - with equation_implementation(LEGACY), pytest.raises(ValueError, match="differs from its execution manifest"): - verify_selection(default.execution.environment) + + # Even if a manifest was constructed inside an explicit unit-test LEGACY scope, + # verify_selection refuses legacy execution in any worker process. + with equation_implementation(LEGACY): + scoped_legacy = steady_job(steady_source) + with pytest.raises(ValueError, match="legacy worker equation selection is retired"): + verify_selection(scoped_legacy.execution.environment) + with pytest.raises(ValueError, match="differs from its execution manifest"): + verify_selection(default.execution.environment) with pytest.raises(ValueError, match="differs from its execution manifest"): - verify_selection(scoped.execution.environment) + verify_selection(scoped_legacy.execution.environment) -def test_spawned_and_queued_steady_workers_run_their_prepared_selection( +def test_spawned_steady_worker_executes_assembled_and_refuses_legacy_manifest( steady_source: BuildSource, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: from examples.research_1d.steady import load_device @@ -192,91 +181,164 @@ def test_spawned_and_queued_steady_workers_run_their_prepared_selection( from support.equation_provenance import expected monkeypatch.delenv(ENVIRONMENT, raising=False) + assembled_job = steady_job(steady_source) with equation_implementation(LEGACY): - scoped = steady_job(steady_source) - jobs = {"assembled-default": steady_job(steady_source), "legacy-scope": scoped} - monkeypatch.setenv(ENVIRONMENT, LEGACY) - jobs["legacy-process"] = steady_job(steady_source) - monkeypatch.delenv(ENVIRONMENT) - with equation_implementation(ASSEMBLED): # the submitting context does not select; the manifest does - results = run(jobs, tmp_path) - device = compile_device_1d(load_device(), intervals_per_layer=12) - for name, result in results.items(): - implementation = declared(jobs[name]) - assert binding(result) == expected("DC1DProblem.steady_jv", device, implementation), name - assert results["legacy-scope"]["steady_result"] == results["assembled-default"]["steady_result"] - assert results["legacy-scope"]["saved_words"] == results["assembled-default"]["saved_words"] - assert binding(results["legacy-scope"]) == binding(results["legacy-process"]) + legacy_scoped_job = steady_job(steady_source) + limits = ResourceLimits(30.0, 1536 * 1024**2, 96 * 1024**2, None, None) + with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: + ok_handle = assembled_job.submit(supervisor, "assembled-default", limits) + bad_handle = legacy_scoped_job.submit(supervisor, "legacy-refused", limits) -@pytest.mark.parametrize("family", ("transient", "ionic_transient", "ionic_jv")) -def test_every_1d_worker_family_records_its_parent_selection(family: str, commit: str, tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - from support.equation_provenance import expected + ok_receipt = supervisor.wait(ok_handle, 90).data + assert ok_receipt["store_state"] == "succeeded", ok_receipt + attempt, = store.attempts("assembled-default") + worker_res = attempt["result"]["worker_result"] + device = compile_device_1d(load_device(), intervals_per_layer=12) + assert binding(worker_res) == expected("DC1DProblem.steady_jv", device, ASSEMBLED) - monkeypatch.delenv(ENVIRONMENT, raising=False) - prepare = {"transient": transient_job, "ionic_transient": ionic_transient_job, "ionic_jv": ionic_jv_job}[family] - jobs = {} - for implementation in (ASSEMBLED, LEGACY): - with equation_implementation(implementation): - jobs[implementation] = prepare(commit) - assert declared(jobs[implementation]) == implementation - results = run(jobs, tmp_path) - device, operator, closure = device_of(family) - for implementation, result in results.items(): - assert binding(result) == expected(operator, device, implementation, closure), implementation - assert results[ASSEMBLED]["saved_words"] and results[ASSEMBLED]["saved_words"] == results[LEGACY]["saved_words"] - - -def device_of(family: str) -> tuple[Any, str, int | None]: - """The compiled device, original operator and closure node of each example worker job.""" + bad_receipt = supervisor.wait(bad_handle, 90).data + assert bad_receipt["store_state"] == "failed" + assert "legacy worker equation selection is retired" in bad_receipt["worker_result"]["detail"] + + +@pytest.mark.parametrize("family", ("transient", "ionic_transient", "ionic_jv")) +def test_every_1d_worker_family_executes_assembled_and_records_provenance( + family: str, commit: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: from examples.research_1d.ionic_steady import controls from examples.research_1d.shared_site_ionic_fixture import prepare_confined_shared_site_ion_device from examples.research_1d.steady import load_device from solarlab.device.compile_1d import compile_device_1d from solarlab.device.compile_ionic_1d import compile_ionic_device_1d + from support.equation_provenance import expected - if family == "transient": - return compile_device_1d(load_device(), intervals_per_layer=12), "BackwardEuler1DStep", None - device = compile_ionic_device_1d(prepare_confined_shared_site_ion_device(), intervals_per_layer=(12, 12, 12), - ion_domain_layer="absorber", ion_domain_endpoints=("blocking", "blocking")) - operator = "IonicBackwardEuler1DStep" if family == "ionic_transient" else "Ionic1DProblem.steady_jv" - return device, operator, controls(13).inventory_row_node - + monkeypatch.delenv(ENVIRONMENT, raising=False) + prepare = {"transient": transient_job, "ionic_transient": ionic_transient_job, "ionic_jv": ionic_jv_job}[family] + job = prepare(commit) + assert declared(job) == ASSEMBLED -def test_the_2d_steady_worker_records_its_parent_selection(commit: str, tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """The 2D process example, spawned under each process setting, admits that selection's binding.""" - import json - import os - import sys + limits = ResourceLimits(30.0, 1536 * 1024**2, 96 * 1024**2, None, None) + with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: + handle = job.submit(supervisor, family, limits) + receipt = supervisor.wait(handle, 90).data + assert receipt["store_state"] == "succeeded", receipt + attempt, = store.attempts(family) + result = attempt["result"]["worker_result"] + if family == "transient": + device: Any = compile_device_1d(load_device(), intervals_per_layer=12) + operator, closure = "BackwardEuler1DStep", None + else: + device = compile_ionic_device_1d( + prepare_confined_shared_site_ion_device(), + intervals_per_layer=(12, 12, 12), + ion_domain_layer="absorber", + ion_domain_endpoints=("blocking", "blocking"), + ) + operator = "IonicBackwardEuler1DStep" if family == "ionic_transient" else "Ionic1DProblem.steady_jv" + closure = controls(13).inventory_row_node + assert binding(result) == expected(operator, device, ASSEMBLED, closure) + + +def test_the_2d_steady_worker_executes_assembled_and_refuses_legacy_env( + commit: str, tmp_path: Path, +) -> None: from examples.research_1d.steady import load_device from examples.research_2d.dc_assembly import spatial_input from solarlab.device.compile_2d import compile_device_2d from support.equation_provenance import expected archive = tmp_path / "source.tar" - subprocess.run(["git", "archive", "--format=tar", "--output", str(archive), commit, "--", "src/solarlab"], - cwd=ROOT, check=True, timeout=30) + subprocess.run( + ["git", "archive", "--format=tar", "--output", str(archive), commit, "--", "src/solarlab"], + cwd=ROOT, + check=True, + timeout=30, + ) device = compile_device_2d(load_device(), spatial_input()) - readbacks = {} - for implementation in (ASSEMBLED, LEGACY): - env = {key: value for key, value in os.environ.items() if key != ENVIRONMENT} - env.update({name: "1" for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", - "VECLIB_MAXIMUM_THREADS", "NUMEXPR_NUM_THREADS", "BLIS_NUM_THREADS")}) - if implementation == LEGACY: - env[ENVIRONMENT] = LEGACY - receipt = tmp_path / (implementation + ".json") - result = subprocess.run([sys.executable, "-B", "-m", "examples.research_2d.process_steady", "run", - "--store", str(tmp_path / implementation / "Store"), "--work", str(tmp_path / implementation / "Work"), - "--run-id", "steady2d-" + implementation, "--build-source-commit", commit, "--source-archive", - str(archive), "--current-repository-head", commit, "--targets", "dark", "--receipt-json", str(receipt)], - cwd=ROOT, env=env, capture_output=True, text=True, timeout=60) - assert result.returncode == 0, result.stderr + result.stdout[-2000:] - saved = json.loads(receipt.read_text()) - worker = saved["receipt"]["worker_result"] - assert binding(worker) == expected("DC2DProblem.steady", device, implementation), implementation - assert [ENVIRONMENT, json.dumps(implementation)] in [list(item) for item in worker["capture"]["runtime"]["settings"]] - readbacks[implementation] = saved["readback"]["array_fingerprints"] - assert readbacks[ASSEMBLED] and readbacks[ASSEMBLED] == readbacks[LEGACY] + base_env = {key: value for key, value in os.environ.items() if key != ENVIRONMENT} + base_env.update( + { + name: "1" + for name in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", + "NUMEXPR_NUM_THREADS", + "BLIS_NUM_THREADS", + ) + } + ) + + receipt = tmp_path / "assembled.json" + ok_res = subprocess.run( + [ + sys.executable, + "-B", + "-m", + "examples.research_2d.process_steady", + "run", + "--store", + str(tmp_path / "assembled" / "Store"), + "--work", + str(tmp_path / "assembled" / "Work"), + "--run-id", + "steady2d-assembled", + "--build-source-commit", + commit, + "--source-archive", + str(archive), + "--current-repository-head", + commit, + "--targets", + "dark", + "--receipt-json", + str(receipt), + ], + cwd=ROOT, + env=base_env, + capture_output=True, + text=True, + timeout=60, + ) + assert ok_res.returncode == 0, ok_res.stderr + ok_res.stdout[-2000:] + saved = json.loads(receipt.read_text()) + worker = saved["receipt"]["worker_result"] + assert binding(worker) == expected("DC2DProblem.steady", device, ASSEMBLED) + assert [ENVIRONMENT, json.dumps(ASSEMBLED)] in [list(item) for item in worker["capture"]["runtime"]["settings"]] + + legacy_env = {**base_env, ENVIRONMENT: LEGACY} + bad_res = subprocess.run( + [ + sys.executable, + "-B", + "-m", + "examples.research_2d.process_steady", + "run", + "--store", + str(tmp_path / "legacy" / "Store"), + "--work", + str(tmp_path / "legacy" / "Work"), + "--run-id", + "steady2d-legacy", + "--build-source-commit", + commit, + "--source-archive", + str(archive), + "--current-repository-head", + commit, + "--targets", + "dark", + "--receipt-json", + str(tmp_path / "legacy.json"), + ], + cwd=ROOT, + env=legacy_env, + capture_output=True, + text=True, + timeout=30, + ) + assert bad_res.returncode != 0 + assert "NEWCORE_EQUATIONS=legacy is retired" in (bad_res.stderr + bad_res.stdout) diff --git a/tests/runtime/test_worker_identity.py b/tests/runtime/test_worker_identity.py index ab0d1a84..cf8d23b8 100644 --- a/tests/runtime/test_worker_identity.py +++ b/tests/runtime/test_worker_identity.py @@ -63,11 +63,13 @@ def assert_identity_readback(tmp_path, bound, handle, result, *, unavailable): assert [event for event in store.events(run_id=handle.run_id) if event["kind"] == "terminal"] == events -@pytest.mark.parametrize("field", ["job_schema_sha256", "model_registry_sha256", "legacy_facade_sha256"]) +@pytest.mark.parametrize("field", ["job_schema_sha256", "model_registry_sha256"]) @pytest.mark.parametrize("misses", [1, 3]) def test_startup_ps_timeout_preserves_real_registry_refusal(tmp_path, registered, monkeypatch, field, misses): spec, binding = registered.prepare(JobSubmission.model_validate(declaration())) claimed = json.loads(registered.document.content) + if field == "model_registry_sha256": + claimed["bindings"][0]["model_registry_sha256"] = "0" * 64 claimed[field] = "0" * 64 altered = SourceDocument("explicit-inconsistent-registry-fixture", canonical(claimed)) bound = replace(registered.worker_binding(), registry_sha256=altered.sha256) diff --git a/web/src/device-panel-ion-mode.test.ts b/web/src/device-panel-ion-mode.test.ts index 4c1e1236..f58daa93 100644 --- a/web/src/device-panel-ion-mode.test.ts +++ b/web/src/device-panel-ion-mode.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mountDevicePanel } from './device-panel' import type { DeviceConfig, LayerConfig, SimulationModeName } from './types' -vi.mock('./api', () => ({ +vi.mock('./v2-workstation-client', () => ({ fetchOpticalMaterials: vi.fn().mockResolvedValue([]), fetchLayerTemplates: vi.fn().mockResolvedValue({}), listConfigs: vi.fn().mockResolvedValue([ diff --git a/web/src/device-panel-workspace-config.test.ts b/web/src/device-panel-workspace-config.test.ts index 6bdcf801..6183150b 100644 --- a/web/src/device-panel-workspace-config.test.ts +++ b/web/src/device-panel-workspace-config.test.ts @@ -7,7 +7,7 @@ const mocks = vi.hoisted(() => ({ readDeviceEditor: vi.fn(), })) -vi.mock('./api', () => ({ +vi.mock('./v2-workstation-client', () => ({ fetchOpticalMaterials: vi.fn().mockResolvedValue([]), fetchLayerTemplates: vi.fn().mockResolvedValue({}), getConfig: mocks.getConfig, diff --git a/web/src/device-panel.ts b/web/src/device-panel.ts index 05a4cebe..7e00ea9a 100644 --- a/web/src/device-panel.ts +++ b/web/src/device-panel.ts @@ -3,7 +3,7 @@ import { getConfig, fetchOpticalMaterials, fetchLayerTemplates, -} from './api' +} from './v2-workstation-client' import { renderDeviceEditor, readDeviceEditor, setOpticalMaterialOptions } from './config-editor' import { mountStackVisualizer } from './stack/stack-visualizer' import { validate } from './stack/stack-validator' diff --git a/web/src/impedance-panels.test.ts b/web/src/impedance-panels.test.ts index 414cf134..ecc45de7 100644 --- a/web/src/impedance-panels.test.ts +++ b/web/src/impedance-panels.test.ts @@ -6,7 +6,7 @@ const mocks = vi.hoisted(() => ({ mountDevicePanel: vi.fn(), })) -vi.mock('./job-stream', () => ({ +vi.mock('./v2-job-client', () => ({ startJob: mocks.startJob, streamJobEvents: mocks.streamJobEvents, })) diff --git a/web/src/main.ts b/web/src/main.ts index 8fbc2fef..a5b16b89 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -1,9 +1,11 @@ import './style.css' +import { resolveV2ServiceEndpoint } from './v2-workstation-client' const app = document.querySelector('#app')! async function mount() { const query = new URL(location.href).searchParams + const serviceBase = new URL(resolveV2ServiceEndpoint()) if (query.get('view') === 'steady-2d') { const { mountSteady2DPanel } = await import('./panels/steady-2d') app.innerHTML = `

SolarLab

2D steady research

@@ -11,12 +13,12 @@ async function mount() { Ion-free transient Ionic transient Ionic J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#steady-2d')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' const initial = query.get('storeId') && query.get('runId') && query.get('attemptId') ? { storeId: query.get('storeId')!, runId: query.get('runId')!, attemptId: query.get('attemptId')! } : undefined - const panel = mountSteady2DPanel(host, new URL('/steady-service/', location.origin), initial) + const panel = mountSteady2DPanel(host, serviceBase, initial) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'ionic-jv') { @@ -26,12 +28,12 @@ async function mount() { Steady J–V Ion-free transient Ionic transient - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#ionic-jv')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' const initial = query.get('storeId') && query.get('runId') && query.get('attemptId') ? { storeId: query.get('storeId')!, runId: query.get('runId')!, attemptId: query.get('attemptId')! } : undefined - const panel = mountIonicJVPanel(host, new URL('/steady-service/', location.origin), initial) + const panel = mountIonicJVPanel(host, serviceBase, initial) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'ionic-transient') { @@ -41,12 +43,12 @@ async function mount() { Steady J–V Ion-free transient Ionic J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#ionic-transient')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' const initial = query.get('storeId') && query.get('runId') && query.get('attemptId') ? { storeId: query.get('storeId')!, runId: query.get('runId')!, attemptId: query.get('attemptId')! } : undefined - const panel = mountIonicTransientPanel(host, new URL('/steady-service/', location.origin), initial) + const panel = mountIonicTransientPanel(host, serviceBase, initial) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'transient') { @@ -56,12 +58,12 @@ async function mount() { Steady J–V Ionic transient Ionic J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#transient')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' const initial = query.get('storeId') && query.get('runId') && query.get('attemptId') ? { storeId: query.get('storeId')!, runId: query.get('runId')!, attemptId: query.get('attemptId')! } : undefined - const panel = mountTransientPanel(host, new URL('/steady-service/', location.origin), initial) + const panel = mountTransientPanel(host, serviceBase, initial) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'steady-jv') { @@ -72,10 +74,10 @@ async function mount() { Transient · new core Ionic transient Ionic J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#steady-dc')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' - const panel = mountSteadyJVPanel(host, new URL('/steady-service/', location.origin)) + const panel = mountSteadyJVPanel(host, serviceBase) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'configuration') { @@ -86,10 +88,10 @@ async function mount() { Transient · new core Ionic transient Ionic J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#configuration-v2')! host.style.cssText = 'max-width:1440px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' - const panel = mountConfigurationWorkstation(host, new URL('/steady-service/', location.origin)) + const panel = mountConfigurationWorkstation(host, serviceBase) window.addEventListener('pagehide', () => panel.dispose(), { once: true }) await panel.ready } else if (query.get('view') === 'stored-run' && query.get('storeId') && query.get('runId') && query.get('attemptId')) { @@ -97,11 +99,11 @@ async function mount() { app.innerHTML = `

SolarLab

Stored Run Inspector

Configuration · V2 DTO Steady J–V - Workspace / legacy experiments
` + Workstation
` const host = app.querySelector('#stored-run')! host.style.cssText = 'max-width:1300px;margin:auto;padding:20px;overflow:auto;max-height:calc(100vh - 90px)' const panel = mountStoredRunPanel(host, { - endpoint: new URL('/steady-service/', location.origin), + endpoint: serviceBase, storeId: query.get('storeId')!, runId: query.get('runId')!, attemptId: query.get('attemptId')!, diff --git a/web/src/panels/configuration-workstation.ts b/web/src/panels/configuration-workstation.ts index b0ba1b0f..15a8b274 100644 --- a/web/src/panels/configuration-workstation.ts +++ b/web/src/panels/configuration-workstation.ts @@ -183,7 +183,7 @@ export function mountConfigurationWorkstation( input: defaultDeviceInput(), onApply: input => showPreview({ - endpoint: previewEndpoint('configuration/preview/device'), + endpoint: previewEndpoint('configuration-preview/device'), kind: 'device', input: input as DeviceInput, }), @@ -193,7 +193,7 @@ export function mountConfigurationWorkstation( input: defaultTandemInput(), onApply: input => showPreview({ - endpoint: previewEndpoint('configuration/preview/tandem'), + endpoint: previewEndpoint('configuration-preview/tandem'), kind: 'tandem', input: input as TandemInput, }), @@ -203,7 +203,7 @@ export function mountConfigurationWorkstation( input: defaultJVExperimentInput(), onApply: input => showPreview({ - endpoint: previewEndpoint('configuration/preview/experiment'), + endpoint: previewEndpoint('configuration-preview/experiment'), kind: 'experiment', input, }), @@ -213,7 +213,7 @@ export function mountConfigurationWorkstation( input: defaultSpatialExperimentInput(), onApply: input => showPreview({ - endpoint: previewEndpoint('configuration/preview/experiment'), + endpoint: previewEndpoint('configuration-preview/experiment'), kind: 'experiment', input, }), @@ -223,7 +223,7 @@ export function mountConfigurationWorkstation( input: defaultSweepInput(), onApply: input => showPreview({ - endpoint: previewEndpoint('configuration/preview/sweep'), + endpoint: previewEndpoint('configuration-preview/sweep'), kind: 'sweep', input, }), diff --git a/web/src/panels/impedance.ts b/web/src/panels/impedance.ts index c14c50f0..834524b6 100644 --- a/web/src/panels/impedance.ts +++ b/web/src/panels/impedance.ts @@ -1,6 +1,6 @@ import Plotly from 'plotly.js-basic-dist-min' import { mountDevicePanel } from '../device-panel' -import { startJob, streamJobEvents } from '../job-stream' +import { startJob, streamJobEvents } from '../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../progress' import { baseLayout, plotConfig, PALETTE, LINE, MARKER, axisTitle } from '../plot-theme' import { checkField, numField, readCheck, readNum, setStatus } from '../ui-helpers' diff --git a/web/src/panels/jv.test.ts b/web/src/panels/jv.test.ts index 5b2879a6..b33cf73a 100644 --- a/web/src/panels/jv.test.ts +++ b/web/src/panels/jv.test.ts @@ -18,7 +18,7 @@ vi.mock('../device-panel', () => ({ mountDevicePanel: mocks.mountDevicePanel, })) -vi.mock('../job-stream', () => ({ +vi.mock('../v2-job-client', () => ({ startJob: mocks.startJob, streamJobEvents: mocks.streamJobEvents, })) diff --git a/web/src/panels/jv.ts b/web/src/panels/jv.ts index 850164de..30116bd7 100644 --- a/web/src/panels/jv.ts +++ b/web/src/panels/jv.ts @@ -1,6 +1,6 @@ import Plotly from 'plotly.js-basic-dist-min' import { mountDevicePanel, type DevicePanel } from '../device-panel' -import { startJob, streamJobEvents } from '../job-stream' +import { startJob, streamJobEvents } from '../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../progress' import { appendWaveformEvidence, mountJVWaveformControls } from '../jv-waveform-controls' import { baseLayout, plotConfig, PALETTE, LINE, MARKER, axisTitle } from '../plot-theme' diff --git a/web/src/stack/save-as-dialog.ts b/web/src/stack/save-as-dialog.ts index a5602b81..3481345c 100644 --- a/web/src/stack/save-as-dialog.ts +++ b/web/src/stack/save-as-dialog.ts @@ -1,5 +1,5 @@ import type { DeviceConfig } from '../types' -import { checkUserConfigExists, saveUserConfig } from '../api' +import { checkUserConfigExists, saveUserConfig } from '../v2-workstation-client' const FILENAME_RE = /^[a-zA-Z0-9_-]{1,64}$/ const HTML_ESCAPE: Record = { diff --git a/web/src/steady-jv-client.ts b/web/src/steady-jv-client.ts index d2b95e8f..b57a86d0 100644 --- a/web/src/steady-jv-client.ts +++ b/web/src/steady-jv-client.ts @@ -72,7 +72,7 @@ function protocol(value: SteadyProtocol, route: SteadyRoute): void { /** Narrow decoder for this worker's plain C-order float64 NPY payloads. * getArtifact verifies the original bytes first. No pickle/eval/general dtype loader. */ -export function readSteadyArray(bytes: Uint8Array, record: ArtifactRecord, allowEmpty = false): FloatArray { +export function readSteadyArray(bytes: Uint8Array, record: ArtifactRecord, allowEmpty = false, maxRank = 2): FloatArray { check(record.format === 'npy' && bytes.length >= 10 && Array.from(bytes.slice(0, 6)).join(',') === '147,78,85,77,80,89', 'Invalid steady NPY artifact') const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) @@ -85,7 +85,7 @@ export function readSteadyArray(bytes: Uint8Array, record: ArtifactRecord, allow const match = /^\{'descr': '([<>]f8)', 'fortran_order': False, 'shape': \((\d+(?:,\s*\d+)*,?)\),?\s*\}\s*$/.exec(header) check(match, 'Only plain C-order float64 steady arrays are supported') const shape = match[2].split(',').filter(x => x.trim()).map(Number) - check(shape.length >= 1 && shape.length <= 2 && shape.every(n => Number.isSafeInteger(n) && (allowEmpty ? n >= 0 : n > 0)), 'Invalid steady array shape') + check(shape.length >= 1 && shape.length <= maxRank && shape.every(n => Number.isSafeInteger(n) && (allowEmpty ? n >= 0 : n > 0)), 'Invalid steady array shape') const count = shape.reduce((a, b) => a * b, 1) check(Number.isSafeInteger(count) && prefix + length + count * 8 === bytes.length, 'NPY byte count mismatch') check(record.metadata.dtype === match[1] && record.metadata.order === 'C' @@ -143,10 +143,11 @@ export class SteadyJVClient { if (entry.engine !== 'solarlab' || entry.scope !== STEADY_SCOPE || entry.driver !== 'steady_jv') continue const schema = object(entry.input_schema), properties = object(schema.properties) const keys = ['device_id', 'voltage_V', 'intervals_per_layer', 'generation_scale', 'incident_power_W_m2'] + const optionalKeys = ['expected_prepared_sha256', 'expected_source_sha256'] const required = schema.required if (schema.additionalProperties !== false || !Array.isArray(required) || required.length !== keys.length || keys.some(key => !required.includes(key)) - || Object.keys(properties).some(key => !keys.includes(key))) continue + || Object.keys(properties).some(key => !keys.includes(key) && !optionalKeys.includes(key))) continue const voltage = object(properties.voltage_V), grid = object(properties.intervals_per_layer) const installed = object(entry.preparation_context) check(Array.isArray(installed.devices), 'Missing installed device list') diff --git a/web/src/v2-cutover.test.ts b/web/src/v2-cutover.test.ts new file mode 100644 index 00000000..9ef63df5 --- /dev/null +++ b/web/src/v2-cutover.test.ts @@ -0,0 +1,556 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { webcrypto } from './test-helpers/schema-fixture.mjs' +import { + checkUserConfigExists, + fetchOpticalMaterials, + getConfig, + listConfigs, + saveUserConfig, +} from './v2-workstation-client' +import { normalizePresetId, startJob, streamJobEvents } from './v2-job-client' +import { extractExecutionPhysics, formatQualificationBadge } from './workstation/execution-physics' +import { STEADY_SCOPE } from './steady-jv-client' + +const endpoint = 'http://127.0.0.1:8000/' +const registrySha = '1'.repeat(64) +const schemaSha = '2'.repeat(64) +const manifestSha = '3'.repeat(64) + +function jsonResponse(body: unknown, headers: Record = {}, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json', ...headers }, + }) +} + +function makeFloat64Npy(values: number[], shape: number[] = [values.length]): Uint8Array { + const shapeTuple = shape.length === 1 ? `(${shape[0]},)` : `(${shape.join(', ')})` + const header = `{'descr': ' view.setFloat64(10 + padded.length + i * 8, v, true)) + return out +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await webcrypto.subtle.digest('SHA-256', bytes) + return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('') +} + +describe('P09-02 V2 workstation and job client cutover', () => { + const storage = new Map() + + beforeEach(() => { + storage.clear() + vi.stubGlobal('crypto', webcrypto) + vi.stubGlobal('localStorage', { + getItem: (k: string) => storage.get(k) ?? null, + setItem: (k: string, v: string) => { storage.set(k, v) }, + removeItem: (k: string) => { storage.delete(k) }, + }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('loads configs and optical materials from V2 /configs and /materials routes without /api calls', async () => { + const calledUrls: string[] = [] + vi.stubGlobal('fetch', vi.fn(async (input: string | URL) => { + const url = String(input) + calledUrls.push(url) + if (url.endsWith('/configs')) { + return jsonResponse({ sources: [{ id: 'research_1d.yaml', sha256: 'a'.repeat(64), bytes: 64 }] }) + } + if (url.endsWith('/configs/research_1d.yaml')) { + return new Response( + 'device:\n V_bi: 1.05\n Phi: 2.5e21\nlayers:\n - name: Absorber\n role: absorber\n thickness: 4.0e-7\n', + { status: 200, headers: { 'Content-Type': 'application/octet-stream' } }, + ) + } + if (url.endsWith('/materials')) { + return jsonResponse({ + resource_library_sha256: 'b'.repeat(64), + resources: [ + { name: 'MAPbI3', kind: 'nk' }, + { name: 'AM15G', kind: 'spectrum' }, + ], + }) + } + throw new Error(`Unexpected URL: ${url}`) + })) + + const entries = await listConfigs(endpoint) + expect(entries.map(e => e.name)).toEqual(['research_1d.yaml']) + const cfg = await getConfig('research_1d.yaml', endpoint) + expect(cfg.device.V_bi).toBe(1.05) + expect(cfg.layers[0].role).toBe('absorber') + + const mats = await fetchOpticalMaterials(endpoint) + expect(mats).toEqual(['MAPbI3']) + + const reserved = await checkUserConfigExists('research_1d', endpoint) + expect(reserved).toEqual({ exists: true, namespace: 'shipped' }) + const saved = await saveUserConfig('custom_stack', cfg, false, endpoint) + expect(saved).toEqual({ ok: true, saved: 'custom_stack' }) + const reloaded = await getConfig('custom_stack.yaml', endpoint) + expect(reloaded.device.V_bi).toBe(1.05) + expect(calledUrls.every(u => !u.includes('/api/'))).toBe(true) + }) + + it('submits V2 engine="solarlab" jobs, streams durable /runs SSE, reads NPY artifacts, and preserves UNQUALIFIED badge', async () => { + const vBytes = makeFloat64Npy([0, 0.5, 1.0]) + const jBytes = makeFloat64Npy([200, 180, -20]) + const vSha = await sha256Hex(vBytes) + const jSha = await sha256Hex(jBytes) + const vManifestSha = '4'.repeat(64) + const jManifestSha = '5'.repeat(64) + const calledUrls: string[] = [] + const captured: { submission: Record | null } = { submission: null } + + vi.stubGlobal('fetch', vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = String(input) + calledUrls.push(url) + if (url === `${endpoint}experiments`) { + return jsonResponse( + { + schema: 'solarlab.execution-catalog.v1', + job_schema_sha256: schemaSha, + resource_ceiling: { wall_seconds: 30, rss_bytes: 1073741824, output_bytes: 67108864, accepted_steps: null, calls: null }, + bindings: [ + { + experiment_id: 'steady_jv', + version: 1, + engine: 'solarlab', + driver: 'steady_jv', + scope: STEADY_SCOPE, + scientific_qualification: false, + preparation_context: { + devices: [{ device_id: 'research_1d', prepared_sha256: 'c'.repeat(64) }], + }, + }, + ], + }, + { + 'X-Solarlab-Registry': registrySha, + 'X-Solarlab-Job-Schema': schemaSha, + ETag: `"${registrySha}"`, + }, + ) + } + if (url === `${endpoint}jobs`) { + const parsed = JSON.parse(String(init?.body)) as Record + captured.submission = parsed + return jsonResponse( + { + status: 'accepted', + store_id: 'store_v2', + run_id: parsed.run_id, + attempt_id: 'att_1', + execution_catalog_sha256: registrySha, + job_schema_sha256: schemaSha, + scientific_qualification: false, + }, + {}, + 202, + ) + } + const runId = String(captured.submission?.run_id ?? '') + if (url.includes('/attempts/att_1/events')) { + const sse = [ + `id: 1\nevent: queued\ndata: ${JSON.stringify({ sequence: 1, event_key: 'queued', run_id: runId, attempt_id: 'att_1', generation: 0, kind: 'queued', created_ns: 1, payload: {} })}\n\n`, + `id: 2\nevent: terminal\ndata: ${JSON.stringify({ sequence: 2, event_key: 'terminal', run_id: runId, attempt_id: 'att_1', generation: 1, kind: 'terminal', created_ns: 2, payload: { state: 'succeeded', result: { worker_result: { manifest_sha256: manifestSha, scientific_qualification: false } }, artifacts: [] } })}\n\n`, + ].join('') + return new Response(sse, { + status: 200, + headers: { 'Content-Type': 'text/event-stream', 'X-RunStore-ID': 'store_v2' }, + }) + } + if (url.endsWith('/attempts/att_1')) { + const attemptResult = { + worker_result: { + manifest_sha256: manifestSha, + scientific_qualification: false, + steady_result: { + metrics: { + open_circuit_voltage_V: 0.9, + short_circuit_current_A_m2: 200, + fill_factor: 0.75, + efficiency: null, + }, + }, + }, + } + return jsonResponse( + { + attempt_id: 'att_1', + run_id: runId, + attempt_number: 1, + generation: 1, + state: 'succeeded', + created_ns: 1, + started_ns: 1, + finished_ns: 2, + owner_id: 'sup', + result: attemptResult, + terminal: { + state: 'succeeded', + result: attemptResult, + artifacts: [ + { artifact_id: 'art_v', manifest_sha256: vManifestSha }, + { artifact_id: 'art_j', manifest_sha256: jManifestSha }, + ], + }, + }, + { 'X-RunStore-ID': 'store_v2' }, + ) + } + if (url === `${endpoint}artifacts/art_v`) { + return jsonResponse( + { + artifact_id: 'art_v', + run_id: runId, + attempt_id: 'att_1', + generation: 1, + name: 'voltage_V', + format: 'npy', + phase: 'committed', + sha256: vSha, + manifest_sha256: vManifestSha, + size_bytes: vBytes.byteLength, + relative_path: 'objects/v', + metadata: { dtype: '>((resolve, reject) => { + let resultObj: Record | undefined + streamJobEvents>(handle, { + onProgress: () => {}, + onResult: r => { resultObj = r }, + onError: msg => reject(new Error(msg)), + onDone: () => { + if (resultObj) resolve(resultObj) + else reject(new Error('stream closed without result')) + }, + }) + }) + + const { pure, receipt } = extractExecutionPhysics(completed) + expect(pure.V_fwd).toEqual([0, 0.5, 1.0]) + expect(pure.J_fwd).toEqual([200, 180, -20]) + expect(receipt.engine).toBe('solarlab') + expect(receipt.scientificQualification).toBe(false) + expect(formatQualificationBadge(receipt).label).toBe('Unqualified · Engineering Preview') + expect(calledUrls.every(u => !u.includes('/api/'))).toBe(true) + + // Uninstalled capability refuses cleanly without falling back to legacy endpoints. + await expect(startJob('eqe', null, {}, null, endpoint)).rejects.toThrow('legacy execution fallback is retired') + }) + + it('decodes 1D-4D steady_2d NPY artifacts into real grid_x, grid_y, terminal mean J, and 2D snapshots', async () => { + const nx = 3 + const ny = 4 + const k = 2 + const xBytes = makeFloat64Npy([0, 4.0e-7, 8.0e-7], [nx]) + const yBytes = makeFloat64Npy([0, 1.0e-7, 2.5e-7, 4.0e-7], [ny]) + const secBytes = makeFloat64Npy( + [ + 1.6e-9, 1.6e-9, 1.6e-9, 1.6e-9, 1.6e-9, + -1.76e-4, -1.76e-4, -1.76e-4, -1.76e-4, -1.76e-4, + ], + [k, ny + 1], + ) + const phiValues = Array.from({ length: k * ny * nx }, (_, i) => 0.01 * i) + const phiBytes = makeFloat64Npy(phiValues, [k, ny, nx]) + const carrierValues = Array.from({ length: 2 * k * ny * nx }, (_, i) => 1.0e20 + 1.0e18 * i) + const carrierBytes = makeFloat64Npy(carrierValues, [2, k, ny, nx]) + + const artifacts = [ + { id: 'art_x', name: 'x_m', bytes: xBytes, shape: [nx], msha: '6'.repeat(64) }, + { id: 'art_y', name: 'y_m', bytes: yBytes, shape: [ny], msha: '7'.repeat(64) }, + { id: 'art_sec', name: 'section_terminal_current_A_m', bytes: secBytes, shape: [k, ny + 1], msha: '8'.repeat(64) }, + { id: 'art_phi', name: 'potential_V', bytes: phiBytes, shape: [k, ny, nx], msha: '9'.repeat(64) }, + { id: 'art_car', name: 'carrier_density_m3', bytes: carrierBytes, shape: [2, k, ny, nx], msha: 'a'.repeat(64) }, + ] + const shas = new Map() + for (const a of artifacts) { + shas.set(a.id, await sha256Hex(a.bytes)) + } + + const captured: { submission: Record | null } = { submission: null } + vi.stubGlobal('fetch', vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = String(input) + if (url === `${endpoint}experiments`) { + return jsonResponse( + { + schema: 'solarlab.execution-catalog.v1', + job_schema_sha256: schemaSha, + resource_ceiling: { wall_seconds: 30, rss_bytes: 1073741824, output_bytes: 67108864, accepted_steps: null, calls: null }, + bindings: [ + { + experiment_id: 'steady_2d', + version: 1, + engine: 'solarlab', + driver: 'steady_2d', + scope: 'uniform_no_grain_classical_2d_steady', + scientific_qualification: false, + preparation_context: { + devices: [{ device_id: 'research_1d', prepared_sha256: 'c'.repeat(64) }], + fixed_numerical_policy: { + voltage_V: 0.002, + spatial: { lateral_length_m: 8.0e-7, Nx: 2, Ny_per_layer: 1, lateral_bc: 'neumann', geometry_policy: 'rectangular_half_endpoint_neumann_2d_v1' }, + controls: { auxiliary_1d: {}, full_2d: {} }, + initial: { scheme: 'auxiliary_1d_broadcast' }, + }, + }, + }, + ], + }, + { + 'X-Solarlab-Registry': registrySha, + 'X-Solarlab-Job-Schema': schemaSha, + ETag: `"${registrySha}"`, + }, + ) + } + if (url === `${endpoint}jobs`) { + const parsed = JSON.parse(String(init?.body)) as Record + captured.submission = parsed + return jsonResponse( + { + status: 'accepted', + store_id: 'store_2d', + run_id: parsed.run_id, + attempt_id: 'att_2d', + execution_catalog_sha256: registrySha, + job_schema_sha256: schemaSha, + scientific_qualification: false, + }, + {}, + 202, + ) + } + const runId = String(captured.submission?.run_id ?? '') + if (url.includes('/attempts/att_2d/events')) { + const sse = [ + `id: 1\nevent: terminal\ndata: ${JSON.stringify({ sequence: 1, event_key: 'terminal', run_id: runId, attempt_id: 'att_2d', generation: 1, kind: 'terminal', created_ns: 2, payload: { state: 'succeeded', result: { worker_result: { manifest_sha256: manifestSha, scientific_qualification: false } }, artifacts: [] } })}\n\n`, + ].join('') + return new Response(sse, { + status: 200, + headers: { 'Content-Type': 'text/event-stream', 'X-RunStore-ID': 'store_2d' }, + }) + } + if (url.endsWith('/attempts/att_2d')) { + const attemptResult = { + worker_result: { + manifest_sha256: manifestSha, + scientific_qualification: false, + registered_numerical_policy: { voltage_V: 0.002 }, + registered_spatial_declaration: { lateral_bc: 'neumann' }, + steady_2d_result: { + schema: 'solarlab.steady-2d.result.v1', + accepted_count: k, + lateral_width_m: 8.0e-7, + shape_Ny_Nx: [ny, nx], + scientific_qualification: false, + }, + }, + } + return jsonResponse( + { + attempt_id: 'att_2d', + run_id: runId, + attempt_number: 1, + generation: 1, + state: 'succeeded', + created_ns: 1, + started_ns: 1, + finished_ns: 2, + owner_id: 'sup', + result: attemptResult, + terminal: { + state: 'succeeded', + result: attemptResult, + artifacts: artifacts.map(a => ({ artifact_id: a.id, manifest_sha256: a.msha })), + }, + }, + { 'X-RunStore-ID': 'store_2d' }, + ) + } + for (const a of artifacts) { + const sha = shas.get(a.id)! + if (url === `${endpoint}artifacts/${a.id}`) { + return jsonResponse( + { + artifact_id: a.id, + run_id: runId, + attempt_id: 'att_2d', + generation: 1, + name: a.name, + format: 'npy', + phase: 'committed', + sha256: sha, + manifest_sha256: a.msha, + size_bytes: a.bytes.byteLength, + relative_path: `objects/${a.id}`, + metadata: { dtype: '>((resolve, reject) => { + let resultObj: Record | undefined + streamJobEvents>(handle, { + onProgress: () => {}, + onResult: r => { resultObj = r }, + onError: msg => reject(new Error(msg)), + onDone: () => { + if (resultObj) resolve(resultObj) + else reject(new Error('stream closed without result')) + }, + }) + }) + + const { pure, receipt } = extractExecutionPhysics(completed) + expect(pure.grid_x).toEqual([0, 400, 800]) + expect(pure.grid_y).toEqual([0, 100, 250, 400]) + expect(pure.V).toEqual([0.002]) + expect((pure.J as number[]).length).toBe(1) + expect((pure.J as number[])[0]).toBeCloseTo(-220.0, 10) + const snaps = pure.snapshots as Array<{ V: number; phi: number[][]; n: number[][]; p: number[][] }> + expect(snaps).toHaveLength(1) + expect(snaps[0].V).toBe(0.002) + expect(snaps[0].phi).toHaveLength(ny) + expect(snaps[0].phi[0]).toEqual([0.12, 0.13, 0.14]) + expect(snaps[0].n[0][0]).toBeCloseTo(1.0e20 + 1.0e18 * 12, 4) + expect(snaps[0].p[0][0]).toBeCloseTo(1.0e20 + 1.0e18 * 36, 4) + expect(receipt.scientificQualification).toBe(false) + }) + + it('normalizes configPath to select matching installed V2 device and refuses uninstalled presets without falling back to devices[0]', async () => { + expect(normalizePresetId('research_1d')).toBe('research_1d') + expect(normalizePresetId('research_1d.yaml')).toBe('research_1d') + expect(normalizePresetId('examples/research_1d/device.json')).toBe('research_1d') + + const submittedDeviceIds: string[] = [] + vi.stubGlobal('fetch', vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = String(input) + if (url === `${endpoint}experiments`) { + return jsonResponse( + { + schema: 'solarlab.execution-catalog.v1', + job_schema_sha256: schemaSha, + resource_ceiling: { wall_seconds: 30, rss_bytes: 1073741824, output_bytes: 67108864, accepted_steps: null, calls: null }, + bindings: [ + { + experiment_id: 'steady_jv', + version: 1, + engine: 'solarlab', + driver: 'steady_jv', + scope: STEADY_SCOPE, + scientific_qualification: false, + preparation_context: { + devices: [ + { device_id: 'research_1d', prepared_sha256: 'c'.repeat(64) }, + { device_id: 'classical_pin', prepared_sha256: 'd'.repeat(64) }, + ], + }, + }, + ], + }, + { + 'X-Solarlab-Registry': registrySha, + 'X-Solarlab-Job-Schema': schemaSha, + ETag: `"${registrySha}"`, + }, + ) + } + if (url === `${endpoint}jobs`) { + const parsed = JSON.parse(String(init?.body)) as { run_id: string; input: { device_id: string } } + submittedDeviceIds.push(parsed.input.device_id) + return jsonResponse( + { + status: 'accepted', + store_id: 'store_v2', + run_id: parsed.run_id, + attempt_id: 'att_1', + execution_catalog_sha256: registrySha, + job_schema_sha256: schemaSha, + scientific_qualification: false, + }, + {}, + 202, + ) + } + throw new Error(`Unexpected URL: ${url}`) + })) + + await startJob('jv', null, { n_points: 3, V_max: 1.0 }, 'classical_pin.yaml', endpoint) + await startJob('jv', null, { n_points: 3, V_max: 1.0 }, 'examples/research_1d/device.json', endpoint) + expect(submittedDeviceIds).toEqual(['classical_pin', 'research_1d']) + + await expect(startJob('jv', null, {}, 'calado2016_ion_sweep.yaml', endpoint)).rejects.toThrow( + 'Configuration "calado2016_ion_sweep.yaml" is not installed on the V2 steady_jv route', + ) + await expect(startJob('jv', null, {}, 'custom_stack.yaml', endpoint)).rejects.toThrow( + 'Configuration "custom_stack.yaml" is not installed on the V2 steady_jv route', + ) + expect(submittedDeviceIds).toEqual(['classical_pin', 'research_1d']) + }) +}) diff --git a/web/src/v2-job-client.ts b/web/src/v2-job-client.ts new file mode 100644 index 00000000..f0e87bce --- /dev/null +++ b/web/src/v2-job-client.ts @@ -0,0 +1,556 @@ +/** + * V2 solarlab_server job submission, durable SSE subscription, and result readback. + * + * Uses exclusively V2 routes (`/experiments`, `/jobs`, `/runs/{run}/attempts/{attempt}/events`, + * `/results/{run}/attempts/{attempt}`, `/artifacts/{id}/content`) with engine='solarlab' + * and zero fallback to retired legacy endpoints. + */ +import { StoredRunClient, RunClientError } from './run-client' +import type { AttemptIdentity, StoredObject } from './run-client' +import { readSteadyArray, requestJobService, voltageGrid, STEADY_SCOPE } from './steady-jv-client' +import type { FloatArray } from './steady-jv-client' +import { resolveV2ServiceEndpoint } from './v2-workstation-client' +import type { + DarkJVResult, + DispatchableJobKind, + JobStreamHandlers, + JV2DResult, + JVResult, + SpatialSnapshot2D, + TPVResult, +} from './types' + +interface EncodedV2JobHandle { + v: 2 + endpoint: string + storeId: string + runId: string + attemptId: string + kind: DispatchableJobKind + driver: string + catalogSha256: string + voltageV?: number +} + +function encodeHandle(handle: EncodedV2JobHandle): string { + return 'v2:' + btoa(JSON.stringify(handle)) +} + +function decodeHandle(jobId: string): EncodedV2JobHandle { + if (!jobId.startsWith('v2:')) { + throw new RunClientError('protocol', 'Invalid V2 job handle; legacy job identifiers are not accepted for live dispatch') + } + const parsed = JSON.parse(atob(jobId.slice(3))) as EncodedV2JobHandle + if (!parsed || parsed.v !== 2 || !parsed.storeId || !parsed.runId || !parsed.attemptId) { + throw new RunClientError('protocol', 'Malformed V2 job handle') + } + return parsed +} + +function asObject(value: unknown, msg = 'Expected object'): StoredObject { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new RunClientError('protocol', msg) + } + return value as StoredObject +} + +function makeRunId(prefix: string): string { + const token = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' + ? crypto.randomUUID().replace(/[^A-Za-z0-9_-]/g, '') + : Math.random().toString(36).slice(2, 12) + Date.now().toString(36) + return `${prefix}_${token}`.slice(0, 96) +} + +/** + * Normalize a workstation configuration path to an installed preset ID: + * `research_1d`, `research_1d.yaml`, and `examples/research_1d/device.json` + * all map to `research_1d`. + */ +export function normalizePresetId(configPath: string): string { + const parts = configPath.trim().replace(/\\/g, '/').split('/').filter(Boolean) + let leaf = parts[parts.length - 1] ?? '' + if (/^device\.(json|ya?ml)$/i.test(leaf) && parts.length >= 2) leaf = parts[parts.length - 2] + return leaf.replace(/\.(json|ya?ml)$/i, '') +} + +/** + * Select the installed V2 route device for the requested configuration. + * A non-null configuration that is not installed on the route is refused + * explicitly; it is never silently replaced by another registered device. + */ +function selectRouteDevice(prep: StoredObject, configPath: string | null, route: string): string { + const devices = Array.isArray(prep.devices) ? prep.devices.map(d => asObject(d)) : [] + if (devices.length === 0) { + throw new RunClientError('protocol', `Installed ${route} route has no registered devices`) + } + const ids = devices.map(d => String(d.device_id)) + if (configPath === null) return ids[0] + const raw = configPath.trim() + const wanted = normalizePresetId(raw) + const match = wanted.length > 0 + ? ids.find(id => id === raw || id === wanted || normalizePresetId(id) === wanted) + : undefined + if (match === undefined) { + throw new Error( + `Configuration "${configPath}" is not installed on the V2 ${route} route (installed: ${ids.join(', ')}); ` + + 'refusing to substitute a different device.', + ) + } + return match +} + +export async function startJob( + kind: DispatchableJobKind, + _device: unknown, + params: Record, + configPath: string | null = null, + endpoint?: string | URL, +): Promise { + const base = resolveV2ServiceEndpoint(endpoint) + const { value: catalog, response: expResp } = await requestJobService(base, 'experiments') + const registrySha = expResp.headers.get('X-Solarlab-Registry') ?? '' + const schemaSha = expResp.headers.get('X-Solarlab-Job-Schema') ?? '' + if (!/^[a-f0-9]{64}$/.test(registrySha) || !/^[a-f0-9]{64}$/.test(schemaSha)) { + throw new RunClientError('protocol', 'Missing X-Solarlab-Registry or X-Solarlab-Job-Schema header on GET /experiments') + } + if (catalog.schema !== 'solarlab.execution-catalog.v1' || !Array.isArray(catalog.bindings)) { + throw new RunClientError('protocol', 'Invalid execution catalog document from GET /experiments') + } + const ceiling = asObject(catalog.resource_ceiling, 'Missing resource_ceiling') + const bindings = catalog.bindings.map(b => asObject(b)) + + let selectedEntry: StoredObject | undefined + let inputPayload: Record | undefined + let driver = '' + + if (kind === 'jv' || kind === 'dark_jv') { + selectedEntry = bindings.find( + b => b.engine === 'solarlab' && b.driver === 'steady_jv' && b.scope === STEADY_SCOPE, + ) + if (selectedEntry) { + const prep = asObject(selectedEntry.preparation_context) + const deviceId = selectRouteDevice(prep, configPath, 'steady_jv') + const nPoints = Math.max(2, Math.min(101, Math.round(Number(params.n_points ?? 25)))) + const vMax = Number.isFinite(Number(params.V_max)) && Number(params.V_max) !== 0 ? Number(params.V_max) : 1.1 + const requestedGrid = Math.round(Number(params.N_grid ?? 36)) + const intervals = Math.max(2, Math.min(256, Math.max(4, Math.round(requestedGrid / 3)))) + const isDark = kind === 'dark_jv' || params.illuminated === false + inputPayload = { + device_id: deviceId, + voltage_V: voltageGrid(0, vMax, nPoints), + intervals_per_layer: intervals, + generation_scale: isDark ? 0 : 1, + incident_power_W_m2: null, + } + driver = 'steady_jv' + } + } else if (kind === 'tpv') { + selectedEntry = bindings.find( + b => b.engine === 'solarlab' && b.driver === 'transient_1d', + ) + if (selectedEntry) { + const prep = asObject(selectedEntry.preparation_context) + const deviceId = selectRouteDevice(prep, configPath, 'transient_1d') + const sampleCount = 9 + const tEnd = Math.min(1, Math.max(1e-6, Number(params.t_end ?? 1e-4))) + const times = Array.from({ length: sampleCount }, (_, i) => (tEnd * i) / (sampleCount - 1)) + const wallCeiling = Math.min(30, Number(ceiling.wall_seconds ?? 30)) + inputPayload = { + device_id: deviceId, + times_s: times, + voltage_V: times.map((_, i) => (i === 0 ? 0 : 0.02)), + generation_scale: times.map((_, i) => (i === 1 ? 1.05 : 1.0)), + intervals_per_layer: 12, + controls: { + max_steps: sampleCount - 1, + wall_s: Math.min(20, wallCeiling), + newton_budget: { + max_iterations: 30, + max_residual_evaluations: 240, + max_jacobian_evaluations: 30, + max_backtracks: 12, + }, + }, + } + driver = 'transient_1d' + } + } else if (kind === 'jv_2d') { + selectedEntry = bindings.find( + b => b.engine === 'solarlab' && b.driver === 'steady_2d', + ) + if (selectedEntry) { + if (params.microstructure) { + throw new Error( + 'Grain-boundary 2D microstructure is not installed on this V2 steady_2d HTTP route; only uniform Neumann 2D steady is registered.', + ) + } + const prep = asObject(selectedEntry.preparation_context) + const deviceId = selectRouteDevice(prep, configPath, 'steady_2d') + const policy = asObject(prep.fixed_numerical_policy) + const illum = params.illuminated !== false + inputPayload = { + device_id: deviceId, + voltage_V: Number(policy.voltage_V ?? 0.002), + generation_scales: illum ? [0, 1] : [0], + spatial: asObject(policy.spatial), + controls: asObject(policy.controls), + initial: asObject(policy.initial), + } + driver = 'steady_2d' + } + } + + if (!selectedEntry || !inputPayload) { + throw new Error( + `Experiment "${kind}" has no installed V2 solarlab execution route in GET /experiments; legacy execution fallback is retired.`, + ) + } + + const runId = makeRunId(driver) + const wallLimit = Math.min(30, Number(ceiling.wall_seconds ?? 30)) + const submission = { + schema_version: 'solarlab.job-submission.v1', + run_id: runId, + experiment_id: String(selectedEntry.experiment_id), + version: Number(selectedEntry.version), + engine: 'solarlab', + input: inputPayload, + limits: { + wall_seconds: wallLimit, + rss_bytes: Number(ceiling.rss_bytes), + output_bytes: Number(ceiling.output_bytes), + accepted_steps: null, + calls: null, + }, + } + + const { value: accepted, response: postResp } = await requestJobService(base, 'jobs', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Solarlab-Registry': registrySha, + 'X-Solarlab-Job-Schema': schemaSha, + }, + body: JSON.stringify(submission), + }) + if (postResp.status !== 202 || accepted.status !== 'accepted') { + throw new RunClientError('protocol', 'Unexpected POST /jobs acceptance response') + } + + return encodeHandle({ + v: 2, + endpoint: base, + storeId: String(accepted.store_id), + runId: String(accepted.run_id), + attemptId: String(accepted.attempt_id), + kind, + driver, + catalogSha256: registrySha, + ...(driver === 'steady_2d' && typeof inputPayload.voltage_V === 'number' + ? { voltageV: inputPayload.voltage_V } + : {}), + }) +} + +async function adaptV2Result( + handle: EncodedV2JobHandle, + reader: StoredRunClient, + target: AttemptIdentity, +): Promise> { + const snapshot = (await reader.getAttempt(target)).value + if (!snapshot.terminal || snapshot.state !== 'succeeded') { + throw new RunClientError('protocol', `Attempt ended in state ${snapshot.state}`) + } + const worker = asObject(snapshot.result?.worker_result, 'Missing worker_result') + const manifestSha = String(worker.manifest_sha256 ?? '') + const manifestEnvelope = { + scientific_qualification: false, + execution: { worker_result: worker }, + execution_manifest: { + engine: 'solarlab', + driver: handle.driver, + manifest_sha256: manifestSha, + scientific_qualification: false, + }, + } + + if (handle.driver === 'steady_jv') { + const arrays: Record = {} + for (const ref of snapshot.terminal.artifacts) { + const art = await reader.getArtifact(target, ref) + const name = String(art.record.value.name) + if (name === 'voltage_V' || name === 'output_current_A_m2') { + arrays[name] = readSteadyArray(art.bytes, art.record.value) + } + } + const V = arrays.voltage_V?.values ?? [] + const J = arrays.output_current_A_m2?.values ?? [] + const doc = asObject(worker.steady_result) + const rawMetrics = asObject(doc.metrics) + const vocRaw = rawMetrics.open_circuit_voltage_V + const vocBracketed = typeof vocRaw === 'number' && Number.isFinite(vocRaw) + const metrics = { + V_oc: vocBracketed ? vocRaw : 0, + J_sc: typeof rawMetrics.short_circuit_current_A_m2 === 'number' ? rawMetrics.short_circuit_current_A_m2 : (J[0] ?? 0), + FF: typeof rawMetrics.fill_factor === 'number' && Number.isFinite(rawMetrics.fill_factor) ? rawMetrics.fill_factor : 0, + PCE: typeof rawMetrics.efficiency === 'number' && Number.isFinite(rawMetrics.efficiency) ? rawMetrics.efficiency : 0, + voc_bracketed: vocBracketed, + } + if (handle.kind === 'dark_jv') { + const darkPayload: DarkJVResult = { + V, + J: J.map(v => Math.abs(v)), + n_ideality: Number.NaN, + J_0: Number.NaN, + V_fit_lo: V[0] ?? 0, + V_fit_hi: V[V.length - 1] ?? 0, + } + return { ...darkPayload, ...manifestEnvelope } + } + const jvPayload: JVResult = { + V_fwd: V, + J_fwd: J, + V_rev: [...V].reverse(), + J_rev: [...J].reverse(), + metrics_fwd: metrics, + metrics_rev: metrics, + hysteresis_index: 0, + } + return { ...jvPayload, ...manifestEnvelope } + } + + if (handle.driver === 'transient_1d') { + const arrays: Record = {} + for (const ref of snapshot.terminal.artifacts) { + const art = await reader.getArtifact(target, ref) + const name = String(art.record.value.name) + if ( + name === 'accepted_times_s' + || name === 'requested_voltage_V' + || name === 'terminal_total_current_density_A_m2' + ) { + arrays[name] = readSteadyArray(art.bytes, art.record.value, true) + } + } + const t = arrays.accepted_times_s?.values ?? [] + const V = (arrays.requested_voltage_V?.values ?? []).slice(0, t.length) + const termJ = arrays.terminal_total_current_density_A_m2?.values ?? [] + const J = t.map((_, i) => (i === 0 ? 0 : termJ[(i - 1) * 2] ?? 0)) + const v0 = V[0] ?? 0 + const deltaV = V.map(v => v - v0) + const tpvPayload: TPVResult = { + t, + V, + J, + delta_V: deltaV, + tau: null, + V_oc: v0, + delta_V0: deltaV[1] ?? 0, + non_identifiable_reason: 'voltage_step_transient_1d_no_exponential_fit', + } + return { ...tpvPayload, ...manifestEnvelope } + } + + if (handle.driver === 'steady_2d') { + const arrays: Record = {} + for (const ref of snapshot.terminal.artifacts) { + const art = await reader.getArtifact(target, ref) + const name = String(art.record.value.name) + if ( + name === 'x_m' + || name === 'y_m' + || name === 'section_terminal_current_A_m' + || name === 'potential_V' + || name === 'carrier_density_m3' + ) { + arrays[name] = readSteadyArray(art.bytes, art.record.value, true, 4) + } + } + const summary = asObject(worker.steady_2d_result, 'Missing steady_2d_result summary') + const xArr = arrays.x_m + const yArr = arrays.y_m + const secArr = arrays.section_terminal_current_A_m + const phiArr = arrays.potential_V + const carrierArr = arrays.carrier_density_m3 + if (!xArr || !yArr || !secArr || !phiArr || !carrierArr) { + throw new RunClientError('protocol', 'Incomplete steady_2d NPY artifacts') + } + if (xArr.shape.length !== 1 || yArr.shape.length !== 1) { + throw new RunClientError('protocol', 'Invalid steady_2d grid axis rank') + } + const nx = xArr.shape[0] + const ny = yArr.shape[0] + const lateralWidthM = Number(summary.lateral_width_m) + if (!Number.isFinite(lateralWidthM) || lateralWidthM <= 0) { + throw new RunClientError('protocol', 'Invalid steady_2d lateral_width_m') + } + if (secArr.shape.length !== 2 || secArr.shape[1] < 2) { + throw new RunClientError('protocol', 'Invalid steady_2d section_terminal_current_A_m shape') + } + const k = secArr.shape[0] + const cols = secArr.shape[1] + if ( + phiArr.shape.length !== 3 + || phiArr.shape[0] !== k + || phiArr.shape[1] !== ny + || phiArr.shape[2] !== nx + || carrierArr.shape.length !== 4 + || carrierArr.shape[0] !== 2 + || carrierArr.shape[1] !== k + || carrierArr.shape[2] !== ny + || carrierArr.shape[3] !== nx + ) { + throw new RunClientError('protocol', 'Mismatched steady_2d field dimensions') + } + + const grid_x = xArr.values.map(v => v * 1e9) + const grid_y = yArr.values.map(v => v * 1e9) + const policy = worker.registered_numerical_policy && typeof worker.registered_numerical_policy === 'object' + ? (worker.registered_numerical_policy as Record) + : {} + const spatialDecl = worker.registered_spatial_declaration && typeof worker.registered_spatial_declaration === 'object' + ? (worker.registered_spatial_declaration as Record) + : {} + const lateralBc = spatialDecl.lateral_bc === 'periodic' ? 'periodic' : 'neumann' + const operatingVoltageV = typeof handle.voltageV === 'number' && Number.isFinite(handle.voltageV) + ? handle.voltageV + : (typeof policy.voltage_V === 'number' && Number.isFinite(policy.voltage_V) ? policy.voltage_V : 0.002) + + const slice2D = (flat: number[], offset: number, rows: number, rowCols: number): number[][] => + Array.from({ length: rows }, (_, r) => + flat.slice(offset + r * rowCols, offset + (r + 1) * rowCols), + ) + const zeroGrid = (rows: number, rowCols: number): number[][] => + Array.from({ length: rows }, () => Array.from({ length: Math.max(0, rowCols) }, () => 0)) + + let V: number[] = [] + let J: number[] = [] + let snapshots: SpatialSnapshot2D[] = [] + if (k > 0) { + const targetIdx = k - 1 + const lowerA_m = secArr.values[targetIdx * cols] + const upperA_m = secArr.values[targetIdx * cols + (cols - 1)] + const meanTerminalJ = (0.5 * (lowerA_m + upperA_m)) / lateralWidthM + V = [operatingVoltageV] + J = [meanTerminalJ] + const cellCount = ny * nx + snapshots = [ + { + V: operatingVoltageV, + x: grid_x, + y: grid_y, + phi: slice2D(phiArr.values, targetIdx * cellCount, ny, nx), + n: slice2D(carrierArr.values, targetIdx * cellCount, ny, nx), + p: slice2D(carrierArr.values, (k + targetIdx) * cellCount, ny, nx), + Jx_n: zeroGrid(ny, nx - 1), + Jy_n: zeroGrid(ny - 1, nx), + Jx_p: zeroGrid(ny, nx - 1), + Jy_p: zeroGrid(ny - 1, nx), + }, + ] + } + + const jv2dPayload: JV2DResult = { + V, + J, + grid_x, + grid_y, + lateral_bc: lateralBc, + snapshots, + metrics: { V_oc: 0, J_sc: 0, FF: 0, PCE: 0, voc_bracketed: false }, + } + return { ...jv2dPayload, steady_2d_summary: summary, ...manifestEnvelope } + } + + return manifestEnvelope +} + +export function streamJobEvents( + jobId: string, + handlers: JobStreamHandlers, +): () => void { + let handle: EncodedV2JobHandle + try { + handle = decodeHandle(jobId) + } catch (err) { + queueMicrotask(() => { + handlers.onError(err instanceof Error ? err.message : String(err)) + handlers.onDone() + }) + return () => {} + } + + const reader = new StoredRunClient(handle.endpoint, handle.storeId, 64 * 1024 ** 2) + const target: AttemptIdentity = Object.freeze({ runId: handle.runId, attemptId: handle.attemptId }) + let finished = false + const finish = () => { + if (finished) return + finished = true + handlers.onDone() + } + + const sub = reader.subscribe(target, doc => { + const ev = doc.value + if (ev.kind === 'queued' || ev.kind === 'running') { + handlers.onProgress({ + stage: ev.kind, + current: ev.kind === 'running' ? 1 : 0, + total: 2, + eta_s: null, + message: `SolarLab worker ${ev.kind}`, + }) + return + } + if (ev.kind === 'progress') { + const ui = (ev.payload?.ui_progress ?? {}) as Record + handlers.onProgress({ + stage: typeof ui.stage === 'string' ? ui.stage : 'progress', + current: typeof ui.current === 'number' ? ui.current : 1, + total: typeof ui.total === 'number' ? ui.total : 1, + eta_s: typeof ui.eta_s === 'number' ? ui.eta_s : null, + message: typeof ui.message === 'string' ? ui.message : String(ui.stage ?? 'running'), + }) + return + } + if (ev.kind === 'terminal') { + const payload = ev.payload as { state: string; result?: Record } + if (payload.state !== 'succeeded') { + const resObj = payload.result ?? {} + const wr = (resObj.worker_result ?? resObj) as Record + const detail = wr.detail ?? wr.reason ?? payload.state + handlers.onError(String(detail)) + finish() + return + } + void adaptV2Result(handle, reader, target) + .then(adapted => { + handlers.onResult(adapted as unknown as TResult) + finish() + }) + .catch(err => { + handlers.onError(err instanceof Error ? err.message : String(err)) + finish() + }) + } + }) + + void sub.done + .then(end => { + if (!finished && (end.reason === 'disconnected' || end.reason === 'terminal_acknowledged')) { + if (end.transportError) { + handlers.onError(end.transportError instanceof Error ? end.transportError.message : String(end.transportError)) + } + finish() + } + }) + .catch(err => { + if (!finished) { + handlers.onError(err instanceof Error ? err.message : String(err)) + finish() + } + }) + + return () => { + sub.unsubscribe() + } +} diff --git a/web/src/v2-workstation-client.ts b/web/src/v2-workstation-client.ts new file mode 100644 index 00000000..3ce64486 --- /dev/null +++ b/web/src/v2-workstation-client.ts @@ -0,0 +1,444 @@ +/** + * V2 solarlab_server configuration, material, and browser-preset client. + * + * Uses exclusively V2 routes (`/configs`, `/configs/{id}`, `/materials`, + * `/configuration-preview/device`) with zero legacy wire endpoints. + */ +import type { + ConfigEntry, + DeviceConfig, + LayerConfig, + LayerRole, + LayerTemplate, +} from './types' + +const USER_PRESETS_STORAGE_KEY = 'solarlab.v2.user_presets.v1' + +export function resolveV2ServiceEndpoint(explicit?: string | URL): string { + if (explicit !== undefined) { + const url = new URL(explicit) + return url.href.replace(/\/$/, '') + '/' + } + const configured = import.meta.env.VITE_SOLARLAB_SERVICE_BASE + if (typeof configured === 'string' && configured.trim().length > 0) { + const url = new URL(configured, globalThis.location?.origin ?? 'http://127.0.0.1:8000') + return url.href.replace(/\/$/, '') + '/' + } + const origin = globalThis.location?.origin + if (origin && /^https?:\/\//.test(origin)) { + return origin.replace(/\/$/, '') + '/' + } + return 'http://127.0.0.1:8000/' +} + +interface StoredUserPresetMap { + [stem: string]: DeviceConfig +} + +function readLocalUserPresets(): StoredUserPresetMap { + try { + const raw = globalThis.localStorage?.getItem(USER_PRESETS_STORAGE_KEY) + if (!raw) return {} + const parsed = JSON.parse(raw) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {} + return parsed as StoredUserPresetMap + } catch { + return {} + } +} + +function writeLocalUserPresets(map: StoredUserPresetMap): void { + globalThis.localStorage?.setItem(USER_PRESETS_STORAGE_KEY, JSON.stringify(map)) +} + +function parseScalar(raw: string): unknown { + const value = raw.trim() + if (value === '' || value === 'null' || value === '~') return null + if (value === 'true') return true + if (value === 'false') return false + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { + return value.slice(1, -1) + } + const num = Number(value) + if (Number.isFinite(num)) return num + return value +} + +function parseQuantityNumber(value: unknown, fallback = 0): number { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string') { + const trimmed = value.trim() + const match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*(.*)$/.exec(trimmed) + if (match) { + const n = Number(match[1]) + const unit = match[2].trim() + if (unit === 'nm') return n * 1e-9 + if (unit === 'um' || unit === 'µm') return n * 1e-6 + if (unit === 'cm^2/(V s)' || unit === 'cm^2/Vs') return n * 1e-4 + if (unit === 'cm^-3') return n * 1e6 + if (unit === 'cm^-1') return n * 1e2 + return n + } + } + return fallback +} + +function normalizeRole(raw: unknown): LayerRole { + const s = String(raw ?? 'absorber') + if ( + s === 'ETL' + || s === 'HTL' + || s === 'absorber' + || s === 'front_contact' + || s === 'back_contact' + || s === 'substrate' + ) { + return s + } + const upper = s.toUpperCase() + if (upper === 'ETL' || upper === 'HTL') return upper + return 'absorber' +} + +function layerFromMapping(raw: Record, materialParams?: Record): LayerConfig { + const merged = { ...(materialParams ?? {}), ...(raw.parameters as Record | undefined ?? {}), ...raw } + const num = (key: string, fallback: number): number => + merged[key] !== undefined && merged[key] !== null ? parseQuantityNumber(merged[key], fallback) : fallback + return { + name: String(raw.name ?? raw.id ?? 'layer'), + role: normalizeRole(raw.role), + thickness: num('thickness', 2e-7), + eps_r: num('eps_r', 10), + mu_n: num('mu_n', 1e-4), + mu_p: num('mu_p', 1e-4), + ni: num('ni', 1e11), + N_D: num('N_D', 0), + N_A: num('N_A', 0), + D_ion: num('D_ion', 0), + P0: num('P0', 0), + P_lim: num('P_lim', 1e30), + D_ion_neg: merged.D_ion_neg !== undefined ? num('D_ion_neg', 0) : undefined, + P0_neg: merged.P0_neg !== undefined ? num('P0_neg', 0) : undefined, + tau_n: num('tau_n', 1e-6), + tau_p: num('tau_p', 1e-6), + n1: num('n1', 1e11), + p1: num('p1', 1e11), + B_rad: num('B_rad', 0), + C_n: num('C_n', 0), + C_p: num('C_p', 0), + alpha: num('alpha', 0), + Eg: merged.Eg !== undefined ? num('Eg', 1.6) : undefined, + chi: merged.chi !== undefined ? num('chi', 3.9) : undefined, + optical_material: typeof merged.optical_material === 'string' ? merged.optical_material : undefined, + } +} + +export function parseConfigDocument(text: string): DeviceConfig { + const trimmed = text.replace(/^\uFEFF/, '').trim() + if (trimmed.startsWith('{')) { + const parsed = JSON.parse(trimmed) as Record + if (parsed.device && Array.isArray(parsed.layers)) { + return parsed as unknown as DeviceConfig + } + const dto = (parsed.device && typeof parsed.device === 'object' && !Array.isArray(parsed.device) && Array.isArray((parsed.device as Record).layers) + ? parsed.device + : parsed) as Record + const materialsById = new Map>() + if (Array.isArray(dto.materials)) { + for (const m of dto.materials) { + if (m && typeof m === 'object') { + const rec = m as Record + if (typeof rec.id === 'string' && rec.parameters && typeof rec.parameters === 'object') { + materialsById.set(rec.id, rec.parameters as Record) + } + } + } + } + const settings = (dto.settings as Record | undefined) ?? {} + const rawLayers = Array.isArray(dto.layers) ? dto.layers : [] + const layers = rawLayers + .filter((item): item is Record => Boolean(item && typeof item === 'object')) + .map(item => { + const matId = typeof item.material === 'string' ? item.material : undefined + return layerFromMapping(item, matId ? materialsById.get(matId) : undefined) + }) + return { + device: { + V_bi: settings.V_bi !== undefined && settings.V_bi !== null ? parseQuantityNumber(settings.V_bi, 1.05) : 1.05, + Phi: parseQuantityNumber(settings.Phi, 2.5e21), + T: settings.T !== undefined ? parseQuantityNumber(settings.T, 300) : 300, + mode: 'full', + }, + layers, + } + } + + // Minimal deterministic YAML reader for shipped standard device presets (`device:` + `layers:`). + const device: Record = {} + const layers: Array> = [] + let section: 'none' | 'device' | 'interfaces' | 'layers' = 'none' + let currentLayer: Record | null = null + const interfaces: Array<[number, number]> = [] + + for (const rawLine of trimmed.split(/\r?\n/)) { + const commentIdx = rawLine.indexOf('#') + const line = (commentIdx >= 0 ? rawLine.slice(0, commentIdx) : rawLine).replace(/\s+$/, '') + if (!line.trim()) continue + if (/^device:\s*$/.test(line)) { + section = 'device' + currentLayer = null + continue + } + if (/^layers:\s*$/.test(line)) { + section = 'layers' + currentLayer = null + continue + } + if (/^[A-Za-z0-9_]+:/.test(line)) { + section = 'none' + currentLayer = null + continue + } + if (section === 'device' && /^\s{2}interfaces:\s*$/.test(line)) { + section = 'interfaces' + continue + } + if (section === 'interfaces') { + const pairMatch = /^\s*-\s*\[\s*([^,\]]+)\s*,\s*([^\]]+)\s*\]/.exec(line) + if (pairMatch) { + interfaces.push([Number(pairMatch[1]) || 0, Number(pairMatch[2]) || 0]) + continue + } + if (/^\s{2}[A-Za-z0-9_]+:/.test(line)) { + section = 'device' + } + } + if (section === 'device') { + const kv = /^\s{2}([A-Za-z0-9_]+):\s*(.*)$/.exec(line) + if (kv) device[kv[1]] = parseScalar(kv[2]) + continue + } + if (section === 'layers') { + const itemStart = /^\s{2}-\s*([A-Za-z0-9_]+):\s*(.*)$/.exec(line) + if (itemStart) { + currentLayer = { [itemStart[1]]: parseScalar(itemStart[2]) } + layers.push(currentLayer) + continue + } + const kv = /^\s{4}([A-Za-z0-9_]+):\s*(.*)$/.exec(line) + if (kv && currentLayer) { + currentLayer[kv[1]] = parseScalar(kv[2]) + } + } + } + if (interfaces.length > 0) device.interfaces = interfaces + return { + device: { + V_bi: typeof device.V_bi === 'number' ? device.V_bi : 1.05, + Phi: typeof device.Phi === 'number' ? device.Phi : 2.5e21, + ...device, + } as DeviceConfig['device'], + layers: layers.map(l => layerFromMapping(l)), + } +} + +export async function listConfigs(endpoint?: string | URL): Promise { + const base = resolveV2ServiceEndpoint(endpoint) + const shipped: ConfigEntry[] = [] + try { + const res = await fetch(new URL('configs', base), { cache: 'no-store' }) + if (res.ok) { + const data = (await res.json()) as { sources?: Array<{ id: string }> } + for (const item of data.sources ?? []) { + if (typeof item.id === 'string' && item.id.length > 0) { + shipped.push({ + name: item.id, + namespace: 'shipped', + device_type: item.id.toLowerCase().includes('tandem') ? 'tandem_2T' : 'single_junction', + tier_compat: ['legacy', 'fast', 'full'], + }) + } + } + } + } catch { + // Offline or configuration preview context unconfigured; still surface local user presets. + } + const userMap = readLocalUserPresets() + const userEntries: ConfigEntry[] = Object.keys(userMap) + .sort() + .map(stem => ({ + name: `${stem}.yaml`, + namespace: 'user', + device_type: 'single_junction', + tier_compat: ['legacy', 'fast', 'full'], + })) + return [...shipped, ...userEntries] +} + +export async function getConfig(name: string, endpoint?: string | URL): Promise { + const stem = name.replace(/\.ya?ml$/i, '') + const userMap = readLocalUserPresets() + if (Object.hasOwn(userMap, stem)) { + return structuredClone(userMap[stem]) + } + const base = resolveV2ServiceEndpoint(endpoint) + const encoded = name.split('/').map(encodeURIComponent).join('/') + const res = await fetch(new URL(`configs/${encoded}`, base), { cache: 'no-store' }) + if (!res.ok) { + throw new Error(`GET /configs/${name} failed: HTTP ${res.status}`) + } + const text = await res.text() + return parseConfigDocument(text) +} + +export async function fetchOpticalMaterials(endpoint?: string | URL): Promise { + const base = resolveV2ServiceEndpoint(endpoint) + const res = await fetch(new URL('materials', base), { cache: 'no-store' }) + if (!res.ok) throw new Error(`GET /materials failed: HTTP ${res.status}`) + const data = (await res.json()) as { resources?: Array<{ name: string; kind: string }> } + return (data.resources ?? []) + .filter(item => item.kind === 'nk' && typeof item.name === 'string') + .map(item => item.name) +} + +const BUILTIN_LAYER_TEMPLATES: Record = { + MAPbI3_absorber: { + role: 'absorber', + optical_material: null, + description: 'Intrinsic MAPbI3 perovskite absorber', + source: 'SolarLab V2 built-in template', + defaults: { + name: 'MAPbI3', + role: 'absorber', + thickness: 4e-7, + eps_r: 24.1, + mu_n: 2e-4, + mu_p: 2e-4, + ni: 1e11, + N_D: 0, + N_A: 0, + D_ion: 0, + P0: 0, + tau_n: 5e-7, + tau_p: 5e-7, + n1: 1e11, + p1: 1e11, + B_rad: 5e-17, + C_n: 1e-40, + C_p: 1e-40, + alpha: 1e7, + Eg: 1.6, + chi: 3.9, + }, + }, + TiO2_ETL: { + role: 'ETL', + optical_material: null, + description: 'Compact n-type TiO2 electron transport layer', + source: 'SolarLab V2 built-in template', + defaults: { + name: 'TiO2', + role: 'ETL', + thickness: 1e-7, + eps_r: 9.0, + mu_n: 5e-5, + mu_p: 1e-6, + ni: 1e7, + N_D: 1e24, + N_A: 0, + D_ion: 0, + P0: 0, + tau_n: 1e-6, + tau_p: 1e-6, + n1: 1e7, + p1: 1e7, + B_rad: 0, + C_n: 0, + C_p: 0, + alpha: 0, + Eg: 3.2, + chi: 4.0, + }, + }, + Spiro_HTL: { + role: 'HTL', + optical_material: null, + description: 'Doped p-type Spiro-OMeTAD hole transport layer', + source: 'SolarLab V2 built-in template', + defaults: { + name: 'Spiro', + role: 'HTL', + thickness: 1e-7, + eps_r: 3.5, + mu_n: 1e-6, + mu_p: 2e-5, + ni: 1e8, + N_D: 0, + N_A: 1e24, + D_ion: 0, + P0: 0, + tau_n: 1e-6, + tau_p: 1e-6, + n1: 1e8, + p1: 1e8, + B_rad: 0, + C_n: 0, + C_p: 0, + alpha: 0, + Eg: 2.2, + chi: 3.2, + }, + }, +} + +export async function fetchLayerTemplates(): Promise> { + return structuredClone(BUILTIN_LAYER_TEMPLATES) +} + +export interface SaveUserConfigResult { + ok: true + saved: string +} + +export interface SaveUserConfigError { + ok: false + status: number + detail: string +} + +export type SaveUserConfigResponse = SaveUserConfigResult | SaveUserConfigError + +export async function checkUserConfigExists( + name: string, + endpoint?: string | URL, +): Promise<{ exists: boolean; namespace: 'shipped' | 'user' | null }> { + const entries = await listConfigs(endpoint) + const match = entries.find( + e => e.name === name || e.name === `${name}.yaml` || e.name === `${name}.yml`, + ) + if (!match) return { exists: false, namespace: null } + return { exists: true, namespace: match.namespace } +} + +export async function saveUserConfig( + name: string, + config: DeviceConfig, + overwrite = false, + endpoint?: string | URL, +): Promise { + const trimmed = name.trim().replace(/\.ya?ml$/i, '') + if (!/^[a-zA-Z0-9_-]{1,64}$/.test(trimmed)) { + return { ok: false, status: 422, detail: 'Invalid preset filename' } + } + const probe = await checkUserConfigExists(trimmed, endpoint) + if (probe.exists && probe.namespace === 'shipped') { + return { ok: false, status: 409, detail: `"${trimmed}" is reserved by a shipped preset` } + } + if (probe.exists && probe.namespace === 'user' && !overwrite) { + return { ok: false, status: 409, detail: `"${trimmed}" already exists` } + } + const map = readLocalUserPresets() + map[trimmed] = structuredClone(config) + writeLocalUserPresets(map) + return { ok: true, saved: trimmed } +} diff --git a/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts b/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts index 4aa53d3b..1532b1fc 100644 --- a/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts +++ b/web/src/workstation/p06-08-manifest-diagnostics-and-catalog.test.ts @@ -18,13 +18,12 @@ vi.mock('plotly.js-basic-dist-min', () => ({ }, })) -vi.mock('../job-stream', () => ({ +vi.mock('../v2-job-client', () => ({ startJob: mocks.startJob, streamJobEvents: mocks.streamJobEvents, })) -vi.mock('../api', () => ({ - BASE: '', +vi.mock('../v2-workstation-client', () => ({ listConfigs: mocks.listConfigs, })) diff --git a/web/src/workstation/panes/dark-jv-pane.ts b/web/src/workstation/panes/dark-jv-pane.ts index 0919cd6a..795dd136 100644 --- a/web/src/workstation/panes/dark-jv-pane.ts +++ b/web/src/workstation/panes/dark-jv-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, DarkJVResult } from '../../types' diff --git a/web/src/workstation/panes/degradation-pane.ts b/web/src/workstation/panes/degradation-pane.ts index 33ad52fe..6a3405eb 100644 --- a/web/src/workstation/panes/degradation-pane.ts +++ b/web/src/workstation/panes/degradation-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, DegResult } from '../../types' diff --git a/web/src/workstation/panes/dynamic-defect-transient-pane.test.ts b/web/src/workstation/panes/dynamic-defect-transient-pane.test.ts index 2c61ef03..7d0bcb95 100644 --- a/web/src/workstation/panes/dynamic-defect-transient-pane.test.ts +++ b/web/src/workstation/panes/dynamic-defect-transient-pane.test.ts @@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({ resize: vi.fn(), })) -vi.mock('../../job-stream', () => ({ +vi.mock('../../v2-job-client', () => ({ startJob: mocks.startJob, streamJobEvents: mocks.streamJobEvents, })) diff --git a/web/src/workstation/panes/dynamic-defect-transient-pane.ts b/web/src/workstation/panes/dynamic-defect-transient-pane.ts index 167491b7..8b25d755 100644 --- a/web/src/workstation/panes/dynamic-defect-transient-pane.ts +++ b/web/src/workstation/panes/dynamic-defect-transient-pane.ts @@ -1,5 +1,5 @@ import { dynamicDefectTransientEligibility } from '../../explicit-defect-capability' -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import type { DeviceConfig, DynamicDefectTransientResult } from '../../types' import { numField, readNum, setStatus } from '../../ui-helpers' diff --git a/web/src/workstation/panes/el-pane.ts b/web/src/workstation/panes/el-pane.ts index 19f168b3..a305e234 100644 --- a/web/src/workstation/panes/el-pane.ts +++ b/web/src/workstation/panes/el-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import { hasTMMOptics } from '../../device-utils' diff --git a/web/src/workstation/panes/eqe-pane.ts b/web/src/workstation/panes/eqe-pane.ts index 5e980f51..a22944d4 100644 --- a/web/src/workstation/panes/eqe-pane.ts +++ b/web/src/workstation/panes/eqe-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import { hasTMMOptics } from '../../device-utils' diff --git a/web/src/workstation/panes/experiment-pane.test.ts b/web/src/workstation/panes/experiment-pane.test.ts index 567a3f2f..2f1d4233 100644 --- a/web/src/workstation/panes/experiment-pane.test.ts +++ b/web/src/workstation/panes/experiment-pane.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('../../job-stream', () => ({ startJob: vi.fn(), streamJobEvents: vi.fn() })) +vi.mock('../../v2-job-client', () => ({ startJob: vi.fn(), streamJobEvents: vi.fn() })) -import { startJob } from '../../job-stream' +import { startJob } from '../../v2-job-client' import type { DeviceConfig } from '../../types' import { mountExperimentPane, type ExperimentPaneHandle } from './experiment-pane' diff --git a/web/src/workstation/panes/impedance-pane.ts b/web/src/workstation/panes/impedance-pane.ts index 1d258598..42425f99 100644 --- a/web/src/workstation/panes/impedance-pane.ts +++ b/web/src/workstation/panes/impedance-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { setNumberInputValue } from '../../number-input' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { diff --git a/web/src/workstation/panes/jv-2d-pane.test.ts b/web/src/workstation/panes/jv-2d-pane.test.ts index 33d391d3..a8182f12 100644 --- a/web/src/workstation/panes/jv-2d-pane.test.ts +++ b/web/src/workstation/panes/jv-2d-pane.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('../../job-stream', () => ({ +vi.mock('../../v2-job-client', () => ({ startJob: vi.fn(), streamJobEvents: vi.fn(), })) diff --git a/web/src/workstation/panes/jv-2d-pane.ts b/web/src/workstation/panes/jv-2d-pane.ts index 9bad054d..3b819a22 100644 --- a/web/src/workstation/panes/jv-2d-pane.ts +++ b/web/src/workstation/panes/jv-2d-pane.ts @@ -7,7 +7,7 @@ * as 1D J-V; subsequent phases (microstructure, dual ions, etc.) will add * inputs here as they are implemented. */ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import { describeActivePhysics } from '../../active-physics' diff --git a/web/src/workstation/panes/jv-pane.test.ts b/web/src/workstation/panes/jv-pane.test.ts index 4910a58e..d594bd2a 100644 --- a/web/src/workstation/panes/jv-pane.test.ts +++ b/web/src/workstation/panes/jv-pane.test.ts @@ -9,14 +9,14 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import figureReferenceJSON from '../../../../perovskite-sim/tests/fixtures/IonDiffusivityFigureReference.json?raw' -vi.mock('../../job-stream', () => ({ +vi.mock('../../v2-job-client', () => ({ startJob: vi.fn(), streamJobEvents: vi.fn(), })) import { mountJVPane } from './jv-pane' import type { DeviceConfig } from '../../types' -import { startJob } from '../../job-stream' +import { startJob } from '../../v2-job-client' import { mountExperimentPane } from './experiment-pane' const figureReference = JSON.parse(figureReferenceJSON) diff --git a/web/src/workstation/panes/jv-pane.ts b/web/src/workstation/panes/jv-pane.ts index 7c6b7ee5..296c7ca7 100644 --- a/web/src/workstation/panes/jv-pane.ts +++ b/web/src/workstation/panes/jv-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { mountJVWaveformControls } from '../../jv-waveform-controls' import { setStatus, numField, readNum, checkField, readCheck } from '../../ui-helpers' diff --git a/web/src/workstation/panes/mott-schottky-pane.ts b/web/src/workstation/panes/mott-schottky-pane.ts index 53a09c5f..a4e2c028 100644 --- a/web/src/workstation/panes/mott-schottky-pane.ts +++ b/web/src/workstation/panes/mott-schottky-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, MottSchottkyResult } from '../../types' diff --git a/web/src/workstation/panes/suns-voc-pane.ts b/web/src/workstation/panes/suns-voc-pane.ts index 639a9ea1..b876db71 100644 --- a/web/src/workstation/panes/suns-voc-pane.ts +++ b/web/src/workstation/panes/suns-voc-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, SunsVocResult } from '../../types' diff --git a/web/src/workstation/panes/tandem-pane.ts b/web/src/workstation/panes/tandem-pane.ts index 86d09230..a491b0a4 100644 --- a/web/src/workstation/panes/tandem-pane.ts +++ b/web/src/workstation/panes/tandem-pane.ts @@ -1,5 +1,5 @@ -import { listConfigs } from '../../api' -import { startJob, streamJobEvents } from '../../job-stream' +import { listConfigs } from '../../v2-workstation-client' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, readNum, numField } from '../../ui-helpers' import { mountTandemStackVisualizer } from '../../stack/tandem-stack-visualizer' diff --git a/web/src/workstation/panes/tpv-pane.test.ts b/web/src/workstation/panes/tpv-pane.test.ts index 4aa17857..55d0e702 100644 --- a/web/src/workstation/panes/tpv-pane.test.ts +++ b/web/src/workstation/panes/tpv-pane.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('../../job-stream', () => ({ +vi.mock('../../v2-job-client', () => ({ startJob: vi.fn(), streamJobEvents: vi.fn(), })) -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import type { DeviceConfig } from '../../types' import { mountTPVPane } from './tpv-pane' diff --git a/web/src/workstation/panes/tpv-pane.ts b/web/src/workstation/panes/tpv-pane.ts index 999e9317..52dc07fd 100644 --- a/web/src/workstation/panes/tpv-pane.ts +++ b/web/src/workstation/panes/tpv-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, TPVResult } from '../../types' diff --git a/web/src/workstation/panes/voc-grain-sweep-pane.ts b/web/src/workstation/panes/voc-grain-sweep-pane.ts index b79d7ace..ba89d213 100644 --- a/web/src/workstation/panes/voc-grain-sweep-pane.ts +++ b/web/src/workstation/panes/voc-grain-sweep-pane.ts @@ -5,7 +5,7 @@ * entered as a CSV of nm values; τ_GB / GB width default to literature-typical * values for moderately passivated MAPbI3 (τ_GB = 1 ns, width = 10 nm). */ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, VocGrainSweepResult } from '../../types' diff --git a/web/src/workstation/panes/voc-t-pane.ts b/web/src/workstation/panes/voc-t-pane.ts index 70122caa..0f08b394 100644 --- a/web/src/workstation/panes/voc-t-pane.ts +++ b/web/src/workstation/panes/voc-t-pane.ts @@ -1,4 +1,4 @@ -import { startJob, streamJobEvents } from '../../job-stream' +import { startJob, streamJobEvents } from '../../v2-job-client' import { createProgressBar, type ProgressBarHandle } from '../../progress' import { setStatus, numField, readNum } from '../../ui-helpers' import type { DeviceConfig, VocTResult } from '../../types' diff --git a/web/src/workstation/shell.ts b/web/src/workstation/shell.ts index 2b22774e..a0fd20c7 100644 --- a/web/src/workstation/shell.ts +++ b/web/src/workstation/shell.ts @@ -1,6 +1,6 @@ import { ContentItem, GoldenLayout } from 'golden-layout' import type { LayoutConfig, ResolvedLayoutConfig } from 'golden-layout' -import { getConfig, listConfigs } from '../api' +import { getConfig, listConfigs } from '../v2-workstation-client' import type { Workspace, Device, Run, ExperimentKind } from './types' import { STORAGE_KEY, diff --git a/web/vite.config.ts b/web/vite.config.ts index 1db3f0da..7f449f68 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -1,18 +1,40 @@ import { defineConfig } from 'vite' +const backendTarget = + (globalThis as unknown as { process?: { env?: Record } }).process?.env + ?.VITE_SOLARLAB_SERVER ?? 'http://127.0.0.1:8000' + +const v2Routes = [ + '/schema', + '/configuration-schema', + '/configs', + '/configuration-preview', + '/materials', + '/experiments', + '/jobs', + '/runs', + '/results', + '/artifacts', +] as const + export default defineConfig({ server: { port: 5173, proxy: { + ...Object.fromEntries( + v2Routes.map((route) => [ + route, + { + target: backendTarget, + changeOrigin: true, + }, + ]), + ), '/steady-service': { - target: 'http://127.0.0.1:8000', + target: backendTarget, changeOrigin: true, rewrite: (path) => path.replace(/^\/steady-service/, ''), }, - '/api': { - target: 'http://127.0.0.1:8000', - changeOrigin: true, - }, }, }, }) From c01afb72e92f756096cd230ac67dc5137abdc342 Mon Sep 17 00:00:00 2001 From: Xuan-Yan Chen Date: Thu, 19 Nov 2026 23:05:46 +0800 Subject: [PATCH 30/46] M: retire dead legacy_engine and legacy browser wire before P09-01 wheel freeze --- .github/workflows/ci.yml | 2 +- pyproject.toml | 6 + .../RefactorTransitionBoundariesV1.json | 8 +- src/solarlab/config/legacy_fields.py | 2 +- src/solarlab_server/legacy_engine/__init__.py | 239 ------------------ .../test_legacy_consumer_registration.py | 11 +- tests/refactor/test_package_boundaries.py | 60 +++-- tests/refactor/test_package_preparation.py | 3 + tests/refactor/test_release_bundle.py | 21 +- tests/runtime/legacy_fixtures.py | 75 ------ tests/runtime/test_job_route_client.py | 18 +- tests/runtime/test_legacy_engine.py | 150 ----------- .../test_p06_route_and_sse_closeout.py | 5 +- tests/runtime/test_p09_server_cutover.py | 9 +- tests/runtime/test_scan_execution.py | 38 --- web/src/api.ts | 139 ---------- web/src/job-stream.ts | 58 ----- web/tests/ion-flow.html | 2 +- 18 files changed, 95 insertions(+), 751 deletions(-) delete mode 100644 src/solarlab_server/legacy_engine/__init__.py delete mode 100644 tests/runtime/legacy_fixtures.py delete mode 100644 tests/runtime/test_legacy_engine.py delete mode 100644 web/src/api.ts delete mode 100644 web/src/job-stream.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b095557..a437a867 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -153,7 +153,7 @@ jobs: --durations=20 --junitxml=${{ runner.temp }}/packages-${{ matrix.python }}.xml - name: Check typed configuration, registry and runtime preparation run: | - uv run --frozen --no-sync ruff check --no-cache src scripts/generate_configuration_schema.py tests/refactor/test_configuration_schema_export.py tests/refactor/test_configuration_input_types.py tests/refactor/test_configuration_preparation.py tests/refactor/test_registry_preparation.py tests/refactor/test_device_configuration_preparation.py tests/refactor/test_complex_configuration_preparation.py tests/refactor/test_structured_registry_preparation.py tests/refactor/test_execution_identity_preparation.py tests/refactor/test_behavior_context.py tests/refactor/test_experiment_registry_startup.py tests/refactor/test_input_domain_closure.py tests/refactor/test_legacy_behavior_execution.py tests/refactor/test_legacy_execution_context.py tests/refactor/legacy_driver_observer.py tests/refactor/test_effective_behavior_identity.py tests/refactor/test_configuration_migration.py tests/refactor/test_execution_manifest.py tests/refactor/test_release_bundle.py tests/refactor/test_binding_identity.py tests/refactor/test_registry_mapping.py tests/runtime/test_run_store.py tests/runtime/test_execution.py tests/runtime/test_legacy_engine.py tests/runtime/legacy_fixtures.py tests/runtime/execution_workers.py tests/runtime/test_event_service.py tests/runtime/test_configuration_schema_service.py tests/runtime/test_configuration_preview.py tests/unit/contracts tests/unit/mesh tests/unit/discretization tests/unit/physics/electrostatics tests/unit/physics/statistics tests/unit/physics/contacts tests/unit/physics/transport tests/unit/physics/band_structure tests/unit/physics/field_mobility + uv run --frozen --no-sync ruff check --no-cache src scripts/generate_configuration_schema.py tests/refactor/test_configuration_schema_export.py tests/refactor/test_configuration_input_types.py tests/refactor/test_configuration_preparation.py tests/refactor/test_registry_preparation.py tests/refactor/test_device_configuration_preparation.py tests/refactor/test_complex_configuration_preparation.py tests/refactor/test_structured_registry_preparation.py tests/refactor/test_execution_identity_preparation.py tests/refactor/test_behavior_context.py tests/refactor/test_experiment_registry_startup.py tests/refactor/test_input_domain_closure.py tests/refactor/test_legacy_behavior_execution.py tests/refactor/test_legacy_execution_context.py tests/refactor/legacy_driver_observer.py tests/refactor/test_effective_behavior_identity.py tests/refactor/test_configuration_migration.py tests/refactor/test_execution_manifest.py tests/refactor/test_release_bundle.py tests/refactor/test_binding_identity.py tests/refactor/test_registry_mapping.py tests/runtime/test_run_store.py tests/runtime/test_execution.py tests/runtime/execution_workers.py tests/runtime/test_event_service.py tests/runtime/test_configuration_schema_service.py tests/runtime/test_configuration_preview.py tests/unit/contracts tests/unit/mesh tests/unit/discretization tests/unit/physics/electrostatics tests/unit/physics/statistics tests/unit/physics/contacts tests/unit/physics/transport tests/unit/physics/band_structure tests/unit/physics/field_mobility uv run --frozen --no-sync mypy --cache-dir /dev/null src/solarlab src/solarlab_server - name: Check generated configuration schema run: uv run --frozen --no-sync python scripts/generate_configuration_schema.py --check diff --git a/pyproject.toml b/pyproject.toml index e46aa692..430b2948 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -213,6 +213,12 @@ type = "forbidden" source_modules = ["solarlab_research"] forbidden_modules = ["perovskite_sim", "backend"] +[[tool.importlinter.contracts]] +name = "Server package has no legacy dependency" +type = "forbidden" +source_modules = ["solarlab_server"] +forbidden_modules = ["perovskite_sim", "backend"] + [[tool.importlinter.contracts]] name = "Companion packages are independent" type = "independence" diff --git a/reproducibility/RefactorTransitionBoundariesV1.json b/reproducibility/RefactorTransitionBoundariesV1.json index 550dc4c4..97340ad5 100644 --- a/reproducibility/RefactorTransitionBoundariesV1.json +++ b/reproducibility/RefactorTransitionBoundariesV1.json @@ -20,7 +20,9 @@ "execution_facade": { "id": "legacy-engine", "owner": "WS4", - "status": "implemented_W03", + "status": "historical", + "historical": true, + "retired_after_commit": "9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495", "module": "solarlab_server.legacy_engine", "path": "src/solarlab_server/legacy_engine/__init__.py", "symbol": "prepare_legacy_job", @@ -209,7 +211,9 @@ "web/src/job-stream.ts" ], "owner": "WS4", - "status": "retained_legacy_wire_clients", + "status": "historical", + "historical": true, + "retired_after_commit": "9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495", "replacement": "Registered product clients and the single reviewed user-entry switch", "exit_tasks": ["P06-06", "P09-02", "P09-03"] } diff --git a/src/solarlab/config/legacy_fields.py b/src/solarlab/config/legacy_fields.py index 42b563c4..0a2873cf 100644 --- a/src/solarlab/config/legacy_fields.py +++ b/src/solarlab/config/legacy_fields.py @@ -85,7 +85,7 @@ def retained_legacy_fields(source: SourceDocument) -> LegacyDeviceFieldsInput | } JV_HINT_CONSUMER_BINDINGS = ( {"path": "web/src/workstation/panes/jv-pane.ts", - "sha256": "a5b63f7bfdf0f951ea49fa9fa33e315d51bac05e532d66ed02a4cb07af938850"}, + "sha256": "6425acbbdf1ad973c1959e423ecf862870b713955542e0427d7f0a23e9b4af49"}, {"path": "web/src/jv-waveform-controls.ts", "sha256": "9d9fdf0b6d9245d9707dac60f09177343e4e7ad6adb3391a016bad5d9a64d4e2"}, ) diff --git a/src/solarlab_server/legacy_engine/__init__.py b/src/solarlab_server/legacy_engine/__init__.py deleted file mode 100644 index 9bdcb8b2..00000000 --- a/src/solarlab_server/legacy_engine/__init__.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Explicit high-level transition to the three source-audited old drivers. - -The public entry prepares data for the shared supervisor. Only its registered -child worker imports the old engine, after manifest/environment/source checks. -Existing backend and research consumers remain registered until their separate -migration tasks; this facade does not activate routes or qualify new physics. -""" - -from __future__ import annotations - -import base64 -from dataclasses import dataclass, fields, is_dataclass -import hashlib -import importlib.metadata -import importlib.util -import json -import os -from pathlib import Path -import platform -import struct -import sys -from typing import Any - -from solarlab.config.behavior import BehaviorContext -from solarlab.config.identity import ( - BuildSource, ExecutionDescription, ExecutionEngine, ExecutionManifest, IdentityInputs, - RuntimeEnvironment, -) -from solarlab.config.legacy_execution import LegacyExecutionContext -from solarlab.experiments.execution import JobHandle, ProcessSupervisor -from solarlab.experiments.worker import ( - ManifestBinding, ResourceLimits, WorkerBinding, WorkerContext, WorkerRequest, WorkerResult, -) -from solarlab.io.artifacts import bytes_artifact -from solarlab.materials.source import SourceDocument - -__all__ = ["LegacyJob", "legacy_environment", "legacy_description", "prepare_legacy_job", "legacy_worker_binding"] - -_THREADS = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "VECLIB_MAXIMUM_THREADS", "NUMEXPR_NUM_THREADS") -_PACKAGES = ("numpy", "scipy", "PyYAML", "pydantic", "threadpoolctl") -_REGISTRY = SourceDocument("solarlab.legacy-facade-registry.v1", b'{"drivers":["ion_hysteresis","scaps_steady_state","scaps_transient"],"engine":"legacy","fallback":"forbidden"}') -_SCHEMA = SourceDocument("solarlab.legacy-facade-request.v1", b'{"fields":["engine","driver","input_id","input_base64","context_sha256"],"version":1}') - - -def _document(name: str, value: Any) -> SourceDocument: - return SourceDocument(name, json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()) - - -def _environment(invocation: LegacyExecutionContext) -> tuple[tuple[str, str | None], ...]: - return tuple(sorted({**invocation.export()["environment"], **dict.fromkeys(_THREADS, "1")}.items())) - - -def legacy_environment(invocation: LegacyExecutionContext) -> RuntimeEnvironment: - """Describe the requested child environment without changing the parent. - - Versions come from this installation. The worker must independently - observe them after installing the explicit behavior/thread settings. - """ - if type(invocation) is not LegacyExecutionContext: - raise ValueError("an explicit supported legacy invocation is required") - return RuntimeEnvironment(platform.python_implementation(), platform.python_version(), platform.system(), platform.machine(), - tuple((name, importlib.metadata.version(name)) for name in _PACKAGES), - tuple((key, json.dumps(value)) for key, value in _environment(invocation))) - - -def _roles(invocation: LegacyExecutionContext) -> dict[str, SourceDocument]: - record = invocation.export() - preparation = record["behavior"]["source_inspection"]["preparation"] - # These original high-level drivers create their seed/grid internally. - # Bind that exact recipe, never label it a supplied/qualified working point. - return { - "protocol": _document("legacy.protocol.v1", {"driver": record["driver"], "arguments": record["arguments"]}), - "preparation": _document("legacy.preparation.v1", record), - "initial_state": _document("legacy.initial-recipe.v1", { - "input_sha256": invocation.input_source.sha256, "recipe": preparation, - "source": "created_by_original_driver", "supplied_working_point": False}), - "grid": _document("legacy.grid-recipe.v1", {"input_sha256": invocation.input_source.sha256, - "N_grid": record["arguments"]["N_grid"], "source": "created_by_original_driver"}), - "numeric_controls": _document("legacy.driver-controls.v1", preparation["actual_driver_arguments"]), - } - - -def legacy_description(invocation: LegacyExecutionContext, *, implementation: BuildSource, - environment: RuntimeEnvironment, current_repository_head: str) -> ExecutionDescription: - """Bind the full original invocation and its source-defined seed recipe.""" - roles = _roles(invocation) - return ExecutionDescription(roles["protocol"], roles["preparation"], roles["initial_state"], roles["grid"], - roles["numeric_controls"], implementation, environment, current_repository_head) - - -@dataclass(frozen=True, slots=True) -class LegacyJob: - request: WorkerRequest - execution: ManifestBinding - - def submit(self, supervisor: ProcessSupervisor, run_id: str, limits: ResourceLimits) -> JobHandle: - return supervisor.submit(run_id, "legacy", self.request, limits, execution=self.execution) - - -def prepare_legacy_job( - invocation: LegacyExecutionContext, inputs: IdentityInputs, execution: ExecutionDescription, *, - engine: ExecutionEngine, manifest: ExecutionManifest, expected_sha256: str, -) -> LegacyJob: - """Prepare one explicit old-engine job; no execution or route activation.""" - if type(engine) is not ExecutionEngine or engine.name != "legacy": - raise ValueError("this facade requires the explicit legacy engine; fallback is forbidden") - if type(invocation) is not LegacyExecutionContext or type(engine.behavior) is not BehaviorContext: - raise ValueError("this facade supports only the three audited BehaviorContext drivers") - if engine.behavior.content_sha256 != invocation.behavior.content_sha256: - raise ValueError("the engine and original invocation have different behavior contexts") - if any(getattr(execution, name) != document for name, document in _roles(invocation).items()): - raise ValueError("execution roles differ from the original legacy invocation") - binding = ManifestBinding(manifest, inputs, execution, engine, expected_sha256, _environment(invocation)) - identity = manifest.export()["document"]["execution_identity"] - request = WorkerRequest(_document("legacy.invocation.v1", { - "engine": engine.name, "driver": invocation.behavior.driver, - "input_id": invocation.input_source.id, "input_base64": base64.b64encode(invocation.input_source.content).decode(), - "context_sha256": invocation.content_sha256, - }), _REGISTRY, _SCHEMA, _document("legacy.execution-identity.v1", identity), - identity["payload"]["H_input"], identity["payload"]["H_physics"]) - binding.validate_request(request) - return LegacyJob(request, binding) - - -def legacy_worker_binding() -> WorkerBinding: - return WorkerBinding.from_function("legacy", _run_legacy, registry_sha256=_REGISTRY.sha256, schema_sha256=_SCHEMA.sha256) - - -def _installed_sources(invocation: LegacyExecutionContext, execution: ExecutionDescription) -> Path: - if "perovskite_sim" in sys.modules: - raise ValueError("legacy engine was imported before source and environment verification") - spec = importlib.util.find_spec("perovskite_sim") - if spec is None or spec.origin is None: - raise ValueError("the explicitly requested legacy engine is not installed") - root = Path(spec.origin).resolve().parent - required = {"perovskite_sim/" + source.id: source.content for source in invocation.behavior.sources} - files = {source.id: source.content for source in execution.implementation.files} - # SourceDocument deliberately excludes empty bytes. The original package - # initializer is empty and is checked as such, never fabricated content. - if Path(spec.origin).read_bytes() != b"": - raise ValueError("legacy package initializer is no longer the original empty file") - if not {"perovskite_sim/models/config_loader.py", *required} <= files.keys(): - raise ValueError("legacy implementation is missing required original source content") - if any(files[key] != value for key, value in required.items()): - raise ValueError("implementation differs from the audited behavior sources") - for name, expected in files.items(): - if not name.startswith("perovskite_sim/"): - raise ValueError("legacy implementation source IDs must be relative to perovskite_sim") - path = root / name.removeprefix("perovskite_sim/") - if not path.resolve().is_relative_to(root) or path.read_bytes() != expected: - raise ValueError("installed legacy implementation content differs: " + name) - actual = {"perovskite_sim/" + str(path.relative_to(root)) for path in root.rglob("*.py") if path.stat().st_size} - if actual != files.keys(): - raise ValueError("installed nonempty legacy Python source coverage differs") - for table in invocation.behavior.device.resources.tables: - path = root / "data/nk" / (table.name + ".csv") - if table.kind != "nk" or not path.resolve().is_relative_to(root / "data/nk"): - raise ValueError("legacy facade has no source-bound resolver for this resource") - if path.read_bytes() != table.source.content: - raise ValueError("installed legacy resource content differs: " + table.name) - return root - - -def _words(value: Any) -> Any: - """Lossless transitional payload; no decimal projection of numeric words.""" - import numpy as np - if is_dataclass(value) and not isinstance(value, type): - return {"type": type(value).__qualname__, "fields": {f.name: _words(getattr(value, f.name)) for f in fields(value)}} - if isinstance(value, np.ndarray): - if value.dtype.hasobject: - raise ValueError("object arrays are not a supported numeric result") - return {"dtype": value.dtype.str, "shape": list(value.shape), "raw_hex": value.tobytes(order="C").hex()} - if isinstance(value, np.generic): - return {"dtype": value.dtype.str, "raw_hex": value.tobytes().hex()} - if type(value) is float: - return {"binary64_be": struct.pack(">d", value).hex()} - if value is None or type(value) in (str, bool, int): - return value - if type(value) is bytes: - return {"bytes_b64": base64.b64encode(value).decode()} - if isinstance(value, (list, tuple)): - return [_words(item) for item in value] - if isinstance(value, dict) and all(type(key) is str for key in value): - return {key: _words(item) for key, item in value.items()} - raise ValueError("unsupported original result type: " + type(value).__qualname__) - - -def _run_legacy(request: WorkerRequest, worker: WorkerContext) -> WorkerResult: - binding = worker.consume_manifest(request, engine="legacy") - body = json.loads(request.request.content) - if (set(body) != {"engine", "driver", "input_id", "input_base64", "context_sha256"} - or body["engine"] != "legacy" or type(binding.engine.behavior) is not BehaviorContext): - raise ValueError("invalid explicit legacy invocation") - invocation = LegacyExecutionContext(binding.engine.behavior, - SourceDocument(body["input_id"], base64.b64decode(body["input_base64"], validate=True))) - if body["driver"] != invocation.behavior.driver or body["context_sha256"] != invocation.content_sha256: - raise ValueError("request differs from the source-bound original invocation") - if _environment(invocation) != binding.environment: - raise ValueError("worker environment differs from the actual behavior context") - if any(getattr(binding.execution, name) != document for name, document in _roles(invocation).items()): - raise ValueError("worker execution roles differ from the original legacy invocation") - root = _installed_sources(invocation, binding.execution) - worker.check_cancel() - # Imports occur only inside the isolated child, after all checks above. - from perovskite_sim.models.config_loader import load_device_from_yaml - from perovskite_sim.scaps_compat.loader import load_scaps_yaml - from perovskite_sim.experiments import jv_sweep, steady_state, waveform_jv - from threadpoolctl import threadpool_info, threadpool_limits - - path = Path.cwd() / "original-input.yaml" - with path.open("xb") as stream: - stream.write(invocation.input_source.content) - # Public preparation records already import NumPy for immutable resource - # arrays. Bound the live BLAS pools too, including SciPy's newly loaded one. - with threadpool_limits(limits=1): - threadpools = threadpool_info() - if any(item["num_threads"] != 1 for item in threadpools): - raise ValueError("legacy child numerical thread limit was not installed") - stack = (load_scaps_yaml(path) if invocation.behavior.driver.startswith("scaps_") else load_device_from_yaml(path)) - arguments = dict(invocation.export()["arguments"]) - worker.progress({"stage": "legacy_driver", "driver": invocation.behavior.driver, - "manifest_sha256": binding.expected_sha256}) - if invocation.behavior.driver == "scaps_transient": - result = jv_sweep.run_jv_sweep(stack, **arguments) - elif invocation.behavior.driver == "scaps_steady_state": - result = steady_state.solve_voc_ss(stack, **arguments) - elif invocation.behavior.driver == "ion_hysteresis": - waveform = waveform_jv.JVWaveform.from_dict(arguments.pop("waveform")) - result = waveform_jv.run_waveform_jv(stack, waveform, **arguments) - else: - raise ValueError("unsupported old driver; fallback is forbidden") - worker.check_cancel() - data = json.dumps(_words(result), sort_keys=True, separators=(",", ":"), allow_nan=False).encode() - return WorkerResult.from_dict({"engine": "legacy", "driver": invocation.behavior.driver, - "manifest_sha256": binding.expected_sha256, "H_execution": binding.manifest.execution_sha256, - "input_sha256": invocation.input_source.sha256, "context_sha256": invocation.content_sha256, - "legacy_source_root": str(root), "pid": os.getpid(), "threadpools": threadpools, "scientific_qualification": False, - "payload_sha256": hashlib.sha256(data).hexdigest()}, artifacts=(("legacy_result", bytes_artifact(data, metadata= - {"schema": "solarlab.legacy-raw-result.v1", "encoding": "exact_numeric_words"})),)) diff --git a/tests/refactor/test_legacy_consumer_registration.py b/tests/refactor/test_legacy_consumer_registration.py index ed39f850..8fdad51a 100644 --- a/tests/refactor/test_legacy_consumer_registration.py +++ b/tests/refactor/test_legacy_consumer_registration.py @@ -64,9 +64,10 @@ def test_current_inventory_agrees_with_the_accepted_audit( current: tuple[dict[str, Any], dict[str, Any], tuple[Consumer, ...], dict[str, Any]], ) -> None: policy, previous, consumers, lanes = current - # Independent AcceptanceV2 / UnregisteredLegacyConsumersV1 inventory: - # 99 direct files (excluding backend-only support), 47 lane/executor pairs. - # Audit sha256: 31c7bbbf8a081000036333de6deb27c735441344470083679390ab9933ea0b55. + # Independent AcceptanceV2 / UnregisteredLegacyConsumersV1 inventory after + # retiring dead web/src/{api,job-stream}.ts post-9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495: + # 97 direct files (excluding backend-only support), 47 lane/executor pairs. + # Prior 99-file audit sha256: a79669a57c072f6dc35d976a05d4eed03ec59e9c3bedc6f7494a820144d852be. # A deliberate inventory change needs a refreshed audit; CI needs no archive. inventory = { "consumer_paths": sorted({consumer.path for consumer in consumers}), @@ -74,13 +75,13 @@ def test_current_inventory_agrees_with_the_accepted_audit( } encoded = json.dumps(inventory, sort_keys=True, separators=(",", ":")).encode() assert hashlib.sha256(encoded).hexdigest() == ( - "a79669a57c072f6dc35d976a05d4eed03ec59e9c3bedc6f7494a820144d852be" + "9017bd64e66a007da3b2be043762fb6e3126c47ba8240a12bdb1ed1fb8b30c6e" ) assert registration_violations(ROOT, policy, previous, consumers, lanes) == [] @pytest.mark.parametrize("group_id", [ - "legacy-notebooks", "retained-research-benchmark-tools", "legacy-browser-wire", + "legacy-notebooks", "retained-research-benchmark-tools", ]) def test_removing_an_accepted_group_exposes_every_affected_consumer( current: tuple[dict[str, Any], dict[str, Any], tuple[Consumer, ...], dict[str, Any]], diff --git a/tests/refactor/test_package_boundaries.py b/tests/refactor/test_package_boundaries.py index 1c7fb41b..73763f55 100644 --- a/tests/refactor/test_package_boundaries.py +++ b/tests/refactor/test_package_boundaries.py @@ -6,6 +6,7 @@ import hashlib import importlib from importlib import resources +import importlib.util import inspect import json import os @@ -173,33 +174,42 @@ def test_registered_legacy_boundaries_have_real_consumers_and_explicit_exits(): facade = value["execution_facade"] assert facade["owner"] == "WS4" assert facade["module"] == "solarlab_server.legacy_engine" - assert facade["status"] == "implemented_W03" - module = importlib.import_module(facade["module"]) - assert (ROOT / facade["path"]).is_file() - assert facade["symbol"] == "prepare_legacy_job" - assert facade["symbol"] in module.__all__ - assert tuple(inspect.signature(getattr(module, facade["symbol"])).parameters) == ( - "invocation", "inputs", "execution", "engine", "manifest", "expected_sha256", - ) - assert facade["submission"]["symbol"] == "LegacyJob.submit" - assert "LegacyJob" in module.__all__ and callable(module.LegacyJob.submit) registration = facade["worker"] - assert registration["factory"] in module.__all__ - binding = getattr(module, registration["factory"])() - assert (binding.id, binding.module, binding.symbol) == ( - registration["id"], facade["module"], registration["symbol"], - ) - assert binding.id == "legacy" and binding.symbol == "_run_legacy" - assert tuple(inspect.signature(getattr(module, binding.symbol)).parameters) == ("request", "worker") - assert binding.source_sha256 == hashlib.sha256(Path(inspect.getfile(module)).read_bytes()).hexdigest() assert registration["registry"]["document"] == { "drivers": ["ion_hysteresis", "scaps_steady_state", "scaps_transient"], "engine": "legacy", "fallback": "forbidden", } - for name, digest in (("registry", binding.registry_sha256), ("request_schema", binding.schema_sha256)): - record = registration[name] - raw = json.dumps(record["document"], sort_keys=True, separators=(",", ":")).encode() - assert record["sha256"] == hashlib.sha256(raw).hexdigest() == digest + if facade.get("historical") is True or facade.get("status") == "historical": + assert facade["retired_after_commit"] == "9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495" + assert not (ROOT / facade["path"]).exists() + assert importlib.util.find_spec(facade["module"]) is None + for name in ("registry", "request_schema"): + record = registration[name] + raw = json.dumps(record["document"], sort_keys=True, separators=(",", ":")).encode() + assert record["sha256"] == hashlib.sha256(raw).hexdigest() + else: + assert facade["status"] == "implemented_W03" + module = importlib.import_module(facade["module"]) + assert (ROOT / facade["path"]).is_file() + assert facade["symbol"] == "prepare_legacy_job" + assert facade["symbol"] in module.__all__ + assert tuple(inspect.signature(getattr(module, facade["symbol"])).parameters) == ( + "invocation", "inputs", "execution", "engine", "manifest", "expected_sha256", + ) + assert facade["submission"]["symbol"] == "LegacyJob.submit" + assert "LegacyJob" in module.__all__ and callable(module.LegacyJob.submit) + assert registration["factory"] in module.__all__ + binding = getattr(module, registration["factory"])() + assert (binding.id, binding.module, binding.symbol) == ( + registration["id"], facade["module"], registration["symbol"], + ) + assert binding.id == "legacy" and binding.symbol == "_run_legacy" + assert tuple(inspect.signature(getattr(module, binding.symbol)).parameters) == ("request", "worker") + assert binding.source_sha256 == hashlib.sha256(Path(inspect.getfile(module)).read_bytes()).hexdigest() + for name, digest in (("registry", binding.registry_sha256), ("request_schema", binding.schema_sha256)): + record = registration[name] + raw = json.dumps(record["document"], sort_keys=True, separators=(",", ":")).encode() + assert record["sha256"] == hashlib.sha256(raw).hexdigest() == digest planning = facade["historical_planning"] assert planning["status"] == "planned_for_M1_not_implemented_by_WS2" assert planning["symbol"] == "run" and planning["source_commit"] @@ -212,6 +222,7 @@ def test_registered_legacy_boundaries_have_real_consumers_and_explicit_exits(): assert adapter["exit_tasks"] for group in value["consumer_groups"]: if group.get("historical") is True or group.get("status") == "historical": + assert all(not (ROOT / path).exists() for path in group["paths"]) continue assert group["owner"] and group["exit_tasks"] assert all((ROOT / path).is_file() for path in group["paths"]) @@ -224,6 +235,11 @@ def test_registered_legacy_submission_passes_the_same_request_and_manifest(): value = json.loads((ROOT / "reproducibility/RefactorTransitionBoundariesV1.json").read_text()) facade = value["execution_facade"] + if facade.get("historical") is True or facade.get("status") == "historical": + assert facade["retired_after_commit"] == "9358f24b31b642f8c6c1a9a3d46b0cbbfe7fc495" + assert not (ROOT / facade["path"]).exists() + assert importlib.util.find_spec(facade["module"]) is None + return module = importlib.import_module(facade["module"]) request, manifest, limits, handle = (object() for _ in range(4)) supervisor = Mock(spec=["submit"]) diff --git a/tests/refactor/test_package_preparation.py b/tests/refactor/test_package_preparation.py index ac3eb2e5..93a4579c 100644 --- a/tests/refactor/test_package_preparation.py +++ b/tests/refactor/test_package_preparation.py @@ -144,6 +144,9 @@ def test_import_linter_accepts_actual_package_sources(tmp_path): ("solarlab_research", "perovskite_sim", False), ("solarlab_research", "backend", False), ("solarlab_research", "solarlab_server", False), + ("solarlab_server", "perovskite_sim", False), + ("solarlab_server", "backend", False), + ("solarlab_server", "perovskite_sim", True), ("solarlab_server", "solarlab_research", False), ("solarlab.materials", "solarlab.config", False), ("solarlab.materials", "solarlab.device", False), diff --git a/tests/refactor/test_release_bundle.py b/tests/refactor/test_release_bundle.py index 240767d1..7ea2ea99 100644 --- a/tests/refactor/test_release_bundle.py +++ b/tests/refactor/test_release_bundle.py @@ -147,7 +147,8 @@ def test_complete_actual_source_bundle_is_immutable_and_preserves_commit_meaning source, bundle = frozen assert bundle.profile == "target" assert not any( - item.path.startswith("site/perovskite_sim/") for item in bundle.files + item.path.startswith(("site/perovskite_sim/", "site/solarlab_server/legacy_engine/")) + for item in bundle.files ) assert any( item.path == "site/solarlab_server/_web_dist/index.html" @@ -360,7 +361,14 @@ def installation(frozen, tmp_path_factory): with zipfile.ZipFile(wheel) as zf: wnames = zf.namelist() assert not any( - n.startswith(("perovskite_sim/", "perovskite-sim/", "backend/")) + n.startswith( + ( + "perovskite_sim/", + "perovskite-sim/", + "backend/", + "solarlab_server/legacy_engine/", + ) + ) for n in wnames ), wnames assert "solarlab/materials/data/default_catalog_v1.json" in wnames @@ -368,7 +376,11 @@ def installation(frozen, tmp_path_factory): with tarfile.open(sdist) as tf: snames = tf.getnames() assert not any( - "perovskite-sim/" in n or "perovskite_sim/" in n for n in snames + "perovskite-sim/" in n + or "perovskite_sim/" in n + or "solarlab_server/legacy_engine/" in n + or n.endswith(("/web/src/api.ts", "/web/src/job-stream.ts")) + for n in snames ), snames assert any(n.endswith("/web/dist/index.html") for n in snames), snames @@ -399,7 +411,8 @@ def installation(frozen, tmp_path_factory): sys.path = [str(site)] + [p for p in sys.path if p] assert importlib.util.find_spec('perovskite_sim') is None assert importlib.util.find_spec('backend') is None -for forbidden in ('perovskite_sim', 'backend'): +assert importlib.util.find_spec('solarlab_server.legacy_engine') is None +for forbidden in ('perovskite_sim', 'backend', 'solarlab_server.legacy_engine'): try: importlib.import_module(forbidden) except ModuleNotFoundError: diff --git a/tests/runtime/legacy_fixtures.py b/tests/runtime/legacy_fixtures.py deleted file mode 100644 index ebfaee32..00000000 --- a/tests/runtime/legacy_fixtures.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Real bounded old-driver inputs; no mock executor or numerical replacement.""" - -from dataclasses import replace -import json -from pathlib import Path -import subprocess -import sys - -from solarlab.config.behavior import behavior_source_requirements, inspect_historical_behavior -from solarlab.config.device_import import import_standard_device -from solarlab.config.identity import BuildSource, ExecutionEngine, execution_manifest -from solarlab.config.legacy_defaults import read_legacy_default_catalog -from solarlab.config.legacy_execution import LegacyExecutionContext -from solarlab.config.resolve_device import resolve_device -from solarlab.config.scaps_input import import_scaps_device -from solarlab.materials.resources import ResourceLibrary, ResourceTable -from solarlab.materials.source import SourceDocument -from solarlab_server.legacy_engine import legacy_description, legacy_environment, prepare_legacy_job - -ROOT = Path(__file__).resolve().parents[2] -LEGACY = ROOT / "perovskite-sim/perovskite_sim" -sys.path.insert(0, str(ROOT / "tests/refactor")) -from test_execution_identity_preparation import identity_inputs # noqa: E402 -from test_behavior_context import selection # noqa: E402 - -_CATALOG = ("models/parameters.py", "models/device.py", "models/defects.py", "physics/statistics.py", - "physics/band_gap_narrowing.py", "scaps_compat/loader.py", "constants.py", - "twod/microstructure.py", "models/tandem_config.py") - - -def make_job(driver="scaps_transient", *, arguments=None, environment=(), runtime_change=None, changed_resource=False): - sources = tuple(SourceDocument(name, (LEGACY / name).read_bytes()) for name, _ in behavior_source_requirements()) - default = read_legacy_default_catalog(tuple(SourceDocument(name, (LEGACY / name).read_bytes()) for name in _CATALOG)) - tables = ResourceLibrary(tuple(ResourceTable(path.stem, "nk", SourceDocument(path.name, path.read_bytes())) - for path in sorted((LEGACY / "data/nk").glob("*.csv")))) - if changed_resource: - first = tables.tables[0] - tables = ResourceLibrary((replace(first, source=replace(first.source, content=first.source.content + b"\n# changed resource\n")), - *tables.tables[1:])) - if driver == "ion_hysteresis": - raw = json.loads((ROOT / "perovskite-sim/tests/fixtures/IonDiffusivityFigureReference.json").read_bytes())["request"] - original = SourceDocument("ion-original.json", json.dumps(raw["device"]).encode()) - supplied = {**raw["params"], "N_grid": 8, "V_max": .02, "v_rate": 1000., "n_points": 3, - "save_snapshots": True, "decompose_currents": True, - "waveform": {**raw["params"]["waveform"], "branch_dwell_s": 1e-6, "dark_prep_s": 1e-6, - "dark_seed_s": 1e-6, "turnaround_s": 1e-6}} - editable = import_standard_device(original, id="legacy_job", defaults=default) - else: - original = SourceDocument("scaps-original.yaml", (ROOT / "perovskite-sim/configs/scaps_mirror_v2.yaml").read_bytes()) - supplied = ({"N_grid": 30, "V_hi": 1.3, "tol_v": .02, "iface_states": False} - if driver == "scaps_steady_state" else - {"N_grid": 8, "n_points": 3, "v_rate": 1000., "V_max": .02, - "save_snapshots": True, "decompose_currents": True}) - editable = import_scaps_device(original, id="legacy_job", defaults=default) - supplied.update(arguments or {}) - device = resolve_device(editable, default, tables, sources=(original,)) - problem = "dc" if driver == "scaps_steady_state" else "transient" - behavior = inspect_historical_behavior(device, selection(device, problem), driver=driver, sources=sources, - environment=environment, arguments=SourceDocument("original-arguments.json", json.dumps(supplied).encode())) - inputs = identity_inputs(device, problem=problem, effective_behavior=behavior) - invocation = LegacyExecutionContext(behavior, original) - commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() - # All old Python source bytes, with their real unchanged build association. - subprocess.run(["git", "diff", "--exit-code", "HEAD", "--", "perovskite-sim/perovskite_sim"], - cwd=ROOT, check=True, capture_output=True) - build = BuildSource(commit, tuple(SourceDocument("perovskite_sim/" + str(path.relative_to(LEGACY)), path.read_bytes()) - for path in sorted(LEGACY.rglob("*.py")) if path.stat().st_size)) - runtime = legacy_environment(invocation) - if runtime_change: - runtime = replace(runtime, **runtime_change) - description = legacy_description(invocation, implementation=build, environment=runtime, current_repository_head=commit) - engine = ExecutionEngine("legacy", behavior) - manifest = execution_manifest(inputs, description, engine=engine) - job = prepare_legacy_job(invocation, inputs, description, engine=engine, manifest=manifest, expected_sha256=manifest.sha256) - return job, invocation diff --git a/tests/runtime/test_job_route_client.py b/tests/runtime/test_job_route_client.py index ac7d097c..55cd4711 100644 --- a/tests/runtime/test_job_route_client.py +++ b/tests/runtime/test_job_route_client.py @@ -45,15 +45,15 @@ def test_actual_v2_typescript_client_executes_solarlab_job_and_retired_legacy_ro ["'./steady-jv-client'", "'./steady-jv-client.mjs'"], ["'./v2-workstation-client'", "'./v2-workstation-client.mjs'"], ]); -await writeFile(`${outDir}/base.mjs`, `export const BASE = ${JSON.stringify(endpoint.replace(/\\/$/, ''))};`); -await transpile('job-stream', [["'./api'", "'./base.mjs'"]]); - -// 1. Retained legacy job-stream.ts is explicitly refused with HTTP 410 and zero fallback. -const legacyMod = await import(pathToFileURL(`${outDir}/job-stream.mjs`)); -await assert.rejects( - () => legacyMod.startJob('jv', null, {}, 'fixture:scaps'), - err => String(err.message).includes('410'), -); +// 1. Retired legacy POST /api/jobs route is explicitly refused with HTTP 410 and zero fallback. +const legacyRes = await fetch(`${endpoint}api/jobs`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ kind: 'jv', config_name: 'fixture:scaps', params: {} }), +}); +assert.equal(legacyRes.status, 410); +const legacyBody = await legacyRes.json(); +assert.equal(legacyBody.detail?.code ?? legacyBody.code, 'legacy_execution_retired'); // 2. Production V2 job client submits engine='solarlab' via POST /jobs and streams durable RunStore events. const { startJob, streamJobEvents } = await import(pathToFileURL(`${outDir}/v2-job-client.mjs`)); diff --git a/tests/runtime/test_legacy_engine.py b/tests/runtime/test_legacy_engine.py deleted file mode 100644 index 54924780..00000000 --- a/tests/runtime/test_legacy_engine.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Real isolated workers, original short driver calls, and refusal boundaries.""" - -from dataclasses import replace -import hashlib -import json -import os -from pathlib import Path -import subprocess -import sys - -import pytest - -from solarlab.config.identity import ExecutionEngine, execution_manifest -from solarlab.experiments.execution import ProcessSupervisor -from solarlab.experiments.worker import ManifestBinding, ResourceLimits, WorkerRequest -from solarlab.io.run_store import RunStore -from solarlab.materials.source import SourceDocument -from solarlab_server.legacy_engine import legacy_worker_binding, prepare_legacy_job -from legacy_fixtures import ROOT, make_job - - -def pool(store, path): - return ProcessSupervisor(store, path, (legacy_worker_binding(),), max_active=1, max_pending=1, - shared_rss_bytes=4 * 1024**3, shared_output_bytes=128 * 1024**2) - - -def limits(): - return ResourceLimits(90., 1024**3, 64 * 1024**2, None, None) - - -def assert_closed(receipt): - value = receipt.data - assert value["process_exit_observed"] and value["process_joined"] and value["terminal_committed"] - with pytest.raises(ChildProcessError): - os.waitpid(value["pid"], os.WNOHANG) - return value - - -@pytest.mark.parametrize("driver", ("scaps_transient", "ion_hysteresis", "scaps_steady_state")) -def test_real_worker_matches_original_driver_numeric_payload(tmp_path, monkeypatch, driver): - monkeypatch.setenv("SOLARLAB_DOS_BAND", "1") # child explicitly clears this inherited value - before = dict(os.environ) - job, invocation = make_job(driver) - # Existing W08 observer calls the original driver directly, independently - # of the facade, capturing exact scalar/array words and the full return. - source = tmp_path / "original.yaml" - source.write_bytes(invocation.input_source.content) - request = tmp_path / "direct-request.json" - raw = invocation.export() - request.write_text(json.dumps({"driver": driver, "input_path": str(source), - "input_sha256": invocation.input_source.sha256, "environment": raw["environment"], - "arguments": raw["arguments"], "argument_form": "driver_keywords"})) - direct = tmp_path / "direct.json" - environment = dict(os.environ) - for key, value in job.execution.environment: - if value is None: - environment.pop(key, None) - else: - environment[key] = value - result = subprocess.run([sys.executable, "-I", "-B", str(ROOT / "tests/refactor/legacy_driver_observer.py"), - "--request", str(request), "--output", str(direct)], - env=environment, capture_output=True, text=True, timeout=90) - assert result.returncode == 0, result.stdout + result.stderr - original = json.loads(direct.read_bytes()) - assert original["complete"] and original["capture_errors"] == [] - with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: - receipt = assert_closed(supervisor.wait(job.submit(supervisor, driver, limits()), 95)) - assert receipt["store_state"] == "succeeded", receipt - records = [store.artifact(key) for key in receipt["terminal_artifacts"]] - payload = next(item for item in records if item["name"] == "legacy_result") - actual = store.read_artifact(payload["artifact_id"]) - assert json.loads(actual) == original["result"] - manifest = next(item for item in records if item["name"] == "execution_manifest") - assert store.read_artifact(manifest["artifact_id"]) == job.execution.manifest.canonical_json - assert receipt["worker_result"]["manifest_sha256"] == job.execution.expected_sha256 - assert receipt["worker_result"]["scientific_qualification"] is False - assert receipt["resources"]["calls"] is None # no invented internal step counters - events = [row for row in store.events(run_id=driver) if row["kind"] == "terminal"] - assert len(events) == 1 - assert dict(os.environ) == before - evidence = os.environ.get("SOLARLAB_LEGACY_WORKER_EVIDENCE") - if evidence: - with Path(evidence).open("a") as stream: - stream.write(json.dumps({"driver": driver, "bitwise_equal": True, - "direct_pid": original["pid"], "direct_seconds": original["elapsed_seconds"], - "payload_sha256": hashlib.sha256(actual).hexdigest(), "worker": receipt}, allow_nan=False) + "\n") - - -@pytest.mark.parametrize("change", ("missing_manifest", "wrong_runtime", "wrong_engine", "original_driver_error", "installed_source", "installed_resource")) -def test_real_worker_refuses_or_fails_without_engine_fallback(tmp_path, change): - job, invocation = make_job("ion_hysteresis" if change == "wrong_engine" else "scaps_transient", - arguments={"n_points": 1} if change == "original_driver_error" else None, - changed_resource=change == "installed_resource", - runtime_change={"python_version": "0.0"} if change == "wrong_runtime" else None) - execution = None if change == "missing_manifest" else job.execution - request = job.request - if change == "installed_source": - binding = job.execution - files = binding.execution.implementation.files - changed = replace(binding.execution, implementation=replace(binding.execution.implementation, - files=(replace(files[0], content=files[0].content + b"\n# other source\n"), *files[1:]))) - manifest = execution_manifest(binding.inputs, changed, engine=binding.engine) - altered = prepare_legacy_job(invocation, binding.inputs, changed, engine=binding.engine, - manifest=manifest, expected_sha256=manifest.sha256) - execution, request = altered.execution, altered.request - if change == "wrong_engine": - engine = ExecutionEngine("solarlab") - inputs = replace(job.execution.inputs, effective_behavior=None) - manifest = execution_manifest(inputs, job.execution.execution, engine=engine) - identity = manifest.export()["document"]["execution_identity"] - request = WorkerRequest(request.request, request.registry, request.schema, - SourceDocument("other-engine", json.dumps(identity, sort_keys=True, separators=(",", ":")).encode()), - identity["payload"]["H_input"], identity["payload"]["H_physics"]) - execution = ManifestBinding(manifest, inputs, job.execution.execution, engine, - manifest.sha256, job.execution.environment) - with RunStore(tmp_path / "store") as store, pool(store, tmp_path / "work") as supervisor: - value = assert_closed(supervisor.wait(supervisor.submit(change, "legacy", request, limits(), execution=execution), 95)) - assert value["store_state"] == "failed", value - assert value["worker_result"]["reason"] == "worker_exception", value - expected = {"missing_manifest": "requires a complete execution manifest", "wrong_runtime": "runtime environment", - "wrong_engine": "wrong execution engine", "original_driver_error": "n_points must be >= 2", - "installed_source": "installed legacy implementation content differs", - "installed_resource": "installed legacy resource content differs"} - assert expected[change] in value["worker_result"]["detail"], value - assert not value["terminal_artifacts"] - terminal = [event for event in store.events(run_id=change) if event["kind"] == "terminal"] - assert len(terminal) == 1 and terminal[0]["payload"]["state"] == "failed" - - -def test_preparation_refuses_wrong_engine_changed_roles_and_manifest_pin(): - job, invocation = make_job() - binding = job.execution - for changes, message in (({"engine": ExecutionEngine("solarlab")}, "explicit legacy"), - ({"expected_sha256": "0" * 64}, "frozen")): - args = dict(engine=binding.engine, manifest=binding.manifest, expected_sha256=binding.expected_sha256) - args.update(changes) - with pytest.raises(ValueError, match=message): - prepare_legacy_job(invocation, binding.inputs, binding.execution, **args) - changed = replace(binding.execution, grid=SourceDocument("wrong-grid", b"{}")) - with pytest.raises(ValueError, match="roles differ"): - prepare_legacy_job(invocation, binding.inputs, changed, engine=binding.engine, - manifest=binding.manifest, expected_sha256=binding.expected_sha256) - - -def test_isolated_import_does_not_load_an_engine_or_open_a_store(tmp_path): - code = "import sys; import solarlab_server.legacy_engine; assert not set(sys.modules) & {'perovskite_sim', 'scipy', 'sksundae', 'flint'}" - completed = subprocess.run([sys.executable, "-I", "-B", "-c", code], cwd=tmp_path, - capture_output=True, text=True, timeout=10) - assert completed.returncode == 0, completed.stderr - assert list(tmp_path.iterdir()) == [] diff --git a/tests/runtime/test_p06_route_and_sse_closeout.py b/tests/runtime/test_p06_route_and_sse_closeout.py index ece952ee..f47e9321 100644 --- a/tests/runtime/test_p06_route_and_sse_closeout.py +++ b/tests/runtime/test_p06_route_and_sse_closeout.py @@ -4,6 +4,7 @@ import hashlib import io import json +from pathlib import Path import subprocess import time @@ -12,7 +13,6 @@ from examples.research_1d.service import committed_implementation from examples.research_1d.steady import load_device -from legacy_fixtures import LEGACY, ROOT from solarlab.config.device_import import import_standard_device from solarlab.config.legacy_defaults import read_legacy_default_catalog from solarlab.config.legacy_wire import prepare_legacy_wire @@ -35,6 +35,9 @@ pytestmark = pytest.mark.requires_clean_core +ROOT = Path(__file__).resolve().parents[2] +LEGACY = ROOT / "perovskite-sim/perovskite_sim" + DEFAULT_PATHS = ( "models/parameters.py", "models/device.py", diff --git a/tests/runtime/test_p09_server_cutover.py b/tests/runtime/test_p09_server_cutover.py index f97976ed..d6cbdbc7 100644 --- a/tests/runtime/test_p09_server_cutover.py +++ b/tests/runtime/test_p09_server_cutover.py @@ -358,15 +358,12 @@ def test_dockerfile_compose_and_production_web_sources_are_cut_over() -> None: assert "Dockerfile.backend" not in text assert "backend.main:app" not in text - retained_legacy_wire = { - ROOT / "web/src/api.ts", - ROOT / "web/src/job-stream.ts", - } + assert not (ROOT / "src/solarlab_server/legacy_engine").exists() + assert not (ROOT / "web/src/api.ts").exists() + assert not (ROOT / "web/src/job-stream.ts").exists() import_legacy_re = re.compile(r"""from\s+['"](?:\.\.?/)*(?:api|job-stream)['"]""") offenders: list[str] = [] for ts_file in sorted((ROOT / "web/src").rglob("*.ts")): - if ts_file in retained_legacy_wire or ts_file.name.endswith(".test.ts"): - continue if import_legacy_re.search(ts_file.read_text()): offenders.append(str(ts_file.relative_to(ROOT))) assert offenders == [] diff --git a/tests/runtime/test_scan_execution.py b/tests/runtime/test_scan_execution.py index 00087f8c..0408b90a 100644 --- a/tests/runtime/test_scan_execution.py +++ b/tests/runtime/test_scan_execution.py @@ -1,10 +1,8 @@ """P06-05 real spawn, bounded shared capacity, resume and exact result reuse.""" from dataclasses import FrozenInstanceError, replace -import hashlib import json import multiprocessing -import os from pathlib import Path import random import struct @@ -458,42 +456,6 @@ def test_real_parent_crash_preserves_completed_and_queued_points_and_explicit_ne assert artifact(store, "restart-1")[0] == bytes.fromhex(json.loads(executions[1].execution.initial_state.content)["words"]) -def test_real_legacy_facade_scan_matches_single_runs_serial_and_random_parallel(tmp_path): - from legacy_fixtures import make_job - from solarlab_server.legacy_engine import legacy_worker_binding - - jobs = [make_job(arguments={"V_max": voltage})[0] for voltage in (.02, .03)] - limits = ResourceLimits(60., 1024**3, 64 * 1024**2, None, None) - records = [(RunSpec.from_binding("legacy", job.request, limits, job.execution), job.execution) for job in jobs] - evidence = [] - with RunStore(tmp_path / "db") as store, ProcessSupervisor(store, tmp_path / "work", (legacy_worker_binding(),), - max_active=2, max_pending=1, shared_rss_bytes=4 * 1024**3, shared_output_bytes=512 * 1024**2) as supervisor: - originals = [] - for i, job in enumerate(jobs): - h = job.submit(supervisor, f"single-{i}", limits) - returned = supervisor.wait(h, 65).data - assert returned["store_state"] == "succeeded", returned - originals.append(artifact(store, h.run_id, "legacy_result")[0]) - for name, order, width in (("legacy-serial", [0, 1], 1), ("legacy-random", [1, 0], 2)): - spec, executions = declaration(name, records, order=order) - result = supervisor.scan(spec, executions=executions, max_in_flight=width).wait(125) - assert result["state"] == "succeeded", result - for point in result["points"]: - i = int(point["point_id"][1:]) - content, _ = artifact(store, point["run_id"], "legacy_result") - assert content == originals[i] - assert point["initial_state"]["sha256"] == jobs[i].execution.execution.initial_state.sha256 - assert point["result"]["worker_result"]["scientific_qualification"] is False - receipt = supervisor.wait(JobHandle(store.store_id, point["run_id"], point["attempt_id"]), 1).data - evidence.append({"scan": name, "point": point["point_id"], "bitwise_equal": True, - "payload_sha256": hashlib.sha256(content).hexdigest(), "H_execution": point["H_execution"], - "initial_state": point["initial_state"], "process": point["result"]["process"], - "resources": receipt["resources"], "scientific_qualification": False}) - path = os.environ.get("SOLARLAB_SCAN_EVIDENCE") - if path: - Path(path).write_bytes(canonical({"real_legacy_points": evidence}) + b"\n") - - def test_job_provenance_is_sealed_to_the_actual_manifest_and_claimed_attempt(make_spec, tmp_path): from copy import deepcopy from solarlab.reproducibility.job_provenance import JobProvenance, worker_result_provenance diff --git a/web/src/api.ts b/web/src/api.ts deleted file mode 100644 index 28d9e9d6..00000000 --- a/web/src/api.ts +++ /dev/null @@ -1,139 +0,0 @@ -import type { - DeviceConfig, - JVResult, - ISResult, - DegResult, - JVParams, - ISParams, - DegParams, - ConfigEntry, - LayerTemplate, - TandemJVPayload, -} from './types' - -export const BASE = import.meta.env.VITE_API_BASE ?? 'http://127.0.0.1:8000' - -async function handle(res: Response): Promise { - if (!res.ok) { - throw new Error(`HTTP ${res.status}: ${await res.text()}`) - } - const data = await res.json() - return data.result as T -} - -export async function listConfigs(): Promise { - const res = await fetch(`${BASE}/api/configs`) - if (!res.ok) throw new Error(`HTTP ${res.status}`) - const data = await res.json() - return data.configs as ConfigEntry[] -} - -export async function getConfig(name: string): Promise { - const res = await fetch(`${BASE}/api/configs/${encodeURIComponent(name)}`) - if (!res.ok) throw new Error(`HTTP ${res.status}`) - const data = await res.json() - return data.config as DeviceConfig -} - -export async function fetchOpticalMaterials(): Promise { - const res = await fetch(`${BASE}/api/optical-materials`) - if (!res.ok) throw new Error(`fetchOpticalMaterials failed: ${res.status}`) - const data = (await res.json()) as { materials: string[] } - return data.materials -} - -export async function fetchLayerTemplates(): Promise> { - const res = await fetch(`${BASE}/api/layer-templates`) - if (!res.ok) throw new Error(`fetchLayerTemplates failed: ${res.status}`) - const data = (await res.json()) as { templates: Record } - return data.templates -} - -export interface SaveUserConfigResult { - ok: true - saved: string -} - -export interface SaveUserConfigError { - ok: false - status: number - detail: string -} - -export type SaveUserConfigResponse = SaveUserConfigResult | SaveUserConfigError - -export async function saveUserConfig( - name: string, - config: DeviceConfig, - overwrite = false, -): Promise { - const res = await fetch(`${BASE}/api/configs/user`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, config, overwrite }), - }) - if (res.ok) { - const data = await res.json() - return { ok: true, saved: data.saved as string } - } - let detail = `HTTP ${res.status}` - try { - const data = await res.json() - if (data?.detail) detail = String(data.detail) - } catch { /* non-JSON body */ } - return { ok: false, status: res.status, detail } -} - -export async function checkUserConfigExists( - name: string, -): Promise<{ exists: boolean; namespace: 'shipped' | 'user' | null }> { - const entries = await listConfigs() - const match = entries.find( - e => e.name === `${name}.yaml` || e.name === `${name}.yml`, - ) - if (!match) return { exists: false, namespace: null } - return { exists: true, namespace: match.namespace } -} - -export async function runJV(device: DeviceConfig, params: JVParams): Promise { - const res = await fetch(`${BASE}/api/jv`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ device, ...params }), - }) - return handle(res) -} - -export async function runImpedance(device: DeviceConfig, params: ISParams): Promise { - const res = await fetch(`${BASE}/api/impedance`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ device, ...params }), - }) - return handle(res) -} - -export async function runDegradation(device: DeviceConfig, params: DegParams): Promise { - const res = await fetch(`${BASE}/api/degradation`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ device, ...params }), - }) - return handle(res) -} - -export async function runTandem( - configPath: string, - N_grid = 40, - n_points = 15, -): Promise { - const res = await fetch(`${BASE}/api/tandem`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ config_path: configPath, N_grid, n_points }), - }) - if (!res.ok) { - throw new Error(`tandem run failed: ${res.status} ${await res.text()}`) - } - return res.json() as Promise -} diff --git a/web/src/job-stream.ts b/web/src/job-stream.ts deleted file mode 100644 index e1156e26..00000000 --- a/web/src/job-stream.ts +++ /dev/null @@ -1,58 +0,0 @@ -import type { DispatchableJobKind, JobStartResponse, JobStreamHandlers, ProgressEvent } from './types' -import { BASE } from './api' - -export async function startJob( - kind: DispatchableJobKind, - device: unknown, - params: Record, - configPath: string | null = null, -): Promise { - const resp = await fetch(`${BASE}/api/jobs`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ kind, device, params, config_path: configPath }), - }) - if (!resp.ok) { - throw new Error(`POST /api/jobs failed: ${resp.status} ${resp.statusText}`) - } - const body = (await resp.json()) as JobStartResponse - return body.job_id -} - -export function streamJobEvents( - jobId: string, - handlers: JobStreamHandlers, -): () => void { - const source = new EventSource(`${BASE}/api/jobs/${jobId}/events`) - source.addEventListener('progress', (e: MessageEvent) => { - try { - handlers.onProgress(JSON.parse(e.data) as ProgressEvent) - } catch (err) { - console.error('failed to parse progress event', err) - } - }) - source.addEventListener('result', (e: MessageEvent) => { - try { - handlers.onResult(JSON.parse(e.data) as TResult) - } catch (err) { - handlers.onError(`failed to parse result: ${String(err)}`) - } - }) - source.addEventListener('error', (e: MessageEvent) => { - // Native EventSource 'error' fires on connection close with no data — - // only surface as a user error when the server sent an SSE `event: error` - // frame (which carries JSON). - if (!e.data) return - try { - const payload = JSON.parse(e.data) as { message?: string } - handlers.onError(payload.message ?? 'stream error') - } catch { - handlers.onError('stream error') - } - }) - source.addEventListener('done', () => { - handlers.onDone() - source.close() - }) - return () => source.close() -} diff --git a/web/tests/ion-flow.html b/web/tests/ion-flow.html index fd12bd54..8274974a 100644 --- a/web/tests/ion-flow.html +++ b/web/tests/ion-flow.html @@ -18,7 +18,7 @@