How the solver works and how to change equations#

Changing soil, climate or rock inputs usually only requires editing the example notebook. To change a chemical relationship, start in src/smew/equations.py.

How each timestep is solved#

SMEW updates the stored amounts of water and chemical species from their fluxes, then solves the coupled chemical-equilibrium equations. It starts from an estimate based on the previous state and adjusts concentrations and exchange fractions until the equations are satisfied closely enough.

Mathematically, it seeks \(F(x; q)=0\), where \(x\) contains the unknowns and \(q\) the fixed parameters and inventories. Each component of \(F\) is a residual: the mismatch in one balance or equilibrium relationship. In the code, p holds the trial unknowns \(x\), and out holds their residuals.

Python mode uses SciPy’s fsolve; compiled mode uses cminpack’s hybrd. Both use a modified Powell hybrid method, estimate derivatives numerically, and share the equations in equations.py.

Convergence and accuracy#

Solver convergence means the numerical stopping criterion was met; it does not establish physical accuracy. Check the equation residuals, mass balances and sensitivity to the timestep dt.

Note

The main chemistry solve uses xtol=1e-12 as a stopping tolerance for relative changes between successive estimates. A residual above 0.1 in absolute value triggers a retry with a different hydrogen estimate and xtol=1e-14; residuals still above 0.1 cause CHEMISTRY_NO_CONVERGENCE. Residuals use the model’s scaled units, so rescaling an equation changes this check. These tolerances do not set the time resolution.

Trial concentrations are not constrained to be positive, so an intermediate estimate can make an equation undefined. See When a simulation fails for troubleshooting.

Find the equation to change#

Edit the residual functions in src/smew/equations.py. For example, this line calculate the 8th residual:

out[7] = Ca*nZrs1000 + f_Ca/2*CEC_tot - Ca_tot

Check your change#

Use an editable installation and start in Python mode.

  1. Edit the residual in src/smew/equations.py and, where possible, evaluate it at a known solution to check signs, units and variable order.

  2. Restart the notebook kernel and rerun a familiar scenario with the same weather inputs. Compare mass balances, concentrations and exchange fractions.

  3. Before rebuilding, declare any new intermediate variables in equations.pxd as needed for compilation. New parameters or unknowns require the additional changes in Solver implementation reference.

  4. Rebuild the C extensions, then restart in compiled mode and compare with the Python results, allowing for small rounding differences:

    # Rebuild after changing the equations.
    spin install-native
    

See Installation and builds for setup instructions. Run spin test to check the existing scenarios without replacing their reference results.