This week we showed our visit to the Encina Wastewater Authority in Carlsbad, CA where they treat wastewater so that it can be returned to the ocean. Perhaps that's something that you haven't given much thought, but it was quite fascinating to see how they accomplished this task and they have a very impressive facility. And yes, mathematics factors in to many of the processes happening there.
Most of the work treating the water is done by bacteria and other microorganisms. The staff must constantly monitor and adjust the ratio of these organisms to the amount of solid "food" coming in. There is a large aeration tank where the organisms consume the waste followed by a secondary tank where the organisms and matter clump to form an "activated sludge." Some of this sludge is directed back to the aeration tank as needed to keep a 0.5 ratio. In the end, 100% of the sludge is used internally or processed into fertilizer.
After the microorganisms have done their work, the water is ready to be returned to the ocean, after being tested of course.
You can find more information on the Encina Water Authority at their website.