How the calculations are built, part 5: coast, lake, drinking water and groundwater
Part 4 covered the river network and the dam. This part covers the rest of the water page: a drawn coastal area with its eelgrass, a lake with its fishing and its status, the raw water of a drinking-water source, and the groundwater under a drawn area.
docs/calculations-water.md explains what each number means and where the inputs come from. This document explains
the code. File paths are relative to backend/EcoVal.Api/Features/Water/. Code excerpts are copied from the source
and shortened; // … marks what is left out.
Contents
- 1. Overview
- 2. The coast: eelgrass
- 3. The coast: the harbour's side, the seabed and the shore
- 4. A lake
- 5. Drinking water: a trend with a statistical test
- 6. Groundwater
- 7. Summary
1. Overview
These four sections work on polygons again, like the forest page, but most of their inputs are vector data in PostGIS (meadows, lakes, water bodies, aquifers), not rasters. The lookups measure overlaps in the database, and the calculators turn hectares into values.
flowchart LR
P["Drawn area or picked lake"] --> L["Lookups (PostGIS):<br/>overlaps in hectares, rows of data"]
L --> C1["CoastCalculator"]
L --> C2["LakeCalculator"]
L --> C3["DrinkingWaterCalculator"]
L --> C4["GroundwaterCalculator"]
R["One raster: wave exposure"] --> C1
G["Fishing grid (part 1, section 6.5)"] --> C2
Two building blocks recur and are worth stating once.
The annuity. Many values here are "so many kronor a year, every year". The present value of 1 kr a year from year to the horizon is called an annuity factor:
so a constant yearly value is worth today. With and years, : thirty years of 1 kr are worth about 18 kr today.
// Money.cs
public static double Annuity(double discountRate, int horizonYears, int fromYear = 1) =>
PresentValue(_ => 1, discountRate, horizonYears, fromYear);
Indexing. Every published amount is moved to the price year with the consumer price index, as in parts 2 to 4
(Money.Indexed).
2. The coast: eelgrass
Files: Coast/CoastCalculator.cs, Coast/WaveExposure.cs. Eelgrass meadows are nurseries for fish and bury carbon
and nitrogen in their sediment. The section values a meadow in three scenarios: kept, built over by a harbour, and
(where a meadow has been lost) restored.
2.1 Sheltered or exposed: classifying by pixel centres
How much carbon a meadow holds depends on how sheltered it is. A raster of wave exposure puts each piece of meadow in the sheltered or the exposed group. A piece can straddle the cut-off, so it is split by the share of its pixel centres on each side:
if (value >= cutoff)
{
high[owners[p]]++;
}
else
{
low[owners[p]]++;
}
// …
sheltered += hectares * l / (l + h);
exposed += hectares * h / (l + h);
Two details make this robust:
- A fallback for small pieces. A piece smaller than a pixel may contain no pixel centre at all. It then takes the value at its interior point (a point guaranteed to lie inside it), and is left unclassed only if that has no value either.
- One read for all pieces. All points of all pieces are gathered into one list and read from the raster in one
pass, with an
ownersarray remembering which piece each point belongs to. Reading piece by piece would decompress the same raster blocks again and again.
2.2 The stock per hectare: a weighted mean of three groups
A meadow's sheltered, exposed and unclassed hectares each take their group's published stock, and the meadow's stock per hectare is their area-weighted mean:
var unclassed = Math.Max(0, hectares - shelteredHectares - exposedHectares);
double Mean(Func<ParameterRange, double> pick) =>
(shelteredHectares * pick(sheltered) + exposedHectares * pick(exposed) + unclassed * pick(pooled)) / hectares;
return new ParameterRange(Mean(range => range.Low), Mean(range => range.Central), Mean(range => range.High));
The low case assumes the sediment stays in place when the meadow dies; the central and high cases assume the top 35 cm erodes, which the study's cores indicate happened.
2.3 A kept meadow: three yearly services
Per hectare and year a meadow gives fish (a yearly value in kronor), buries carbon and buries nitrogen. Over the horizon:
is the fish value, the carbon buried (as tonnes of CO₂), the carbon price in year (the same price paths as the forest's carbon value, part 2, section 9.1), the nitrogen buried and its price.
Fish and nitrogen have a constant price, so they use the annuity. Carbon's price changes by year, so it needs the full sum:
double FishPv(int case_, int from) => fishCases[case_] * Annuity(from, options);
double CarbonPv(int case_, int from) => Discounted(year => carbonBurial * carbonPaths[case_][Math.Min(year, carbonPaths[case_].Length - 1)], from, options);
double NitrogenPv(int case_, int from) => nitrogenBurial * nitrogen[case_] * Annuity(from, options);
Each takes a first year from, which the restoration scenario uses below.
2.4 Built over: the stock released, plus everything a kept meadow would have given
A harbour on the meadow releases the sediment's stock at once and ends the yearly services. The cost per hectare is
(the 1000 turns tonnes of nitrogen into kilograms, the unit of its price).
double CarbonRelease(int c) => stockCases[c].Item1 * carbonPaths[c][0];
double NitrogenRelease(int c) => stockCases[c].Item2 * 1000 * nitrogen[c];
// …
double HarbourCost(int c) =>
(CarbonRelease(c) + NitrogenRelease(c) + FishPv(c, 1) + CarbonPv(c, 1) + NitrogenPv(c, 1)) * currentHectares + HaloLost(c);
The release is priced at year 0 and not discounted, as for a felling in part 2.
2.5 The ring around a harbour: integrating a curve
A harbour also thins the eelgrass around it. A field study measured eelgrass cover at 0, 2, 4 and 6 m from a dock's edge, with full cover returning at 7.5 m. The share of cover lost in that ring is one minus the mean cover over the ring, and the mean of a curve is its area divided by its width.
With the surveyed points joined by straight lines, the area under the curve is a sum of trapezoids. For points :
var points = distancesMetres.Zip(coverPercent).Where(point => point.First < haloMetres).Append((haloMetres, 100.0)).ToList();
// …
var area = 0.0;
for (var i = 1; i < points.Count; i++)
{
area += (points[i].Item1 - points[i - 1].Item1) * (points[i].Item2 + points[i - 1].Item2) / 2;
}
return 1 - area / (haloMetres - points[0].Item1) / 100;
This is the trapezoid rule, the simplest form of numerical integration. For floating docks it gives a loss of 60 %, for docks on poles 36 %. Those are the central and low cases; the high case is the study's own overall figure.
The value lost in the ring is then its hectares times the loss share times what a kept hectare gives.
2.6 Restored: a cost now against a benefit later, if it works
Replanting a lost meadow costs money now. The benefit comes later (a planted meadow takes years to mature) and only if the planting succeeds (with probability : 0.39, 0.44 or 0.64). The expected benefit is
var grownFrom = options.RestorationMaturityYears + 1;
double Benefit(int c) =>
restorableHectares * success[c] * (FishPv(c, grownFrom) + CarbonPv(c, grownFrom) + NitrogenPv(c, grownFrom));
This is where the from parameter earns its place: the same three functions give the values from year 1 for a kept
meadow and from year 4 for a restored one.
The net pairs the low benefit with the high cost, as every net in EcoVal does:
ValueRange.Spanning(benefit.Low - cost.High, benefit.Central - cost.Central, benefit.High - cost.Low, 0)
3. The coast: the harbour's side, the seabed and the shore
3.1 What a harbour earns
The page also shows the other side of the scale: what a marina on the drawn area would bring in. The number of berths is the counted berths of existing marinas plus an estimate for the rest of the water, at a density of berths per hectare (106, 132 or 152, the quartiles over 14 Swedish marinas):
var berths = new[]
{
countedBerths + density.Low * estimated,
countedBerths + density.Central * estimated,
countedBerths + density.High * estimated,
};
var fees = new[] { berths[0] * fee.Low, berths[1] * fee.Central, berths[2] * fee.High };
A marina that is only partly inside the area contributes its berths in proportion:
marina.Berths * Math.Min(1, marina.InsideHectares / marina.Hectares).
Whether a new marina is possible at all is decided from how much of the area is water and whether there is shore to build from, as a chain of conditions that returns a code:
var newMarina = waterHectares is null ? HarbourNewMarinaStatuses.Possible
: Math.Round(waterHectares.Value, 2) <= 0 ? HarbourNewMarinaStatuses.NoWater
: Math.Round(landHectares!.Value, 2) <= 0 && Math.Round(marinaHectares, 2) <= 0 ? HarbourNewMarinaStatuses.NoShore
: Math.Round(extensionHectares, 2) <= 0 ? HarbourNewMarinaStatuses.NoRoom
: HarbourNewMarinaStatuses.Possible;
The comment above it explains the rounding: the conditions are tested on the values as they will be sent, so the code and the figures the user sees can never disagree (0.004 ha of water shown as "0.00 ha" must also count as no water).
3.2 The seabed: from "at least" to "exactly"
The seabed disturbance data gives, for each risk class, the area at that class or higher. The page wants the area at exactly each class, so that the classes add up. That is a difference of neighbours:
double Only(SeabedMapping mapping, int riskClass, bool eelgrass) =>
Math.Round(Math.Max(0, AtLeast(mapping, riskClass, eelgrass) - AtLeast(mapping, riskClass + 1, eelgrass)), 2);
3.3 The shore: a density against a threshold
How built-up a shore is, is expressed as constructions (jetties, piers, quays) per 100 m of shoreline, shown next to a published threshold above which a shore counts as degraded:
4. A lake
File: Lake/LakeCalculator.cs.
4.1 Fishing days: three bases
A national survey gives fishing days per fishing area, with a margin of error. The days become a range by subtracting and adding the margin, never below zero:
public static ValueRange Spread(double thousand, double margin) =>
new(Math.Max(0, thousand - margin) * 1000, thousand * 1000, (thousand + margin) * 1000);
How a lake gets its share depends on what is known, and the result carries a code saying which basis was used:
| Basis code | When | Formula |
|---|---|---|
OwnLake |
A great lake with its own surveyed days | The lake's days × the share of the lake in the selection |
RegionByPeople |
Any other lake, when the fishing grid is loaded | By the people within reach (part 1, section 6.5) |
RegionPerHectare |
The fallback | The region's days per hectare × the lake's hectares |
NotPublished |
The survey gives no days for the area | No value |
The by-people basis is the model whose calibration part 1 described in full; this is where it is used.
4.2 The value of the days
A fishing day is worth a consumer surplus that differs by fishing area. A selection that spans several areas adds them up area by area:
var byArea = lakes
.Where(lake => lake.FishingDays is not null)
.GroupBy(lake => lake.FishingArea)
.Select(group => (PerDay: SekPerDay(group.Key, options), Days: Sum(group.Select(lake => lake.FishingDays))))
.ToList();
// …
RoundTo(byArea.Sum(area => area.Days.Central * area.PerDay.Central), 0),
When several areas are involved, the "value per day" shown is the total value over the total days (a weighted mean), so that the three figures on the page (days, value per day, value per year) multiply out:
var perDay = byArea.Count switch
{
0 => SekPerDay(null, options),
1 => byArea[0].PerDay,
_ => new ValueRange(
dayTotals.Low > 0 ? Math.Round(perYear.Low / dayTotals.Low) : byArea.Min(area => area.PerDay.Low),
// …
4.3 The commercial catch: the range is the years
The great lakes' commercial catch is published per year. With only a couple of years, the range is simply the lowest year, the mean and the highest year, each scaled by the share of the lake in the selection:
low += values.Min() * share;
central += values.Average() * share;
high += values.Max() * share;
This is the third way a range is built in EcoVal, after "three parameter sets" and "every combination": the spread between observed years.
4.4 Status: how far from the target
The water authorities class each water body's ecological status on a five-step scale and set a target. The page shows how many steps the body is short of its target. The classes become ranks and the gap is a subtraction, never negative:
private static int Rank(string code) => code switch
{
FishStatusClasses.High => 5,
FishStatusClasses.Good => 4,
FishStatusClasses.Moderate => 3,
FishStatusClasses.Poor => 2,
_ => 1,
};
// …
ecological is null || target is null ? null : Math.Max(0, Rank(target) - Rank(ecological)),
Most of the status code is translation: the source's letters and Swedish phrases are mapped to stable codes with
switch expressions ("Vatten" => ChemicalMedia.Water), so that no display text leaves the API. Unit conversion is
done the same way, with a tuple pattern that returns null for any combination it does not know:
public static double? Background(double? value, string? unit, string limitUnit) => (value, unit, limitUnit) switch
{
(null, _, _) => null,
(var v, "µg/l", ChemicalLimitUnits.MicrogramsPerLitre) => v,
(var v, "µg/kg TS", ChemicalLimitUnits.MicrogramsPerKgDryWeight) => v,
(var v, "mg/kg TS", ChemicalLimitUnits.MicrogramsPerKgDryWeight) => v * 1000,
_ => null,
};
Returning null for an unknown unit is deliberate: showing no background is better than showing one in the wrong
unit.
5. Drinking water: a trend with a statistical test
File: Lake/DrinkingWaterCalculator.cs. For a lake that is a drinking-water source, the page shows the raw water's
organic carbon (which makes water brown and costly to treat): its latest level, its class, and whether it is
rising or falling over the years.
That last question is a statistical one, and this is the one place in EcoVal where a statistical test is run at request time on the data of the place the user picked.
Kind of method: non-parametric trend estimation and testing (Sen's slope with the Mann–Kendall test). It is statistics, not machine learning, and it is not least-squares regression either. Nothing is trained or stored: each request computes it afresh from that lake's yearly means.
5.1 The level and its class
The latest level is the mean of the last three measured years. Its class comes from a list of published bounds: the class is the number of bounds the value has reached.
public static string ClassOf(double value, double[] bounds, string[] codes)
{
var index = 0;
while (index < bounds.Length && value >= bounds[index])
{
index++;
}
return codes[index];
}
A value exactly on a bound belongs to the class above (>=), which the comment ties to how the source report
writes its classes ("4–8").
5.2 Why not an ordinary regression line?
Fitting a least-squares line through the yearly means (as for the stream width in part 1) would be the obvious choice, but water chemistry breaks its assumptions: a single flood year can sit far off the rest, and a least-squares line is pulled hard by such a point because it squares the distances. The methods used here work on signs and medians instead, which a single extreme year can hardly move.
5.3 Sen's slope: the median of all pairwise slopes
Take every pair of years and compute the slope between them. With years there are pairs. Sen's slope is the median of those slopes:
5.4 The Mann–Kendall test: is the trend real?
The test asks: if there were no trend, how surprising would this series be? It counts, over all pairs, how many times the later value is higher minus how many times it is lower:
With no trend, rises and falls are equally likely and is near zero. Its variance under "no trend" is known, with a correction for tied values (groups of equal values):
and the test statistic is
If the trend is called rising or falling (a 5 % test); otherwise the verdict is "no clear trend".
Both the slopes and come out of the same double loop:
var slopes = new List<double>(n * (n - 1) / 2);
var s = 0;
for (var i = 0; i < n; i++)
{
for (var j = i + 1; j < n; j++)
{
var difference = rows[j].Mean - rows[i].Mean;
slopes.Add(difference / (rows[j].Year - rows[i].Year)); // for Sen's slope
s += Math.Sign(difference); // for Mann–Kendall's S
}
}
slopes.Sort();
var ties = rows.GroupBy(row => row.Mean).Select(group => group.Count()).Where(count => count > 1);
var variance = (n * (n - 1.0) * (2 * n + 5) - ties.Sum(t => t * (t - 1.0) * (2 * t + 5))) / 18;
// …
var z = s == 0 ? 0 : (s - Math.Sign(s)) / Math.Sqrt(variance);
var code = Math.Abs(z) <= options.TrendZ ? TrendCodes.NoClearTrend : z > 0 ? TrendCodes.Rising : TrendCodes.Falling;
Note n - 1.0 and t - 1.0: the .0 makes the arithmetic floating-point, for the same reason as the cast in the
ramp-up of part 4.
A series shorter than ten years gets no trend at all (TooShort): with few years the test has too little power to
say anything.
5.5 The range of the slope
The 95 % range of Sen's slope also comes from the sorted list of pairwise slopes. With , the lower and upper bounds are the slopes at positions
in the sorted list. A larger variance pushes the two positions apart and widens the range.
var count = slopes.Count;
var c = options.TrendZ * Math.Sqrt(variance);
var lower = (int)Math.Round((count - c) / 2);
var upper = (int)Math.Round((count + c) / 2) + 1;
return (Median(slopes), slopes[Math.Clamp(lower - 1, 0, count - 1)], slopes[Math.Clamp(upper - 1, 0, count - 1)], code);
5.6 One year follows the last: the serial correlation correction
The test assumes each year is independent of the one before. A lake's water stays in the lake for years, so a high year tends to be followed by another high year. Then the series holds less independent information than its length suggests, and the plain test calls a trend too often.
The correction (Hamed and Rao 1998) inflates the variance by a factor , where is the "effective" number of independent years. The series is first detrended with Sen's slope and turned into ranks; with the ranks' correlation with themselves years later:
Only lags whose is itself significant are included ().
var ranks = Ranks(rows.Select(row => row.Mean - slopePerYear * row.Year).ToArray()); // detrend, then rank
// …
for (var lag = 1; lag < n; lag++)
{
var product = 0.0;
for (var t = 0; t + lag < n; t++)
{
product += (ranks[t] - mean) * (ranks[t + lag] - mean);
}
var correlation = product / spread;
if (Math.Abs(correlation) > bound)
{
sum += (n - lag) * (n - lag - 1.0) * (n - lag - 2.0) * correlation;
}
}
return Math.Max(1, 1 + 2 / (n * (n - 1.0) * (n - 2.0)) * sum);
A deliberate departure from the published formula. The last line never lets the factor fall below 1. As published, the factor can be below 1 when values alternate up and down, which would narrow the variance and make the test call trends more easily. The comment in the source records what was found when this was checked on the real lakes: in short series the factor fell below 1 by chance for 19 of 90 lakes and turned three "no clear trend" verdicts into trends, the opposite of the correction's purpose. So only the widening direction is applied, and the comment says so, with the script that checked it. This is a good model for how to document a judgement call in statistical code.
5.7 From a trend to a cost
A rising trend of mg/l per decade costs a waterworks öre per cubic metre per decade, with the cost of one more mg/l. Both have a range, and the slope may be negative, so the low and high of the product are found by trying all four corner combinations:
var products = new[] { slope.Low * orePerMg.Low, slope.Low * orePerMg.High, slope.High * orePerMg.Low, slope.High * orePerMg.High };
cost = new ValueRange(Math.Round(products.Min(), 2), Math.Round(slope.Central * orePerMg.Central, 2), Math.Round(products.Max(), 2));
Multiplying low by low and high by high is only right when both factors are positive. For a falling trend (a negative slope), the most negative product is the low slope times the high cost. Taking the minimum and maximum of all four corners is the general rule for the range of a product, and it is used here because the sign is not known in advance.
6. Groundwater
File: Lake/GroundwaterCalculator.cs. Groundwater that can be pumped clean is treated as a natural waterworks: its
value is the treatment cost that surface water would have needed.
6.1 From a yield class to cubic metres a year
The geological survey classes each aquifer by how much water it can yield, in litres per second: 1–5, 5–25, 25–125 and so on. Each class is five times the one before. For such a scale the natural midpoint is the geometric mean, not the arithmetic one:
For the class 5–25 l/s this gives 11.2 l/s; the arithmetic mean (15) would sit too close to the top of a scale that grows by multiplication.
var (low, high) = AquiferYieldClasses.SoilBounds(zone.YieldCode)!.Value;
var top = high ?? low;
var central = low == 0 ? top / 2 : Math.Sqrt(low * top);
The two special cases are handled explicitly: the lowest class starts at 0, where a geometric mean would be 0, so it takes half its upper bound; the open top class ("above 125") has no upper bound, so its lower bound is used and the result is flagged as a minimum.
One litre a second for a year is
/// <summary>m³ in a year of one litre a second.</summary>
public const double CubicMetresPerYearPerLitreSecond = 365 * 86_400 / 1_000.0;
and the page also shows it as people supplied, at 180 litres a person a day.
6.2 The price: the middle of four figures
Four published figures give the treatment cost saved per cubic metre (two from Dutch accounts, two from a Swedish municipality), each indexed from its own year. The range is their lowest and highest, and the central value is the middle of the four, which for an even count is the mean of the two in between (the median):
Array.Sort(figures);
return ValueRange.Spanning(figures[0], (figures[1] + figures[2]) / 2, figures[3], 2);
With only four figures from two sources, a median is a better central value than a mean, because one outlying figure cannot drag it.
The value is then volume times price, rounded to thousands of kronor:
7. Summary
| Section | Kind of calculation | Regression or fitted model? |
|---|---|---|
| Eelgrass: sheltered or exposed | Share of pixel centres on each side of a cut-off | No |
| Eelgrass: stock per hectare | Area-weighted mean of published stocks | No |
| Eelgrass: kept, built over, restored | Annuities and a discounted sum; expected value with a success rate | No |
| The ring around a harbour | Trapezoid rule on surveyed cover | No |
| Harbour income | Berths × fee; a density from observed marinas | No (quartiles of 14 marinas) |
| Seabed, shore | Differences of cumulative areas; a density | No |
| Lake: fishing days by people | Gravity model | Calibrated by EcoVal (part 1, section 6.5) |
| Lake: value, commercial catch, status | Sums, min/mean/max over years, rank differences | No |
| Raw-water trend | Sen's slope and the Mann–Kendall test, with a serial-correlation correction | A statistical estimate and test, computed per request; nothing stored |
| Groundwater | Geometric mean of class bounds; median of four prices | No |
The raw-water trend completes the picture of where statistics appear in EcoVal:
- Fitted offline, stored as options: the gravity models, the growth model's parameters (parts 1 and 2).
- Fitted when the API starts, kept in memory: the stream width regression, the fish densities (part 1).
- Computed per request from the place's own data: the raw-water trend (this part).
- Borrowed from publications: the berry models, the organic-carbon coefficient, the eel relations (parts 3 and 4).