# SPDX-License-Identifier: AGPL-3.0-only
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 14:34:44 2019
"""
import warnings
import numpy as np
from numba import njit
import smew
from smew._utils import _solve_system, _solver_work_size, _solver_njit
from smew._utils import CEC_CALCIUM_SYSTEM, F_CEC_ALK_TO_CONC_SYSTEM, TOTAL_TO_CEC_SYSTEM
from smew.errors import (
ErrorCode, _float_text, _solver_error, raise_for_error,
)
#------------------------------------------------------------------------------
# conc to CEC fractions
[docs]
def conc_to_f_CEC(conc_in,pH_in,soil,conv_mol,conv_Al):
"""Calculate CEC fractions with Python/SciPy or Numba/cminpack."""
# Ensure inputs are contiguous float64 arrays for Numba compilation and C double* compatibility.
result, error_code, error_message = _conc_to_f_CEC(np.ascontiguousarray(conc_in, dtype=np.float64), pH_in, soil, conv_mol, conv_Al)
raise_for_error(error_code, error_message)
if error_message:
warnings.warn(error_message, RuntimeWarning, stacklevel=2)
return result
@_solver_njit
def _conc_to_f_CEC(conc_in, pH_in, soil, conv_mol, conv_Al):
"""Return (results or None, error_code, error_message); conc_in has 5 values, soil is supported."""
#constants
K_CEC = smew.K_GT_CEC(soil,conv_mol) #CEC Gaines-Thomas
K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H = K_CEC
K1, K2, K3, K4 = smew.K_Al(conv_mol) #Al speciation
# cations (mol-conv/l)
Ca, Mg, K, Na, Al_w = conc_in
H = 10.0**(-pH_in) * conv_mol
# aluminium speciation
Al = (H**4 / (H**4 + H**3*K1 + H**2*K1*K2 + H*K1*K2*K3 + K1*K2*K3*K4))*Al_w #mol-conv/l
#CEC fractions
calcium_state = np.array((0.2,))
parameters = np.array((Al, conv_Al, Ca, Mg, Na, K, H, K_Ca_Al, K_Ca_Mg, K_Ca_Na, K_Ca_K, K_Ca_H))
residual = np.empty(calcium_state.size)
work = np.empty(_solver_work_size(calcium_state.size))
status = _solve_system(CEC_CALCIUM_SYSTEM, calcium_state, parameters, residual, work, 1.49012e-8)
if status <= 0:
return _solver_error(
status, residual, ErrorCode.CEC_RESIDUAL, ErrorCode.CEC_SOLVER_INPUT,
'ic.conc_to_f_CEC'
+ '; pH=' + _float_text(pH_in)
+ ', Ca=' + _float_text(Ca)
+ ', Al=' + _float_text(Al)
+ ', trial_f_Ca=' + _float_text(calcium_state[0]),
)
f_Ca = calcium_state[0]
f_Al = (Al/conv_Al) * (f_Ca**3 / (K_Ca_Al * Ca**3))**0.5
f_Mg = Mg * (f_Ca / (K_Ca_Mg*Ca))
f_Na = Na * (f_Ca / (K_Ca_Na*Ca))**0.5
f_K = K * (f_Ca / (K_Ca_K*Ca))**0.5
f_H = H * (f_Ca / (K_Ca_H*Ca))**0.5
f_CEC_in = [f_Ca, f_Mg, f_K, f_Na, f_Al, f_H]
return (f_CEC_in, K_CEC), 0, ("MINPACK stopped with status " + str(status) if status != 1 else "")
#------------------------------------------------------------------------------
# CEC fractions to conc
[docs]
@njit(nogil=True, error_model="numpy")
def f_CEC_to_conc(f_CEC_in, pH_in, soil, conv_mol,conv_Al):
#pH
H = 10.0**(-pH_in) * conv_mol
#constants
K_CEC = smew.K_GT_CEC(soil,conv_mol) #CEC Gaines-Thomas
K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H = K_CEC
K1, K2, K3, K4 = smew.K_Al(conv_mol) #Al speciation
#f_CEC [-]
f_Ca, f_Mg, f_K, f_Na, f_Al, f_H = f_CEC_in
#estimates of concentrations
Ca = (f_Ca/K_Ca_H) * (H/f_H)**2
Ca_ratio = Ca / f_Ca
Mg = Ca_ratio * K_Ca_Mg * f_Mg
K = (Ca_ratio * K_Ca_K)**0.5 * f_K
Na = (Ca_ratio * K_Ca_Na)**0.5 * f_Na
Al = (Ca_ratio**3 * K_Ca_Al)**0.5 * f_Al * conv_Al
Al_w = Al / (H**4 / (H**4 + H**3*K1 + H**2*K1*K2 + H*K1*K2*K3 + K1*K2*K3*K4))
conc_in = [Ca, Mg, K, Na, Al_w]
K_CEC = [K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H]
return conc_in, K_CEC
#------------------------------------------------------------------------------
# CEC fractions and Alk for recalibrating K_Ca_H and concentrations
[docs]
def f_CEC_Alk_to_conc(f_CEC_in, K_CEC, pH_in, Alk_in, conv_mol,conv_Al):
"""Calculate CEC fractions with Python/SciPy or Numba/cminpack."""
# Ensure inputs are contiguous float64 arrays for Numba compilation and C double* compatibility.
result, error_code, error_message, _ = _f_CEC_Alk_to_conc(
np.ascontiguousarray(f_CEC_in, dtype=np.float64),
np.ascontiguousarray(K_CEC, dtype=np.float64),
pH_in, Alk_in, conv_mol, conv_Al
)
raise_for_error(error_code, error_message)
if error_message:
warnings.warn(error_message, RuntimeWarning, stacklevel=2)
return result
@_solver_njit
def _f_CEC_Alk_to_conc(f_CEC_in, K_CEC, pH_in, Alk_in, conv_mol,conv_Al):
"""Return (result or None, error_code, error_message, solver_status)."""
#pH
H = 10**(-pH_in)*conv_mol
#constants
K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H0 = K_CEC #CEC constants
K1, K2, K3, K4 = smew.K_Al(conv_mol) #Al speciation
#f_CEC [-]
f_Ca, f_Mg, f_K, f_Na, f_Al, f_H = f_CEC_in
# Initial guess
Ca = (f_Ca/K_Ca_H0) * (H/f_H)**2
# Use numpy array to store scalar (needed to retrieve the value by reference after the solver)
Ca = np.array((Ca,))
parameters = np.array((f_Ca, K_Ca_Mg, f_Mg, K_Ca_Na, f_Na, K_Ca_K, f_K, Alk_in))
residual = np.empty(1)
# Sized according to MINPACK hybrd scratchpad requirements: n*(3*n + 13)/2.
work = np.empty(8)
status = _solve_system(F_CEC_ALK_TO_CONC_SYSTEM, Ca, parameters, residual, work, 1.49012e-8)
# Extract the residual
Ca = Ca[0]
if status <= 0:
_, error_code, error_message = _solver_error(
status, residual, ErrorCode.F_CEC_ALK_TO_CONC_RESIDUAL, ErrorCode.F_CEC_ALK_TO_CONC_SOLVER_INPUT,
'ic.f_CEC_Alk_to_conc'
+ '; Initial guess (Ca) =' + _float_text(Ca)
+ '; pH=' + _float_text(pH_in)
+ ', f_Ca=' + _float_text(f_Ca)
+ ', K_Ca_Mg=' + _float_text(K_Ca_Mg)
+ ', f_Mg=' + _float_text(f_Mg)
+ ', K_Ca_Na=' + _float_text(K_Ca_Na)
+ ', f_Na=' + _float_text(f_Na)
+ ', K_Ca_K=' + _float_text(K_Ca_K)
+ ', f_K=' + _float_text(f_K)
+ ', Alk_in=' + _float_text(Alk_in),
)
return None, error_code, error_message, status
#return values
K_Ca_H = (f_Ca/Ca)*(H/f_H)**2
Mg = (Ca/f_Ca)*K_Ca_Mg*f_Mg
K = ((Ca/f_Ca)*K_Ca_K)**(1/2)*f_K
Na = ((Ca/f_Ca)*K_Ca_Na)**(1/2)*f_Na
Al = ((Ca/f_Ca)**3*K_Ca_Al)**(1/2)*f_Al*conv_Al
Al_w = Al/(H**4/(H**4+H**3*K1+H**2*K1*K2+H*K1*K2*K3+K1*K2*K3*K4)) #[mol_conv/l]
conc_in = [Ca, Mg, K, Na, Al_w]
return (conc_in, K_Ca_H), 0, ("MINPACK stopped with status " + str(status) if status != 1 else ""), status
#------------------------------------------------------------------------------
# Input: Total (Ca, Mg, K, Na) and CEC base saturation (or acid saturation, f_H+f_Al)
[docs]
def total_to_f_CEC_and_conc(
total_in,
pH_in,
f_acid,
s,
soil,
n,
Zr,
CEC_tot,
conv_mol,
conv_Al,
):
"""Infer concentrations and CEC fractions using the process-wide JIT setting."""
# Ensure inputs are contiguous float64 arrays for Numba compilation and C double* compatibility.
result, error_code, error_message = _total_to_f_CEC_and_conc(
np.ascontiguousarray(total_in, dtype=np.float64), pH_in, f_acid,
np.ascontiguousarray(s, dtype=np.float64), soil, n, Zr, CEC_tot, conv_mol, conv_Al,
)
raise_for_error(error_code, error_message)
if error_message:
warnings.warn(error_message, RuntimeWarning, stacklevel=2)
return result
@_solver_njit
def _total_to_f_CEC_and_conc(
total_in,
pH_in,
f_acid,
s,
soil,
n,
Zr,
CEC_tot,
conv_mol,
conv_Al,
):
"""Return (results or None, error_code, error_message) for valid inputs; see docs/errors.rst."""
#constants
K_CEC = smew.K_GT_CEC(soil, conv_mol) #CEC Gaines-Thomas
K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H = K_CEC
K1, K2, K3, K4 = smew.K_Al(conv_mol) #Al speciation
# total (mol-conv/m2)
Ca_tot, Mg_tot, K_tot, Na_tot = total_in
H = 10.0**(-pH_in) * conv_mol
#initial guess
f_Ca0 = 0.8 * (1 - f_acid)
f_Mg0 = 0.1 * (1 - f_acid)
f_K0 = 0.05 * (1 - f_acid)
f_Na0 = 0.05 * (1 - f_acid)
f_H0 = f_acid * 0.3
f_Al0 = f_acid * 0.7
n_Zr_s_1000 = n * Zr * s[0] * 1000
Mg0 = (Mg_tot - (f_Mg0/2)*CEC_tot) / n_Zr_s_1000
Ca0 = (Ca_tot - (f_Ca0/2)*CEC_tot) / n_Zr_s_1000
Na0 = (Na_tot - f_Na0*CEC_tot) / n_Zr_s_1000
K0 = (K_tot - f_K0*CEC_tot) / n_Zr_s_1000
Al0 = f_Al0 * conv_Al * (K_Ca_Al * Ca0**3 / f_Ca0**3)**0.5
Al_w0 = Al0 / (H**4 / (H**4 + H**3*K1 + H**2*K1*K2 + H*K1*K2*K3 + K1*K2*K3*K4))
Al_tot0 = (f_Al0/3)*CEC_tot*conv_Al + Al_w0*n_Zr_s_1000
x0 = np.array((Al_w0, Al0, Al_tot0, Mg0, Ca0, Na0, K0, f_Mg0, f_Na0, f_K0, f_Ca0, f_Al0, f_H0))
#system solution
parameters = np.array((
H, n, Zr, s[0], CEC_tot, conv_Al, K1, K2, K3, K4,
Ca_tot, Mg_tot, K_tot, Na_tot, f_acid, K_Ca_Al,
K_Ca_Mg, K_Ca_Na, K_Ca_K, K_Ca_H,
))
residual = np.empty(x0.size)
work = np.empty(_solver_work_size(x0.size))
status = _solve_system(TOTAL_TO_CEC_SYSTEM, x0, parameters, residual, work, 1e-14)
if status <= 0:
return _solver_error(
status, residual, ErrorCode.TOTAL_CEC_RESIDUAL, ErrorCode.TOTAL_CEC_SOLVER_INPUT,
'ic.total_to_f_CEC_and_conc'
+ '; pH=' + _float_text(pH_in)
+ ', s=' + _float_text(s[0])
+ ', CEC_total=' + _float_text(CEC_tot)
+ ', trial_Ca=' + _float_text(x0[4]),
)
# _solve_system writes the converged solution directly into the guess array x0.
Al_w, Al, Al_tot, Mg, Ca, Na, K, f_Mg, f_Na, f_K, f_Ca, f_Al, f_H = x0
#K_Ca_Al = (Al/conv_Al/f_Al)**2*(f_Ca/Ca)**3
#K_Ca_H = (f_Ca/Ca)*(H/f_H)**2
K_CEC = [K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H]
conc_in = [Ca, Mg, K, Na, Al_w]
f_CEC_in = [f_Ca, f_Mg, f_K, f_Na, f_Al, f_H]
return (conc_in, f_CEC_in, K_CEC), 0, ("MINPACK stopped with status " + str(status) if status != 1 else "")
#------------------------------------------------------------------------------
# Calibration of K constants on coupled f_CEC and conc measurements
[docs]
@njit(nogil=True, error_model="numpy")
def f_CEC_and_conc_to_K(f_CEC_in, conc_in, pH_in, soil, conv_mol,conv_Al):
#pH
H = 10.0**(-pH_in) * conv_mol
#f_CEC [-]
f_Ca, f_Mg, f_K, f_Na, f_Al, f_H = f_CEC_in
#conc [-]
Ca, Mg, K, Na, Al_w = conc_in
# Al spec
K1, K2, K3, K4 = smew.K_Al(conv_mol)
Al = (H**4 / (H**4 + H**3*K1 + H**2*K1*K2 + H*K1*K2*K3 + K1*K2*K3*K4))*Al_w
#estimates of K constants
K_Ca_Mg = (f_Ca/Ca) * (Mg/f_Mg)
K_Ca_K = (f_Ca/Ca) * (K/f_K)**2
K_Ca_Na = (f_Ca/Ca) * (Na/f_Na)**2
K_Ca_Al = (f_Ca/Ca)**3 * (f_Al / (Al/conv_Al))**2
K_Ca_H = (f_Ca/Ca) * (H/f_H)**2
K_CEC = [K_Ca_Mg, K_Ca_K, K_Ca_Na, K_Ca_Al, K_Ca_H]
return K_CEC
conc_to_f_CEC_numba = _conc_to_f_CEC
total_to_f_CEC_and_conc_numba = _total_to_f_CEC_and_conc