Preprint
Article

This version is not peer-reviewed.

Structure-Preserving Neural Compilation of a Conceptual Hydrological Model: Bidirectional Translation Between a White-Box Xinanjiang Program and a Trainable Neural Network

Submitted:

28 November 2026

Posted:

30 November 2026

You are already at the latest version

Abstract
Conceptual hydrological models and deep learning models are frequently framed as contrasting and complementary paradigms. The former are transparent and physically interpretable but constrained by prior functional assumptions, whereas the latter are expressive but often lack physical constraints and interpretability. Taking the three-source Xinanjiang (XAJ) model as a case study, this paper develops and validates a structure-compilation route in which each operation of a white-box computational program is systematically rewritten as a computational-graph node composed of affine transformations and element-wise activations. The resulting model is a recurrent neural network (RNN) whose weights are manually specified and whose outputs are bitwise equivalent to the original program at floating-point machine precision. Four general conversion rules are proposed: (i) min/max operations as ReLU combinations; (ii) power-law curves as Pow activations; (iii) conditional branches through closed-form elimination or hard-threshold activation with value-range selection; and (iv) temporal recursion as a weight-shared RNN. The XAJ model is compiled into a network cell containing 93 nodes and 117 weighted edges (63 affine nodes, 25 ReLU nodes, one Step node, and four power activations). In a 1400-day synthetic catchment experiment, the maximum output deviation between the compiled network and the classical if/else implementation is 2.84 × 10-13 m3/s, and the cross-computed NSE is 1.000000000000000. Furthermore, a total of 11 physical parameters are unfrozen as trainable weights through log/sigmoid transformations and calibrated by Limited-memory Broyden-Fletcher-Goldfarb-Shanno with Boundary algorithm against observations containing 7% multiplicative noise. After 150 iterations, the validation-period NSE increased from 0.510 to 0.991 (calibration period: 0.598 to 0.994), essentially reaching the theoretical noise ceiling of approximately 0.995 implied by the 7% multiplicative observation noise. Five of the 11 parameters (the evapotranspiration coefficient K, the tension-water capacity WM, the curve exponent B, the free-water capacity SM and the groundwater recession constant CG) were recovered within 5%, whereas the routing and evapotranspiration parameters deviate by 5-27% owing to parameter equifinality. Nevertheless, the trained weights can be written back directly into the hand-wired network. These results indicate that the same architecture behaves as a deterministic hydrological model when weights are frozen and as a gradient-trainable neural network when weights are unfrozen. The approach is further compared with purely black-box deep learning, traditional white-box modelling, physics-informed neural networks (PINNs) in terms of inductive bias, data efficiency, interpretability, differentiability, and engineering feasibility. Potential applications in coupled data assimilation, parameter regionalization, large-sample parallel forecasting, and physics-data hybrid modelling are discussed.
Keywords: 
;  ;  ;  

1. Introduction

1.1. Two Hydrological Forecasting Paradigms

Catchment hydrological forecasting has largely developed along two routes. The process-based route builds deterministic models from physical or conceptual descriptions of evapotranspiration, runoff generation, and routing. Representative examples include the Stanford model, the Xinanjiang model (Zhao, 1984; Zhao, 1992), SWAT, and VIC. Such models are structurally transparent, can explicitly preserve water balance, contain physically meaningful parameters, and can be transferred to ungauged basins. However, their expressive capacity is limited by prescribed functional forms, and they often struggle to represent nonlinear spatiotemporal heterogeneity in complex underlying surfaces. The data-driven route, represented by long short-term memory (LSTM) networks, learns mappings directly from meteorological forcing to streamflow observations. Large-sample studies have shown that LSTMs can match or even outperform manually calibrated conceptual models (Kratzert et al., 2018, 2019), and they have demonstrated advantages in global-scale extreme-flood prediction for ungauged basins (Nearing et al., 2024). Nevertheless, black-box models suffer from data hunger, lack guaranteed physical consistency, and show weak out-of-distribution generalization and interpretability (Reichstein et al., 2019).

1.2. Hybrid Modelling and Differentiable Programming

Efforts to bridge these two routes have produced the physics-informed machine learning (PIML) spectrum (Karniadakis et al., 2021). This spectrum ranges from physics-informed neural networks (PINNs), which embed physical residuals in the loss function, to hybrid architectures that replace specific model components with neural networks, and further to differentiable programming approaches that use automatic differentiation to make process models end-to-end differentiable, e.g., universal differential equations (UDEs, Rackauckas et al., 2020), and differentiable parameter learning (DPL; Feng et al., 2022). The value of differentiable programming lies in enabling white-box structures and black-box learning to be optimized jointly within a single gradient system, thereby combining physical constraints with data-driven expressiveness.

1.3. “Program-As-Network” Structure Compilation

Recently, the open-source project Handwired (Lou, 2026) introduced an alternative formulation, suggesting any deterministic program with bounded value ranges can be rewritten as a neural network composed only of matrix multiplications and element-wise activations, with manually hard-coded weights, and can be bitwise equivalent to the original program; in this sense, a program can be regarded as a special case of a neural network. A systematic implementation of this idea for a complete hydrological model has not yet been reported. If a mature conceptual hydrological model can be compiled as a whole into a neural network, three benefits follow: (i) it demonstrates that a white-box model is a member of the neural-network family fully determined by physical priors, providing a rigorous conceptual basis for unified physics-data modelling; (ii) the compiled artefact is naturally differentiable and can serve as a trainable component in deep-learning frameworks; and (iii) network weights are physical parameters, so interpretability, transferability, and auditability are fully preserved.

1.4. Contributions

Using the three-source Xinanjiang model as an example, this paper makes the following contributions: (1) a classical if/else reference implementation is established, with simplified routing comprising linear reservoirs and river-network storage recession; (2) four general conversion rules are proposed to compile the entire model into a manually wired RNN, and machine-precision equivalence is verified; (3) physical parameters are unfrozen as trainable weights, calibrated by gradient methods, and examined for parameter recovery and weight write-back consistency; (4) the proposed method is systematically compared with purely black-box deep learning, traditional white-box modelling, PINNs, and symbolic regression/symbolic neural networks; and (5) application prospects in coupled hydrological models, large-sample basin forecasting, and physics-data hybrid modelling are discussed. All source code is released with this paper.

2. Methods

2.1. Reference Model

The three-source Xinanjiang model (Zhao, 1992) is adopted. It includes three-layer evapotranspiration from the upper, lower and deep tension-water storages (WU, WL, WD), whose capacities are WUM, WLM and WDM (the tension-water capacity of the whole soil column is WM = WUM + WLM + WDM); runoff generation from a tension-water storage-capacity curve controlled by the storage capacity WM and the curve exponent B; separation of surface runoff, interflow and groundwater through a free-water storage-capacity curve controlled by the free-water capacity SM and the exponent EX; and routing through linear reservoirs and river-network storage recession described by the interflow and groundwater outflow coefficients KI and KG, the linear-reservoir recession coefficients CI and CG, and the channel-storage recession coefficient CS. The remaining two coefficients are the evapotranspiration conversion coefficient K, which scales pan evaporation into potential evapotranspiration, and the deep-layer evapotranspiration coefficient C, which limits the evapotranspiration demand that the deep layer can satisfy. There are 11 calibrated parameters: K, WM, B, C, SM, EX, KI, KG, CI, CG, and CS. Three common simplifications are used: evapotranspiration follows the EL=C(E−EU) remaining-demand version; runoff-source separation adopts a closed-form solution (when R=0, the formula degenerates to an identity, eliminating one branch); and the conversion between the runoff-generating area fraction FR and the whole catchment is neglected. The model state vector x=(WU,WL,WD,S,QI,QG,Q) collects the three tension-water storages, the free-water storage S, and the interflow, groundwater and channel storages QI, QG and Q; the input u=(P,EM) is daily rainfall P and pan evaporation EM, and the output q (m³/s) is the simulated discharge.

2.2. Conversion Rules

Rule 1 (extrema and truncation). Truncation is expressed as a composition of min/max operations. Any piecewise-linear function can be represented exactly by a finite affine combination of ReLUs.
min a , b = b − Re LU b − a
max a , b = a + ReLU b − a
Rule 2 (power-law curves). The storage-capacity and free-water capacity curves contain (1−x)γ for x∈[0,1]. A custom Pow γ activation is introduced. Like softmax, it is a smooth activation that is not piecewise linear and does not break the computational-graph form.
Rule 3 (conditional branches). (a) Closed-form elimination is preferred: the runoff-source branch if R>0 disappears after closed-form reformulation. (b) Hard-threshold selection is used where the runoff-generation/evapotranspiration branch if PE≥0 has different state structures on the two sides and cannot be eliminated in closed form. A hard-threshold activation s = Step(PE) is introduced, and exact multiplicative gating is implemented through a value-range selection trick: for a nonnegative variable x and a 0/1 gate s:
s ⋅ x = x − ReLU x − BIG ⋅ s
where BIG is a constant far above the upper bound of the value range (taken as 10⁹ in this paper).
The two state branches are linearly fused as:
X ' = neg + s ⋅ pos − neg
where the positive and negative parts of (pos−neg) are each gated by value-range operations. This trick requires prior knowledge of intermediate value ranges, which also explains why Handwired requires explicit value-range declarations.
Rule 4 (temporal recursion). The state update xt+1=F(xt;ut,θ) is compiled as an RNN cell with weights shared across all time steps; unfolding over T steps yields a weight-shared network of depth T. The routing components (recessions of QI, QG, and Q) are already affine recursions and become recurrent edges of the network.

2.3. Compiled Structure

A single time-step cell contains 93 nodes and 117 weighted edges, composed of 63 affine nodes, 25 ReLUs, one Step, and four Pow activations. All 117 weights are deterministic functions of the 11 physical parameters (and constants such as WM and SM), with zero training. The entire model is an RNN with seven hidden-state units, and the readout layer is a single affine transformation.

2.4. Weight Unfreezing and Gradient Training

The 11 physical parameters are exposed as unconstrained trainable weights θ through log transformations (positive parameters) or sigmoid transformations (parameters in (0,1)). The constraint KI+KG≤0.9 is automatically satisfied by parameterization. The Limited-memory Broyden-Fletcher-Goldfarb-Shanno with Boundary (L-BFGS-B) algorithm is used to minimize the calibration-period mean squared error, with gradients approximated by two-point finite differences; the 60-day warm-up period is excluded from the loss. The observation series is generated by adding 7% multiplicative noise to the reference-model output.

3. Results

3.1. Numerical Equivalence

The synthetic experiment is generated from a fixed random seed (42) so that every run is exactly reproducible. Rain occurs on 30% of the days; rain depths are drawn from an exponential distribution with a mean of 12 mm and truncated at 120 mm, giving a mean rainfall of 3.80 mm/d over the 1400 days. Potential evaporation follows a seasonal sine curve between 1.2 and 3.8 mm/d. The basin area is 1000 km2 and the time step is 24 h. The model starts from WU = 4.5 mm, WL = 32.5 mm, WD = 28.0 mm, S = 1.5 mm and zero routing storages. The 11 free parameters and the three derived tension-water capacities are listed in Table 1; the classical implementation and the compiled network use exactly the same values, because the network weights are the parameters themselves.
A synthetic catchment provides 1400 days of daily data (mean rainfall 3.80 mm/d, mean streamflow 20.23 m³/s, peak 268.9 m³/s). The classical implementation and the compiled network are compared as Table 2.
Figure 1 summarises the experiment. Panel (a) shows the rainfall hyetograph and the potential-evaporation curve that drive both implementations. Panel (b) overlays the two simulated hydrographs: the compiled network (dashed) lies on top of the classical result (solid) at the resolution of the plot, including the recession limbs and the eight local peaks above 150 m³/s. Panel (c) plots the absolute daily deviation on a logarithmic scale; it fluctuates between 10⁻17 and 10⁻12 m³/s without any temporal trend, so the difference neither grows along the recursion nor concentrates on particular flow regimes.
The deviation originates entirely from differences in floating-point summation order: the compiled network computes both branches and selects through gating, whereas the classical implementation uses single-side short-circuit summation. The difference is at machine precision and is not a structural error.

3.2. Water Balance

Water balance was checked for all storages (three tension-water layers, free water, three routing linear reservoirs, and river-network storage). The residual is 31.8 mm, accounting for 0.6% of rainfall. This residual stems from the simplified treatment of the saturated-area fraction (FR) in the reference formulation; it is inherited from the conceptual model itself, i.e., the compilation adds no extra mass loss.

3.3. Unfrozen Training and Parameter Recovery

The 1400 days are split chronologically: the first 700 days form the calibration period and the remaining 700 days the validation period, with the first 60 days discarded as warm-up to remove the influence of the initial state. Synthetic observations are obtained by perturbing the reference simulation with 7% multiplicative Gaussian noise, q_obs = q_ref (1 + ε), ε ~ N(0, 0.07²). For any model that reproduces q_ref exactly, this noise defines the highest attainable NSE, 1 − σ²/(1 + σ²) ≈ 0.995, which is therefore used as the theoretical ceiling in Table 3.
Initial weights were deliberately set to parameters deviating from the true values by -7% to 120% (calibration NSE 0.598, validation NSE 0.510). Table 3 shows the performances after L-BFGS-B training for 150 iterations (0.9 s). Figure 2 compares the observed and simulated streamflow over the calibration and validation periods.
The recovery errors of the 11 parameters were WM 0.04%, CG 0.07%, K 0.21%, SM 3.2%, B 3.5%, CI 5.3%, CS 8.2%, KG 13.0%, KI 20.2%, C 24.6% and EX 27.4%. The larger errors of KI/KG, C and EX arise from the well-known equifinality of routing (KI, KG, CS) and evapotranspiration (K, EX, C) parameters, where compensating errors leave the simulated hydrograph almost unchanged. The trained weights were written back directly into the hand-wired network, with a maximum output difference of 7.4×10⁻13 m3/s. Hence the same architecture is a hydrological model when frozen and a neural network when unfrozen.

3.4. Computational Cost

All timings below were measured on a single CPU core (Python 3.6, NumPy 1.14, Numba 0.38) without GPU acceleration. The reference implementation evaluates the 1400-day series in about 2 ms (≈1.4 μs per daily step). The hand-wired network needs about 0.12 s for the same series, i.e. roughly 60 times longer, because every arithmetic operation is an explicit node of the computational graph (93 nodes and 117 edges per step) instead of a compiled loop. With the forward model compiled by Numba, a complete L-BFGS-B calibration (150 iterations, 2,040 function evaluations, 11 trainable weights) takes 0.9 s, so training remains inexpensive despite the overhead of the graph formulation. Since the compiled model is a plain sequence of affine and element-wise operations, it can in principle be migrated to PyTorch or JAX to exploit GPU batch parallelism and automatic differentiation; the present implementation deliberately stays in pure NumPy so that equivalence with the original program can be verified operation by operation.

4. Discussion: Comparison with Other Methods

4.1. Pure Black-Box Deep Learning (e.g., LSTM)

Similarity: both are trainable recurrent networks in form. The compiled model can even be regarded as a network with an extremely strong hyper-structural prior and with weights initialized at physical parameters.
The essential difference lies in weight provenance and generalization mechanism. The inductive bias of an LSTM comes only from the data distribution and the recurrent structure, and its generalization relies on large samples (Kratzert et al., 2019). The inductive bias of the compiled network comes from the functional forms of four decades of hydrological knowledge; its “pre-training” is performed by human physical modelling, so stable behaviour can be obtained in small-sample catchments and can be audited through the physical meaning of parameters. Conversely, an LSTM can learn processes outside the function space of the compiled model and thus has a higher expressive ceiling. The two are not competitors but complementary ends of a spectrum: the compiled network is the prior-extreme end, the LSTM is the data-extreme end, and the intermediate zone is occupied by hybrid models.
Gradient properties differ as well. The compiled network contains one hard-threshold Step and several value-range selection gates, where gradients are zero or undefined. Training experiments nevertheless show that these non-differentiable points have measure zero and that parameter complementarity provides bypass paths, so L-BFGS converges well. Pure ReLU networks also contain measure-zero non-differentiable points, with limited practical impact.

4.2. Traditional White-Box Methods

The compiled network is bitwise equivalent to the traditional Xinanjiang model and therefore offers no gain in “forecasting” per se. This is a key point that needs to be clarified for practitioners: the value of the method lies not in accuracy but in engineering form.
(a) Differentiability. Traditional models typically rely on derivative-free calibration methods, such as shooting methods or SCE-UA (Duan et al., 1992), which often require thousands to tens of thousands of function evaluations. In compiled/differentiable form, the model can be differentiated directly; this paper reaches the noise ceiling with 2,040 function evaluations (150 iterations), whereas derivative-free methods typically require one to two orders of magnitude more evaluations for the same problem.
(b) Framework interoperability. The model becomes an ordinary module in a deep-learning framework and can be freely concatenated with LSTM residual networks, attention gates, and other components for end-to-end joint training.
(c) Gradients for non-calibration tasks. Beyond parameter calibration, gradients also support sensitivity analysis, uncertainty propagation (e.g., through linearization or Laplace approximation), and variational/gradient-based data assimilation (4DVar-type); all of these can be performed using the same automatic-differentiation infrastructure.

4.3. Physics-Informed Neural Networks (PINNs)

PINNs embed physical equations as soft constraints in the loss (Karniadakis et al., 2021), and the trained network “approximately satisfies” the equations. The present method embeds physical equations as hard structure in the computational graph, and the network “exactly equals” the model. Consequences of this difference are as follows.
(a) Constraint satisfaction. PINNs rely on collocation sampling and penalty weights and can suffer from constraint conflicts and training instability; the compiled model unconditionally satisfies mass conservation and all process equations.
(b) Expressive freedom. A PINN can approximate arbitrary solutions between collocation points (including PDEs without analytical solutions); the compiled model can only express the original model family (the solution family on the parameter manifold). In other words, PINNs suit problems where “the equation is known but the solution is unknown,” whereas compilation suits problems where “the model is known but parameters and couplings are unknown.”
(c) Interpretability. PINN weights have no direct physical meaning; compiled weights are physical parameters.
(d) Nesting. The two can be nested: using the compiled model as a backbone and a PINN-style residual network to learn process terms not covered by the model, thereby combining hard-constraint structure with soft-constraint expressiveness.

4.4. Relation to Knowledge-Guided and Hybrid Modelling

The proposed method essentially provides a low-level interface specification for the hybrid-modelling spectrum: any white-box component in a hybrid architecture (residual learning, parameter prediction, process replacement) can and should exist as a differentiable computational graph. Compared with differentiable-programming routes such as DPL (Feng et al., 2022) and UDE (Rackauckas et al., 2020), the additional contribution here is an explicit wiring consisting solely of affine transformations and element-wise activations. It does not depend on how autograd handles if/else (many frameworks have gaps between their backpropagation rules and numerical semantics for branches). After wiring, the equivalence between the network and the original program is provable and machine-verifiable.

4.6. Limitations

1. Simplified routing. Muskingum channel routing is not included (piecewise-constant/linear structures remain compatible with the conversion rules, but the node count would increase).
2. Hard-threshold activation. Step cannot be represented exactly by a pure ReLU network (due to the continuity limitation of ReLU networks); this is an inherent boundary of the Handwired route. Fortunately, such activations occur rarely (one in this paper) and have measure zero.
3. Value-range dependence. The value-range selection trick requires prior knowledge of upper bounds (the choice of BIG), and margins are needed for extreme events.
4. Fixed structure. The expressive capacity of the compiled network is limited by the prior of the original model and cannot spontaneously learn processes outside the model.
5. Synthetic-data experiments. Training behaviour under real-world observation-error structures and input uncertainty remains to be tested.

5. Outlook: Towards Large-Scale Catchment Hydrological Forecasting

5.1. Large-Sample Parallelism and Regionalization

The compiled model is a fully vectorized computational graph and is therefore naturally compatible with JAX’s vmap/pmap or PyTorch batch dimensions. The same network can forward the parameter sets of N catchments in batch, potentially simulating thousands of catchments simultaneously on a single GPU. This transforms the large-sample regionalization problem of “one set of physical parameters per catchment” (i.e., regressing parameters on catchment attributes) into a standard multi-task learning problem: catchment attributes are mapped by a small network to the weights of the compiled model (a parameter predictor), and streamflows from all catchments are used for joint training. This combines the data scale of large-sample LSTM studies in the spirit of Kratzert et al. (2019) with structural priors, and may yield reliability superior to that of purely data-driven models in small ungauged catchments.

5.2. Joint Architectures with Deep Components

Typical architectures include: (i) residual learning, q=q_physical(θ(u)) + LSTM_residual(u,attributes); (ii) time-varying parameters, θ_t=g_θ(attributes, season, antecedent states), where a small network dynamically supplies the physical-model weights to characterize human activities and climate non-stationarity; and (iii) input correction, where precipitation/evapotranspiration are corrected by a deep network before driving the compiled model. In all three, the white-box part retains mass conservation and an interpretable skeleton.

5.3. Data Assimilation and Real-Time Forecasting

Differentiability enables gradient-based assimilation (4DVar, variational methods) and differentiable particle filters to act directly on model states. A future direction is a fully differentiable model chain coupling land surface, hydrology, and river dynamics, achieving an integrated gradient system for “forecast-correction-uncertainty quantification.”

5.4. Interpretability Guaranteed by Construction

The weights of the compiled network are physical parameters. Global sensitivity analysis (Sobol), parameter uncertainty (Bayesian posteriors, differentiable likelihood), and model auditing can be performed on the same graph, providing white-box-level transparency for operational forecasting trust and explainable AI (XAI) requirements. This is a “guaranteed-by-construction” interpretability that no post-hoc explanation method (SHAP/attention maps) can match.

5.5. Engineering Roadmap

For existing operational systems (often Fortran/C/VB single-catchment programs), migration is suggested in three steps: (1) rewrite the core computation as a differentiable implementation using the rules in this paper (framework-independent; numerical equivalence can be verified first); (2) connect to the observation system for gradient calibration, replacing derivative-free calibration; and (3) gradually introduce deep components and multi-catchment batching. The first step alone can deliver training-efficiency and framework-interoperability benefits.

6. Conclusions

This paper compiles the three-source Xinanjiang hydrological model into a 93-node recurrent neural network composed only of affine transformations and ReLU/Step/Pow activations, with all weights manually specified by 11 physical parameters. Numerical experiments show that the compiled network is bitwise equivalent to the original program at floating-point machine precision (max|Δq| ≈ 2.84 × 10-13 m3/s). After unfreezing the physical parameters as trainable weights, gradient calibration drives the validation-period NSE to the theoretical noise ceiling; five of the 11 parameters were recovered within 5%, while the routing and evapotranspiration parameters deviate by 5–27%, and weights can travel losslessly between the network and model identities. The core methodological conclusions are:
1. A conceptual hydrological model is a member of the neural-network family fully determined by physical priors; “white-box” and “black-box” are two ends of a spectrum distinguished by whether weights are frozen, not a methodological divide.
2. Structure compilation endows traditional models with differentiability and framework interoperability without sacrificing any numerical behaviour.
3. This approach forms a complementary spectrum alongside PINNs, symbolic regression, and black-box deep learning, ranging from hard structural constraints and soft physical constraints to structural induction and structural freedom. Therefore, their combined use is preferable to mutual replacement.
For large-scale catchment forecasting, differentiability is the infrastructure that allows physical models to enter the modern machine-learning ecosystem and participate in large-sample regionalization and end-to-end hybrid modelling. The engineering benefits are immediately available, while the scientific ceiling depends on hybrid-architecture design, a direction worthy of joint investment by the hydrological and machine-learning communities.

Data and code availability

All source code is released as a single self-contained Python script (xaj_neural_network_dump.py, 591 lines, requiring only NumPy, SciPy, Numba and Matplotlib). It contains the classical reference implementation, the hand-wired network, the equivalence test, the unfrozen gradient training and the plotting routines, and therefore regenerates every figure and table of this paper in a single run. The synthetic forcing is generated with a fixed NumPy seed (42, MT19937), so repeated runs are bitwise reproducible.

Appendix A. Quick-Reference Table of Conversion Rules

Table A1. Quick-reference of the original program constructs, their equivalent network forms, and corresponding applications in the Xinanjiang model.
Table A1. Quick-reference of the original program constructs, their equivalent network forms, and corresponding applications in the Xinanjiang model.
Original program construct Equivalent network form Use in the Xinanjiang model
min(a,b) b − ReLU(b−a) min(WL, C·rem), min(AU+R, SMM), etc.
max(a,b) a + ReLU(b−a) max(0, 1−W/WM), etc.
Truncation to [0,c] x + ReLU(−x) − ReLU(x−c) WU/WL/WD state updates
(1−x)γ, x∈[0,1] Pow γ activation Storage-capacity curve (2 Pow nodes), free-water capacity curve (2 Pow nodes)
if R>0 (eliminable branch) Closed form: formula degenerates to identity when R=0 Runoff-source separation
if PE≥0 (structural branch) s=Step(PE);
s·x = x−ReLU(x−BIG·s); X’=neg+s·(pos−neg)
Runoff-generation/evapotranspiration path switching
State recursion xt+1=F(xt,ut) RNN cell with weights shared across time steps Whole model (7 hidden units)
Linear reservoir/recession Pure affine recursion (recurrent edge) QI, QG, Q

Appendix B. Structural Statistics of the Compiled Network Cell

Table B1. Summary of the structural components and their counts within the compiled network cell.
Table B1. Summary of the structural components and their counts within the compiled network cell.
Component Count
Inputs 2 (P, EM) + 7 hidden states (WU, WL, WD, S, QI, QG, Q)
Total nodes 93
Affine nodes 63
ReLU 25
Step 1
Pow γ 4 (γ = 1/(1+B), 1+B,1/(1+EX),1+EX)
Weighted edges 117
Trainable weights (after unfreezing) 11 (parameterized by log/sigmoid)
Readout layer 1 affine transformation (×F/(3.6Δt))

Appendix C. Experimental Record

All numerical results in this paper were obtained from sandbox-executable experiments (28 November 2026). Repeated runs with the same seed reproduce the results exactly. Key intermediate products (data, figures, result JSON, runnable source code) are archived at a https://zenodo.org/records/24621114.

References

  1. Duan, Q.; Sorooshian, S.; Gupta, V. K. Effective and efficient global optimization for conceptual rainfall-runoff models. Water Resour. Res. 1992, 28(4), 1015–1031. [Google Scholar] [CrossRef]
  2. Feng, D.; Liu, J.; Lawson, K.; et al. Differentiable, Learnable, Regionalized Process-Based Models With Multiphysical Outputs can Approach State-Of-The-Art Hydrologic Prediction Accuracy. Water Resour. Res. 2022, 58, e2022WR032404. [Google Scholar] [CrossRef]
  3. Karniadakis, G. E.; Kevrekidis, I. G.; Lu, L.; et al. Physics-informed machine learning. Nat. Rev. Phys. 2021, 3(6), 422–440. [Google Scholar] [CrossRef]
  4. Kratzert, F.; Klotz, D.; Brenner, C.; et al. Rainfall–runoff modelling using Long Short-Term Memory (LSTM) networks. Hydrol. Earth Syst. Sci. 2018, 22(11), 6005–6022. [Google Scholar] [CrossRef]
  5. Kratzert, F.; Klotz, D.; Shalev, G.; et al. Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets. Hydrol. Earth Syst. Sci. 2019, 23(12), 5089–5110. [Google Scholar] [CrossRef]
  6. Lou, C. Handwired: Turn your regular JavaScript code into a neural net [Computer software]. GitHub. 2026. Available online: https://github.com/chenglou/handwired.
  7. Nearing, G.; Cohen, D.; Dube, V.; et al. Global prediction of extreme floods in ungauged watersheds. Nature 2024, 627, 559–563. [Google Scholar] [CrossRef] [PubMed]
  8. Rackauckas, C.; Ma, Y.; Martensen, J.; et al. Universal differential equations for scientific machine learning. arXiv 2020, arXiv:2001.04385. [Google Scholar]
  9. Reichstein, M.; Camps-Valls, G.; Stevens, B.; et al. Deep learning and process understanding for data-driven Earth system science. Nature 2019, 566, 195–204. [Google Scholar] [CrossRef] [PubMed]
  10. Zhao, R. J. Catchment Hydrological Simulation; (in Chinese). Water Resources and Electric Power Press: Beijing, 1984. [Google Scholar]
  11. Zhao, R. J. The Xinanjiang model applied in China. J. Hydrol. 1992, 135(1-4), 371–381. [Google Scholar] [CrossRef]
Figure 1. (a) Synthetic rainfall (vertical bars) and potential evaporation (dashed line); (b) daily discharge simulated by the classical implementation (solid) and by the compiled network (dashed); (c) absolute daily deviation between the two implementations on a logarithmic scale.
Figure 1. (a) Synthetic rainfall (vertical bars) and potential evaporation (dashed line); (b) daily discharge simulated by the classical implementation (solid) and by the compiled network (dashed); (c) absolute daily deviation between the two implementations on a logarithmic scale.
Preprints 246947 g001
Figure 2. (a) Observed and calibrated hydrographs for the calibration and validation periods, with the 60-day warm-up shaded; (b) observed versus simulated discharge (open circles: calibration; filled circles: validation) with the 1:1 line.
Figure 2. (a) Observed and calibrated hydrographs for the calibration and validation periods, with the 60-day warm-up shaded; (b) observed versus simulated discharge (open circles: calibration; filled circles: validation) with the 1:1 line.
Preprints 246947 g002
Table 1. True parameter values of the synthetic catchment used by both implementations.
Table 1. True parameter values of the synthetic catchment used by both implementations.
Symbol Description Value
K Evaporation coefficient (−) 0.85
WUM Upper-layer tension-water capacity (mm) 15
WLM Lower-layer tension-water capacity (mm) 65
WDM Deep-layer tension-water capacity (mm) 40
WM Total tension-water capacity, WUM+WLM+WDM (mm) 120
B Storage–area curve exponent (−) 0.35
C Deep-layer evaporation coefficient (−) 0.15
SM Free-water capacity (mm) 30
EX Free-water curve exponent (−) 1.5
KI Interflow outflow coefficient (−) 0.25
KG Groundwater outflow coefficient (−) 0.45
CI Interflow recession constant (−) 0.62
CG Groundwater recession constant (−) 0.965
CS River-network recession constant (−) 0.25
Table 2. Equivalence metrics between the classical implementation and the compiled network.
Table 2. Equivalence metrics between the classical implementation and the compiled network.
Metric Value
Maximum absolute deviation max|Δq| 2.84×10⁻13 m³/s
Deviation relative to peak 1.06×10⁻15
Cross-computed NSE 1.000000000000000
Table 3. Training performance before and after unfreezing.
Table 3. Training performance before and after unfreezing.
Metric Calibration period Validation period
NSE before training 0.598 0.510
NSE after training 0.994 0.991
Theoretical noise ceiling — 0.995
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.