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
- 2. Recreation
- 3. Berries
- 4. Nutrients to water after felling
- 5. Drinking water downstream
- 6. Wet ground: organic carbon and mercury
- 7. Wetland and drained peat
- 8. Protected and valuable nature
- 9. Summary
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:
is the physical quantity in year (visits, kilograms, tonnes), its price, the discount rate (3.5 %) and the horizon (100 years). Each section differs only in how it produces . 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 times a number of visits for the class. The class bounds give the range: the lowest count in each class, the survey's own index value, and the highest.
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 (1.15 % a year) for each year since the survey, because people value their time more as incomes rise.
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:
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 of residents' visits that are made while staying in commercial accommodation is taken out of the residents' models:
with the visits per guest night for municipality '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 , the polygon's share of nearby adults' visits from the distance model (part 1, section 6.1), the share of visits that are everyday visits , and the uncounted share .
The range pairs the lows and the highs. is computed for each of the three distances , 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 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 , the rest at the trip value (a longer outing is worth more):
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:
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 the kept stand has age and the felled one has the age since its latest felling, . The share of the recreation value lost that year is how far the felled stand's score falls short:
and the loss over the horizon is the present value of that share of the yearly recreation value :
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:
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:
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 (in %) from a logistic model, where the linear predictor is a sum of coefficients times stand properties:
For bilberry (Miina et al. 2009), with stand age , basal area , pine share , a term for planted stands and a reference altitude:
Second, the yield from the cover, as a log-linear model (so the yield is the exponential of a sum):
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.
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:
/// <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:
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 are the picked share times the area times the difference in crop:
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:
with the polygon's overlap with subcatchment .
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 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 :
It lasts years after each felling (5 in the south, 10 in the north), then returns to the forest's level.
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 is the same in every pulse year, the present value factors into , the price and a sum of discount factors over the pulse years:
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 of everything that drains to the source:
The felled streams carry mg/l more organic carbon and 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:
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 .
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
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 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 , 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:
The intercept 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).
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:
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:
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 metres lasts are its carbon divided by its yearly loss, where is the carbon per cubic metre (kg) and the loss (tonnes of carbon per hectare and year):
The 10,000 is the square metres in a hectare (so 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 of the peat is in depth class . The share still emitting in year is
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();
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):
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
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"]
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:
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.
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):
where is the hectares with raster value (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:
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:
- Borrowed coefficients (berries, organic carbon): EcoVal evaluates a published formula. The coefficients are options with their source; nothing is trained.
- 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.
- 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.