8000 Fix equilibrium non-convergence between pH 4.2 and 5.05 for chelate mixtures by rafatahmed · Pull Request #58 · rafatahmed/Flahax · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Fix the equilibrium solver failing to converge between pH 4.2 and 5.05 for chelate-rich mixed solutions (#52). From the cold start (every free activity at total/1000), Newton crawled toward strongly complexed free ions (EDTA, DTPA and EDDHA with Fe and Cu) until its iteration limit; an acid target of pH 5.0 for the mixed-product fixture failed. A failed solve now restarts from a continued-fraction mass-balance estimate (Wigley 1977). A pH 4-9 scan of the three mixed fixtures (1,503 solves) goes from 215 failures to none; converging solves are unchanged because the restart runs only after a failure.
- The NNLS solver raises `InputError` when it is still not optimal at its iteration cap, instead of silently returning a non-optimal fit (#55). No benchmark fit reaches the cap.
- `recommend()` reports `targetIonBalance`, the cation and anion meq/L implied by the formula (P as H2PO4-, S as SO4 2-), and warns when the sums differ by more than 10%. Eight shipped formulas exceed it, which explains most recipe misses (#39); for example Pepper (Howard Resh) is -39.5% and the U of Florida tomato clusters are +19% to +30%.
- `recommend()` reports `unmetTargets`: each positive target missed by more than 1% with a reason (`no_source`, `limited_by_ceiling`, `incidental_tradeoff`, `conflicting_targets` with the conflicting targets, and whether chloride products would reach it) (#39). The 1% tolerance is documented as a FlahaX assumption.
Expand Down
41 changes: 41 additions & 0 deletions src/flahax/aqueous_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from .root_finding import shrink_bracket

LN10 = math.log(10.)
# Continued-fraction sweeps before Newton when the cold start does not converge (#52).
PRESOLVE_SWEEPS = 200

@lru_cache(maxsize=1)
def chemistry():
Expand Down Expand Up @@ -73,7 +75,44 @@ def _damped_step(evaluate, x, residual, matrix):
damping*=10
return None

def _continued_fraction(logs, totals, bases, records, sparse, ph, strength, sweeps=PRESOLVE_SWEEPS):
"""Mass-balance pre-iteration (Wigley 1977 continued fraction): rescale each free
activity by total/sum, damped by its largest stoichiometric coefficient."""
root=math.sqrt(strength)
def lgamma(z):
return -.509*z*z*(root/(1+root)-.3*strength) if z else .1*strength
offsets=[r['beta']-ph*r['powers'].get('H+',0)-lgamma(r['charge']) for r in records]
power=[max([abs(v) for nz in sparse for j,v in nz if j==k]+[1.]) for k in range(len(bases))]
logs=list(logs)
for _ in range(sweeps):
sums=[0.]*len(bases)
for o,nz in zip(offsets,sparse):
a=10.**max(-300,min(100,o+sum(v*logs[j] for j,v in nz)))
for j,v in nz:
sums[j]+=a*v
worst=0.
for k,b in enumerate(bases):
if sums[k]<=0:
continue
change=(math.log10(totals[b])-math.log10(sums[k]))/power[k]
logs[k]+=change
worst=max(worst,abs(change))
if worst<1e-3:
break
return logs

def solve(totals, ph, *, phases=(), ionic_strength=None, temperature_c=25.):
try:
return _solve(totals, ph, phases=phases, ionic_strength=ionic_strength, temperature_c=temperature_c)
except DeliveryError as exc:
if exc.code != 'nonconvergent':
raise
# The cold start (every free activity at total/1000) can leave Newton crawling far
# from strongly complexed free ions (#52); restart from a continued-fraction estimate.
return _solve(totals, ph, phases=phases, ionic_strength=ionic_strength, temperature_c=temperature_c,
presolve=True)

def _solve(totals, ph, *, phases=(), ionic_strength=None, temperature_c=25., presolve=False):
if temperature_c != 25:
raise DeliveryError('temperature_out_of_range','reaction dataset is restricted to 25 C')
if not math.isfinite(ph) or not 0 <= ph <= 14:
Expand All @@ -98,6 +137,8 @@ def solve(totals, ph, *, phases=(), ionic_strength=None, temperature_c=25.):
sparse=[[(j,v) for j,v in enumerate(s) if v] for s in stoich]
strength=ionic_strength if ionic_strength is not None else min(.05,max(1e-8,sum(totals.values())))
logs=[math.log10(totals[b])-3 for b in bases]
if presolve:
logs=_continued_fraction(logs,totals,bases,records,sparse,ph,strength)
active=[]
solids={}
water=1.
Expand Down
33 changes: 33 additions & 0 deletions tests/test_chemistry_acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,39 @@ def test_near_singular_newton_step_does_not_stall(self):
for component,residual in result.residuals.items():
self.assertLess(abs(residual),1e-9*result.totals[component]+1e-15)

def test_low_ph_chelate_mixtures_converge(self):
# #52: below pH ~5.05 the cold start left Newton crawling toward strongly
# complexed free ions (EDTA/DTPA/EDDHA with Fe and Cu) until its iteration limit.
from benchmarks.cases import read_fixture
for name in ('products/mixed_products','phases/mixed_product_phases'):
data=read_fixture(name)
for ph in (4.2,4.3,4.5,4.7,4.9,5.0):
with self.subTest(fixture=name,ph=ph):
result=solve(data['runtime_totals'],ph,phases=data.get('phases',()))
for component,residual in result.residuals.items():
self.assertLess(abs(residual),1e-9*result.totals[component]+1e-15)

def test_acid_target_at_ph_five_for_chelate_mixture(self):
# Failed on main with 'aqueous Newton iteration limit' (#52).
from benchmarks.cases import read_fixture
data=read_fixture('products/mixed_target_ph_nitric')
result=nitric_target(data['runtime_totals'],data['initial_ph'],5.)
self.assertAlmostEqual(result.target.ph,5.)
self.assertGreater(result.nitric_acid_molal,0.)
self.assertAlmostEqual(result.target.totals['NO3-']-data['runtime_totals']['NO3-'],result.nitric_acid_molal,places=14)

def test_converging_solves_do_not_use_the_restart(self):
import flahax.aqueous_model as model
from benchmarks.cases import read_fixture
calls=[]
original=model._continued_fraction
model._continued_fraction=lambda *a,**k: calls.append(1) or original(*a,**k)
try:
solve(read_fixture('products/mixed_products')['runtime_totals'],6.)
finally:
model._continued_fraction=original
self.assertEqual(calls,[])

def test_chloride_salts_keep_chloride_and_add_no_nitrate(self):
calcium=catalogue_dose_totals({'Calcium Chloride (Dihydrate)':1.})
self.assertNotIn('NO3-',calcium)
Expand Down
Loading
0