{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-0",
   "metadata": {},
   "source": [
    "# Sizing an A²O plant for nitrogen and phosphorus\n",
    "\n",
    "The volumes, sludge age, recycle and ferric dose of an A²O plant that meets **NH₄ < 1**, **TN < 10** and **TP < 2 g/m³** at steady state, for a constant influent. Each step of the textbook sequence is a simulation of the whole plant instead of a hand calculation:\n",
    "\n",
    "1. **Bio-P first:** the anaerobic zone, sized by its share of the biomass.\n",
    "2. **Nitrification:** the aerobic sludge age that brings ammonia to its target.\n",
    "3. **Denitrification:** the internal recycle, and the smallest anoxic zone that meets TN.\n",
    "4. **Volume:** the waste flow that holds the design MLSS.\n",
    "5. **Ferric chloride** in the aerobic tank, for the phosphorus bio-P leaves behind.\n",
    "6. **A second opinion:** Nelder–Mead looks for a smaller plant.\n",
    "\n",
    "*Copyright (c) 2026 Nonlineum Labs. Released under the MIT License, whose text is the last cell.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from scipy.optimize import brentq, minimize\n",
    "\n",
    "import nonlineum.theo as theo\n",
    "\n",
    "engine = theo.start_engine()     # an engine of this notebook's own\n",
    "plant = theo.plant"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-2",
   "metadata": {},
   "source": [
    "## Design basis\n",
    "\n",
    "The targets sit below the limits, which leaves room for the dynamic check that comes later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-3",
   "metadata": {},
   "outputs": [],
   "source": [
    "T_design    = 12.0     # °C, the cold month\n",
    "NH4_target  = 0.7      # gN/m³ effluent ammonia (limit 1)\n",
    "TN_target   = 8.0      # gN/m³ effluent total nitrogen (limit 10)\n",
    "TP_target   = 1.5      # gP/m³ effluent total phosphorus (limit 2)\n",
    "MLSS_target = 3500.0   # gTSS/m³ in the aerobic tank\n",
    "R_IR_max    = 5        # × Q, the most internal recycle the design may pump"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-4",
   "metadata": {},
   "source": [
    "## The plant\n",
    "\n",
    "Anaerobic, anoxic and aerobic tanks, a clarifier, and ferric chloride dosed into the aerobic tank. The return sludge goes to the anaerobic tank, the internal recycle from the aerobic to the anoxic one.\n",
    "\n",
    "The waste sludge is drawn from the aerobic tank, so the aerobic sludge age is simply V_AE / Q_WAS. A PID controller holds 2 g/m³ of oxygen in the aerobic tank."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-5",
   "metadata": {},
   "outputs": [],
   "source": [
    "plant.add_influent(\"Influent\")\n",
    "plant.add_combiner(\"RAS_combiner\")\n",
    "plant.add_cstr(\"AN\")\n",
    "plant.add_combiner(\"IR_combiner\")\n",
    "plant.add_cstr(\"AX\")\n",
    "plant.add_unit(\"FerricChlorideDosing\", \"Ferric\")\n",
    "plant.add_combiner(\"Fe_combiner\")\n",
    "plant.add_cstr(\"AE\")\n",
    "plant.add_splitter(\"WAS_pump\", kind=\"pumped\")\n",
    "plant.add_splitter(\"IR_pump\", kind=\"pumped\")\n",
    "plant.add_clarifier(\"Clarifier\")\n",
    "plant.add_effluent(\"Effluent\")\n",
    "plant.add_effluent(\"Sludge\")\n",
    "\n",
    "plant.connect(\"Influent.outlet\",     \"RAS_combiner.inlet1\")\n",
    "plant.connect(\"RAS_combiner.outlet\", \"AN.inlet\")\n",
    "plant.connect(\"AN.outlet\",           \"IR_combiner.inlet1\")\n",
    "plant.connect(\"IR_combiner.outlet\",  \"AX.inlet\")\n",
    "plant.connect(\"AX.outlet\",           \"Fe_combiner.inlet1\")\n",
    "plant.connect(\"Ferric.outlet\",       \"Fe_combiner.inlet2\")\n",
    "plant.connect(\"Fe_combiner.outlet\",  \"AE.inlet\")\n",
    "plant.connect(\"AE.outlet\",           \"WAS_pump.inlet\")\n",
    "plant.connect(\"WAS_pump.ppd\",        \"Sludge.inlet\")\n",
    "plant.connect(\"WAS_pump.ofl\",        \"IR_pump.inlet\")\n",
    "plant.connect(\"IR_pump.ppd\",         \"IR_combiner.inlet2\")\n",
    "plant.connect(\"IR_pump.ofl\",         \"Clarifier.inlet\")\n",
    "plant.connect(\"Clarifier.ufl\",       \"RAS_combiner.inlet2\")\n",
    "plant.connect(\"Clarifier.ofl\",       \"Effluent.inlet\")\n",
    "plant.pull()\n",
    "\n",
    "Q = plant.Influent.Q                    # m³/d, Theo's default influent\n",
    "plant.Influent.T = T_design\n",
    "plant.AN.Q_air_NTP = 0.0\n",
    "plant.AX.Q_air_NTP = 0.0\n",
    "plant.Clarifier.Q_ufl_setpoint = Q      # return sludge, 1 × Q\n",
    "plant.Ferric.Q = 0.0                    # m³/d of 40 % ferric chloride solution\n",
    "plant.add_pid(\"DO_AE\", measure=\"AE.SO2\", actuate=\"AE.Q_air_NTP\", setpoint=2.0,\n",
    "          Kp=30_000, Ti=15, out_min=30_000, out_max=600_000, bias=250_000)\n",
    "plant.set_steady_state(True, window=20) # a run ends once nothing moves any more"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-6",
   "metadata": {},
   "source": [
    "## One evaluation\n",
    "\n",
    "A design point is the aerobic sludge age, the anaerobic and anoxic shares of the bioreactor volume, the internal recycle and the ferric dose. `evaluate` sets the plant to it, runs it from where the last run ended until it is steady, and returns what came out. Every evaluation is also kept in `runs`.\n",
    "\n",
    "Steady means that the plant's state, taken as a whole, moves by less than 0.1 % over 20 days, twice in a row. After a small change in the ferric dose, effluent phosphorus takes about 40 days to settle, so a shorter window can end a run before the change has played out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-7",
   "metadata": {},
   "outputs": [],
   "source": [
    "runs = []\n",
    "Q_WAS = 500.0      # m³/d, a first guess; step 0 corrects it for the MLSS\n",
    "Fe = 0.0           # m³/d of ferric chloride solution; step 5 sets it\n",
    "\n",
    "\n",
    "def evaluate(SRT_aer, f_AN, f_AX, R_IR):\n",
    "    V_AE = SRT_aer * Q_WAS\n",
    "    V_bio = V_AE / (1 - f_AN - f_AX)\n",
    "    plant.AN.V = f_AN * V_bio\n",
    "    plant.AX.V = f_AX * V_bio\n",
    "    plant.AE.V = V_AE\n",
    "    plant.WAS_pump.Q_ppd_setpoint = Q_WAS\n",
    "    plant.IR_pump.Q_ppd_setpoint = R_IR * Q\n",
    "    plant.Ferric.Q = Fe\n",
    "\n",
    "    plant.capture_initials()\n",
    "    outcome = plant.run(stop_time=2000)\n",
    "\n",
    "    air = plant.history([\"AE\"], [\"Q_air_NTP\"]).iloc[-1, 0]\n",
    "    row = dict(step=step, SRT_aer=SRT_aer, f_AN=f_AN, f_AX=f_AX, R_IR=R_IR, Fe=Fe,\n",
    "               V_AN=plant.AN.V, V_AX=plant.AX.V, V_AE=V_AE, V_bio=V_bio, Q_WAS=Q_WAS,\n",
    "               NH4=plant.Effluent.SNHx, NO3=plant.Effluent.SNO3, TN=plant.Effluent.TN,\n",
    "               TP=plant.Effluent.TP, PO4=plant.Effluent.SPO4, MLSS=plant.AE.XTSS,\n",
    "               air=air, days=outcome[\"at\"], steady=outcome[\"ending\"] == \"steady_state_found\")\n",
    "    runs.append(row)\n",
    "    print(\"%-16s SRT %5.2f d  AN %.2f  AX %.2f  IR %.1f  Fe %.2f | NH4 %5.2f  TN %5.2f  TP %5.2f  MLSS %4.0f\"\n",
    "          % (step, SRT_aer, f_AN, f_AX, R_IR, Fe, row[\"NH4\"], row[\"TN\"], row[\"TP\"], row[\"MLSS\"]))\n",
    "    return row"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-8",
   "metadata": {},
   "source": [
    "## Step 0: a cold start\n",
    "\n",
    "A first guess, run from Theo's default initial state, so that every later evaluation starts from a plant with sludge in it.\n",
    "\n",
    "With the sludge wasted from the aerobic tank, the MLSS there is the sludge production over the waste flow, whatever the volume. So one correction of the waste flow holds the design MLSS, and from then on V_AE = SRT_aer × Q_WAS."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-9",
   "metadata": {},
   "outputs": [],
   "source": [
    "step = \"0 cold start\"\n",
    "SRT_aer, f_AN, f_AX, R_IR = 15.0, 0.15, 0.25, 3\n",
    "first = evaluate(SRT_aer, f_AN, f_AX, R_IR)\n",
    "print(\"Influent: %.0f m³/d, COD %.0f, TKN %.1f, TP %.1f g/m³\"\n",
    "      % (Q, plant.Influent.COD, plant.Influent.TKN, plant.Influent.TP))\n",
    "Q_WAS = Q_WAS * first[\"MLSS\"] / MLSS_target\n",
    "print(\"Waste flow for %.0f gTSS/m³: %.0f m³/d\" % (MLSS_target, Q_WAS))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-10",
   "metadata": {},
   "source": [
    "## Step 1: bio-P first\n",
    "\n",
    "Phosphorus-accumulating organisms (PAOs) take up volatile fatty acids in the anaerobic zone, and the anaerobic zone must be large enough for the fermentation that makes them. Dold and Conidi (WEFTEC 2019) show that most poorly performing bio-P plants have anaerobic zones that are too small. They cite the WRC (1984) guideline for the anaerobic share of the biomass: 0.15 to 0.20 for an influent COD of 400 to 700 g/m³. Theo's default influent has 551.\n",
    "\n",
    "In an A²O plant the MLSS is about the same in every zone, so the share of the biomass is the share of the volume. A loop shows what the share does to the effluent phosphorus:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-11",
   "metadata": {},
   "outputs": [],
   "source": [
    "step = \"1 bio-P\"\n",
    "for f in (0.05, 0.10, 0.15, 0.20, 0.25):\n",
    "    row = evaluate(SRT_aer, f, f_AX, R_IR)\n",
    "    print(\"    anaerobic share %.2f: %4.0f m³, PO4 in the anaerobic tank %4.1f, effluent TP %4.2f gP/m³\"\n",
    "          % (f, row[\"V_AN\"], plant.AN.SPO4, row[\"TP\"]))\n",
    "\n",
    "f_AN = 0.20        # the upper end of the guideline: bio-P does most of the work"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-12",
   "metadata": {},
   "source": [
    "## Steps 2 and 3: nitrification and denitrification\n",
    "\n",
    "Effluent ammonia falls as the aerobic sludge age grows, so [`brentq`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.brentq.html) can find the sludge age where ammonia meets its target ([Brent's method](https://en.wikipedia.org/wiki/Brent%27s_method)).\n",
    "\n",
    "For denitrification a loop shows what the internal recycle does to TN; then `brentq` finds the smallest anoxic share that meets TN."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-13",
   "metadata": {},
   "outputs": [],
   "source": [
    "step = \"2 recycle\"\n",
    "for R in range(1, R_IR_max + 1):\n",
    "    evaluate(SRT_aer, f_AN, f_AX, R)\n",
    "R_IR = R_IR_max    # TN still falls with every extra 1 × Q, so take the most the design allows\n",
    "\n",
    "\n",
    "def ammonia_excess(SRT):\n",
    "    return evaluate(SRT, f_AN, f_AX, R_IR)[\"NH4\"] - NH4_target\n",
    "\n",
    "\n",
    "def tn_excess(f):\n",
    "    return evaluate(SRT_aer, f_AN, f, R_IR)[\"TN\"] - TN_target"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-14",
   "metadata": {},
   "source": [
    "## Step 4: the volume\n",
    "\n",
    "The sludge production moves with the sludge age, and ferric chloride adds sludge of its own, so the waste flow is corrected for the design MLSS. The volumes follow from it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-15",
   "metadata": {},
   "outputs": [],
   "source": [
    "def hold_mlss():\n",
    "    global Q_WAS\n",
    "    row = evaluate(SRT_aer, f_AN, f_AX, R_IR)\n",
    "    Q_WAS = Q_WAS * row[\"MLSS\"] / MLSS_target"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-16",
   "metadata": {},
   "source": [
    "## Step 5: ferric chloride\n",
    "\n",
    "Whatever phosphorus bio-P leaves behind, ferric chloride dosed into the aerobic tank precipitates. `brentq` again, this time for the dose that meets the TP target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-17",
   "metadata": {},
   "outputs": [],
   "source": [
    "def tp_excess(dose):\n",
    "    global Fe\n",
    "    Fe = dose\n",
    "    return evaluate(SRT_aer, f_AN, f_AX, R_IR)[\"TP\"] - TP_target\n",
    "\n",
    "\n",
    "def dose_ferric():\n",
    "    global Fe\n",
    "    TP_bio = tp_excess(0.0) + TP_target          # what bio-P leaves on its own\n",
    "    Fe = brentq(tp_excess, 0.0, 2.0, xtol=0.002) + 0.002 if TP_bio > TP_target else 0.0\n",
    "    return TP_bio"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-18",
   "metadata": {},
   "source": [
    "## Steps 3 to 5 in turn\n",
    "\n",
    "The steps depend on each other. Nitrifiers decay in the unaerated zones, and the anoxic zone removes what nitrification makes. Ferric chloride uses up alkalinity, which slows nitrification, and it adds sludge of its own. So steps 3 to 5 run twice in turn.\n",
    "\n",
    "`brentq` stops within its tolerance (`xtol`) of the answer, on either side of it, so each result is rounded up by that tolerance, to the safe side."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-19",
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in (1, 2):\n",
    "    step = \"3 SRT, round %d\" % n\n",
    "    SRT_aer = brentq(ammonia_excess, 5, 60, xtol=0.05) + 0.05\n",
    "    step = \"3 anoxic, round %d\" % n\n",
    "    f_AX = brentq(tn_excess, 0.05, 0.35, xtol=0.002) + 0.002\n",
    "    step = \"4 volume, round %d\" % n\n",
    "    hold_mlss()\n",
    "    step = \"5 ferric, round %d\" % n\n",
    "    TP_bio = dose_ferric()\n",
    "    print(\"Round %d: aerobic sludge age %.2f d, anoxic share %.3f, ferric %.3f m³/d\"\n",
    "          % (n, SRT_aer, f_AX, Fe))\n",
    "\n",
    "step = \"5 design\"\n",
    "design = evaluate(SRT_aer, f_AN, f_AX, R_IR)\n",
    "if Fe > 0:\n",
    "    Fe_kg = Fe * plant.Ferric.SFe3 / 1000                      # kg Fe/d\n",
    "    P_kg = (TP_bio - design[\"TP\"]) * Q / 1000                  # kg P/d the ferric removed\n",
    "    print(\"Ferric: %.2f m³/d of solution, %.0f kg Fe/d, %.1f mol Fe per mol P it removed\"\n",
    "          % (Fe, Fe_kg, (Fe_kg / 55.85) / (P_kg / 30.97)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-20",
   "metadata": {},
   "source": [
    "## Step 6: a second opinion\n",
    "\n",
    "[Nelder–Mead](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method) moves the sludge age, the anoxic share and the recycle together, looking for a smaller bioreactor that still meets every target ([an animation](https://www.youtube.com/watch?v=j2gcuRVbwR0) shows how it walks). A missed target counts as a penalty on the volume."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-21",
   "metadata": {},
   "outputs": [],
   "source": [
    "step = \"6 Nelder-Mead\"\n",
    "\n",
    "\n",
    "def penalised_volume(x):\n",
    "    SRT, f, R = x\n",
    "    if not (3 <= SRT <= 40 and 0.05 <= f <= 0.6 and 1 <= R <= R_IR_max):\n",
    "        return 1e12\n",
    "    row = evaluate(SRT, f_AN, f, R)\n",
    "    miss = sum(max(0.0, row[k] / target - 1) ** 2\n",
    "               for k, target in ((\"NH4\", NH4_target), (\"TN\", TN_target), (\"TP\", TP_target)))\n",
    "    return row[\"V_bio\"] * (1 + 100 * miss)\n",
    "\n",
    "\n",
    "minimize(penalised_volume, [SRT_aer, f_AX, R_IR], method=\"Nelder-Mead\",\n",
    "         options={\"maxfev\": 30, \"xatol\": 0.05, \"fatol\": 10})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-22",
   "metadata": {},
   "source": [
    "## The design"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-23",
   "metadata": {},
   "outputs": [],
   "source": [
    "def meets(row):\n",
    "    return row[\"NH4\"] <= NH4_target and row[\"TN\"] <= TN_target and row[\"TP\"] <= TP_target\n",
    "\n",
    "\n",
    "print(\"The design meets every target.\" if meets(design) else \"The design misses a target.\")\n",
    "smaller = [r for r in runs if r[\"step\"] == step and meets(r) and r[\"V_bio\"] < design[\"V_bio\"]]\n",
    "if smaller:\n",
    "    print(\"Nelder–Mead found a smaller plant: %.0f m³\" % min(r[\"V_bio\"] for r in smaller))\n",
    "else:\n",
    "    print(\"Nelder–Mead found no smaller plant that meets every target.\")\n",
    "\n",
    "print(pd.Series({\n",
    "    \"Anaerobic, anoxic, aerobic volume [m³]\": \"%.0f, %.0f, %.0f\" % (design[\"V_AN\"], design[\"V_AX\"], design[\"V_AE\"]),\n",
    "    \"Bioreactor [m³]\":                        round(design[\"V_bio\"]),\n",
    "    \"HRT [h]\":                                round(design[\"V_bio\"] / Q * 24, 1),\n",
    "    \"Aerobic sludge age [d]\":                 round(design[\"SRT_aer\"], 1),\n",
    "    \"MLSS in the aerobic tank [gTSS/m³]\":     round(design[\"MLSS\"]),\n",
    "    \"Waste sludge [m³/d]\":                    round(design[\"Q_WAS\"]),\n",
    "    \"Internal recycle [m³/d]\":                round(design[\"R_IR\"] * Q),\n",
    "    \"Air [Nm³/d]\":                            round(design[\"air\"]),\n",
    "    \"Ferric chloride solution [m³/d]\":        round(design[\"Fe\"], 2),\n",
    "    \"Effluent NH4, TN, TP [g/m³]\":            \"%.2f, %.2f, %.2f\" % (design[\"NH4\"], design[\"TN\"], design[\"TP\"]),\n",
    "}).to_string())\n",
    "\n",
    "pd.DataFrame(runs).to_csv(\"runs.csv\", index=False)\n",
    "print(\"%d evaluations\" % len(runs))\n",
    "engine.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-24",
   "metadata": {},
   "source": [
    "## License\n",
    "\n",
    "MIT License\n",
    "\n",
    "Copyright (c) 2026 Nonlineum Labs\n",
    "\n",
    "Permission is hereby granted, free of charge, to any person obtaining a copy\n",
    "of this software and associated documentation files (the \"Software\"), to deal\n",
    "in the Software without restriction, including without limitation the rights\n",
    "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
    "copies of the Software, and to permit persons to whom the Software is\n",
    "furnished to do so, subject to the following conditions:\n",
    "\n",
    "The above copyright notice and this permission notice shall be included in all\n",
    "copies or substantial portions of the Software.\n",
    "\n",
    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
    "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
    "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
    "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
    "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
    "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n",
    "SOFTWARE."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
