Source code for smew.errors

# SPDX-License-Identifier: AGPL-3.0-only
"""Model error codes and Python exceptions.

Compiled entry points return (result, error_code, error_message).
Never renumber or reuse a published code. Raise only at the Python boundary.
"""

from enum import IntEnum, unique

import numpy as np
from numba.extending import register_jitable


[docs] @unique class ErrorCode(IntEnum): OK = 0 # Nonlinear solves: 1000-1099. WATER_ALK_RESIDUAL = 1001 WATER_ALK_SOLVER_INPUT = 1002 CHEMISTRY_RESIDUAL = 1011 CHEMISTRY_SOLVER_INPUT = 1012 CHEMISTRY_RETRY_RESIDUAL = 1021 CHEMISTRY_RETRY_SOLVER_INPUT = 1022 CHEMISTRY_NO_CONVERGENCE = 1023 # Biogeochemistry inputs and initial conditions: 1100-1199. BIOGEOCHEM_INSUFFICIENT_CATIONS = 1101 BIOGEOCHEM_MISSING_PORES = 1102 # Organic carbon: 2000-2999. RESPIRATION_INITIAL_ACTIVITY = 2001 RESPIRATION_MEAN_ACTIVITY = 2002 # Initial condition solvers: 3000-3999. CEC_RESIDUAL = 3001 CEC_SOLVER_INPUT = 3002 TOTAL_CEC_RESIDUAL = 3011 TOTAL_CEC_SOLVER_INPUT = 3012 F_CEC_ALK_TO_CONC_RESIDUAL = 3021 F_CEC_ALK_TO_CONC_SOLVER_INPUT = 3022 WEATHERING_ERROR = 4001 # Vegetation: 5000-5999. VEGETATION_CAPACITY = 5001 VEGETATION_INITIAL_FRACTION = 5002 VEGETATION_STAGE = 5003 VEGETATION_STAGE_ORDER = 5004 VEGETATION_GROWTH = 5005
@register_jitable def _float_text(value): """Format debug floats to about eight significant digits in nopython mode. Numba cannot format floats with str/f-strings. Scaling a decade at a time also handles subnormal values without overflowing powers of ten. """ if np.isnan(value): return "nan" negative = np.signbit(value) sign = "-" if negative else "" if np.isinf(value): return sign + "inf" if value == 0: return sign + "0" magnitude = abs(float(value)) exponent = 0 while magnitude >= 10.0: magnitude /= 10.0 exponent += 1 while magnitude < 1.0: magnitude *= 10.0 exponent -= 1 rounded = int(round(magnitude * 10000000.0)) if rounded >= 100000000: rounded = 10000000 exponent += 1 digits = str(rounded).rstrip("0") if exponent < -4 or exponent >= 8: mantissa = digits[0] if len(digits) > 1: mantissa += "." + digits[1:] return sign + mantissa + "e" + ("+" if exponent >= 0 else "-") + str(abs(exponent)) point = exponent + 1 if point <= 0: return sign + "0." + "0" * (-point) + digits if point >= len(digits): return sign + digits + "0" * (point - len(digits)) return sign + digits[:point] + "." + digits[point:] @register_jitable def _series_diagnostic(name, values, dt): """Summarize a full forcing series on failure, without dumping its values.""" count = 0 first = -1 for index in range(values.size): if not np.isfinite(values[index]): count += 1 if first == -1: first = index text = name + ': mean=' + _float_text(np.mean(values)) text += ', nonfinite_count=' + str(count) if first != -1: text += ', first_nonfinite_step=' + str(first) text += ', first_nonfinite_time_days=' + _float_text(first * dt) text += ', first_nonfinite_value=' + _float_text(values[first]) return text @register_jitable def _solver_error(status, residual, residual_code, input_code, context): """Return a failure triple without reading unwritten solver buffers.""" code = residual_code if status == -1 else input_code reason = ("Residual evaluation failed (nonfinite values)" if status == -1 else "Native solver received invalid buffers or settings") message = reason + "; solver_status=" + str(status) if status == -1 or status > 0: norm = 0.0 for value in residual: if not np.isfinite(value): norm = np.nan break norm = max(norm, abs(value)) message += ", max_abs_residual=" + _float_text(norm) return None, code.value, message + "; " + context
[docs] class SMEWError(Exception): """Model failure with a globally unique code and a complete debug message.""" def __init__(self, code, message): self.code = ErrorCode(code) self.message = message super().__init__(f"[SMEW{int(self.code):04d} {self.code.name}] {message}") def __reduce__(self): # Preserve constructor arguments when Dask/pickle transports the error. return type(self), (self.code, self.message)
[docs] class SMEWValueError(SMEWError, ValueError): """Model input or convergence error; remains catchable as ValueError."""
[docs] class SMEWSolverError(SMEWError, RuntimeError): """Invalid solver residual; remains catchable as RuntimeError."""
[docs] def raise_for_error(code, message): """Raise a Python exception after the compiled calculation has returned.""" if code != ErrorCode.OK: exception = SMEWSolverError if code in ( ErrorCode.WATER_ALK_RESIDUAL, ErrorCode.CHEMISTRY_RESIDUAL, ErrorCode.CHEMISTRY_RETRY_RESIDUAL, ErrorCode.CEC_RESIDUAL, ErrorCode.TOTAL_CEC_RESIDUAL, ErrorCode.F_CEC_ALK_TO_CONC_RESIDUAL, ) else SMEWValueError raise exception(code, message)