Skip to main content
Nature Communications logoLink to Nature Communications
. 2026 Aug 25;17:10170. doi: 10.1038/s41467-026-76968-5

Smart and sustainable production of fertilizer by electrochromic self-perception recovery of ammonium from wastewater

Rui Wei 1, Yanbiao Liu 1,✉, Changyong Zhang 2, Peng Xu 3, Nanqi Ren 3, Shijie You 3,✉
PMCID: PMC13601573  PMID: 42778563

Abstract

Ammonium-containing wastewater represents both an environmental burden and a recoverable nitrogen resource. Here we develop an electrochromic self-perception recovery (ECSPR) system that integrates selective intercalation, intrinsic electrochromism and data-driven control for recovering ammonium to produce value-added fertilizer in a smart manner. The system employs a copper hexacyanoferrate (CuHCF) electrode capable of selective NH4+ intercalation (selectivity coefficient of 5–38 versus other cations) with high capacity (2.2–2.7 mmol g−1). Fe-dominated redox conversion with secondary Cu valence modulation couples charge transfer with reversible color switching, enabling visible self-perception of adsorption-desorption states. Image recognition and machine learning convert electrode images into quantitative adsorption states, which are used as the decision variable to schedule adsorption-desorption and route flows in real time. In continuous-flow operation with actual swine wastewater, the ECSPR system achieves cumulative recovery efficiency of 90.2% over 10 cycles with self-feedback regulation at energy consumption of 4.9 kWh kg−1 N on average. Liquid ammonium sulfate fertilizer is produced directly with comparable agronomic performance to commercial products. Life-cycle and techno-economic analyses further indicate environmental benefits and economic feasibility. Overall, this study provides an intelligent strategy for ammonium recovery and fertilizer production from wastewater, making wastewater treatment more economical and more sustainable.

Subject terms: Environmental chemistry, Pollution remediation, Electrochemistry


The authors develop an electrochromic self-perception recovery system that integrates electrochromism-based sensing, predictive modelling and automatic control. This system enables smart ammonium recovery from wastewater and converts it into liquid fertilizer.

Introduction

Ammonia (NH3) serves as an indispensable reactive nitrogen feedstock for agriculture, chemical industries, and green energy systems, with annual demand estimated to reach 600 million tonnes by 20501–3. Currently, industrial-scale production mainly relies on the energy-intensive Haber-Bosch process (Fig. 1a), responsible for 1.5–2.5% of global energy consumption and 1–2% of global carbon emissions1,4. Meanwhile, anthropogenic activities increase the discharge of ammonia nitrogen into aquatic ecosystems, primarily in the form of ammonium (NH4+) released from agricultural runoff, animal husbandry, and municipal or industrial effluents3,5, which can supply ~30% of global fertilizer nitrogen6. This not only leads to eutrophication, biodiversity loss and greenhouse gas emissions, but also represents a valuable yet underutilized nitrogen reservoir7,8. Therefore, great interest is motivated by the need for Sustainable Development Goals (SDGs 2, 6, 12, 13, 14)9 to produce value-added products through ammonium recovery from wastewater.

Fig. 1. Vision and design of a smart electrochemical ammonium recovery system.

Fig. 1

a Two pathways of the ammonia cycle. In the traditional pathway (upper loop), NH3 produced from N2 via Haber-Bosch process is largely used for the production of industrial chemicals and fertilizers. Downstream use and livestock feeding generate NH4+-rich wastewater, which typically undergoes nitrification and denitrification in a wastewater treatment plant (WWTP) and is ultimately returned to the atmosphere as N2. In the possible electrochemical recovery pathway (lower loop), NH4+ in wastewater can be directly recovered back to NH3 or downstream nitrogen products. b Schematic illustration of the electrochromic self-perception recovery (ECSPR) system containing three coupled layers of material responsiveness, visual perception and system intelligence.

Recovering nitrogen products from wastewater remains a challenge due to the requirements for selective separation and enrichment from complex matrices and efficient conversion into qualified products under precise operational control10,11. Electrochemical separation offers a sustainable, controllable, and potentially scalable strategy (Fig. 1a), where electrosorption leverages voltage-switchable electrode interfaces to program reversible ion adsorption and desorption12–14. Capacitive electrosorption offers a promising approach by enriching ions in the electric double layer, but suffers from limited capacity ( < 10 mg N g−1) and poor selectivity ( < 5) for NH4+, due to its similar charge and hydrated radius ( ~ 3.31 Å) to those of prevalent interferents such as Na+ ( ~ 3.58 Å) and K+ ( ~ 3.31 Å)14,15. Faradaic electrosorption couples ion intercalation with electron transfer in redox-active hosts that can be tailored at the molecular scale, facilitating readily switchable control of ion uptake and release with high selectivity and capacity16–18. These hosts can act as redox reservoirs to decouple NH4+ intercalation/deintercalation from opposing half-reactions in membrane-free configurations, and meanwhile realize on-demand production of value-added NH4+ products19,20. However, practical deployment is hampered by poor selectivity, low efficiency and operational complexity. In particular, most electrochemical recovery systems work based on preset voltage/time programs or indirect bulk electrical responses. These non-specific signals may originate from target ion intercalation-deintercalation and parasitic reactions (e.g., oxygen and hydrogen evolution), and are sensitive to solution conductivity, coexisting ions, concentration polarization and pH fluctuation21,22. Such signals are unlikely to provide a direct indication of the ion-occupancy state of redox-active electrodes for adsorption-desorption under dynamic conditions. Hence, it is highly desirable to develop an efficient, smart, and sustainable Faradaic electrosorption system with intrinsic process-state perception for recovery of ammonium from wastewater.

In nature, color provides a universal language for perception and feedback, endowing organisms with the capability to visually sense and respond to environmental stimuli. Inspired by visual intelligence, electrochromism offers an opportunity to integrate in situ sensing into electrochemical ammonium recovery systems. Electrochromic materials undergo reversible optical transitions that intrinsically couple to ion intercalation and redox reactions23. Ion insertion/extraction induces changes in the oxidation states of redox-active centers, which alter the electronic structure and optical absorption. The resulting color evolution directly reflects the intercalation state that serves as an intrinsic signal of ion occupancy, rather than relying on external sensing input. Such a feature has been widely exploited in smart energy storage and chemical sensing to realize intuitive and non-invasive tracking24,25, yet its application to real-time process perception and closed-loop control in wastewater treatment remains largely unexplored. Representative platforms such as open-framework Prussian blue analogues (PBAs), tunnel-structured WO3 and MoO3, mediate selective and fast NH4+ storage via molecular sieving and host-guest interactions, while exhibiting intrinsic electrochromism based on redox-active metal centers26–28. Coupling Faradaic ion storage with electrochromic feedback is expected to enable real-time self-perception of ammonium recovery state, thereby converting electrode color into machine-readable variables for closed-loop actuation.

Based on this rationale, our previous work established a proof-of-concept static platform that linked the colorimetric response of Prussian blue to NH4+ adsorption and desorption, demonstrating automated electro-switching via visual feedback29. Herein, we advance this concept into an electrochromic self-perception recovery (ECSPR) system capable of closed-loop operation in a continuous-flow process for autonomous ammonium recovery and fertilizer production. Copper hexacyanoferrate (CuHCF) is used as a model redox-active electrode to couple selective NH4+ intercalation with intrinsic electrochromism. A computer-vision framework converts captured in situ electrode images into quantitative adsorption states via supervised learning. The state serves as the decision variable for the controller to smartly manipulate real-time adsorption-desorption. The ECSPR system achieves 90.2% NH4+ recovery from swine wastewater with second-scale feedback regulation, robust cycling, and low energy consumption. Liquid ammonium sulfate fertilizer is produced directly for agronomic use. Such an ECSPR strategy provides a smart and efficient solution for converting ammonium-containing waste streams into ready-to-use fertilizer, contributing to a circular nitrogen economy.

Results

Conceptual design of the electrochromic self-perception recovery system

We proposed an electrochromic self-perception recovery (ECSPR) system that enabled intelligent, closed-loop ammonium recovery by visually sensing its operational state and adaptively scheduling adsorption-desorption cycles in real time. The ECSPR system was schematically designed to integrate three synergistic layers of material responsiveness, visual perception, and autonomous process control (Fig. 1b). This integration directly coupled ion-selective intercalation with intrinsic electrochromic sensing, which in turn drove event-driven actuation, forming a coherent perception-decision-action loop.

At the material level, we employed a redox-active electrode where selective NH4+ intercalation was intrinsically coupled to electrochromism. The design followed a cascade: (i) NH4+ intercalation drove reversible redox transitions of metal centers for charge compensation; (ii) the redox transitions modulated electronic structure and optical absorption of the electrode; and (iii) the resulting color change encoded ionic occupancy. Thus, the optical response was generated by the same intercalation/redox process responsible for NH4+ uptake and release, allowing electrode color to serve as an intrinsic material-state signal. To maintain this one-to-one mapping under continuous operation, the active phase should afford open transport pathways, fast and reversible electron-ion exchange at mild potentials, and structural robustness. This coupling enabled the electrode to act as both reaction interface and real-time sensing medium, which provided the physical basis for self-perception.

At the perception level, intrinsic color evolution was used as the primary sensing signal for in situ state recognition. A computer-vision framework acquired electrode images at fixed intervals, applied region-of-interest selection and color balancing to suppress illumination drift, and extracted image features (e.g., colorimetric descriptors in RGB/HSV space). These features were mapped to adsorption state by supervised learning using machine learning or deep learning models, providing real-time, non-contact, and quantitative predictions. Imaging was conducted under controlled illumination to establish a reliable color-adsorption relationship, while broader deployment would require expanded datasets and robustness validation under realistic conditions.

At the system-integration level, the electrosorption cell was integrated into a continuous-flow configuration, with the imaging unit, power supplies, and pumps interfaced to the central controller via digital links (e.g., serial or wireless) to enable coordinated operation. The predicted adsorption state from the vision model served as the real-time decision variable for event-driven control. When predefined thresholds were met, a discrete-event controller switched operating conditions to schedule adsorption or desorption, coordinating electrode polarity and flow routing to initiate NH4+ uptake, release, and product collection. This vision-guided closed loop delivered fast response and stable cycling without manual intervention, and the modular architecture supported parallelization and scale-out for decentralized deployment.

Ammonium-selective intercalation of redox-active CuHCF electrode

Copper hexacyanoferrate (CuHCF), a representative Prussian blue analogue (PBA), was selected as the electrode material due to its combined capabilities for selective ion intercalation, reversible redox activity, and intrinsic electrochromism30,31. Its open Fe-CN-Cu cubic framework contained interstitial sites (3.2–4.6 Å) that closely matched the hydrated radius of NH4+ (3.31 Å), which theoretically enabled size-selective intercalation (Fig. 2a). Such intercalation might be further assisted by hydrogen bonding between NH4+ protons and lattice N atoms, which could lower dehydration barriers and stabilize occupancy32. Fe-centered redox transitions together with possible Cu valence modulation could mediate reversible electrochromic switching that optically reports NH4+ uptake and release. Guided by this rationale, CuHCF was synthesized by co-precipitation and coated onto indium tin oxide (ITO) glass to construct an optically accessible CuHCF film electrode (Fig. 2b).

Fig. 2. Construction of a redox-active copper hexacyanoferrate (CuHCF) electrode for NH4+-selective intercalation.

Fig. 2

a Crystal structure and electrochromic response of CuHCF, showing size-selective intercalation of NH4+ into the open framework and reversible color switching along with intercalation and deintercalation. Yellow and red blocks denote the corresponding electrode colors. b Preparation of CuHCF film electrode by co-precipitation, filtration and collection, slurry preparation and doctor-blade coating. c Transmission electron microscopy (TEM) image of CuHCF with the inset showing the selected-area electron diffraction (SAED) pattern, and energy-dispersive X-ray spectroscopy (EDS) elemental mappings of C, N, Fe and Cu. TEM images are representative of three independent experiments with similar results. d X-ray diffraction (XRD) pattern. e Cyclic voltammetry (CV) curves of CuHCF electrode in 1 M NH4Cl, 1 M NaCl, 1 M KCl, 0.5 M MgCl2 and 0.5 M CaCl2 at 5 mV s−1. Yellow and red blocks indicate the electrode color change, and 0.93 V denotes the NH4+ intercalation potential. f Relationship between the intercalation potential difference of NH4+ vs. M+ (Na+, K+) and NH4+/M+ molar ratio, calculated based on the Nernst equation. Orange and blue shaded regions indicate preferential NH4+ and M+ intercalation, respectively, and the ellipse marks the typical NH4+/M+ molar-ratio range in common wastewater. g Selectivity coefficients of NH4+ relative to K+, Na+, Ca2+ and Mg2+ of CuHCF electrode in binary (5 mM each) solution, multi-salt (2 mM each) solution, and actual swine wastewater. The selectivity coefficient is dimensionless and is reported as (-). Error bars in the figures represent the standard deviations (mean ± SD, n = 3) from three replicate experiments. Source data are provided as a Source Data file.

The as-prepared CuHCF exhibited quasi-cubic morphology with an average edge length of ~68 nm (Fig. 2c). Elemental mapping indicated uniform distribution of C, N, Fe, and Cu elements. X-ray diffraction (XRD) patterns displayed sharp diffraction peaks at 2θ of 17.6°, 24.9°, 35.4°, and 39.7° (Fig. 2d), indexed to (200), (220), (400), and (420) planes of face-centered cubic CuHCF framework (space group of Fm-3m; JCPDS No. 86-0514). This was consistent with the (200), (220) planes and polycrystalline characteristics detected in the selected-area electron diffraction (SAED) pattern (inset in Fig. 2c). X-ray photoelectron spectroscopy (XPS) confirmed mixed valence in CuHCF (Supplementary Fig. 1). The Fe 2p spectrum showed components attributable to Fe(III) (710.1 eV, 723.4 eV) and Fe(II) (708.4 eV, 721.6 eV), while the Cu 2p spectrum resolved Cu(II) (935.7 eV, 955.7 eV) and Cu(I) (933.0 eV, 952.9 eV). The C 1 s spectrum exhibited the expected signals of C≡N ligands, and Fourier transform infrared (FTIR) further showed a distinct ν(C≡N) stretching band located at 2100 cm−1 (Supplementary Fig. 2). These results confirmed an open PBA-type framework of CuHCF that provided suitable interstitial channels for cation intercalation.

To evaluate the cation intercalation properties, we performed cyclic voltammetry (CV) in 1 M NH4Cl, 1 M NaCl, 1 M KCl, 0.5 M MgCl2 and 0.5 M CaCl2 at 5 mV s−1. Reversible redox chemistry appeared with intercalation potentials of NH4+, K+, Na+, Ca2+, and Mg2+ at 0.93 V, 0.88 V, 0.78 V, 0.77 V, and 0.77 V, respectively (Fig. 2e), with the largest peak current density in NH4Cl (1.9 A g−1). The specific capacity derived from galvanostatic charge-discharge (GCD) tests at 100 mA g−1 showed a similar tendency (Supplementary Fig. 3). The highest value of 68.7 mAh g−1 was obtained in NH4Cl, which was higher than that in KCl (40.0 mAh g−1), NaCl (30.6 mAh g−1), CaCl2 (11.6 mAh g−1), and MgCl2 (5.5 mAh g−1) by a factor of approximately 1.72, 2.25, 5.90, and 12.45, respectively. These findings demonstrated a strong thermodynamic and kinetic preference for NH4+ intercalation over competing cations (K+, Na+, Ca2+ and Mg2+). Electrochemical impedance spectroscopy (EIS) further revealed the lowest charge-transfer resistance in NH4Cl, modestly higher in KCl ( ~ 1.2-fold) and markedly larger in NaCl ( ~ 3.5-fold), and similar responses in NH4+-containing swine wastewater (Supplementary Figs. 4 and 5, Supplementary Table 1). Consistently, the intercalation potential in the swine wastewater differed from NH4Cl by merely 0.03 V (Supplementary Fig. 6), evidencing robust NH4+ selectivity in realistic matrices. From the Nernst analysis of CV curves, the differences in thermodynamic driving forces (0.15 V for NH4+/Na+ and 0.05 V for NH4+/K+) indicated that NH4+ intercalation was preferred when the molar ratio of NH4+/Na+ > 1.13 × 10−3 or NH4+/K+ > 1.12 × 10−1 (Fig. 2f and Supplementary Text 1), consistent with conditions common in manure and typical municipal wastewater (Supplementary Table 2).

We next assessed the selective adsorption performance under constant voltage (0.6 V) in binary-salt (5 mM for each) solution, multi-salt (2 mM for each) solution, and actual swine wastewater. The NH4+ adsorption capacity (2.2–2.7 mmol g−1) was nearly an order of magnitude higher than that of K+ (0.27–0.44 mmol g−1) and Na+ (0.21–0.29 mmol g−1), and more than twenty-fold higher than that of Ca2+ (0.11–0.12 mmol g−1) and Mg2+ (0.08–0.10 mmol g−1) (Supplementary Fig. 7). The corresponding selectivity coefficients of NH4+/K+, NH4+/Na+, NH4+/Ca2+ and NH4+/Mg2+ (Fig. 2g) were 5.3, 8.9, 23.4, and 29.5 in the binary-salt solutions, 8.6, 10.8, 19.5, and 26.7 in the multi-salt solution, and 7.5, 11.4, 21.1, and 38.1 in the actual swine wastewater, respectively. The adsorption preference followed the order of NH4+ > K+ > Na+ > Ca2+ > Mg2+, consistent with the CV trends and previous studies28,33. Collectively, these results showed that the CuHCF film electrode selectively intercalated ammonium even under chemically complex conditions, supporting its practical deployment for ammonium recovery.

Coupling of electrochemically switchable adsorption-desorption and electrochromic feedback

To investigate the coupling among NH4+ adsorption-desorption, redox reactions, and color transitions, we employed a continuous-flow hybrid electrosorption cell comprising a CuHCF film electrode and a stainless-steel mesh electrode enclosed within a quartz housing with an optical viewing window (Fig. 3a and Supplementary Fig. 8). The reactor operated in a single-pass configuration at 1.5 mL min−1 using a synthetic NH4+-containing wastewater (10 mM). Adsorption was driven at cell voltages of 0.4–0.8 V (stainless-steel mesh as anode), whereas desorption was performed at −1.5 to −1.1 V (stainless-steel mesh as cathode). The process exhibited distinct voltage dependence (Fig. 3b and Supplementary Fig. 9). At 0.4 V, the NH4+ uptake reached 1.8 mmol g−1, and increasing the voltage to 0.6 V accelerated adsorption to saturation within 10 min with a capacity of 2.7 mmol g−1, corresponding to a 50% increase. Further elevation to 0.8 V produced no additional gain, indicating a saturation limit. Reversing the polarity initiated desorption, and increasing the voltage from −1.1 to −1.5 V progressively shortened the release time, reaching 8 min at −1.5 V. Across this range, the desorption efficiency consistently exceeded 99%, which indicated a fast and highly reversible electrochemically switchable adsorption-desorption process.

Fig. 3. Mechanistic coupling between electrically switchable adsorption-desorption and electrochromic response.

Fig. 3

a Disassembly diagram of the continuous-flow hybrid electrosorption cell composed of a CuHCF film working electrode and a stainless-steel mesh counter electrode enclosed within a quartz housing. b Adsorption capacity under different voltages. Error bars in the figures represent the standard deviations (mean ± SD, n = 3) from three replicate experiments. c Fourier-transform infrared (FTIR) spectra of CuHCF electrode at different states. The inset shows the enlarged 1100–1500 cm−1 region. d Fe 2p X-ray photoelectron spectroscopy (XPS) spectra and e Cu 2p XPS spectra of CuHCF electrode at different states. f Schematic illustration of the electrochemical NH4+ recovery mechanism. During NH4+ uptake, CuHCF is reduced, while water oxidation occurs at the anode. During NH4+ release, NH4+-intercalated CuHCF is oxidized, while H+ reduction occurs at the cathode with H2 evolution. g Optical images of CuHCF electrode at different states. h Ultraviolet-visible (UV-vis) transmittance map of CuHCF electrode. Source data are provided as a Source Data file.

To elucidate structural evolution and interfacial interactions during the adsorption-desorption process, FTIR spectra of CuHCF at defined states were collected (Fig. 3c). The characteristic ν(C≡N) stretching vibration at ~2100 cm−1 persisted throughout, which confirmed an intact framework during cycling. Two additional bands emerged at 1403 cm−1 and 1237 cm−1 during adsorption, associated with N − H bending vibrations32. The former corresponded to non-hydrogen-bonded N−H of intercalated NH4+, while the latter originated from transient N−H···N hydrogen bonds between NH4+ and CuHCF lattice nitrogen atoms. Upon desorption, both bands disappeared, indicating rupture of these hydrogen bonds and complete release of NH4+. This reversible bonding/debonding behavior evidenced the structural reversibility of the CuHCF framework and the dynamic role of hydrogen bonds in the NH4+ intercalation-deintercalation process. Beyond explaining the excellent reversibility, these molecular interactions also rationalized the high selectivity. The interstitial channels of CuHCF (3.2–4.6 Å) closely matched the hydrated radius of NH4+ (3.31 Å), and the relatively low hydration free energy (307 kJ mol−1) facilitated partial dehydration upon intercalation28,34. In contrast, competing cations (K+, Na+, Ca2+, Mg2+) exhibited size mismatch and/or higher hydration energies (Supplementary Table 3). The additional stabilization via N−H···N hydrogen bonds further lowered the intercalation barrier for NH4+32,35. These synergistic structural, thermodynamic, and interfacial effects underpinned the preferential NH4+ adsorption of the CuHCF electrode.

To clarify charge compensation, the valence-state evolution of Fe and Cu during cycling was analyzed by XPS. The Fe 2p spectra (Fig. 3d and Supplementary Fig. 10a) exhibited a marked decrease in the Fe(III) fraction from 79.0% to 45.5% after adsorption, accompanied by a corresponding increase in Fe(II) from 21.0% to 54.5%. During desorption, Fe(II) was re-oxidized to Fe(III), with the spectrum returning close to its initial state. The Cu 2p spectra (Fig. 3e and Supplementary Fig. 10b) revealed a decrease in Cu(II) from 56.1% to 46.9% and an increase in Cu(I) from 43.9% to 53.1% upon adsorption, followed by a return to the initial distribution after desorption. The Fe(III)/Fe(II) redistribution showed a larger amplitude ( ~33 percentage points) during the adsorption-desorption cycle than the Cu(II)/Cu(I) variation ( ~9 percentage points). This contrast suggested that the reversible Fe(III)/Fe(II) redox couple dominated charge compensation during the NH4+ intercalation-deintercalation, whereas the accompanying Cu(II)/Cu(I) valence modulation played a secondary role in regulating the local electronic structure36.

A coupled mechanism was proposed for the electrochemically switchable adsorption-desorption process (Fig. 3f). Under negative polarization (voltage of 0.6 V), the CuHCF electrode drove NH4+ migration and intercalation into the open lattice. This was accompanied by dominant reduction of Fe(III) to Fe(II) and secondary Cu(II)/Cu(I) valence modulation, and the formation of stabilizing N−H···N hydrogen bonds. Upon polarity reversal (voltage of −1.5 V), the electrode was oxidized, the hydrogen bonds were disrupted, and NH4+ ions were expelled from the lattice, regenerating the pristine framework. Concurrently, water reduction at the counter electrode produced H2, offering a potential pathway for co-beneficial energy recovery.

Critically, these reversible redox transitions directly modulated the electronic structure of CuHCF, manifesting as intrinsic electrochromism. During NH4+ intercalation under negative polarization (0.6 V), the CuHCF electrode displayed a distinct color change from orange-yellow to dark reddish-brown, whereas reverse polarization ( −1.5 V) restored the original oxidation state and color (Fig. 3g). Corresponding ultraviolet-visible (UV-vis) transmittance map (Fig. 3h) displayed a redshift of the main absorption peak from ~400 to 490 nm during adsorption, followed by a blueshift back to ~400 nm during desorption. This reversible optical modulation was mechanistically linked to the Fe(III)/Fe(II)-dominated redox transition accompanied by Cu(II)/Cu(I) valence modulation, thereby correlating ion intercalation, electron transfer, and color evolution. Such self-indicative color change enabled real-time, reagent-free visualization of adsorption state, providing the fundamental mechanism for intelligent perception and autonomous control in the ECSPR system.

Visual self-perception and predictive modelling

The one-to-one correspondence between NH4+ intercalation and color evolution enabled the electrode to act as an intrinsic optical sensing element. We therefore established a visual self-perception framework (Fig. 4a) that acquired electrode images during continuous-flow operation, extracted colorimetric features via image recognition and mapped them by supervised learning to a quantitative adsorption state (Supplementary Text 2). To evaluate model performance in realistic wastewater, predictive models were trained and validated using datasets collected from adsorption-desorption experiments conducted in actual swine wastewater under controlled imaging conditions.

Fig. 4. Establishment of color recognition and intelligent prediction model.

Fig. 4

a Workflow of color recognition-assisted adsorption modelling and control. The CuHCF electrode region is selected as the region of interest (ROI) for color balance and RGB feature extraction. The dataset is split 80:20 into training and test sets, with ten-fold cross-validation within the training set; machine-learning (ML) models (using random forest as an example) are then trained to predict adsorption states and guide feedback regulation of voltage and flow. b Comparison of final model performance for predicting ammonium adsorption amount using artificial neural network (ANN), gradient boosting regression (GBR), Lasso regression, k-nearest neighbors (KNN), multiple linear regression (MLR), random forest (RF), Ridge regression, support vector regression (SVR) and extreme gradient boosting (XGBoost). Mean absolute error (MAE), root mean square error (RMSE) and coefficient of determination (R2) are used as evaluation metrics. c Prediction performance of the RF model. Source data are provided as a Source Data file.

We benchmarked nine machine learning algorithms, including artificial neural network (ANN), random forest (RF), extreme gradient boosting (XGBoost), gradient boosting regression (GBR), support vector regression (SVR), k-nearest neighbors (KNN), multiple linear regression (MLR), Ridge regression, and Lasso regression (Supplementary Table 4). Ten-fold cross-validation within the training set confirmed that nonlinear models (ANN, RF, XGBoost, GBR, SVR and KNN) generally achieved higher validation accuracy and lower fold-to-fold variation than linear models (MLR, Ridge and Lasso), supporting the robustness of nonlinear color-to-adsorption mapping (Supplementary Fig. 11). As shown in Fig. 4b and Supplementary Fig. 12, compared with linear models (R2 < 0.89, RMSE > 0.20, and MAE > 0.16), nonlinear models consistently achieved higher predictive accuracy, with R2 > 0.97, RMSE < 0.10, and MAE < 0.08 across training and test sets. This confirmed the inherently nonlinear relationship between optical features and adsorption amounts. RF offered the best overall balance of accuracy and generalization, with R2 = 0.9977, RMSE = 0.0314, MAE = 0.0221 on the training set, and R2 = 0.9816, RMSE = 0.0884, MAE = 0.0636 on the test set (Fig. 4c). ANN, GBR, KNN, SVR and XGBoost also performed well, with R2 values on the test set of 0.9838, 0.9755, 0.9802, 0.9810 and 0.9754, respectively, though none surpassed RF in accuracy and stability. Accordingly, the RF model was selected as the final prediction model and integrated as the core state-estimation module into the ECSPR system (Fig. 4a, lower panel).

Feature importance analysis of the RF model identified the highest contribution of G channel (73.5%), followed by R channel (21.3%) and B channel (5.2%) (Supplementary Fig. 13). The feature ranking was consistent with the orange-yellow to dark reddish-brown electrochromic transition, indicating that the model captured a physically meaningful color-adsorption relationship. This intelligent self-perception module enabled non-contact, reagent-free and continuous tracking of electrode state, and supplied quantitative feedback for automatic adjustment of voltage and flow during operation.

System integration for autonomous ammonium recovery and fertilizer production

Building on the visual self-perception framework, we integrated all hardware and software modules into a continuous-flow ECSPR system capable of fully autonomous operation (Fig. 5a and Supplementary Fig. 14). The system comprised a CuHCF electrosorption cell, programmable power supplies, pumps, an imaging module, and a computer-based control unit with a PyQt5 interface. Coded in Python, this interface unified real-time perception, decision-making, and actuation. Specifically, electrode images were processed by the computer vision pipeline and fed to the RF model. The resulting predicted adsorption state served as the decision variable for the control logic, which autonomously triggered voltage switching and flow routing via serial communication according to the discrete-event operation model37 (Supplementary Fig. 15). All process variables were logged continuously, and the architecture supported remote monitoring and cloud-based data processing (Supplementary Fig. 16 and Supplementary Videos 1–3), demonstrating the feasibility of intelligent and distributed operation.

Fig. 5. Construction of the electrochromic self-perception recovery (ECSPR) system and fertilizer product analysis.

Fig. 5

a Schematic of the intelligent continuous-flow ECSPR system integrating power supplies, pumps, an imaging unit, a flow-through reactor and cloud-based data processing. b Nitrogen distribution, and c energy consumption and current efficiency during 10 consecutive ammonium recovery cycles from actual swine wastewater. d Comparison of recovery efficiency and energy consumption with representative electrochemical ammonium recovery technologies listed in Supplementary Table 5. e pH of the recovered liquid product and nitrogen content of the dried solid product. f X-ray diffraction (XRD) pattern of the recovered product. g Tatsoi growth under no fertilizer (control), commercial ammonium sulfate (Comm. AS) and recovered ammonium sulfate (Prod. AS) treatments. h Photographs of harvested plants and leaf biomass and nitrogen content. Error bars in the figures represent the standard deviations (mean ± SD, n = 3) from three independent plant samples. Statistical significance is evaluated by one-way analysis of variance (ANOVA) followed by Tukey’s post hoc test (ns, not significant P > 0.05; **P < 0.01; ***P < 0.001). Source data are provided as a Source Data file.

Autonomous operation was evaluated using 25 mL of actual swine wastewater containing 10.8 mM NH4+ under repeated adsorption-desorption-product collection cycling. During adsorption, wastewater was fed at 1.5 mL min−1 at 0.6 V until the predicted adsorption reached the preset threshold of 2.0 ± 0.1 mmol g−1, followed by reverse pumping at 10 mL min−1 to discharge residual liquid. Desorption was initiated by charging the cell with eluent (25 mM H2SO4 and 25 mM (NH4)2SO4) at 1.5 mL min−1, pausing the pump after filling, and applying −1.5 V. When the predicted value returned to 0 ± 0.1 mmol g−1, the desorption product was withdrawn at 10 mL min−1 and the next cycle began automatically with fresh influent. The closed loop responded within one second, which maintained tight synchronization between perception, decision, and actuation. Across 10 consecutive cycles in actual swine wastewater, the initial NH4+ declined by 92.6%, whereas the coexisting cations showed much lower depletion efficiencies of 37.1% for K+, 23.9% for Na+, 18.2% for Ca2+, and 12.2% for Mg2+ (Supplementary Fig. 17). This suggested selective NH4+ recovery under realistic continuous-flow conditions. Per-cycle recovery decreased from 0.372 to 0.274 mg N as the run progressed, while cumulative recovery reached 3.41 mg N (Fig. 5b). The overall nitrogen balance was 90.2% recovered, 7.4% remaining, and 2.4% lost, demonstrating high capture efficiency in a complex matrix without manual intervention. Such  a small apparent loss should be attributed to residual liquid retained in the tubing and reactor, incomplete collection during flow switching, as well as analytical uncertainty in nitrogen measurement. Specific energy consumption remained 4.42–4.77 kWh kg−1 N for the first five cycles and increased gradually to 6.10 kWh kg−1 N by the tenth cycle (Fig. 5c). Current efficiency showed the opposite trend, exceeding 85% during the early cycles and decreasing to 63.5% in the final cycle. This trend was attributable to reduced NH4+ availability that favored non-target reactions, together with a thickening diffusion boundary layer that increased ohmic and concentration polarization. Averaged across all cycles, the energy demand was 4.9 kWh kg−1 N with an average current efficiency of 78.5%. The average energy demand and recovery efficiency of ECSPR were competitive with those of previously reported electrochemical recovery processes and representative conventional ammonium recovery technologies38–40 (Fig. 5d and Supplementary Table 5). Besides that, ECSPR integrated selective electrosorption, electrochromic self-perception, autonomous closed-loop operation and direct liquid fertilizer production, providing a process-level advantage over conventional open-loop recovery systems.

The desorption effluent served directly as a liquid nitrogen fertilizer candidate with an available nitrogen concentration of approximately 0.14 wt% N (Supplementary Table 6), which represented the net nitrogen level of the collected product after accounting for the initial nitrogen background in the eluent. Although markedly less concentrated than commercial liquid nitrogen fertilizers such as UAN-32 ( ~32 wt% N) or liquid ammonium sulfate ( ~8 wt% N), the recovered solution fell within the typical working range for foliar application (0.1–0.5 wt% N), where dilute formulations were preferred to avoid salt stress and ensure uptake41. The solution was therefore usable without further dilution and could be concentrated or blended to meet distribution specifications. The recovered liquid had a pH of 4.6 (Fig. 5e), comparable to commercial ammonium sulfate formulations (pH 5–6). Following concentration by rotary evaporation, a white crystalline solid was yielded. The nitrogen content of the dried solid was 19.8%, close to the theoretical 21% N of ammonium sulfate (Fig. 5e). XRD identified ammonium sulfate as the dominant phase (JCPDS No. 40-0660), with weak reflections from potassium sulfate implying minor K+ co-recovery which might add nutritional value (Fig. 5f). Given the potential presence of heavy metals in livestock wastewater, we quantified toxic metal elements in the recovered product. Only trace levels of Cu (0.016 mg L−1), Fe (0.080 mg L−1), and Zn (0.003 mg L−1) were detected, while As, Cd, Cr, Pb, and Hg were below detection limits (Supplementary Table 7), which complied with China’s fertilizer safety standard (GB 38400-2019).

To evaluate the fertilizer effectiveness, we performed pot experiments on two leafy vegetables sensitive to nitrogen availability, tatsoi (Brassica rapa subsp. narinosa) and bok choy (Brassica rapa subsp. chinensis), under identical environmental and watering conditions (Supplementary Text 3). Three treatments were compared, i.e., water-sprayed control, commercial ammonium sulfate and recovered liquid fertilizer42, with fertilized plants foliar-sprayed every 10 days using 15 mL of 0.14% N solution. After 40 days, tatsoi grown with both recovered and commercial fertilizer treatments showed dense foliage and robust roots, compared with the control group (Fig. 5g). The number of leaves per plant increased from 6.3 ± 0.6 (control) to 11.0 ± 1.0 (commercial) and 10.3 ± 0.6 (recovered), while the average stem length rose from 6.9 ± 0.4 cm to 11.7 ± 0.5 cm and 12.3 ± 0.6 cm, and the root length from 5.1 ± 0.8 cm to 7.7 ± 0.4 cm and 8.0 ± 0.8 cm, respectively (Supplementary Fig. 18). The average leaf biomass increased from 26.4 ± 3.4 g in the control to 46.2 ± 2.4 g and 46.4 ± 3.5 g in the commercial and recovered groups, and the leaf nitrogen content from 40.2 ± 2.4 mg g−1 to 64.2 ± 3.7 mg g−1 and 61.6 ± 2.4 mg g−1 (Fig. 5h), with no significant difference between the latter two (p > 0.05). Comparable enhancements were observed for bok choy growth (Supplementary Figs. 19 and 20). These results showed that the recovered fertilizer supports biomass accumulation, canopy development and nitrogen assimilation at levels equivalent to commercial ammonium sulfate. To further assess the effects of fertilizer treatments on soil properties, soil pH and heavy metal contents were measured before and after the 40-day tatsoi pot experiment (Supplementary Text 4). The initial soil pH was 6.6, and the final pH values were 6.4, 5.7 and 5.4 for the control, commercial ammonium sulfate and recovered fertilizer treatments, respectively (Supplementary Table 8). The recovered and commercial fertilizers induced comparable slight soil acidification, while the relatively low pH of the recovered fertilizer could help retain ammoniacal nitrogen by reducing ammonia emissions. Furthermore, in the recovered-fertilizer treatment, soil heavy metal contents showed negligible fluctuation ( < 1%) relative to the initial soil background (Supplementary Table 9). Overall, by directly transforming wastewater nitrogen into an effective fertilizer, the ECSPR system established a closed-loop pathway that integrates pollutant removal, resource recovery, and sustainable agricultural use.

Environmental benefits and economic feasibility

The ECSPR system could be envisioned as a modular platform operating at the nexus of wastewater treatment, agriculture, and energy to advance circular nitrogen management. As shown in Fig. 6a, in a practical deployment scenario, ECSPR units could be installed downstream of anaerobic processes to capture ammonium from livestock or industrial wastewater before biological nitrification and convert it into liquid fertilizer for agricultural reuse. This configuration reduced the nitrogen load entering subsequent biological treatment, diverted ammonium from energy-intensive oxidation, and retained downstream processes as polishing steps when needed. To quantify the sustainability benefits of this paradigm shift, scenario-based life-cycle assessment (LCA) and techno-economic analysis (TEA) were conducted for a prospective scaled-up system. We used the treatment of 15 m3 NH4+-containing swine wastewater as the functional unit (FU), and compared the ECSPR system with a conventional anaerobic-oxic (AO) process simulated in BioWin43 (Supplementary Text 5). The ECSPR inventory was derived from mass- and energy-balanced laboratory data and proportionally scaled, which represented a prospective upscaling scenario rather than an engineering demonstration. Detailed assumptions and data sources were provided in Supplementary Text 6.

Fig. 6. Environmental benefits and economic feasibility of the electrochromic self-perception recovery (ECSPR) system.

Fig. 6

a Schematic of the practical application scenarios of the ECSPR system for ammonium-containing wastewater pretreatment, intelligent recovery, product storage and cropland application. b Normalized environmental impacts of the ECSPR and anaerobic-oxic (AO) systems across 18 midpoint impact categories. The AO process is simulated in BioWin, with process and life-cycle inventory (LCI) details in Supplementary Text 5, Supplementary Fig. 20 and Supplementary Table 10. ECSPR scale-up, system boundary and LCI details are provided in Supplementary Text 6, Supplementary Fig. 21 and Supplementary Tables 11–14. Full names, definitions and calculation methods of the categories are provided in Supplementary Text 7 and Supplementary Table 15. c Monetized environmental impacts of the two systems, expressed in Chinese yuan (CNY) per functional unit (FU) using the ChinataxRCP model, as described in Supplementary Text 8 and Supplementary Table 16. d Environmental risk indexes of the ECSPR system, as described in Supplementary Text 8. e Benefit-to-cost ratio (BCR) analysis of the ECSPR system, including capital, electricity, electrode, chemical and other costs, and benefits from environmental monetization, liquid fertilizer recovery and hydrogen production. Assumptions and calculations are provided in Supplementary Text 9 and Supplementary Table 17. Source data are provided as a Source Data file.

Environmental performance was evaluated with ReCiPe 2016 method under cradle-to-grave boundaries (Supplementary Text 7, Supplementary Figs. 21 and 22, and Supplementary Tables 10–15). Positive values denoted burdens and negative values denoted credits from product substitution. Figure 6b and Supplementary Fig. 23 illustrated the LCA results and contributors. The dominant environmental burdens of the ECSPR system arose from electricity and chemical inputs (64.9–97.1%), but these were partially or fully offset by credits from co-produced ammonium sulfate and hydrogen. Compared with the AO process that showed uniformly positive burdens, the ECSPR system delivered substantially lower net impacts, improving 17 of 18 indicators and achieving net-negative outcomes in 11. For global warming potential (GWP), the ECSPR system yielded 1.38 kg CO2 eq per FU, corresponding to ~95% lower than the AO process, which was consistent with the scope of SDG 13 (Climate action). Air quality indicators (SOD, IR, OFHH, OFTE, FPF) declined by 64–168% after product credits were accounted for. For water quality indicators, FEP, MEP, FET and MET declined by 92–554% because nitrogen was retained as fertilizer rather than discharged, while water consumption (WC) was slightly higher than the AO process due to make-up liquids and reagent preparation. This aligned with SDG 6 (Clean water and sanitation) and SDG 14 (Life below water). Soil indicators (TA, TE, LU) fell by 60–136%. Human health indicators (HCT, HNCT) dropped by 165–231%. Resource depletion indicators (MRS, FRS) decreased by a factor of 2.3 to 26, reflecting avoided mining and displacement of fossil-based hydrogen. According to SDG 12 (Responsible consumption and production), technologies that minimize energy and resource consumption while maximizing resource reuse are recommended. Also, the fertilizer product could be directly used for agricultural production, falling within the scope of SDG 2 (Zero Hunger).

Actual deployment entails trade-offs across environmental, economic, and social dimensions, while monetization could provide a solution to integrate all environmental impacts across the life cycle and to enable a normalized evaluation with economic accounting44. We applied a regionalized life-cycle monetization model (ChinataxRCP, Heilongjiang, China)44 to convert grouped indicators (air, water, soil, human health, resource) into externality costs (Supplementary Text 8 and Table 16). The total externality of the ECSPR system equaled −179.8 CNY per FU, markedly lower than 63.9 CNY per FU for AO (Fig. 6c). Negative externalities (credits) were observed in water, soil, human health and resource indicators, and near-zero but lower-than-AO externalities in air. This reflected benefits from avoided fertilizer manufacture and fossil-hydrogen production as well as reduced releases during operation. Further integration of the impacts into environmental-risk indices confirmed the robustness of these trends (Fig. 6d). The ECSPR system fell consistently within the low-to-no-risk zone across environmental compartments, showing the largest benefit in water ( −4.82), followed by soil ( −1.73), human health ( −1.07), and resource stress ( −0.97), whereas presenting a minor positive index in air (0.06). These results confirmed that shifting from pollutant removal to resource recovery fundamentally redistributed environmental burdens and reduced overall risk.

We then integrated the monetized environmental impacts as externality costs into a life-cycle cost framework, alongside capital and operational costs (Supplementary Text 9 and Table 17). Total cost of the ECSPR system was 116.2 CNY per FU, accounting for capital, electricity, electrode replacement, and chemicals (Fig. 6e). This was partly offset by direct revenues (93.8 CNY per FU) from liquid ammonium sulfate fertilizer and hydrogen gas, and more substantially by monetized externality savings (179.8 CNY per FU). Without externality credits, the benefit-to-cost ratio (BCR) fell below 1, reflecting that the current prospective system remained economically unfavorable if only direct market revenues were considered. With credits internalized, it reached a robust BCR of 2.35. These results indicated the transformative potential of externalities caused by their internalization, such as compensating those who have environmental credits and taxing those who cause environmental burdens45. Overall, the ECSPR system was a preferable alternative to the conventional AO process when considering both environmental and economic perspectives.

Discussion

We establish an electrochromic self-perception recovery (ECSPR) system by integrating ammonium-selective intercalation, intrinsic electrochromism and data-driven control, which enables smart ammonium recovery with real-time self-perception rather than fixed, externally supervised operation. By directly linking ammonium intercalation, Fe-dominated redox conversion with secondary Cu valence modulation, and color evolution, the CuHCF electrode functions as both reaction interface and sensing medium. A visual self-perception framework based on computer vision and machine learning interprets adsorption states from electrode images, which serve as the decision variable to schedule adsorption-desorption and flow routing in real time. Unlike conventional electrical feedback, the electrochromic signal provides a material-intrinsic readout of the redox-coupled NH4+ adsorption-desorption state, enabling process decisions to be directly linked to electrode-state evolution. Operating continuously with real swine wastewater, the system autonomously completes adsorption-desorption-product collection cycles in a closed loop, achieving recovery efficiency of 90.2% with average energy consumption of 4.9 kWh kg−1 N. Liquid ammonium sulfate fertilizer is produced directly, with composition and agronomic performance comparable to commercial products. Thus, the ECSPR system shifts electrochemical ammonium recovery from open-loop, time-based operation to a perception-driven, self-regulated, closed-loop module that couples internal material states directly to process decisions, reducing reliance on external sensors and manual intervention.

From a sustainability perspective, this work reconfigures nitrogen management from a linear disposal process into a circular, value-generating practice. By diverting wastewater ammonium from energy-intensive removal pathways (e.g., nitrification-denitrification) to decentralized fertilizer production, it partially displaces Haber-Bosch-derived nitrogen and redefines the role of treatment units in the nitrogen cycle from pollutant removal to resource supply. Life-cycle assessment further shows that, once credits for avoided ammonium sulfate production are accounted for, the ECSPR pathway reduces 17 of the 18 midpoint impacts, including global warming potential, and achieves net-negative outcomes in 11 categories. When the monetized value of these avoided externalities is internalized, the process attains a robust benefit-to-cost ratio and demonstrates economic feasibility. Thus, advancing such circular nitrogen technologies requires fostering policy and market frameworks that internalize their societal benefits, thereby bridging technological innovation with SDGs on climate action, responsible production, clean water, and food security.

There are several limitations and opportunities for further studies. At the electrode material and cell-configuration level, transparent ITO-supported CuHCF films are valuable model electrodes for validating the adsorption-electrochromism relationship, but their adsorption capacity and scalability are limited by thin and planar configuration required for optical interrogation. Future scale-up should transfer electrochromic CuHCF coatings to 3D-structured porous electrodes with larger optically accessible surfaces. A practical route would be a windowed module, in which the CuHCF-coated surface is exposed to a flow channel with an optical window embedded with micro-cameras or optical fibers, while the counter electrode is positioned outside the imaging path or in a separated compartment. Counter electrodes can use large-area, low-polarization and corrosion-resistant materials like dimensionally stable mixed-metal-oxide/titanium electrodes. pH gradients induced by hydrogen or oxygen evolution reaction could be mitigated by using a membrane-separated cell, thereby alleviating the possibility of CuHCF corrosion and preserving ion transport and optical accessibility. At the perception level, transferability of the self-perception model remains a challenge. The current RF model is trained using one source of pretreated swine wastewater under controlled illumination, and the accuracy may decline in realistic wastewater due to turbidity, chromaticity, ionic composition, organic matter, fouling state and complex imaging background. Future work should incorporate multi-modal datasets, embedded color references and periodic calibration. Deep learning models with transfer learning capability, especially when constrained by electrochemical priors such as monotonic adsorption-desorption behavior and electrical signal-capacity relationships, may further improve robustness across variable field conditions. From the viewpoint of SWOT, these limitations are balanced by the strengths of ECSPR in integrating selective ammonium recovery, intrinsic visual self-perception, autonomous closed-loop control and direct fertilizer production. They are further offset by opportunities for decentralized nutrient recovery from livestock wastewater, industrial side streams and other ammonium-containing effluents, particularly as digital water infrastructure and circular-nitrogen policies continue to develop. Therefore, this work provides a proof-of-concept for smart self-perception ammonium recovery, and addressing challenges associated with materials, reactors and algorithms will support the translation of ECSPR into a scalable intelligent module for circular nitrogen management.

Conceptually, the perception-decision-action architecture is not limited to ammonium recovery. By tuning the host lattice chemistry and retraining the recognition model, it can, in principle, be extended to other high-value ions whose uptake couples to redox-coupled electrochromic response. Taken together, the coupling of electrochemical ion intercalation with optical signaling establishes a general design principle for self-regulated resource valorization. Our study suggests a convenient approach for smart, multi-element, self-perception resource recovery modules embedded in digitally monitored wastewater-agriculture management systems, potentially contributing to the development of future circular-economy networks.

Methods

Chemicals and materials

All chemicals were used as received without further purification. Potassium ferricyanide (K3[Fe(CN)6], ≥99.5%), copper sulfate (CuSO4, ≥99.5%), Nafion 115 solution (5 wt%), ammonium chloride (NH4Cl, ≥99.5%), sodium chloride (NaCl, ≥99.5%), potassium chloride (KCl, ≥99.5%), calcium chloride (CaCl2, ≥99%), magnesium chloride (MgCl2, ≥99%), sulfuric acid (H2SO4, 98%), ammonium sulfate ((NH4)2SO4, ≥99.5%), and ethanol ( ≥ 99.9%) were purchased from Sigma-Aldrich Co., Ltd (USA). Ultrapure water (18.2 MΩ cm) from a Milli-Q system was used for all experiments unless noted. Indium tin oxide (ITO)-coated glass substrates (sheet resistance of 7 ~ 10 Ω/sq, thickness of 1 mm) were purchased from Luoyang Shangzhuo Technology Co., Ltd., China.

Synthesis of CuHCF

CuHCF was synthesized using a co-precipitation route. Typically, 50 mL of 5 mM K3[Fe(CN)6] solution and 50 ml of 10 mM CuSO4 solution were added dropwise (0.5 mL min−1 each) into 100 mL of ultrapure water under vigorous stirring at room temperature. The resulting precipitate was collected by vacuum filtration, rinsed repeatedly with ultrapure water and ethanol, and dried overnight.

Electrode fabrication

CuHCF film electrode was prepared through doctor-blade slurry casting. ITO glass substrates were cleaned by sequential ultrasonication in ethanol and ultrapure water, and dried at 60 °C. CuHCF powders were dispersed ultrasonically for 30 min in a mixed solvent of Nafion solution (5 wt%; 1 µL mg−1) and ethanol (1.5 µL mg−1) to form a homogeneous slurry. The slurry was doctor-bladed onto the pre-treated ITO with a wet thickness of 100 µm and dried under ambient conditions, yielding a CuHCF film electrode with a loading of ~1.0 mg cm−2.

Physicochemical characterization

Crystal structures were analyzed by X-ray diffraction (XRD, Bruker D8 ADVANCE, Germany). Morphology and microstructure were examined by transmission electron microscopy (TEM, FEI Talos F200X G2, USA) equipped with energy-dispersive X-ray spectroscopy (EDS). Elemental states were characterized by X-ray photoelectron spectroscopy (XPS, Thermo Scientific K-Alpha, USA). Fourier-transform infrared spectroscopy (FTIR, Thermo Scientific Nicolet iN10, USA) was employed to probe vibrational features. Electrode color evolution was monitored by UV-Vis spectroscopy (Persee TU1901, China) in the range of 300–800 nm.

Electrochemical measurement

Electrochemical tests were performed on a CHI 760E electrochemical workstation (CH Instruments, Inc., China) using a three-electrode system with CuHCF film as working electrode, graphite plate as counter electrode, and Ag/AgCl as reference electrode. All potentials were referenced to the standard hydrogen electrode (SHE) unless otherwise specified. EIS was conducted at open-circuit potential with a perturbation amplitude of 5 mV over a frequency range from 0.01 Hz to 10 MHz. CV was measured in NH4Cl (1 M), NaCl (1 M), KCl (1 M), CaCl2 (0.5 M), MgCl2 (0.5 M), and actual swine wastewater to assess competitive cation intercalation. The potential window was 0.5–1.4 V and the scan rate was 5 mV s−1. GCD measurements were performed in the same electrolytes at a mass-normalized current density of 100 mA g−1.

Experimental setup and operation of the continuous-flow electrosorption system

A hybrid electrosorption cell (Fig. 3a and Supplementary Fig. 8) was assembled using a CuHCF film electrode and a stainless-steel mesh electrode (each 40 × 40 mm), separated by a nonconductive serpentine-flow spacer to maintain electrode spacing (1 mm) and guide fluid distribution. The reactor housing was constructed from quartz glass to enable real-time visualization of the CuHCF electrode. Four side ports were integrated for continuous operation: (i) wastewater influent inlet, (ii) treated-effluent outlet, (iii) desorption-eluent inlet, and (iv) product outlet for recovered solution. For adsorption-desorption cycling tests, only the influent and effluent ports were used to evaluate the electrosorption performance of the CuHCF electrode before introducing color tracking and closed-loop control. The experimental setup consisted of a peristaltic pump (Longer BT100-2J, China), an electrosorption cell, and a DC power supply (HSPY 36-03, China). Unless otherwise specified, adsorption-desorption experiments were conducted using the asymmetric two-electrode configuration in single-pass mode.

During operation, cation intercalation (adsorption) was driven by cathodic polarization of the CuHCF electrode, whereas deintercalation (desorption) was induced by anodic polarization. Adsorption was conducted at constant cell voltages of 0.4–0.8 V (stainless-steel mesh as the positive electrode), and desorption was carried out at voltages of −1.5 to −1.1 V (stainless-steel mesh as the negative electrode). Unless otherwise specified, the influent flow rate was 1.5 mL min−1, and experiments were performed at ambient temperature (25 ± 1 °C). For voltage optimization, single salt solution of 10 mM NH4Cl was treated at the above mentioned voltage range. To assess the selectivity of NH4+ over other cations, the cell was operated with (i) binary salt solutions containing 5 mM NH4Cl and 5 mM of competing cations (e.g., NaCl, KCl, CaCl2, or MgCl2), (ii) a mixed-salt solution containing 2 mM each of NH4Cl, NaCl, KCl, CaCl2 and MgCl2, and (iii) actual swine wastewater. Specifically, the actual wastewater was collected from a swine farm in Harbin, China, pre-filtered through 0.45 μm membrane. The influent contained 10.8 mM NH4+ in the presence of coexisting cations (mainly Na+, K+, Ca2+, and Mg2+), and the detailed composition was summarized in Supplementary Table 1. All selectivity tests were conducted at 0.6 V (adsorption) and −1.5 V (desorption).

Effluent from the electrosorption cell was sampled at predetermined intervals and filtered through a 0.45 µm Nylon membrane. Concentrations of NH4+, Na+, K+, Ca2+ and Mg2+ were quantified by ion chromatography (IC, Thermo Scientific Dionex ICS-2100, USA) and inductively coupled plasma mass spectrometry (ICP-MS, Thermo Fisher iCAP Q, USA). The adsorption performance for ion i was evaluated by the stage-specific adsorption amount (AA, mmol g−1) according to Eq. (1).

AAi=Q∫0t(C0−Ct)dtm 1

where Q (L min−1) is the flow rate, m (g) is the CuHCF mass, C0 and Ct (mM) are the initial and time-dependent concentrations of ion i, respectively, and t (min) is the adsorption duration. When the outlet concentration reached a steady plateau, the corresponding maximum value of AA was taken as the adsorption capacity (AC, mmol g−1). The selectivity coefficient (Si/j) for NH4+ over other cations was derived from Eq. (2).

Si/j=∫0tQ(Ci,0−Ci,t)dt/Ci,0∫0tQ(Cj,0−Cj,t)dt/Cj,0 2

where the numerator and denominator are the ion adsorption amounts of species i and j normalized to their initial concentration. Here, i corresponds to NH4+ and j to other cations (Na+, K+, Ca2+, or Mg2+). A value of Si/j exceeding 1 indicates preferential intercalation of NH4+ into the CuHCF electrode over other competing cations.

In situ imaging and predictive modelling

Images of the CuHCF electrode were recorded every 5 s during adsorption-desorption cycling under controlled illumination, and color features within a fixed region of interest were extracted. These features were synchronized with determined NH4+ adsorption amounts to construct a labelled dataset, which was used to train and evaluate nine machine learning models for color-to-adsorption prediction (ANN, RF, XGBoost, GBR, SVR, KNN, MLR, Ridge and Lasso). The dataset contained 654 data pairs, which were randomly divided into training and test subsets at an 80:20 ratio. 10-fold cross-validation was applied to the training set for model validation. Model performance was assessed by R2, root mean square error (RMSE) and mean absolute error (MAE). RF-based feature importance was calculated to identify the contribution of RGB descriptors to adsorption-state prediction. Details of the imaging conditions, image preprocessing, dataset preparation, model configuration, and feature-importance analysis were provided in Supplementary Text 2 and Table 4.

Autonomous ammonium recovery with closed-loop control

Closed-loop control was implemented through a self-developed program based on Python 3.10, enabling autonomous ammonium recovery. The framework integrated the image-based predictive model with serial communication linking two power supplies, three peristaltic pumps, and a control unit (Fig. 5a). In situ electrode images acquired every 5 s were converted into predicted ammonium adsorption amounts, serving as real-time control signals for system logic that autonomously switched among adsorption, desorption, and product collection. A graphical user interface (GUI) was developed using PyQt5 to enable real-time monitoring, data logging with cloud storage, remote control, and safety alarms.

During closed-loop operation, 25 mL of actual swine wastewater was processed through repeated adsorption, desorption, and product recovery cycles (n = 10). In the adsorption phase, wastewater was continuously fed at 1.5 mL min−1 (Pump 1) under 0.6 V (Power supply 1), with the effluent recirculated to the influent reservoir. When the predictive model indicated saturation (2.0 mmol g−1), the controller reversed Pump 1 at 10 mL min−1 to remove residual liquid. Desorption eluent (25 mM H2SO4 and 25 mM (NH4)2SO4) was then supplied at 1.5 mL min−1 (Pump 2) to fill the reactor, after which Pump 2 was stopped and −1.5 V was applied (Power Supply 2) to initiate desorption. The background eluent was used to provide conductivity and product matrix, and was subtracted as the initial nitrogen background when calculating the net recovered nitrogen and recovery efficiency. Desorption ended when the predicted adsorption returned to baseline, and the recovered product was withdrawn at 10 mL min−1 (Pump 3). The system then automatically restarted the next cycle with wastewater influent. All process variables (voltage, current, flow rate, flow direction, and predicted adsorption) were logged continuously. The recovery efficiency (ηrec, %), specific energy consumption (SEC, kWh kg−1 N), and current efficiency (CE, %) over the 10-cycle run were calculated using Eqs. (3–5).

ηrec=∑k=1n(Cprod,k−Celu)Vprod,kCfeedVfeed×100% 3
SEC=∑k=1n∫0tads,kUads,kIads,kdt+∫0tdes,kUdes,kIdes,kdt3.6∑k=1n(Cprod,k−Celu)Vprod,kMN 4
CE=zF∑k=1n(Cprod,k−Celu)Vprod,k×10−3∑k=1n(∫0tads,kIads,kdt+∫0tdes,kIdes,kdt)×100% 5

where n (10) is the number of cycles, Cprod,k (mM) is the ammonium concentration in the recovered product of cycle k, Celu (mM) is the background concentration in the eluent, Vprod,k (L) is the recovered product volume, Cfeed (mM) is the initial influent ammonium concentration, Vfeed (L) is the influent volume, Uads,k (V) and Udes,k (V) are the applied voltages, Iads,k (A) and Ides,k (A) are the current responses, tads,k (s) and tdes,k (s) are the operation times of adsorption and desorption in cycle k, MN (14 g mol−1) is the molar mass of N, z (2) is the charge number, and F (96485 C mol−1) is the Faraday constant.

Product characterization and fertilizer effectiveness evaluation

The recovered liquid fertilizer was analyzed to determine its composition and suitability for agricultural use. pH was measured with a calibrated pH meter (DZS-708T-A, China). Heavy metals (Hg, As, Cd, Cr, Cu, Fe, Pb, and Zn) were quantified by ICP-MS for comparison with agricultural safety guidelines. To confirm crystalline composition, the liquid product was concentrated to dryness by rotary evaporation (LC-RE-52AA, China), and the solid was examined by XRD. Total nitrogen content of solid samples was measured using an elemental analyzer (elementar Vario EL cube, Germany). Fertilizer effectiveness was evaluated in pot experiments using two leafy vegetables that are sensitive to nitrogen availability, i.e., tatsoi (Brassica rapa subsp. narinosa) and bok choy (Brassica rapa subsp. chinensis), provided in Supplementary Text 3. Soil pH and heavy-metal contents before and after the pot experiment were also measured, with detailed procedures provided in Supplementary Text 4.

Life-cycle assessment, environmental monetization and techno-economic analysis

Life-cycle assessment (LCA) was performed to compare the environmental impacts of the ECSPR system with a conventional AO wastewater treatment process. The FU was defined as the treatment of 15 m3 of ammonium-containing swine wastewater. The AO inventory was constructed from BioWin steady-state simulation outputs, whereas the ECSPR inventory was based on laboratory performance data upscaled to the same FU. LCA was conducted using SimaPro 9.4 with the ReCiPe 2016 midpoint (H) method under a cradle-to-grave system boundary. Detailed inventory data, system boundaries, indicator definitions and calculation procedures are provided in Supplementary Texts 5–7, Supplementary Figs. 21 and 22, and Supplementary Tables 10–15.

Environmental externalities were monetized using the regionalized life-cycle monetization model ChinataxRCP with factors for Heilongjiang province, China. Characterized midpoint results were converted into Chinese yuan (CNY) per FU and grouped into air-, water-, soil-, human health- and resource-related indicators. Environmental risk indexes were derived from the monetized results. Monetization factors and risk-index calculations are provided in Supplementary Text 8 and Supplementary Table 16.

Techno-economic analysis (TEA) was conducted using the same FU and included annualized capital expenditure, operating expenditure, product revenues from recovered liquid ammonium sulfate fertilizer and hydrogen gas, and monetized environmental externalities. The benefit-to-cost ratio (BCR) was calculated by comparing product revenue and environmental credits with annualized capital and operating costs. Detailed assumptions, unit prices and BCR calculations are provided in Supplementary Text 9 and Supplementary Table 17.

Reporting summary

Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.

Supplementary information

41467_2026_76968_MOESM2_ESM.pdf (173.4KB, pdf)

Description of Additional Supplementary Files

Supplementary Video 1 (28.6MB, mp4)
Supplementary Video 2 (28.1MB, mp4)
Supplementary Video 3 (28.7MB, mp4)
Reporting Summary (1.4MB, pdf)

Source data

Source data (4.6MB, xlsx)

Author contributions

S.Y. conceived the research project and supervised the work. R.W. designed and carried out the experiments, performed the modelling, analyzed the results, and wrote the original draft of the paper. R.W. and P.X. performed the LCA and TEA. Y.L., C.Z. and N.R. provided suggestions on the experimental results and discussion. S.Y. and Y.L. validated the results and reviewed and edited the paper.

Peer review

Peer review information

Nature Communications thanks Taeyoung Kim, and the other, anonymous, reviewer(s) for their contribution to the peer review of this work. A peer review file is available.

Funding

This work is supported by the Fundamental and Interdisciplinary Disciplines Breakthrough Plan of the Ministry of Education of China (Grant No. JYB2025XDXM906), the National Natural Science Foundation of China (Grant No. 52325003, U25A20365, W2412093), the China Postdoctoral Science Foundation (Grant No. 2025M781164), and the Postdoctoral Fellowship Program of CPSF (Grant No. GZB20250944), State Key Laboratory of Urban-rural Water Resources and Environment (Harbin Institute of Technology) (No. 2026DX06).

Data availability

The data supporting the conclusions of this study are presented in the paper and the supplementary information. Source data are provided with this paper.

Code availability

All associated project codes in Python for electrode image preprocessing and machine learning model training and evaluation are available in the CodeOcean capsule https://doi.org/10.24433/CO.8488874.v1.

Competing interests

The authors declare no competing interests.

Footnotes

Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

Contributor Information

Yanbiao Liu, Email: yanbiaoliu@dlut.edu.cn.

Shijie You, Email: sjyou@hit.edu.cn.

Supplementary information

The online version contains supplementary material available at https://doi.org/10.1038/s41467-026-76968-5.

References

  • 1.MacFarlane, D. R. et al. A roadmap to the ammonia economy. Joule4, 1186–1205 (2020). [Google Scholar]
  • 2.Mingolla, S. & Rosa, L. Low-carbon ammonia production is essential for resilient and sustainable agriculture. Nat. Food6, 610–621 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 3.Zhang, Q. et al. Solar-driven efficient and selective ammonia recovery from ammonium-containing wastewater. Nat. Sustain.8, 1058–1067 (2025). [Google Scholar]
  • 4.Smith, C., Hill, A. K. & Torrente-Murciano, L. Current and future role of Haber-Bosch ammonia in a carbon-free energy landscape. Energy Environ. Sci.13, 331–344 (2020). [Google Scholar]
  • 5.Schulte-Uebbing, L. F., Beusen, A. H. W., Bouwman, A. F. & de Vries, W. From planetary to regional boundaries for agricultural nitrogen pollution. Nature610, 507–512 (2022). [DOI] [PubMed] [Google Scholar]
  • 6.Yao, F. et al. Electrochemically selective ammonium recovery from wastewater via coupling hydrogen bonding and charge storage. Water Res. 251, 121114 (2024). [DOI] [PubMed] [Google Scholar]
  • 7.Galloway, J. N. et al. Transformation of the nitrogen cycle: recent trends, questions, and potential solutions. Science320, 889–892 (2008). [DOI] [PubMed] [Google Scholar]
  • 8.Yu, C. et al. Managing nitrogen to restore water quality in China. Nature567, 516–520 (2019). [DOI] [PubMed] [Google Scholar]
  • 9.United Nations. Transforming our world: The 2030 agenda for sustainable development. (United Nations, 2015). https://sdgs.un.org/publications/transforming-our-world-2030-agenda-sustainable-development-17981?
  • 10.Chen, C. et al. Donnan dialysis-osmotic distillation (DD-OD) hybrid process for selective ammonium recovery driven by waste alkali. Environ. Sci. Technol.55, 7015–7024 (2021). [DOI] [PubMed] [Google Scholar]
  • 11.Farghali, M. et al. Strategies for ammonia recovery from wastewater: a review. Environ. Chem. Lett.22, 2699–2751 (2024). [Google Scholar]
  • 12.Arges, C. G. et al. Current developments in electrochemical separations. Nat. Chem. Eng.2, 524–528 (2025). [Google Scholar]
  • 13.Alkhadra, M. A. et al. Electrochemical methods for water purification, ion separations, and energy conversion. Chem. Rev.122, 13547–13635 (2022). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 14.Liu, D. et al. Electrochemical ammonia recovery from wastewater: the critical roles of electrode engineering toward scale-up. Water Res.288, 124708 (2026). [DOI] [PubMed] [Google Scholar]
  • 15.He, X. et al. Enhanced NH4+ removal and recovery from wastewater using Na-zeolite-based flow-electrode capacitive deionization: Insight from ion transport flux. Environ. Sci. Technol.57, 8828–8838 (2023). [DOI] [PubMed] [Google Scholar]
  • 16.Fleischmann, S. et al. Pseudocapacitance: From fundamental understanding to high power energy storage materials. Chem. Rev.120, 6738–6782 (2020). [DOI] [PubMed] [Google Scholar]
  • 17.Cho, K.-H., Chen, C.-Y., Aguda, A., Fournier, M. J. & Su, X. Toward sustainable electrochemically mediated separations driven by renewable energy. Joule8, 3259–3280 (2024). [Google Scholar]
  • 18.Zhang, Z. et al. Pushing the limit of layered transition metal oxides with heterolattice oxygen-mediated redox for capacitive deionization. Nat. Commun.16, 3652 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 19.Wang, R. et al. Electrochemical ammonia recovery and co-production of chemicals from manure wastewater. Nat. Sustain.7, 179–190 (2024). [Google Scholar]
  • 20.Wang, F. et al. Modular electrochemical synthesis using a redox reservoir paired with independent half-reactions. Joule5, 149–165 (2021). [Google Scholar]
  • 21.Liu, W., Xu, L. & Lin, S. Principles for optimal electrode design and operation for desalination with electrochemical ion pumping. Environ. Sci. Technol.60, 7544–7554 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 22.Candeago, R. et al. Unraveling the role of solvation and ion valency on redox-mediated electrosorption through in situ neutron reflectometry and Ab initio molecular dynamics. JACS Au4, 919–929 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 23.Gu, C., Jia, A.-B., Zhang, Y.-M. & Zhang, S. X.-A. Emerging electrochromic materials and devices for future displays. Chem. Rev.122, 14679–14721 (2022). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 24.Wu, C. et al. High-performance complementary electrochromic batteries using Nb18W16O93 by the synergistic effects of aqueous Al3+/K+ dual-ion. Angew. Chem. Int. Ed.64, e202415050 (2024). [DOI] [PubMed] [Google Scholar]
  • 25.Yin, L. et al. A stretchable epidermal sweat sensing platform with an integrated printed battery and electrochromic display. Nat. Electron.5, 694–705 (2022). [Google Scholar]
  • 26.Chen, W., Akinyemi, P. & Kim, T. Selective separation of ammonium from wastewater using ion conducting channels of a Prussian blue analogue. Environ. Sci. Technol. Lett.11, 280–286 (2024). [Google Scholar]
  • 27.Liang, G. et al. Initiating hexagonal MoO3 for superb-stable and fast NH4+ storage based on hydrogen bond chemistry. Adv. Mater.32, e1907802 (2020). [DOI] [PubMed] [Google Scholar]
  • 28.Tsai, S. W., Cuong, D. V. & Hou, C. H. Selective capture of ammonium ions from municipal wastewater treatment plant effluent with a nickel hexacyanoferrate electrode. Water Res. 221, 118786 (2022). [DOI] [PubMed] [Google Scholar]
  • 29.Wei, R. et al. Self-reporting electroswitchable colorimetric platform for smart ammonium recovery from wastewater. Water Res.258, 121789 (2024). [DOI] [PubMed] [Google Scholar]
  • 30.Gao, R., Bonin, L., Arroyo, J. M. C., Logan, B. E. & Rabaey, K. Separation and recovery of ammonium from industrial wastewater containing methanol using copper hexacyanoferrate (CuHCF) electrodes. Water Res. 188, 116532 (2021). [DOI] [PubMed] [Google Scholar]
  • 31.Zhao, L. et al. Prussian blue analogues for advanced non-aqueous sodium ion batteries: Redox mechanisms, key challenges and modification strategies. Energy Storage Mater.78, 104256 (2025). [Google Scholar]
  • 32.Zhang, X. et al. Hydrogen bond-assisted ultra-stable and fast aqueous NH4+ storage. Nano-micro Lett.13, 139 (2021). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 33.Kim, T., Gorski, C. A. & Logan, B. E. Ammonium removal from domestic wastewater using selective battery electrodes. Environ. Sci. Technol. Lett.5, 578–583 (2018). [Google Scholar]
  • 34.Tansel, B. Significance of thermodynamic and physical characteristics on permeation of ions during membrane separation: Hydrated radius, hydration free energy and viscous effects. Sep. Purif. Technol.86, 119–126 (2012). [Google Scholar]
  • 35.Tian, Z. et al. High-capacity NH4+ charge storage in covalent organic frameworks. J. Am. Chem. Soc.143, 19178–19186 (2021). [DOI] [PubMed] [Google Scholar]
  • 36.Xu, Y. et al. Dual redox-active copper hexacyanoferrate nanosheets as cathode materials for advanced sodium-ion batteries. Energy Storage Mater.33, 432–441 (2020). [Google Scholar]
  • 37.Bemporad, A. & Morari, M. Control of systems integrating logic, dynamics, and constraints. Automatica35, 407–427 (1999). [Google Scholar]
  • 38.Li, Y. et al. Bipolar membrane electrodialysis for ammonia recovery from synthetic urine: Experiments, modeling, and performance analysis. Environ. Sci. Technol.55, 14886–14896 (2021). [DOI] [PubMed] [Google Scholar]
  • 39.Kogler, A., Gong, M., Williams, K. S. & Tarpeh, W. A. Flexible electrochemical stripping for wastewater ammonia recovery with on-demand product tunability. Environ. Sci. Technol. Lett.11, 886–894 (2024). [Google Scholar]
  • 40.He, J. et al. Pulsed electric field drives chemical-free membrane stripping for high ammonia recovery from urine. Water Res. 251, 121129 (2024). [DOI] [PubMed] [Google Scholar]
  • 41.Liu, M.-Y. et al. Foliar N application on tea plant at its dormancy stage increases the N concentration of mature leaves and improves the quality and yield of spring tea. Front. Plant Sci.12, 753086 (2021). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 42.Rodrigues, M. et al. Application of ammonium fertilizers recovered by an electrochemical system. Resour. Conserv. Recycl.181, 106225 (2022). [Google Scholar]
  • 43.Bisinella de Faria, A. B., Spérandio, M., Ahmadi, A. & Tiruta-Barna, L. Evaluation of new alternatives in wastewater treatment plants based on dynamic modelling and life cycle assessment (DM-LCA). Water Res. 84, 99–111 (2015). [DOI] [PubMed] [Google Scholar]
  • 44.Liu, F. et al. Regionalized life-cycle monetization can support the transition to sustainable rural food waste management in China. Nat. Food4, 797–809 (2023). [DOI] [PubMed] [Google Scholar]
  • 45.Liu, B. & Rajagopal, D. Life-cycle energy and climate benefits of energy recovery from wastes and biomass residues in the United States. Nat. Energy4, 700–708 (2019). [Google Scholar]

Associated Data

This section collects any data citations, data availability statements, or supplementary materials included in this article.

Supplementary Materials

41467_2026_76968_MOESM2_ESM.pdf (173.4KB, pdf)

Description of Additional Supplementary Files

Supplementary Video 1 (28.6MB, mp4)
Supplementary Video 2 (28.1MB, mp4)
Supplementary Video 3 (28.7MB, mp4)
Reporting Summary (1.4MB, pdf)
Source data (4.6MB, xlsx)

Data Availability Statement

The data supporting the conclusions of this study are presented in the paper and the supplementary information. Source data are provided with this paper.

All associated project codes in Python for electrode image preprocessing and machine learning model training and evaluation are available in the CodeOcean capsule https://doi.org/10.24433/CO.8488874.v1.


Articles from Nature Communications are provided here courtesy of Nature Publishing Group

RESOURCES