EcoVal Changelog v0.5.0

How the calculations are built, part 6: the city page and the landing calculator

This is the last part. It covers the city page (tree canopy, shade and cooling in towns) and the landing page's calculator, which shows what a typical forest, mire, eelgrass meadow, lake or esker is worth without a map.

docs/calculations-city.md explains the city page's numbers, and the "landing calculator" sections of docs/calculations.md and docs/calculations-water.md explain the calculator's. This document explains the code. File paths are relative to backend/EcoVal.Api/Features/ unless said otherwise. Code excerpts are copied from the source and shortened; // … marks what is left out.

Contents


1. Overview

The two halves of this part have opposite characters.

The city page is the most raster-heavy part of EcoVal: it reads 1 m pixels, and the heavy work (finding tree crowns, casting their shadows) is done once, offline, by Python scripts that write new rasters. The API then only counts pixels.

flowchart LR
    subgraph offline ["Offline, once per data update (Python + GDAL)"]
        S1["Tree cover and laser heights"] --> P1["city-canopy.py"]
        P1 --> R1["Canopy raster, 1 m"]
        R1 --> P2["city-shade.py<br/>sun position, shadow casting"]
        P2 --> R2["Shade raster, 1 m<br/>one bit per hour"]
    end
    subgraph api ["Per request (C#)"]
        R1 --> C1["CityCoverCalculator:<br/>what each square metre is"]
        R2 --> C2["CityShadeCalculator:<br/>square metres in shade"]
        H["Surface temperature raster, 30 m"] --> C3["CityCoolingCalculator"]
        C1 --> C3
    end

The landing calculator has no data of its own at all. It feeds typical inputs (a stand of a given age, a mire of a given depth) into the same calculators the forest and water pages use.


2. City: what the ground is

Files: City/Cover/CityCoverCalculator.cs, City/Cover/CityCoverReader.cs.

2.1 Three rasters read at the same points

For each sampled square metre the reader looks up three values: the canopy raster (is there something tall here, and how tall?), the land cover class, and the distance to the nearest building outline. The sampling is ClassAreas.Sample from part 1, section 2.3: pixel centres inside the outline, thinned on large areas so that each sample stands for several square metres.

Because samples are counted by pixel centre, their total differs slightly from the outline's true area. The sums are therefore scaled so that the parts add up to the drawn area exactly:

Ak=ak⋅Adrawn∑jajA_k = a_k \cdot \frac{A_{\text{drawn}}}{\sum_j a_j}
var sampled = _kinds.Sum();
var scale = sampled > 0 ? areaSquareMetres / sampled : 0;

2.2 Two sources packed into one raster value

The canopy comes from two sources of different quality: Boverket's tree cover (which has already told trees from roofs) and a laser height model (where a roof is as tall as a tree). Both are stored in one 8-bit raster by an offset: a Boverket pixel holds 100 plus the height in metres, a laser pixel holds the height as it is.

public const short BoverketOffset = 100;
private static bool IsBoverket(short canopy) => canopy >= BoverketOffset;

So the value 112 means "Boverket, 12 m" and 12 means "laser, 12 m". Packing a flag into the number saves a second raster and a second read per pixel.

2.3 The classification: a decision tree

Each sample is sorted into one kind of ground by a fixed sequence of rules. It is a rule-based classifier written by hand, not a trained one:

flowchart TD
    A{"Any of the rasters<br/>without data?"} -->|yes| U["Unmapped"]
    A -->|no| B{"Boverket's source?"}
    B -->|"yes, and 3 m or taller"| C["Canopy"]
    B -->|"yes, lower"| D{"Inside a building?"}
    D -->|yes| BU["Building"]
    D -->|no| G["By land cover:<br/>road, other built, green, bare, water"]
    B -->|"no: laser height"| E{"Inside a building?"}
    E -->|yes| BU
    E -->|no| F{"Water in the land cover?"}
    F -->|yes| W["Water"]
    F -->|no| H{"3 m or taller?"}
    H -->|"yes, but within 2 m<br/>of a building outline"| BU
    H -->|"yes, further away"| C
    H -->|no| G
if (IsBoverket(canopy))
{
    if (IsTall(canopy - BoverketOffset))
    {
        return GroundKind.Canopy;
    }
    return IsBuilding(landClass, buildingMetres) ? GroundKind.Building : Ground(landClass);
}
if (IsBuilding(landClass, buildingMetres))
{
    return GroundKind.Building;
}
if (landClass is Lake or Sea)
{
    return GroundKind.Water;
}
if (IsTall(canopy))
{
    return NearerThan(buildingMetres, options.BuildingEdgeMetres) ? GroundKind.Building : GroundKind.Canopy;
}
return Ground(landClass);

The order of the tests carries the meaning. Water is tested before height because a bridge or a moored boat is tall in the laser data but is not a tree. The edge rule exists because the laser sees the edge of a roof as "tall and just outside the building outline".

2.4 Low and high canopy from one pass

The uncertainty in the laser source sits right beside buildings, where a crown and a roof edge look alike. The range is built by counting the same samples with a narrower and a wider margin around the outlines:

  • High: every tall pixel outside an outline counts as canopy, including the roof-edge pixels.
  • Central: tall pixels within 2 m of an outline are taken as building.
  • Low: tall pixels within 3 m of an outline are left out.
if (kind == GroundKind.Canopy)
{
    // …
    _canopyHigh += squareMetres;
    // The low reading keeps a wider margin to the outlines, where a crown and a roof are hardest to tell
    // apart in laser heights. Boverket's canopy has no such doubt.
    if (boverket || !NearerThan(buildingMetres, options.BuildingEdgeWideMetres))
    {
        _canopyLow += squareMetres;
    }
}

All three are accumulated in one pass over the samples. The calculator is a small stateful class (Add per sample, Result at the end), which suits a streaming read of millions of pixels better than building a list first.


3. City: shade from trees

3.1 The offline part: where is the sun?

File: scripts/city-shade.py (Python, run by scripts/prepare-rasters.sh). To know where shadows fall, the script first needs the sun's position at four times of day on 21 June. It uses the standard astronomical formulas (NOAA's solar calculator, after Meeus). The core relation gives the sun's altitude α\alpha above the horizon from the latitude φ\varphi, the sun's declination δ\delta (how far north of the equator it stands that day) and the hour angle hh (how far the earth has turned since solar noon):

sin⁡α=sin⁡φ sin⁡δ+cos⁡φ cos⁡δ cos⁡h\sin \alpha = \sin\varphi \,\sin\delta + \cos\varphi \,\cos\delta \,\cos h
cos_zenith = math.sin(phi) * math.sin(declination) + math.cos(phi) * math.cos(declination) * math.cos(hour_angle)
zenith = math.acos(max(-1, min(1, cos_zenith)))
# …
return 90 - math.degrees(zenith), azimuth % 360

The rest of sun_position computes δ\delta and hh from the date and time. One practical detail follows it: the map grid (SWEREF 99 TM) does not point exactly to true north except along its central meridian, so the sun's compass bearing is turned by the local difference before it is used on the grid.

3.2 The offline part: casting the shadows

Where a tree's crown throws its shadow

A ray of sunlight that reaches the ground at a point has passed, at horizontal distance dd towards the sun, at the height

z=d⋅tan⁡αz = d \cdot \tan\alpha

The point is in shade if at some distance dd that height lies inside a tree's crown. A tree of height HH is taken to have its crown from a quarter of its height to its top (the trunk below lets the sun through):

shaded  ⟺  ∃ d:14 H(d)  ≤  dtan⁡α  ≤  H(d)\text{shaded} \iff \exists\, d:\quad \tfrac{1}{4}\,H(d) \;\le\; d \tan\alpha \;\le\; H(d)

where H(d)H(d) is the tree height at the pixel dd metres towards the sun.

Testing every pixel against every distance in a Python loop would take days. The script turns the question around. For each step along the ray it works out which tree heights would cast a shadow from that offset, and then tests the whole raster against that height range in one vectorised operation:

while distance * rise <= tallest + 0.5:
    z = distance * rise
    lowest = max(CANOPY_MIN, math.ceil(z - 0.5))
    highest = min(tallest, math.floor(z / TRUNK_SHARE - 0.5))
    if highest >= lowest:
        offset = (round(-distance * math.cos(bearing)), round(distance * math.sin(bearing)))   # rows run south
        # …
    distance += STEP
view = trees[margin + row:margin + row + rows, margin + column:margin + column + columns]
# low <= view <= high in one comparison: the subtraction wraps below low.
np.subtract(view, low, out=scratch)
np.less_equal(scratch, high - low, out=scratch.view(bool))
np.logical_or(shaded, scratch.view(bool), out=shaded)

view is the tree-height raster shifted by the offset, so "the tree row, column pixels towards the sun" is read for all pixels at once. The comment points out a neat trick: with unsigned 8-bit numbers, subtracting low makes every value below low wrap around to a large number, so the two-sided test low <= x <= high becomes a single comparison.

3.3 One bit per hour

The result for each pixel is four yes/no answers (shaded at 11:30, 12:30, 13:30, 14:30). They are stored in one byte as bits:

Bit Value Meaning
0 1 In shade at 11:30
1 2 In shade at 12:30
2 4 In shade at 13:30
3 8 In shade at 14:30

A pixel shaded at 12:30 and 13:30 holds 2+4=62 + 4 = 6. In Python: bits |= shaded.astype(np.uint8) << index.

3.4 The API part: counting bits

File: City/Shade/CityShadeCalculator.cs. The C# side reads the bits back. Testing one hour is a shift and a mask; counting how many hours a pixel is shaded is a "population count" (the number of bits set), for which the processor has a single instruction:

private const int HourBits = (1 << Hours) - 1;      // 0b1111

public static int ShadedHours(short shade) => BitOperations.PopCount((uint)(shade & HourBits));
for (var hour = 0; hour < Hours; hour++)
{
    if ((shade >> hour & 1) == 1)
    {
        _hours[hour] += squareMetres;
    }
}
var shaded = ShadedHours(shade);
if (shaded >= mostHours)
{
    _most += squareMetres;
}

Only ground a person can stand on is counted: a shadow on a roof or on water cools nobody.

public static bool IsGround(GroundKind kind) => kind is not (GroundKind.Building or GroundKind.Water or GroundKind.Unmapped);

The split between the script and the API has one cost that the script's header states plainly: both must agree on what counts as a tree, so the script repeats the classification rules of section 2.3 and the constants of CityOptions. A change to one must be made in the other.


4. City: cooling on hot days

File: City/Cooling/CityCoolingCalculator.cs. A satellite-based raster gives the surface temperature on the hottest summer days in 30 m cells. The page compares a drawn area with the town's sealed ground (roofs, roads, yards).

How much cooler an area is than the town's sealed ground

4.1 What a 30 m cell is: a majority vote

A 30 m heat cell contains 900 square metres of mixed ground. To label it, the reader samples a 3 × 3 grid of points inside it, classifies each with the ground classifier of section 2, and takes the kind that more than half of them have:

var half = points.Length / 2.0;
return off > half ? null
    : sealedGround > half ? HeatCellKind.Sealed
    : canopy > half ? HeatCellKind.Trees
    : green > half ? HeatCellKind.Green
    : HeatCellKind.Mixed;

A cell with no majority is Mixed and counts towards no group, which keeps the groups clean.

4.2 Statistics from a histogram

A town has hundreds of thousands of cells. Their temperatures are whole degrees, so instead of storing every value the reader keeps a histogram: an array of 256 counters per kind, where counts[t] is the number of cells at tt degrees.

private readonly long[][] _counts = Enum.GetValues<HeatCellKind>().Select(_ => new long[256]).ToArray();

public void Add(HeatCellKind kind, short celsius) => _counts[(int)kind][celsius]++;

The mean and the percentiles then come from the counters. With ntn_t cells at temperature tt:

Tˉ=∑tnt⋅t∑tntTq=min⁡{t:∑u≤tnu ≥ q⋅∑unu}\bar{T} = \frac{\sum_t n_t \cdot t}{\sum_t n_t} \qquad T_{q} = \min\Bigl\{ t : \sum_{u \le t} n_u \ \ge\ q \cdot \sum_u n_u \Bigr\}

The percentile is the lowest temperature at which the running total reaches the share qq of all cells:

private static double Percentile(long[] counts, double share)
{
    var target = counts.Sum() * share;
    long seen = 0;
    for (var value = 0; value < counts.Length; value++)
    {
        seen += counts[value];
        if (seen >= target && seen > 0)
        {
            return value;
        }
    }
    return 0;
}

Memory stays at a few kilobytes however large the town is, and no sorting is needed. The town's figures are cached after the first read (TownHeatCache), since they change only when a raster is replaced.

4.3 Cooler than sealed ground

The result is a difference, with the town's sealed ground at its mean as the central case and at its cooler and hotter quarters (the 25th and 75th percentiles) as low and high:

Δcentral=Tˉsealed−TareaΔlow=T25−TareaΔhigh=T75−Tarea\Delta_{\text{central}} = \bar{T}_{\text{sealed}} - T_{\text{area}} \qquad \Delta_{\text{low}} = T_{25} - T_{\text{area}} \qquad \Delta_{\text{high}} = T_{75} - T_{\text{area}}
public static ValueRange CoolerThanSealed(double areaCelsius, TownHeat town) => new(
    Math.Round(town.SealedLowCelsius - areaCelsius, 1),
    Math.Round(town.SealedCelsius - areaCelsius, 1),
    Math.Round(town.SealedHighCelsius - areaCelsius, 1));

It is a comparison of measured surface temperatures, not a model of how much the trees cool the air.

4.4 The people nearby: clipping polygons by hand

The page counts the people living within 300 m of the area. The area is widened by 300 m (a buffer), and each 1 km population square counts by the share of it that lies inside the widened area:

people=∑squares cpc⋅area⁡(c∩zone)1 km2\text{people} = \sum_{\text{squares } c} p_c \cdot \frac{\operatorname{area}(c \cap \text{zone})}{1\ \text{km}^2}

A library call (zone.Intersection(square).Area) would do this, but a whole town's zone has tens of thousands of points and hundreds of squares on its edge, and intersecting the full polygon with each square is slow. The code does it by hand with two classic algorithms.

Sutherland–Hodgman clipping cuts a polygon along a straight line and keeps one side. It walks the ring's edges; a point on the kept side is kept, and where an edge crosses the line the crossing point is added:

if (fromInside)
{
    kept.Add(from);
}
if (fromInside != toInside)
{
    var along = (at - fromValue) / (toValue - fromValue);
    kept.Add(vertical
        ? new Coordinate(from.X + along * (to.X - from.X), at)
        : new Coordinate(at, from.Y + along * (to.Y - from.Y)));
}

A square is four such cuts. The speed-up is in the order: the zone is first cut to a horizontal strip one row of squares high, and each square in that row then cuts only the strip, which has a fraction of the zone's points.

The shoelace formula gives the area of a polygon from its corner coordinates:

A=12∑i(xi yi+1−xi+1 yi)A = \frac{1}{2} \sum_{i} \bigl(x_i\, y_{i+1} - x_{i+1}\, y_i\bigr)
double twice = 0;
for (var i = 1; i + 1 < ring.Count; i++)
{
    twice += (ring[i].X - ring[0].X) * (ring[i + 1].Y - ring[0].Y) - (ring[i + 1].X - ring[0].X) * (ring[i].Y - ring[0].Y);
}
return twice / 2;

The code measures from the ring's first point (ring[0]) and not from the origin. Mathematically that changes nothing, but SWEREF coordinates are in the millions of metres, and multiplying two such numbers and then subtracting loses precision. Small numbers keep the arithmetic exact enough. Holes are handled by a sign: a shell's area is added, a hole's is subtracted.


5. The landing calculator

Files: Calculator/. The landing page lets a visitor move sliders (size, age, soil, how many people live nearby) and see what a typical piece of nature is worth. It has no map and reads no rasters.

5.1 The idea: the same models with typical inputs

flowchart LR
    S["Sliders:<br/>hectares, age, soil, people nearby, region"] --> T["Typical inputs<br/>from national statistics<br/>(CalculatorOptions)"]
    T --> M["The pages' own calculators:<br/>RecreationCalculator, BerryCalculator,<br/>PeatCalculator, CoastCalculator,<br/>GroundwaterCalculator, …"]
    M --> R["One response shape for all five types:<br/>rows with a kind, a tier, a range"]

This is the most important design decision in this folder. The calculator does not have simplified formulas of its own. ForestStandCalculator calls RecreationCalculator.Visits, BerryCalculator.BilberryIndex and YieldCurve.Calibrate, the very methods the forest page uses. A fix to a model therefore reaches both, and the two cannot drift apart.

What the calculator adds is the translation from a slider to the inputs those methods need.

5.2 A typical forest: tables from the inventory

Instead of rasters, the typical stand reads two published tables: the standing volume and the gross growth that the National Forest Inventory finds at each age, per region.

What the forest inventory measures at each age

Both are read with the same "straight lines between points, flat beyond the ends" rule as every other table (part 2, section 3.3), and scaled by the soil slider. The soil factor is the production of the chosen soil step over that of the average step, from the production table:

V=Vtable(a)⋅fsoilfsoil=B(soil)B(average)V = V_{\text{table}}(a) \cdot f_{\text{soil}} \qquad f_{\text{soil}} = \frac{B(\text{soil})}{B(\text{average})}
public static double SoilFactor(ForestInputs inputs, ForestSliders sliders) =>
    MeanProduction(inputs.Soil, inputs.Region, sliders) / MeanProduction(ForestSoils.Average, inputs.Region, sliders);

The yearly CO₂ uptake multiplies the area AA, the measured gross growth g(a)g(a), the soil factor, the share that survives natural mortality and the CO₂ per cubic metre γ\gamma:

U=A⋅g(a)⋅fsoil⋅(1−s)⋅γs=s0+(1−s0)(Vc⋅Vmax⁡)qU = A \cdot g(a) \cdot f_{\text{soil}} \cdot (1 - s) \cdot \gamma \qquad s = s_0 + (1 - s_0)\left(\frac{V}{c \cdot V_{\max}}\right)^{q}

The mortality ss is exactly the forest page's (part 2, section 7.4), with the same options:

double Surviving(double capShare, double background) =>
    Math.Max(0, 1 - (background + (1 - background) * Math.Pow(volume / (capShare * curve.MaxVolume), options.CrowdingExponent)));
// …
var tonnes = surviving.Select((share, c) => inputs.Hectares * gross * soil * share * co2[c]).ToArray();

5.3 Visits without a map: a made-up landscape

The visit model (part 1, section 6.1) needs the people around the forest and the other forest they could visit instead. Without a map, the calculator builds a synthetic landscape of 1 km squares and runs the real model on it:

The made-up landscape behind the landing calculator's visits
  • The forest sits at the centre.
  • The slider's number of adults (500, 5,000, 50,000 or 250,000) is spread evenly over the squares within 10 km.
  • Other forest covers 68 % of every square out to 20 km, Sweden's share of forest land.
var homes = squares.Where(square => Distance(square) > 0 && Distance(square) <= options.ReachKm * SquareMetres).ToList();
var total = sliders.AdultsWithin10Km[inputs.People];
var population = homes
    .Select((square, i) =>
    {
        var adults = total / homes.Count + (i < total % homes.Count ? 1 : 0);
        return new PopulationNear(square.X, square.Y, adults, adults, Distance(square));
    })
    .ToList();

The expression for adults spreads whole people fairly: every square gets the integer share, and the first total % homes.Count squares get one more, so the total is exact. (Integer division is intended here, unlike the two cases in parts 4 and 5 where it had to be avoided.)

The call at the end is the forest page's own method:

return RecreationCalculator.Visits(
    inputs.Hectares, own, forest, population, everydayShare, 1, new ValueRange(0, 0, 0), options);

The comment on this method records two earlier versions that gave wrong answers (a large forest came out worth up to twice as much per hectare as a small one) and why the current distance rule was chosen. A synthetic landscape is easy to get subtly wrong, and the comment keeps that history.

The lake calculator does the same for fishing days: a made-up landscape with the lake at the centre, the adults around it and other water on a fixed share of every square, fed into the fishing model of part 1, section 6.5. Because the weight between two squares depends only on how far apart they are, it precomputes a table of weights by offset instead of calling the exponential for every pair:

// The weight between two squares depends only on their offset, so it is looked up rather than computed.
var span = 2 * waterReach;
var weights = new double[2 * span + 1, 2 * span + 1];

5.4 A typical mire

MireCalculator uses the peat factors of part 3, section 7. The mire's own yearly flow is the rewetted factor if it is intact and the drained factor if it is drained. The carbon it holds is its volume times the carbon per cubic metre, as CO₂:

stock=d⋅10 000⋅A⋅ρC1000⋅4412tonnes of CO2\text{stock} = d \cdot 10\,000 \cdot A \cdot \frac{\rho_C}{1000} \cdot \frac{44}{12} \quad \text{tonnes of CO}_2
var cubicMetres = inputs.DepthMetres * 10_000 * hectares;
var stock = new[] { density.Low, density.Central, density.High }
    .Select(kg => cubicMetres * kg / 1_000 * Co2PerCarbon)
    .ToArray();

What is priced is not the mire's own flow (a natural mire's methane is nobody's emission) but the difference from the other state. A sign makes one formula serve both directions:

// Intact compared with drained keeps the saving out of the air; drained compared with intact lets it out.
var sign = drained ? -1 : 1;
var savings = each.SelectMany(kind => kind.Savings).Select(saving => sign * saving * hectares).ToList();

5.5 A typical eelgrass meadow: a slider between two published cases

The meadow calculator has a slider for how much sediment erodes when the meadow is lost, from 0 to 35 cm. The source study gives the stock for those two ends only. The slider moves between them in a straight line:

s(x)=snone+(seroded−snone)⋅x35s(x) = s_{\text{none}} + (s_{\text{eroded}} - s_{\text{none}}) \cdot \frac{x}{35}
public static double Interpolated(ParameterRange stock, double share) => stock.Low + (stock.Central - stock.Low) * share;

The options comment calls the straight line an assumption, which it is: the study measured the two ends, not the path between them.

5.6 A typical esker

EskerCalculator is the shortest: it builds one aquifer of the chosen yield class and calls the water page's GroundwaterCalculator.Capacity (part 5, section 6). Its one decision is the row's kind. If a waterworks draws from the esker, the water is Valued and enters the total. If not, the same number is a Capacity: shown, not added.

inputs.Source ? CalculatorRowKinds.Valued : CalculatorRowKinds.Capacity,

5.7 One response for five kinds of nature

All five calculators return the same CalculatorResponse: a list of rows, each with a code, a kind, a tier and a range. The kinds say how a row may be used:

Kind Meaning Enters the total?
Valued Priced and counted Yes
Climate A yearly climate flow, priced In the total with climate
Stored A stock, with what it would cost if released No
Indicator Measured against a threshold No
Capacity, Example Shown for comparison No
NotYet A service EcoVal does not value yet No

The NotYet rows matter as much as the valued ones: they tell the visitor which services are missing from the total, so that a low number is not read as "this is all it is worth".


6. Summary of this part

Section Kind of calculation Regression or fitted model?
Ground cover Rule-based classification of sampled pixels; a range from two margins No
Sun position Astronomical formulas No
Shadow casting Geometry along the sun's ray, vectorised; bit masks No
Cooling Majority vote per cell; mean and percentiles from a histogram; differences No
People nearby Polygon clipping and the shoelace formula No
Typical forest Inventory tables, the forest page's growth, visit and berry models Reuses EcoVal's calibrated models and the borrowed berry models
Typical lake The fishing model on a made-up landscape Reuses EcoVal's calibrated fishing parameters
Typical mire, meadow, esker The pages' own factors; linear interpolation for the erosion slider No

Nothing in this part is fitted to data. The city page is geometry and counting; the landing calculator is reuse.


7. All six parts: where statistics and models appear

This closes the series, so here is the answer to "does EcoVal use statistical regression, machine learning, or something else?" in one place.

No machine learning is trained or run by EcoVal. No ML library is referenced, and no model file is shipped.

What Kind Trained by When Where it is documented
Stream width from catchment area Ordinary least-squares regression (log–log) EcoVal API start, from the database Part 1, 5.1
Sea trout densities, smolt ratios, salmon smolts per km Quantiles and calibration ratios EcoVal API start Part 1, 5.2–5.3
Raw-water trend Sen's slope with the Mann–Kendall test EcoVal Each request Part 5, 5
Visits by distance: excursions, tourism Gravity model, calibrated by grid search EcoVal Offline (EcoVal.Calibration) Part 1, 6.1–6.4
Fishing days by people Gravity model, calibrated by weighted least squares on a grid EcoVal Offline (EcoVal.Calibration) Part 1, 6.5
Growth model: production level, mortality, old-forest floor Calibrated by grid search, least squares EcoVal Offline (a Python script) Part 2, 7.7
Form height by age Binned ratio EcoVal Offline (EcoVal.Calibration) Part 1, 6.6
Chanterelle habitat Ridge logistic regression, block cross-validated EcoVal Offline; not used by the app Part 1, 6.7
Berry cover and yield Published logistic and log-linear regressions The papers' authors Borrowed coefficients Part 3, 3.2
Organic carbon from forested wetland One coefficient of a published log-linear regression The paper's authors Borrowed coefficient Part 3, 6
Eel length and weight Published linear and power-law relations SLU Borrowed coefficients Part 4, 10.2
Probability of high nature value A predictive model's output raster Its authors Borrowed output Part 3, 8.5
Nutrient loads A hydrological model's output SMHI Borrowed output Part 3, 4.1

Everything else (most of the app) is deterministic arithmetic on measured data and published factors: sums over pixels, table lookups, products of rates, discounted sums, graph walks and geometry.

Three habits recur in all of it, and they are what to keep when adding to the code:

  1. Formulas are pure functions, separate from the code that reads data, so they can be tested by hand and reused by the calibrations.
  2. Every number is a range, built deliberately: three consistent parameter sets, every combination, the spread of observed years, or corner products, whichever fits the formula.
  3. A number is not stretched beyond its source. Inputs are clamped to the range a model was fitted on, costs are refused outside the dams a study covered, and a missing value is sent as a code saying why, never as a guess.