{ "cells": [ { "cell_type": "markdown", "id": "example-introduction", "metadata": {}, "source": [ "# Example: one year of enhanced weathering\n", "\n", "\n", "## Choose the solver\n", "\n", "Set `NUMBA_DISABLE_JIT` **before importing SMEW or Numba**: `\"1\"` uses Python and SciPy; `\"0\"` uses Numba, Cython equations and the bundled cminpack solver.\n", "The compiled mode requires native extensions, included when `pip install smew` installs a prebuilt wheel from PyPI. The first run in each Python session also includes Numba compilation time.\n", "After changing the mode, **restart the kernel and run all cells**. The documentation runs a copy of this notebook and never saves results back to the original." ] }, { "cell_type": "code", "execution_count": null, "id": "415d234c", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:12:10.878786166Z", "start_time": "2026-11-03T10:12:09.868222200Z" } }, "outputs": [], "source": [ "import os\n", "\n", "# uncomment to use the Python/SciPy version\n", "# os.environ[\"NUMBA_DISABLE_JIT\"] = \"1\" # \"1\": Python/SciPy; \"0\": Numba/Cython/cminpack\n", "\n", "%matplotlib inline\n", "import time; start_time = time.time()\n", "import smew\n", "import matplotlib.pyplot as plt\n", "import matplotlib.gridspec as gridspec\n", "import matplotlib as mpl\n", "from matplotlib import rc\n", "import numpy as np\n", "\n", "\n", "# Prefer Arial, with Liberation Sans and DejaVu Sans as fallbacks.\n", "rc('font', family='sans-serif',\n", " **{'sans-serif': ['Arial', 'Liberation Sans', 'DejaVu Sans']})\n", "mpl.rcParams['axes.linewidth'] = 0.5" ] }, { "cell_type": "markdown", "id": "d53c1261740624a7", "metadata": {}, "source": [ "## Time grid and units" ] }, { "cell_type": "code", "execution_count": null, "id": "1e1e93ca1d79f2a", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:12:10.918104571Z", "start_time": "2026-11-03T10:12:10.902383620Z" } }, "outputs": [], "source": [ "# time \n", "t_end = 1*365 # [d]: number of simulated days\n", "dt = 1/(24*6) # [time resolution (d)]\n", "t=np.arange(0,t_end,dt)\n", "\n", "#units\n", "conv_mol = 1e6 # Conversion from moles to micromols \n", "conv_Al = 1e3 # Conversion for Al species from mols to nanomols\n", "\n", "#water balance\n", "keyword_wb = 1 # 1 = varying soil moisture. 0 = constant soil moisture\n", "\n", "#background inputs of cations and anions\n", "keyword_add = 1 # 1 = balance background losses. 0 = no addition" ] }, { "cell_type": "markdown", "id": "example-water", "metadata": {}, "source": [ "## Weather, vegetation and water balance" ] }, { "cell_type": "code", "execution_count": null, "id": "c16bdf33", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:12:16.159458047Z", "start_time": "2026-11-03T10:12:10.920181304Z" } }, "outputs": [], "source": [ "# HYDROCLIMATE AND WATER BALANCE\n", "\n", "#soil \n", "soil = \"loam\" #sand, loamy sand, sandy loam, loam, clay loam, clay\n", "Zr = 0.3 # [m]: soil depth\n", "rho_bulk = 1.2*1e6 #soil dry mass (g/m3)\n", "s_in = 0.5\n", "\n", "#hydroclimatic\n", "day1 = 1 #initial DOY\n", "latitude = 40*np.pi/180 # [radians]\n", "albedo = 0.25\n", "altitude = 33 #[m]\n", "wind = 1*np.ones(len(t)) #[m/s]\n", "coastal = False \n", "temp_av = 13 # [°C] yearly average\n", "temp_ampl_yr= 11 # [°C] yearly amplitude\n", "temp_ampl_d= 5 # [°C] daily amplitude\n", "\n", "#temp [Celsius]\n", "[temp_air,temp_soil,temp_min,temp_max] = smew.temp(latitude,temp_av, temp_ampl_yr, temp_ampl_d, Zr,t_end,dt,day1)\n", "\n", "#ET0 [m/d]\n", "ET0 = smew.ET0(latitude,altitude,temp_air,temp_soil,temp_min,temp_max, wind,albedo,Zr,coastal,t_end,dt,day1)\n", "\n", "#deterministic rain [m]\n", "# Rain_yr = 0.8 # [m]: yearly rain\n", "# t_rain = 7 #[d]: between rain event\n", "# rain = np.zeros(len(t))\n", "# j = 1\n", "# while j < len(rain):\n", "# rain[j] = Rain_yr/(365/t_rain)\n", "# j = j+int(t_rain/dt)\n", "\n", "#stochastic rain [m]\n", "R_tot = 1.2 # [m/yr]\n", "lamda = 0.25 # [d^(-1)]: average rain frequency \n", "alfa = (R_tot/lamda)/365 # [m]: average rain depth \n", "np.random.seed(0) # Reproducible rainfall with JIT disabled\n", "rain =smew.rain_stoc(lamda, alfa, t_end, dt)\n", "\n", "#stochastic rain with seasonality [m] (only works with multi-year)\n", "#lamda = np.array([0.47, 0.47, 0.4, 0.3, 0.18, 0.11, 0.04, 0.08, 0.28, 0.37, 0.45, 0.45]) # [d^(-1)]: average rain frequency \n", "#alfa = 10**(-3)*np.array([15, 15, 15, 13, 8, 12, 14, 19, 18, 18, 16, 15]) # [mm converted to m]: average rain depth \n", "#rain =smew.rain_stoc_season(lamda, alfa, t_end, dt)\n", "\n", "#vegetation [g/m2]\n", "T_v = 100 # [d] growth time\n", "k_v = 3000 # [g/m2] carrying capacity\n", "RAI = 10 #[m2/m2] root area index\n", "root_d = 0.4*1e-3 #[m] average root diameter\n", "v_in = 1*k_v # [g/m2] ic\n", "t0_v = 0 # [d] starting day of growth\n", "v = smew.veg(v_in, T_v, k_v, t0_v, temp_soil, dt)\n", "\n", "#moisture balance (I, Q [m], L, T, E [m/d])\n", "[s, s_w, s_i, I, L, T, E, Q, Irr, n] = smew.moisture_balance(rain, Zr, soil, ET0, v, k_v, keyword_wb, s_in,t_end,dt)\n", "\n", "#Temp\n", "fig, ax1 = plt.subplots()\n", "color = 'tab:red'\n", "ax1.set_xlabel('t (d)')\n", "ax1.set_ylabel('Temp (°C)', color=color)\n", "ax1.plot(t, temp_soil, color=color)\n", "ax1.tick_params(axis='y', labelcolor=color)\n", "\n", "#moisture\n", "ax2 = ax1.twinx()\n", "color = 'tab:blue'\n", "ax2.set_ylabel('s(-)', color=color)\n", "ax2.plot(t, s, color=color)\n", "ax2.tick_params(axis='y', labelcolor=color)\n", "\n", "# rainfall\n", "ax3 = ax1.twinx()\n", "color = 'tab:green'\n", "ax3.set_ylabel('Rain (mm)', color=color)\n", "ax3.plot(t, rain*1e3, color=color) # Note the swapping of x and y data\n", "ax3.tick_params(axis='y', labelcolor=color)\n", "ax3.spines['right'].set_position(('outward', 55))\n", "fig.tight_layout()\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "example-carbon", "metadata": {}, "source": [ "## Organic carbon and respiration" ] }, { "cell_type": "code", "execution_count": null, "id": "5d4a8d6c", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:12:24.858102239Z", "start_time": "2026-11-03T10:12:16.201364034Z" } }, "outputs": [], "source": [ "# ORGANIC CARBON and RESPIRATION\n", "CO2_atm = smew.CO2_atm(conv_mol)\n", "\n", "#initial pCO2\n", "CO2_air_in = 10*CO2_atm # CO2 in soil air [mol-conv/l] \n", "ratio_aut_het = 1\n", "\n", "#Initial organic carbon\n", "ADD = 1 # added dry litter [gOC/(m2*d)]\n", "SOC_perc = 0.05 # [%]\n", "SOC_in = rho_bulk*SOC_perc/100 #[gOC/m3] \n", "\n", "#SOC balance and respiration\n", "[SOC, r_het, r_aut, D] = smew.respiration(ADD, SOC_in, CO2_air_in, ratio_aut_het, soil, s, v, k_v, Zr, temp_soil,dt,conv_mol)\n", "\n", "# Create a figure and subplots\n", "fig, axs = plt.subplots(2, 1,figsize=(9, 2))\n", "\n", "# Plot the quantities in each subplot\n", "axs[0].plot(t,100*SOC/(rho_bulk),label='crop')\n", "axs[0].set_xticklabels([])\n", "axs[0].set_ylabel('SOC [%]')\n", "axs[1].plot(t, r_het/conv_mol, label = 'resp het')\n", "axs[1].plot(t, (r_het+r_aut)/conv_mol, label = 'resp aut')\n", "axs[1].fill_between(t, r_het/conv_mol, 0, alpha=0.5)\n", "axs[1].fill_between(t, (r_het+r_aut)/conv_mol, r_het/conv_mol,alpha=0.5)\n", "axs[1].legend()\n", "axs[1].set_ylabel('resp [mol/ m2 d]')\n", "\n", "# Display the combined graph\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "example-chemistry", "metadata": {}, "source": [ "## Initial chemistry and rock application" ] }, { "cell_type": "code", "execution_count": null, "id": "7bd46fe1", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:14:39.391842833Z", "start_time": "2026-11-03T10:12:24.903419619Z" } }, "outputs": [], "source": [ "# SOIL BIOGEOCHEMISTRY\n", "\n", "#initial pH\n", "pH_in = 4\n", "\n", "#CEC \n", "CEC_tot = 10 # [mmol_c / 100 g dry-soil] \n", "CEC_tot = CEC_tot*1e-5*rho_bulk*Zr*conv_mol # [mol_c] \n", "\n", "#CEC fractions\n", "f_Ca_in = 0.3\n", "f_Mg_in = 0.15\n", "f_K_in = 0.1\n", "f_Na_in = 0.05\n", "f_Al_in = 0\n", "f_H_in = 0.4\n", "\n", "f_CEC_in = np.array([f_Ca_in, f_Mg_in, f_K_in, f_Na_in, f_Al_in, f_H_in]) \n", "if abs(sum(f_CEC_in)-1) > 1e-3:\n", " raise ValueError(\"Sum of fractions must be 1\")\n", " \n", "#carbonates\n", "CaCO3_in = 0\n", "MgCO3_in = 0\n", "\n", "#conc water\n", "Si_in = 0 \n", "[conc_in, K_CEC] = smew.f_CEC_to_conc(f_CEC_in, pH_in, soil, conv_mol,conv_Al)\n", " \n", "#EW application\n", "M_rock_in = 1000 # [g/m2] of added rock powder\n", "mineral = [\"forsterite\"] \n", "rock_f_in = np.array([1]) # mineral fractions\n", "diss_f = 1 # dissolution factor\n", "d_in = np.array([100])*1e-6 # [m]: diameter classes\n", "psd_perc_in = np.array([1]) # diameter class weight (%)\n", "SSA_in = np.nan # [m2/g]: either measured value or nan to estimate it\n", "t_app = 0 # day of application\n", "\n", "data = smew.biogeochem_balance(n, s, L, T, I, v, k_v, RAI, root_d, Zr, r_het, r_aut, D, temp_soil, pH_in, conc_in, f_CEC_in, K_CEC, CEC_tot, Si_in, CaCO3_in, MgCO3_in, M_rock_in, t_app, mineral, rock_f_in, d_in, psd_perc_in, SSA_in, diss_f, dt, conv_Al, conv_mol, keyword_add)\n", "\n", "print(\"Solver status counts (indices 0–5):\", data[\"solver_status_counts\"])" ] }, { "cell_type": "markdown", "id": "example-results", "metadata": {}, "source": [ "## Output" ] }, { "cell_type": "code", "execution_count": null, "id": "025a3797", "metadata": { "ExecuteTime": { "end_time": "2026-11-03T10:14:43.354387593Z", "start_time": "2026-11-03T10:14:39.419751603Z" } }, "outputs": [], "source": [ "# Create a figure and subplots\n", "fig = plt.figure(figsize=(10,8))\n", "gs = gridspec.GridSpec(3, 2)\n", "\n", "#--------------------------------------------------------------------------------\n", "# First panel - Hydroclimatic\n", "#--------------------------------------------------------------------------------\n", "\n", "axs1 = plt.subplot(gs[0, :])\n", "\n", "#Temp\n", "color = 'tab:red'\n", "axs1.set_xlabel('t (d)')\n", "axs1.set_ylabel('Temp (°C)', color=color)\n", "axs1.plot(t, temp_soil, color=color)\n", "axs1.tick_params(axis='y', labelcolor=color)\n", "\n", "# rainfall\n", "ax2 = axs1.twinx()\n", "color = 'tab:green'\n", "ax2.set_ylabel('Rain (mm)', color=color)\n", "ax2.plot(t, rain*1e3, color=color) # Note the swapping of x and y data\n", "ax2.tick_params(axis='y', labelcolor=color)\n", "\n", "#moisture\n", "ax3 = axs1.twinx()\n", "color = 'tab:blue'\n", "ax3.set_ylabel('s (-)', color=color)\n", "ax3.plot(t, s, color=color)\n", "ax3.tick_params(axis='y', labelcolor=color)\n", "ax3.spines['right'].set_position(('outward', 40))\n", "\n", "#--------------------------------------------------------------------------------\n", "# Second panel - pH and Alk\n", "#--------------------------------------------------------------------------------\n", "\n", "axs2 = plt.subplot(gs[1, 0])\n", "\n", "#pH\n", "color = 'tab:red'\n", "axs2.set_xlabel('t (d)')\n", "axs2.set_ylabel('pH', color=color)\n", "axs2.plot(t, data['pH'], color=color)\n", "axs2.tick_params(axis='y', labelcolor=color)\n", "\n", "# Alk\n", "ax2 = axs2.twinx()\n", "color = 'tab:blue'\n", "ax2.set_ylabel('[Alk] ($\\\\mu$mol/l)', color=color)\n", "ax2.plot(t, data['Alk'], color=color)\n", "ax2.tick_params(axis='y', labelcolor=color)\n", "#axs2.set_xticklabels([])\n", "\n", "#--------------------------------------------------------------------------------\n", "# Third panel - IC\n", "#--------------------------------------------------------------------------------\n", "\n", "axs3 = plt.subplot(gs[1, 1])\n", "\n", "cumulative_sum = 0\n", "i = 0\n", "labels = ['[CO$_3^{2-}$]', '[HCO$_3^{-}$]', '[CO$_2]_\\\\mathrm{w}$', '[CO$_2]_\\\\mathrm{a}$']\n", "for element in ['CO3', 'HCO3', 'CO2_w', 'CO2_air']:\n", " axs3.plot(t, data[element] + cumulative_sum, label=labels[i])\n", " axs3.fill_between(t, cumulative_sum, cumulative_sum + data[element], alpha=0.5)\n", " i = i + 1\n", " cumulative_sum += data[element]\n", " \n", "axs3.set_ylabel('$\\\\mu$mol/l')\n", "axs3.set_xlabel('t(d)')\n", "#axs3.set_xticklabels([])\n", "axs3.yaxis.tick_right()\n", "axs3.yaxis.set_label_position(\"right\") \n", "axs3.legend()\n", "\n", "#--------------------------------------------------------------------------------\n", "# Forth panel - Weathering\n", "#--------------------------------------------------------------------------------\n", "\n", "axs4 = plt.subplot(gs[2, 0])\n", "\n", "color = 'tab:red'\n", "axs4.set_xlabel('t (d)')\n", "axs4.set_ylabel('Rock mass (kg/m$^2$)', color=color)\n", "axs4.plot(t, 1e-3*data['M_rock'][:], color=color)\n", "axs4.tick_params(axis='y', labelcolor=color)\n", "\n", "# Alk\n", "ax2 = axs4.twinx()\n", "color = 'tab:blue'\n", "ax2.plot(t,data['Wr'][0,:]/(conv_mol*24*3600), color=color)\n", "ax2.set_yscale('log')\n", "ax2.set_ylabel('W$_\\\\mathrm{oliv}$ (mol m$^{-2}$ s$^{-1}$)',color=color)\n", "ax2.tick_params(axis='y', labelcolor=color)\n", "\n", "#--------------------------------------------------------------------------------\n", "# Fifth panel - CEC\n", "#--------------------------------------------------------------------------------\n", "\n", "axs5 = plt.subplot(gs[2, 1])\n", "\n", "cumulative_sum = 0\n", "labels = ['f$_\\\\mathrm{H}$', 'f$_\\\\mathrm{Na}$', 'f$_\\\\mathrm{K}$', 'f$_\\\\mathrm{Ca}$', 'f$_\\\\mathrm{Mg}$', 'f$_\\\\mathrm{Al}$']\n", "i=0\n", "for element in ['f_H', 'f_Na', 'f_K', 'f_Ca', 'f_Mg', 'f_Al']:\n", " axs5.plot(t, data[element] + cumulative_sum, label=labels[i])\n", " axs5.fill_between(t, cumulative_sum, cumulative_sum + data[element], alpha=0.5)\n", " cumulative_sum += data[element]\n", " i=i+1\n", "\n", "axs5.set_ylabel('CEC fraction')\n", "axs5.set_xlabel('t(d)')\n", "axs5.yaxis.tick_right()\n", "axs5.yaxis.set_label_position(\"right\")\n", "axs5.legend()\n", "\n", "#-------------------------------------------------------------------\n", "#plot labels\n", "axs1.text(0.95, 0.87, '(a)', transform=axs1.transAxes, fontsize=12, fontweight='bold', zorder = 3)\n", "axs2.text(0.92, 0.87, '(b)', transform=axs2.transAxes, fontsize=12, fontweight='bold', zorder = 3)\n", "axs3.text(0.92, 0.87, '(c)', transform=axs3.transAxes, fontsize=12, fontweight='bold', zorder = 3)\n", "axs4.text(0.92, 0.87, '(d)', transform=axs4.transAxes, fontsize=12, fontweight='bold', zorder = 3)\n", "axs5.text(0.92, 0.87, '(e)', transform=axs5.transAxes, fontsize=12, fontweight='bold', zorder = 3)\n", "\n", "#plotting\n", "plt.tight_layout(pad=2.0)\n", "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.4" } }, "nbformat": 4, "nbformat_minor": 5 }