EcoVal Changelog v0.5.0

How the calculations are built, part 3: recreation, berries, water, peat and protected nature

Parts 1 and 2 covered the foundations and the forest's core chain (stock, timber, growth, carbon). This part covers the rest of the forest page: what the forest gives people who visit it, the berries, what felling does to water, the peat under the trees, and the protected and valuable nature inside the outline.

docs/calculations.md explains what each number means and where the inputs come from. This document explains the code. All file paths are relative to backend/EcoVal.Api/Features/Forest/. Code excerpts are copied from the source and shortened; // … marks what is left out.

Contents


1. What these sections have in common

Most of the sections here price a change over time: felling causes something (lost visits, fewer berries, more leaching) that lasts for some years and then fades. They share one formula, the present value of a yearly flow:

PV=∑t=0H−1pt⋅qt(1+r)tPV = \sum_{t=0}^{H-1} \frac{p_t \cdot q_t}{(1 + r)^{t}}

qtq_t is the physical quantity in year tt (visits, kilograms, tonnes), ptp_t its price, rr the discount rate (3.5 %) and HH the horizon (100 years). Each section differs only in how it produces qtq_t. They also all reuse the felling years of the growth model's two felled paths (part 2, section 8), so that every section agrees on when the forestry path fells again.

flowchart LR
    G["Growth model (part 2):<br/>felling years, stand volume by year,<br/>the kept forest's CO₂ stock"] --> R["Recreation after felling"]
    G --> B["Berries"]
    G --> W["Nutrient leaching"]
    G --> P["Peat: the rewet path's lost uptake"]
    PR["Carbon price cases (part 2)"] --> P

The second thing they share: several sections use regression models published by others. EcoVal does not fit them; it takes the published coefficients and evaluates the formula. Section 9 lists them.


2. Recreation

Files: Recreation/RecreationCalculator.cs, Recreation/RecreationSection.cs, Recreation/RecreationAfterFelling.cs.

How visits are shared by distance (everyday visits, excursions, tourism) and how those models were calibrated is in part 1, sections 6.1 to 6.4. This section covers what surrounds that core: how many visits an adult makes, what a visit is worth, where counted visits take over, and what felling costs.

2.1 Visits per adult: a weighted sum of survey classes

A national survey gives the share of adults in each frequency class ("1–5 times a year", "6–20 times", and so on). Visits per adult is the sum of each class's share wcw_c times a number of visits ncn_c for the class. The class bounds give the range: the lowest count in each class, the survey's own index value, and the highest.

V=∑cwc ncV = \sum_c w_c \, n_c
public static ValueRange VisitsPerAdult(IReadOnlyList<VisitFrequencyClass> classes) => new(
    Math.Round(classes.Sum(c => c.Share * c.Low), 1),
    Math.Round(classes.Sum(c => c.Share * c.Central), 1),
    Math.Round(classes.Sum(c => c.Share * c.High), 1));

With the configured classes the central value is 25.7 visits a year.

2.2 The value of a visit, moved to today's prices

Each study's value per visit is in the prices of the year it was made. Two adjustments bring it to the price year: the consumer price index, and a real income growth gg (1.15 % a year) for each year since the survey, because people value their time more as incomes rise.

vtoday=vstudy⋅KPIprice yearKPIstudy year⋅(1+g) price year−survey yearv_{\text{today}} = v_{\text{study}} \cdot \frac{\text{KPI}_{\text{price year}}}{\text{KPI}_{\text{study year}}} \cdot (1 + g)^{\,\text{price year} - \text{survey year}}
var indexed = Money.Indexed(value.Sek, options.ConsumerPriceIndex, value.PriceYear, options.PriceYear, "Valuation:Recreation");
var surveyYear = value.SurveyYear ?? value.PriceYear;
var growth = Math.Pow(1 + options.IncomeGrowthPerYear, Math.Max(0, options.PriceYear - surveyYear));

The response carries both the indexed value and the value after growth, so the page can show each step.

2.3 Counted visits replace the model

Where an area's visits have actually been counted, the count is used instead of the model. The polygon gets the area's count in proportion to how much of the area it covers:

visitsP=count⋅min⁡ ⁣(1, overlap haarea ha)\text{visits}_P = \text{count} \cdot \min\!\left(1,\ \frac{\text{overlap ha}}{\text{area ha}}\right)
var share = area.AreaHectares > 0 ? Math.Min(1, area.OverlapHectares / area.AreaHectares) : 0;
var whole = new ValueRange(area.VisitsLow, Math.Round((area.VisitsLow + area.VisitsHigh) / 2.0), area.VisitsHigh);

To avoid counting the same land twice, the modelled visits are then scaled by the share of the polygon that lies outside every counted area (uncountedShare), and the excursion and tourism models are run on that uncounted part only:

// Counted visits replace all modelled terms where they apply.
var uncounted = measured.Count == 0 ? polygon : await lookups.FindUncountedPartAsync(polygon, cancellationToken);
var uncountedShare = polygon.Area > 0 ? Math.Clamp(uncounted.Area / polygon.Area, 0, 1) : 0;

2.4 The holiday share: not counting a visit twice

The survey's visits per adult include outings made on holiday. The models place all of an adult's visits near home, while the tourism model counts guests where they stay. A visit made on holiday would therefore be counted twice. The share hh of residents' visits that are made while staying in commercial accommodation is taken out of the residents' models:

h=min⁡ ⁣(1, ∑mdomestic nightsm⋅qmV⋅adults)h = \min\!\left(1,\ \frac{\sum_m \text{domestic nights}_m \cdot q_m}{V \cdot \text{adults}}\right)

with qmq_m the visits per guest night for municipality mm's class.

double Holiday(Func<ParameterRange, double> pick) => data.Municipalities.Values
    .Sum(municipality => municipality.DomesticNights * pick(tourism.VisitsPerNight(tourism.ClassOf(municipality.Code))));
double Share(double holiday, double visitsPerAdult) =>
    visitsPerAdult > 0 ? Math.Min(1, holiday / (visitsPerAdult * data.Adults)) : 0;

Foreign guests are not in the survey at all, so their visits are simply added.

2.5 Putting the everyday visits together

The everyday visits are the product of four factors: visits per adult VV, the polygon's share of nearby adults' visits S(d0)S(d_0) from the distance model (part 1, section 6.1), the share of visits that are everyday visits (1−s)(1−h)(1 - s)(1 - h), and the uncounted share uu.

visits=V⋅S(d0)⋅(1−s)(1−h)⋅u\text{visits} = V \cdot S(d_0) \cdot (1 - s)(1 - h) \cdot u

The range pairs the lows and the highs. SS is computed for each of the three distances d0d_0, and the low case takes the smallest of the three and the high case the largest, whichever distance that happens to be:

var shares = new[] { Share(decayKm.Low), Share(decayKm.Central), Share(decayKm.High) };
var visits = new ValueRange(
    Math.Round(perAdult.Low * shares.Min() * everydayShare.Low * uncountedShare),
    Math.Round(perAdult.Central * shares[1] * everydayShare.Central * uncountedShare),
    Math.Round(perAdult.High * shares.Max() * everydayShare.High * uncountedShare));

A longer d0d_0 does not always mean more visits: it lets people reach this forest from further away, but it also lets them reach every other forest. That is why the code takes Min() and Max() and not shares[0] and shares[2].

Excursions are valued in two parts: those from homes within 10 km at the everyday value vv, the rest at the trip value vtripv_{\text{trip}} (a longer outing is worth more):

value=nnear⋅v+(n−nnear)⋅vtrip\text{value} = n_{\text{near}} \cdot v + (n - n_{\text{near}}) \cdot v_{\text{trip}}

2.6 What felling costs in recreation

A clear-cut is less attractive to visit than a grown forest. A panel of experts scored stands 0–10 by phase of development, and the score is a step function of the stand's age:

How attractive a stand is for recreation, by its age
public static double Score(double age, double[] scores, RecreationAfterFellingOptions options)
{
    var phase = Array.FindIndex(options.PhaseUpperAges, upper => age < upper);
    return scores[phase < 0 ? scores.Length - 1 : phase];
}

In year tt the kept stand has age a0+ta_0 + t and the felled one has the age since its latest felling, τ(t)\tau(t). The share of the recreation value lost that year is how far the felled stand's score falls short:

ℓ(t)=max⁡ ⁣(0, 1−score(τ(t))score(a0+t))\ell(t) = \max\!\left(0,\ 1 - \frac{\text{score}(\tau(t))}{\text{score}(a_0 + t)}\right)

and the loss over the horizon is the present value of that share of the yearly recreation value YY:

loss=∑t=0H−1Y⋅ℓ(t)(1+r)t\text{loss} = \sum_{t=0}^{H-1} \frac{Y \cdot \ell(t)}{(1 + r)^{t}}
double Loss(double sekPerYear, double[] scores, IReadOnlyList<int> fellingYears) =>
    Enumerable.Range(0, horizon)
        .Sum(year => sekPerYear * LostShare(standAgeYears.Value + year, AgeAfterFelling(year, fellingYears), scores, options)
            / Math.Pow(1 + discountRate, year));
public static int AgeAfterFelling(int year, IReadOnlyList<int> fellingYears) =>
    year - fellingYears.Where(felling => felling <= year).DefaultIfEmpty(0).Max();

fellingYears comes from the growth model, so the forestry path loses value again each time it is felled.


3. Berries

File: Berries/BerryCalculator.cs. The section answers: how many kilograms of bilberry and lingonberry does this forest give a year, and how does that change if it is felled?

It is built in three layers:

flowchart TB
    A["Level: the region's measured crop per hectare,<br/>scaled by the county's berry cover"] --> D
    B["Shape: published Finnish models of how the crop<br/>depends on stand age and density"] --> C["Relative index of this stand<br/>against an average stand"]
    C --> D["Crop of this stand, kg/ha/year"]
    D --> E["Along the three paths, year by year:<br/>crop kept − crop felled"]
    E --> F["Picked share × price, discounted"]

3.1 The level: measured crops

The National Forest Inventory publishes each region's total berry crop per year. The mean over the years, divided by the region's forest land, is the crop of an average hectare:

cˉregion=mean⁡y(cropy)forest land\bar{c}_{\text{region}} = \frac{\operatorname{mean}_y(\text{crop}_y)}{\text{forest land}}
public static double RegionKgPerHectare(IReadOnlyList<double> thousandTonnes, double thousandHectares) =>
    thousandTonnes.Average() * 1_000_000 / (thousandHectares * 1_000);

Crops are only published per region, but berry cover (the share of the ground the plants cover) is published per county. The county's level is the region's crop scaled by the ratio of covers:

cˉcounty=cˉregion⋅covercountycoverregion\bar{c}_{\text{county}} = \bar{c}_{\text{region}} \cdot \frac{\text{cover}_{\text{county}}}{\text{cover}_{\text{region}}}

3.2 The shape: published regression models

How does one stand differ from the average? Two Finnish studies fitted models of berry cover and yield to inventory plots. EcoVal uses their published coefficients; it does not fit anything. This is "borrowed regression": the statistics were done by the papers' authors on Finnish data.

Each model has two steps. First, the plant's cover cc (in %) from a logistic model, where the linear predictor η\eta is a sum of coefficients times stand properties:

c=1001+e−ηc = \frac{100}{1 + e^{-\eta}}

For bilberry (Miina et al. 2009), with stand age aa, basal area GG, pine share qq, a term for planted stands and a reference altitude:

ηbil=β0+β1q+β2 [planted]+β3 alt+β4a+β5a2100+β6G+β7G2100\eta_{\text{bil}} = \beta_0 + \beta_1 q + \beta_2\,[\text{planted}] + \beta_3\,\text{alt} + \beta_4 a + \beta_5 \frac{a^2}{100} + \beta_6 G + \beta_7 \frac{G^2}{100}

Second, the yield from the cover, as a log-linear model (so the yield is the exponential of a sum):

yield∝exp⁡ ⁣(γ1c+γ2c2100+γ3ln⁡(G+1))\text{yield} \propto \exp\!\left(\gamma_1 c + \gamma_2 \frac{c^2}{100} + \gamma_3 \ln(G + 1)\right)
public static double BilberryIndex(StandYear stand, double pineShare, bool planted, BerryOptions options)
{
    var m = options.BilberryCoverModel;
    var logit = m.Intercept
        + m.Pine * pineShare
        + (planted ? m.ArtificialRegeneration : 0)
        + m.AltitudePerMetre * options.ReferenceAltitudeMetres
        + m.Age * stand.AgeYears
        + m.AgeSquaredPer100 * stand.AgeYears * stand.AgeYears / 100
        + m.BasalArea * stand.BasalArea
        + m.BasalAreaSquaredPer100 * stand.BasalArea * stand.BasalArea / 100;
    return Yield(CoverPercent(logit), stand.BasalArea, options.BilberryYield);
}

private static double CoverPercent(double logit) => 100 / (1 + Math.Exp(-logit));

private static double Yield(double coverPercent, double basalArea, QuadraticYield model) =>
    Math.Exp(model.Cover * coverPercent
        + model.CoverSquaredPer100 * coverPercent * coverPercent / 100
        + model.LnBasalAreaPlusOne * Math.Log(basalArea + 1));

The squared terms with negative coefficients are what give the curves a peak: bilberry does best in a medium-dense stand, while lingonberry fruits most in the open.

Berry crop by how dense the stand is

The coefficients live in BerryOptions as plain properties, each with the paper and table it comes from:

/// <summary>Miina et al. (2009) Table 2: logit of bilberry cover.</summary>
public sealed class BilberryCoverModel
{
    public double Intercept { get; set; } = -3.8470;
    public double Pine { get; set; } = 0.1209;
    // …
    public double BasalArea { get; set; } = 0.0947;
    public double BasalAreaSquaredPer100 { get; set; } = -0.1916;
}

3.3 Only the ratio is used

The Finnish models' absolute level is not trusted for Sweden, and the yield formula above drops the model's intercept. Only the ratio between this stand and an average stand is used. The average stand is the mean of the index over one full rotation of the forestry path, which stands for a landscape with every age in it:

cstand=cˉcounty⋅I(stand)mean⁡rotationIc_{\text{stand}} = \bar{c}_{\text{county}} \cdot \frac{I(\text{stand})}{\operatorname{mean}_{\text{rotation}} I}
/// <summary>kg per hectare and year: the county's average stand × this stand's index ÷ the average stand's.</summary>
public double KgPerHectare(StandYear stand, bool planted) => LevelPerHectare * Index(stand, planted) / Mean;

This is a common and sound way to combine two sources: a level from local measurements and a shape from a model fitted elsewhere.

3.4 The stand along the paths

The berry models need the stand's age and basal area each year. The growth model gives volume by year, not basal area, so the stand's form height (volume ÷ basal area today, see part 1, section 6.6) converts it and is assumed to stay the same:

Gt=VtF,F=V0G0G_t = \frac{V_t}{F}, \qquad F = \frac{V_0}{G_0}
var formHeight = volumePerHectare / basalArea;
// …
double BasalArea(double volume) => volume / formHeight;
var keep = Enumerable.Range(0, horizonYears)
    .Select(year => new StandYear(standAgeYears + year, BasalArea(paths.KeepVolume[year]), Regrown: false))
    .ToList();

3.5 The loss and its value

The kilograms lost in year tt are the picked share π\pi times the area AA times the difference in crop:

Δt=π⋅A⋅[ckept(t)−cfelled(t)]value=∑t=0H−1p⋅Δt(1+r)t\Delta_t = \pi \cdot A \cdot \bigl[c_{\text{kept}}(t) - c_{\text{felled}}(t)\bigr] \qquad \text{value} = \sum_{t=0}^{H-1} \frac{p \cdot \Delta_t}{(1 + r)^{t}}

Δt\Delta_t can be negative: a young open stand can give more lingonberries than the old one did. The sum keeps the sign, so a gain offsets a loss.

double LostKg(Species species, Case c, List<StandYear> felled, int year) =>
    c.Share * forestHectares * species.KgPerHectare(keep[year], false)
    - c.Share * forestHectares * species.KgPerHectare(felled[year], c.Planted && felled[year].Regrown);

The three cases are small records that bundle a picked share, a price selector and whether the regrown forest is planted, which keeps the low, central and high variants in one table:

var cases = new[]
{
    new Case(share.Low, Planted: false, species => species.Price.Low),
    new Case(share.Central, Planted: true, species => species.Price.Central),
    new Case(share.High, Planted: true, species => species.Price.High),
};

4. Nutrients to water after felling

File: Water/WaterCalculator.cs. A clear-cut leaks more nitrogen and phosphorus to streams than a standing forest for some years.

4.1 The forest's own load per hectare

SMHI models how much nitrogen and phosphorus each subcatchment's forest sends to water. A polygon can overlap several subcatchments, so its load per hectare is the mean of theirs, weighted by how much of the polygon lies in each:

L=∑iloadiforest hai⋅oi∑ioiL = \frac{\sum_i \dfrac{\text{load}_i}{\text{forest ha}_i} \cdot o_i}{\sum_i o_i}

with oio_i the polygon's overlap with subcatchment ii.

var weight = loaded.Sum(row => row.OverlapHectares);
double PerHectare(Func<CatchmentLoadRow, double> kg) =>
    loaded.Sum(row => kg(row) / row.ForestHectares * row.OverlapHectares) / weight;

4.2 The extra leaching: a multiple for a few years

A clear-cut's water carries ff times the forest's concentration (for nitrogen 1.25, 2 or 2.1) with the same runoff. The extra, per year, over the felled area AA:

E=(f−1)⋅L⋅AE = (f - 1) \cdot L \cdot A

It lasts nn years after each felling (5 in the south, 10 in the north), then returns to the forest's level.

Extra nitrogen leaching after felling
var perYear = new ValueRange(
    (factor.Low - 1) * forestPerHectare * felledHectares,
    (factor.Central - 1) * forestPerHectare * felledHectares,
    (factor.High - 1) * forestPerHectare * felledHectares);

4.3 The value: pulses, discounted

Each felling year starts a pulse. Since the extra EE is the same in every pulse year, the present value factors into EE, the price pp and a sum of discount factors over the pulse years:

PV=p⋅E⋅∑t ∈ pulse years(1+r)−tPV = p \cdot E \cdot \sum_{t \,\in\, \text{pulse years}} (1 + r)^{-t}
var pulseYears = fellings
    .SelectMany(start => Enumerable.Range(start, years))
    .Where(year => year >= 0 && year < horizonYears)
    .ToList();
var discount = pulseYears.Sum(year => Math.Pow(1 + discountRate, -year));
// …
CarbonValueCalculator.RoundToHundreds(nutrient.ExtraKgPerYear.Central * discount * nutrient.SekPerKg.Central),

SelectMany turns "each felling year" into "every year of every pulse" in one expression. The forestry path has several felling years, the left-to-grow path only year 0.

4.4 Prices from several sources

Each nutrient has several published prices (the cost of removing it in a wetland, a damage cost, a Swedish value by water district), in different currencies and price years. They are all converted the same way as the carbon prices in part 2:

return price.PerKg * exchange * Index(price.PriceYear, options);

and the range is assembled from them. For phosphorus the low is the removal cost, the central the middle of the district's value band, and the high the larger of the band's top and the damage cost:

var price = ValueRange.Spanning(removal, (band.Low + band.High) / 2 * index, Math.Max(band.High * index, damage), 0);

Spanning (part 1, section 3.1) guarantees low ≤ central ≤ high even where the sources do not come in that order.


5. Drinking water downstream

File: Water/DrinkingWaterDownstreamCalculator.cs. Felling raises the organic carbon (the brown colour) in the streams below it. If a drinking-water source lies downstream, its raw water gets a little browner, and the waterworks pays a little more to clean it.

5.1 Finding the first source downstream

Each subcatchment drains into one other. Starting from each subcatchment the polygon overlaps, the lookup walks downstream step by step and records which subcatchments hold a designated drinking-water source:

flowchart LR
    P["Polygon overlaps<br/>subcatchments A and B"] --> A["A"]
    P --> B["B"]
    A --> C["C"]
    B --> C
    C --> D["D: holds a lake that is<br/>a drinking-water source"]
    D --> E["E … to the sea"]
    style D stroke-width:3px

Pick takes, for each start, the first step whose subcatchment holds a source, then chooses the source that the largest part of the polygon drains to:

var path = steps[start.AroUuid].OrderBy(step => step.Depth).ToList();
var first = path.FirstOrDefault(step => hits[step.AroUuid].Any());
// …
var chosen = reached
    .GroupBy(entry => entry.Hit!.WaterId)
    .OrderByDescending(group => group.Sum(entry => entry.Start.OverlapHectares))
    .ThenBy(group => group.Key, StringComparer.Ordinal)
    .First()
    .ToList();

The second ordering key (ThenBy on the water's id) makes the choice deterministic when two sources tie: the same polygon always gives the same answer.

5.2 The mixing model

The felled land is a share ϕ\phi of everything that drains to the source:

ϕ=AfelledAupstream\phi = \frac{A_{\text{felled}}}{A_{\text{upstream}}}

The felled streams carry ΔC\Delta C mg/l more organic carbon and ρ\rho times as much water. Downstream they mix with water from the rest of the catchment, so the source sees the increase diluted by the share:

ΔCsource=ϕ⋅ΔC⋅ρ\Delta C_{\text{source}} = \phi \cdot \Delta C \cdot \rho

This is a conservative mixing model: it assumes nothing is lost on the way, so it is an upper estimate.

var felled = felledHectares * Math.Clamp(source.StartsHectares / polygonHectares, 0, 1);
var share = felled / (source.UpstreamAreaKm2 * 100);      // km² → ha
// …
double Extra(double increase, double runoff) => share * increase * runoff;

The increase has two phases (the first two years after felling, then two years after scarification), each with its own ΔC\Delta C.

5.3 The cost

A waterworks' cost of one more mg/l of organic carbon is published in öre per cubic metre. The extra cost is

o¨re per m³=ΔCsource⋅κ\text{öre per m³} = \Delta C_{\text{source}} \cdot \kappa

and, summed over the years of each phase, in kronor per million cubic metres of water treated (1 öre/m³ is 10,000 kr per million m³):

// kr per million m³ over a felling's years: öre per m³ × 10,000.
double Sek(Func<ValueRange, double> end) =>
    Math.Round(phases.Sum(phase => end(phase.OrePerCubicMetre) * (phase.ToYear - phase.FromYear + 1)) * 10_000);

The result is per million m³ because the volume a waterworks takes is not public. The share ϕ\phi is also classified against two published thresholds (0.11 and 0.23 of the catchment) and sent as a code, so the page can say whether the effect would be detectable at all.


6. Wet ground: organic carbon and mercury

File: Water/WetGroundWaterCalculator.cs. These are indicators only; nothing is priced.

A Swedish study of 179 headwater streams fitted a regression of organic carbon (TOC) against the share of the catchment that is forested wetland. The model is log-linear: the base-10 logarithm of TOC rises in a straight line with the share ww, with slope 1.3. EcoVal uses that one published coefficient to say how much higher TOC is with this polygon's share than with none:

log⁡10TOC=α+1.3 w⟹TOC(w)TOC(0)−1=10 1.3 w−1\log_{10}\text{TOC} = \alpha + 1.3\,w \quad\Longrightarrow\quad \frac{\text{TOC}(w)}{\text{TOC}(0)} - 1 = 10^{\,1.3\,w} - 1

The intercept α\alpha cancels in the ratio, which is why only the slope is needed.

var beyondStudy = forestOnWetland > options.MaxForestOnWetlandShare;
var tocIncrease = forestOnWetland is { } share
    ? Math.Round(Math.Pow(10, options.TocWetlandCoefficient * Math.Min(share, options.MaxForestOnWetlandShare)) - 1, 2)
    : (double?)null;

The Math.Min is important. The study's catchments had at most 41.2 % forested wetland. A regression says nothing reliable outside the range of the data it was fitted on, so a larger share is computed at 41.2 % and flagged with beyondStudy, and the page shows it as "at least". This is the same guard against extrapolation as the clamping in the chanterelle model (part 1, section 6.7).


7. Wetland and drained peat

Files: Wetland/WetlandCalculator.cs, Wetland/PeatCalculator.cs, Wetland/DitchMask.cs.

7.1 Land cover and soil moisture: class areas, grouped

The land cover and soil moisture rasters hold classes. ClassAreas.Count (part 1, section 2.3) gives hectares per class value, and the calculator folds the many class values into a few groups with a switch on patterns:

switch (LandCoverClasses.Group(value))
{
    case LandCoverGroup.OpenWetland or LandCoverGroup.LowMountainForestOnWetland:
        openWetland += hectares;
        break;
    case LandCoverGroup.ForestOnWetland:
        forestOnWetland += hectares;
        break;
    // …
}

7.2 Which peat is drained: a spatial index

Peat counts as drained when it lies within 25 m of a ditch. Sweden's ditch map has about 30 million lines, so testing each peat pixel against every ditch is out of the question. DitchMask cuts the ditches near the polygon into straight segments and puts them in an R-tree (NetTopologySuite's STRtree), a spatial index that can return "the segments whose bounding box touches this box" without looking at the rest:

public bool Near(double x, double y)
{
    // …
    var point = new Coordinate(x, y);
    foreach (var segment in _index.Query(new Envelope(x - _distance, x + _distance, y - _distance, y + _distance)))
    {
        if (segment.Distance(point) <= _distance)
        {
            return true;
        }
    }
    return false;
}

The query box finds candidates cheaply; the exact distance test then decides. This two-step pattern (a cheap filter, then an exact test) is the same idea as the boundary pixels in part 1, section 2.2.

7.3 Emissions per hectare: three gases in one unit

Drained peat emits carbon dioxide, nitrous oxide and methane. To add them up, each is converted to "CO₂ equivalents" (CO₂e) in two steps: from the mass of the element reported (carbon or nitrogen) to the mass of the gas, by the ratio of molar masses, and from the gas to CO₂e by its global warming potential (GWP: how many times more warming a tonne of the gas causes than a tonne of CO₂ over 100 years).

Edrained=(CCO2+CDOC)⋅4412  +  NN2O⋅4428⋅GWPN2O1000  +  (MCH4+Mditch)⋅GWPCH41000E_{\text{drained}} = \bigl(C_{\text{CO}_2} + C_{\text{DOC}}\bigr)\cdot\frac{44}{12} \;+\; N_{\text{N}_2\text{O}}\cdot\frac{44}{28}\cdot\frac{\text{GWP}_{\text{N}_2\text{O}}}{1000} \;+\; \bigl(M_{\text{CH}_4} + M_{\text{ditch}}\bigr)\cdot\frac{\text{GWP}_{\text{CH}_4}}{1000}

The inputs are tonnes of carbon, kilograms of nitrogen and kilograms of methane per hectare and year; the 1000 turns kilograms into tonnes. The GWPs are 265 for nitrous oxide and 28 for methane.

private const double Co2PerCarbon = 44.0 / 12.0;
private const double NitrousOxidePerNitrogen = 44.0 / 28.0;
private const double MethanePerCarbon = 16.0 / 12.0;

public static double DrainedTonnesPerHectare(DrainedPeatFactor factor, PeatOptions options) =>
    (factor.Co2CarbonTonnes + factor.DocCarbonTonnes) * Co2PerCarbon
    + factor.NitrousOxideNitrogenKg * NitrousOxidePerNitrogen * options.NitrousOxideGwp / 1_000
    + (factor.MethaneKg + factor.DitchMethaneKg) * options.MethaneGwp / 1_000;

Rewetted peat stops losing carbon (it may even take some up) but emits more methane:

Erewetted=(CCO2+CDOC)⋅4412  +  CCH4⋅1612⋅GWPCH41000E_{\text{rewetted}} = \bigl(C_{\text{CO}_2} + C_{\text{DOC}}\bigr)\cdot\frac{44}{12} \;+\; C_{\text{CH}_4}\cdot\frac{16}{12}\cdot\frac{\text{GWP}_{\text{CH}_4}}{1000}
Peat emissions drained and rewetted

The chart shows why the rewetting result has such a wide range: the published 95 % range for rewetted methane is very wide, so rewetting can save a lot or, at the unlucky end, cost more than leaving the peat drained. The code keeps that honest by computing the saving at the low end, the centre and the high end of the methane range:

public double[] Savings => [DrainedTonnes - RewettedHighTonnes, SavingTonnes, DrainedTonnes - RewettedLowTonnes];

7.4 The three cases: by the kind of peat

The emission factors differ by the peat's carbon-to-nitrogen ratio, and no map shows that ratio. So the classes themselves are the range: the low case is the class that emits least, the high case the class that emits most, and the central case the classes' mean weighted by how much of each Sweden has:

Ecentral=∑kEk⋅areak∑kareakE_{\text{central}} = \frac{\sum_k E_k \cdot \text{area}_k}{\sum_k \text{area}_k}
double Weighted(Func<PeatCase, double> value) => classes.Zip(each, (factor, peat) => value(peat) * factor.AreaKha).Sum() / area;
return
[
    each.MinBy(peat => peat.DrainedTonnes)!,
    new PeatCase(Weighted(peat => peat.DrainedTonnes), /* … */),
    each.MaxBy(peat => peat.DrainedTonnes)!,
];

7.5 Peat runs out

Drained peat emits by losing its carbon, so a shallow layer is gone before the horizon ends. The years a layer of depth dd metres lasts are its carbon divided by its yearly loss, where ρC\rho_C is the carbon per cubic metre (kg) and λ\lambda the loss (tonnes of carbon per hectare and year):

T(d)=d⋅10 000⋅ρC/1000λT(d) = \frac{d \cdot 10\,000 \cdot \rho_C / 1000}{\lambda}

The 10,000 is the square metres in a hectare (so d⋅10 000d \cdot 10\,000 is the peat's volume per hectare), and the 1000 turns kilograms into tonnes.

public static double YearsUntilGone(double depthMetres, double carbonKgPerCubicMetre, double carbonLossTonnes) =>
    depthMetres * 10_000 * carbonKgPerCubicMetre / 1_000 / carbonLossTonnes;

No map gives the depth of the peat in a polygon, so the region's known spread of depths is used: a share wjw_j of the peat is in depth class jj. The share still emitting in year tt is

S(t)=∑jwj⋅clamp⁡(Tj−t, 0, 1)S(t) = \sum_j w_j \cdot \operatorname{clamp}\bigl(T_j - t,\ 0,\ 1\bigr)

The clamp makes a class count fully while it lasts, for the fraction of its last year that remains, and not at all afterwards.

public static double[] StillEmitting(IReadOnlyList<double> shares, IReadOnlyList<double> years, int horizonYears) =>
    Enumerable.Range(0, horizonYears)
        .Select(year => shares.Zip(years, (share, lasts) => share * Math.Clamp(lasts - year, 0, 1)).Sum())
        .ToArray();
Drained peat runs out

The cases are paired so that the range widens the way it should: the peat that emits most is given the least carbon per cubic metre, so the high case both emits most and runs out first.

7.6 The value: a flow priced year by year

The drained emission is a yearly flow, priced with the carbon price of each year and discounted (CarbonValueCalculator.PresentValueOfFlow, the flow counterpart of part 2's present value of a gap):

PV=∑t=0H−1P(t)⋅S(t)⋅E⋅A(1+r)tPV = \sum_{t=0}^{H-1} \frac{P(t) \cdot S(t) \cdot E \cdot A}{(1 + r)^{t}}
double[] Flow(int i) => emitting[i].Select(share => share * emission[i]).ToArray();
var emissionSek = Range(
    Enumerable.Range(0, 3).SelectMany(i => prices.All.Select(series =>
        CarbonValueCalculator.PresentValueOfFlow(Flow(i), series, discountRate))),
    CarbonValueCalculator.PresentValueOfFlow(Flow(1), prices.Central, discountRate));

As for the carbon value in part 2, the range is the smallest and largest over every combination (three peat cases times three price cases), with the central case computed directly.

The rewet path saves the difference between drained and rewetted emissions, but the trees on rewetted peat stop growing, so the uptake they would have had is lost. The net yearly flow is

net(t)=S(t)⋅[saving−lost uptake(t)]\text{net}(t) = S(t) \cdot \bigl[\text{saving} - \text{lost uptake}(t)\bigr]

where the lost uptake comes from the growth model's kept-forest stock, as its year-to-year increase:

double[] Lost(double[] stock, double hectares) =>
    Enumerable.Range(0, horizonYears).Select(year => (stock[year + 1] - stock[year]) * hectares).ToArray();
double[] Net(int i, double savedTonnes, double[]? lost) =>
    Enumerable.Range(0, horizonYears).Select(year => emitting[i][year] * (savedTonnes - (lost?[year] ?? 0))).ToArray();

Here the range runs over four dimensions at once: three peat cases, three methane values, three growth runs and three price cases, 81 combinations in all. The nested SelectMany enumerates them and the range takes the minimum and maximum.


8. Protected and valuable nature

These sections count and measure; none is priced ("a value without a price is not zero"). They are mostly geometry and grouping, and the interesting part is avoiding double counting.

8.1 How much may be felled: areas of unions

File: Protection/ForestProtection.cs. A piece of land can be a nature reserve and a Natura 2000 site. Adding the two overlaps would count it twice. The database therefore measures the area of the union of each group of protections inside the outline, and the calculator turns those areas into the split:

flowchart LR
    O["Outline"] --> S["No felling<br/>(reserve, national park, biotope protection, …)"]
    O --> F["Fellable = outline − no felling"]
    F --> P["of which: permit needed (Natura 2000)"]
    F --> A["of which: conservation agreements"]
    F --> K["of which: key biotopes"]
Afellable=max⁡(0, Aoutline−Ano felling)fellable share=AfellableAoutlineA_{\text{fellable}} = \max\bigl(0,\ A_{\text{outline}} - A_{\text{no felling}}\bigr) \qquad \text{fellable share} = \frac{A_{\text{fellable}}}{A_{\text{outline}}}

The felled column's values elsewhere on the page are scaled by this share.

One rule deals with a practical nuisance. An outline drawn around a reserve never matches its border exactly, which leaves a thin strip that looks fellable. Below 0.1 ha or 1 % of the outline, that strip is treated as a sliver and the outline counts as fully protected:

var fellable = Math.Max(outlineHectares - noFelling, 0);
if (noFelling > 0 && (fellable < SliverHectares || fellable < SliverShare * outlineHectares))
{
    noFelling = outlineHectares;
    fellable = 0;
}

8.2 Reindeer herding: unions and differences

File: Reindeer/ReindeerCalculator.cs. Sami villages share winter land, and the year-round land lies across them, so here too the totals are areas of unions. The land used only in winter is a set difference:

Aherding=area⁡(⋃villages∪year-round)Awinter only=area⁡(herding∖year-round)A_{\text{herding}} = \operatorname{area}\Bigl(\bigcup \text{villages} \cup \text{year-round}\Bigr) \qquad A_{\text{winter only}} = \operatorname{area}\bigl(\text{herding} \setminus \text{year-round}\bigr)
var yearRound = Union(yearRoundPieces);
var herding = Union([.. villagePieces, .. yearRoundPieces]);
// …
var winterOnlyHectares = herding is null ? 0 : Hectares(yearRound is null ? herding : herding.Difference(yearRound));

UnaryUnionOp.Union and Difference are NetTopologySuite geometry operations. Overlaps under 0.01 ha are dropped as slivers along shared edges.

8.3 EU habitat types and species records: group and sum

Files: Habitats/NaturaHabitatCalculator.cs, Species/SpeciesCalculator.cs. Both take rows from the database (pieces of mapped habitat; individual species records) and summarise them with LINQ's GroupBy. The species section splits records by recency first:

var recent = records.Where(record => record.Year >= options.RecentFromYear).ToList();
var earlier = records.Where(record => record.Year < options.RecentFromYear).ToList();
var undated = records.Count - recent.Count - earlier.Count;

and then groups by species and sorts by how threatened the species is, with ties broken by the number of records and then the name, so the order is stable:

.OrderBy(found => CategoryRank(found.RedListCategory))
.ThenByDescending(found => found.Records)
.ThenBy(found => found.ScientificName, StringComparer.Ordinal)

8.4 How much has anyone looked: a percentile

File: Species/RecordEffortCalculator.cs. A short species list can mean few species or few visits by recorders. This calculator measures the second, so the page can say which.

It works on the 1 km squares the polygon touches. Two numbers describe the effort:

  • the median number of records among the touched squares that have any record, and where that median sits among all of Sweden's squares with records, as a percentile;
  • the share of the touched squares that have any record at all.
percentile=100⋅∣{Sweden’s squares with fewer records than the median}∣∣{Sweden’s squares with records}∣\text{percentile} = 100 \cdot \frac{\bigl|\{\text{Sweden's squares with fewer records than the median}\}\bigr|}{\bigl|\{\text{Sweden's squares with records}\}\bigr|}

Sweden's distribution is one sorted list, so "how many are below this value" is a binary search: halve the search range until it closes on the position. It takes about 17 steps for 100,000 values instead of 100,000 comparisons.

private static int LowerCount(IReadOnlyList<int> sorted, double value)
{
    int low = 0, high = sorted.Count;
    while (low < high)
    {
        var middle = (low + high) / 2;
        if (sorted[middle] < value)
        {
            low = middle + 1;
        }
        else
        {
            high = middle;
        }
    }
    return low;
}

The two numbers are then turned into a reading by fixed cut-offs:

Reading Condition
none No touched square has a record
little Percentile below 25, or records in fewer than half the squares
well Percentile at least 75, and records in at least three quarters of the squares
typical Anything else
var reading = with == 0 ? EffortReadings.None
    : percentile < options.LittleBelowPercentile || share < options.LittleBelowShare ? EffortReadings.Little
    : percentile >= options.WellFromPercentile && share >= options.WellFromShare ? EffortReadings.Well
    : EffortReadings.Typical;

Note the asymmetry: one weak signal is enough for "little", but both must be strong for "well". Empty squares are kept out of the median on purpose and counted through the share instead, so that Sweden's many unvisited squares do not pull the national reference down to zero.

8.5 Probability of high nature value: reading someone else's trained model

File: ValueCores/ValueCoreCalculator.cs. The raster used here is the output of a predictive model trained by its authors (Naturvärdeskarta Skog, Jonsson et al. 2024): for every hectare, the probability that a field inventory would class it as a forest value core. It is the one place where a trained model's predictions enter the forest page. EcoVal does not train it, run it or hold its parameters; it reads the published raster and summarises it.

The summary is the area-weighted mean probability and the hectares in three bands (the report's own outer classes, at most 0.3 and at least 0.7):

πˉ=∑vv⋅hv100⋅∑vhv\bar{\pi} = \frac{\sum_v v \cdot h_v}{100 \cdot \sum_v h_v}

where hvh_v is the hectares with raster value vv (the probability in percent).

var mean = modelled.Sum(entry => entry.Key * entry.Value) / hectares / 100;
// …
Math.Round(Sum(percent => percent <= options.LowAtMostPercent), 2),
Math.Round(Sum(percent => percent > options.LowAtMostPercent && percent < options.HighAtLeastPercent), 2),
Math.Round(Sum(percent => percent >= options.HighAtLeastPercent), 2),

Because the input is already hectares per value (a histogram from ClassAreas.Count), the mean needs no second pass over the pixels.

8.6 Older deciduous-rich forest: two thresholds, three cases

File: OldForest/DeciduousRichCalculator.cs. A pixel counts when it is both old enough and has enough broadleaf (a broadleaf share of at least 30 %). Both inputs are uncertain: the age has two models (part 2, section 3.1) and the broadleaf share has a lower and a higher reading. The low case requires both conditions with the pessimistic reading of each, the high case with the optimistic reading:

Hlow=∑php⋅1[ap,younger≥τ]⋅1[bp,lower≥0.3]H_{\text{low}} = \sum_p h_p \cdot \mathbb{1}\bigl[a_{p,\text{younger}} \ge \tau\bigr] \cdot \mathbb{1}\bigl[b_{p,\text{lower}} \ge 0.3\bigr]
area[0] += age.Reaches(younger, years) && Rich(share.Lower) ? pixel.Hectares : 0;
area[2] += age.Reaches(older, years) && Rich(share.Higher) ? pixel.Hectares : 0;

Rich compares with a tiny tolerance (value >= minimum - 1e-9), because a share that is exactly 0.3 in the data can arrive as 0.29999999 after floating-point arithmetic, and the definition says "at least".


9. Summary

Section Kind of calculation Regression or fitted model?
Visits per adult, value per visit Weighted sum; price indexing No
Visit sharing by distance Gravity model Calibrated by EcoVal (part 1, sections 6.1–6.4)
Recreation after felling Step function of age; discounted sum No (expert scores)
Berries: level Ratios of published statistics No
Berries: shape Logistic cover model and log-linear yield model Borrowed regression: coefficients from Miina et al. 2009 and Turtiainen et al. 2013, not fitted by EcoVal
Nutrient leaching Published factor on a modelled load; discounted pulses No (SMHI's loads come from SMHI's own hydrological model)
Drinking water downstream Network walk; mixing by area share No (published increases)
Organic carbon from wet ground One coefficient of a log-linear regression Borrowed regression: Löfgren et al. 2014, capped at the study's range
Peat emissions Emission factors, gas conversions, depletion; discounted flow No (inventory and IPCC factors)
Protection, reindeer, habitats, species Geometry unions and grouping No
Recording effort Median, percentile by binary search, cut-offs No
Probability of high nature value Area-weighted mean of a raster Someone else's trained model: EcoVal only reads its output
Deciduous-rich forest Counting pixels against two thresholds No

Three ways a model from elsewhere can enter the app appear in this part, and they are worth telling apart:

  1. Borrowed coefficients (berries, organic carbon): EcoVal evaluates a published formula. The coefficients are options with their source; nothing is trained.
  2. A borrowed model output (nature value probability, SMHI's nutrient loads): EcoVal reads numbers a model produced and has no access to the model itself.
  3. Borrowed factors (peat, leaching multiples, expert scores): single published numbers, not models.

In each case the tier is borrowed or modelled, never measured, which is how the page tells the reader how far to trust it.