EcoVal Changelog v0.5.0

How the calculations are built, part 2: forest stand, timber, growth and carbon

Part 1 (01-foundations-and-fitted-models.md) covered how an outline becomes pixels and how results are carried. This part follows the forest page's core chain: what stands in the polygon, how old it is, what the timber is worth, how fast it grows, and what felling it would cost the climate.

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/. Code excerpts are copied from the source and shortened; // … marks what is left out.

Contents


1. The chain at a glance

flowchart TB
    R["Rasters, 10 m pixels:<br/>volume, biomass, height, diameter, basal area,<br/>age (two models), site index (two species)"]
    R --> S["Forest stock<br/>m³sk, tonnes biomass, t CO₂"]
    R --> A["Stand age per pixel<br/>low, central, high"]
    A --> P["Stand phases<br/>young, thinning, growing, final felling"]
    R --> M["Species mix<br/>pine, spruce, broadleaf"]
    S --> T["Timber value<br/>kr, net of harvesting and regeneration"]
    P --> T
    M --> T
    DB["Database: prices, costs,<br/>retention, regeneration costs"] --> T
    S --> G["Growth model<br/>yield curve from site index"]
    A --> G
    G --> C["Carbon paths over 100 years<br/>keep, forestry, left to grow"]
    C --> V["Carbon value<br/>kr, priced and discounted"]

Two patterns from part 1 recur in every section:

  • Each class has a thin instance method that reads rasters and a static method with the formulas. The static one takes ZonalResult values or plain numbers, so the tests need no files.
  • Low, central and high are produced by running the same formula three times with three parameter sets, not by widening a single result afterwards.

2. The forest stock

File: Features/Forest/Timber/ForestStockCalculator.cs.

2.1 Volume and biomass

Volume and biomass are per-hectare rasters, so their totals are the zonal sums of part 1, section 2.2:

V=ℓ210 000∑psp vp(m³sk)M=ℓ210 000∑psp mp(t dry matter above ground)V = \frac{\ell^2}{10\,000}\sum_p s_p\,v_p \quad \text{(m³sk)} \qquad M = \frac{\ell^2}{10\,000}\sum_p s_p\,m_p \quad \text{(t dry matter above ground)}

In code this is one property on the zonal result: biomass.TotalOfPerHectareValue.

2.2 The CO₂ stock

The biomass raster counts what is above ground. Roots are added with a root-to-shoot ratio RR, the dry matter is turned into carbon with the carbon fraction fCf_C, and carbon into CO₂ with the ratio of their molar masses (a CO₂ molecule weighs 44, the carbon atom in it 12):

CO2=M⋅(1+R)⋅fC⋅4412\text{CO}_2 = M \cdot (1 + R) \cdot f_C \cdot \frac{44}{12}

RR is the uncertain factor (0.2, 0.25, 0.3), so the formula is a local function called three times:

private const double Co2PerCarbon = 44.0 / 12.0;
// …
var biomassTonnes = biomass.TotalOfPerHectareValue;
var r = parameters.RootToShootRatio;
double Co2(double rootToShoot) => biomassTonnes * (1 + rootToShoot) * parameters.CarbonFraction * Co2PerCarbon;
// …
Co2StockTonnes: new ValueRange(Math.Round(Co2(r.Low), 1), Math.Round(Co2(r.Central), 1), Math.Round(Co2(r.High), 1)),

2.3 Means over trees, and stems per hectare

The height, diameter and basal area rasters are 0 where the trees are under 3 m. A plain mean would be dragged down by clear-cuts, so the mean is taken over the pixels that have trees:

xˉtrees=∑psp xpN−N0\bar{x}_{\text{trees}} = \frac{\sum_p s_p\,x_p}{N - N_0}

where NN is the weighted count of valid pixels and N0N_0 of those that are zero.

private static double? MeanOverTrees(ZonalResult? result) =>
    result is { ValidPixels: > 0 } && result.ValidPixels > result.ZeroPixels
        ? result.Sum / (result.ValidPixels - result.ZeroPixels)
        : null;

Stems per hectare follow from geometry. Basal area GG (m²/ha) is the summed cross-section of all stems at breast height. Divide it by one average stem's cross-section, a circle of diameter dd centimetres:

Nstems=Gπ(d200)2N_{\text{stems}} = \frac{G}{\pi \left(\dfrac{d}{200}\right)^2}

The 200 turns a diameter in centimetres into a radius in metres.

var radiusMetres = d / 200;
return Math.Round(g / (Math.PI * radiusMetres * radiusMetres) / 10) * 10;   // rounded to tens

2.4 Forest land: reading two rasters pixel by pixel

"How much of the polygon is forest land, and how much volume stands on it?" needs two rasters at once: the land cover map says which pixels are forest, the volume raster what stands there. RasterStack.Read walks several layers on one grid and hands each pixel's values to a callback as a ReadOnlySpan<short>:

RasterStack.Read<bool>(
    [volumeTiles, landTiles],
    [RasterLayer.Volume.NoData, RasterLayer.LandCover.NoData],
    polygon,
    (StackedCell cell, ReadOnlySpan<short> values, out bool kept) =>
    {
        kept = false;
        // …
        mapped += cell.Hectares;
        if (!LandCoverClasses.IsForest(values[1]))
        {
            return false;
        }
        forest += cell.Hectares;
        // …
            volume += values[0] * cell.Hectares;
        return false;
    });

cell.Hectares is already the pixel's area times its share inside the polygon, so the sums are the weighted sums of part 1. The growth model below works on this forest land and its volume, not on the whole polygon.


3. Stand age and the rules that depend on it

Files: Forestry/StandAgeRules.cs, Forestry/StandRasters.cs, Features/Forest/OldForest/OldForestCalculator.cs.

3.1 Two age models make one range

Skogsstyrelsen publishes the stand age twice: once modelled as if the stand were spruce, once as if it were pine. The two can differ by decades. EcoVal does not pick one. The two become the range, and the central value is the age for the species that grows best at the pixel (the higher site index):

alow=min⁡(aspruce,apine)ahigh=max⁡(aspruce,apine)a_{\text{low}} = \min(a_{\text{spruce}}, a_{\text{pine}}) \qquad a_{\text{high}} = \max(a_{\text{spruce}}, a_{\text{pine}}) acentral={aspruceif SIspruce>SIpineapineif SIpine>SIspruce12(aspruce+apine)if they are equal or missinga_{\text{central}} = \begin{cases} a_{\text{spruce}} & \text{if } SI_{\text{spruce}} > SI_{\text{pine}} \\ a_{\text{pine}} & \text{if } SI_{\text{pine}} > SI_{\text{spruce}} \\ \tfrac{1}{2}(a_{\text{spruce}} + a_{\text{pine}}) & \text{if they are equal or missing} \end{cases}

The implementation is a tuple-valued property with a switch over a nullable bool:

public bool? SpruceLeads => SiteIndexSpruce is { } spruce && SiteIndexPine is { } pine && spruce != pine ? spruce > pine : null;

public (double Low, double Central, double High) Age => (
    Math.Min(AgeSpruce, AgePine),
    SpruceLeads switch { true => AgeSpruce, false => AgePine, null => (AgeSpruce + AgePine) / 2 },
    Math.Max(AgeSpruce, AgePine));

3.2 Hectares above an age threshold

"How many hectares are old forest?" is a count, done three times, once per age case:

Hcase=∑php⋅1[ap,case≥τ]H_{\text{case}} = \sum_p h_p \cdot \mathbb{1}\bigl[a_{p,\text{case}} \ge \tau\bigr]

1[⋅]\mathbb{1}[\cdot] is 1 when the condition holds and 0 otherwise, hph_p the pixel's hectares inside the polygon and τ\tau the threshold (which differs between a northern group of counties and the rest).

ValueRange Hectares(Func<AgedPixel, bool> where, AgeThreshold threshold, int years)
{
    double low = 0, central = 0, high = 0;
    foreach (var pixel in pixels.Where(where))
    {
        var (younger, best, older) = pixel.Stand.Age;
        low += threshold.Reaches(younger, years) ? pixel.Hectares : 0;
        central += threshold.Reaches(best, years) ? pixel.Hectares : 0;
        high += threshold.Reaches(older, years) ? pixel.Hectares : 0;
    }
    return ValueRange.Spanning(low, central, high, digits: 2);
}

Reaches hides whether the threshold is inclusive ("at least 180 years") or exclusive ("older than 140 years"), which differs between the definitions the options cite.

The Forestry Act's regulations give the lowest age for clear-felling as a table by site index. Between the table's rows the value is interpolated linearly, and held at the first and last row beyond them:

τ(SI)=τi+SI−SIiSIi+1−SIi (τi+1−τi)for SIi≤SI≤SIi+1\tau(SI) = \tau_i + \frac{SI - SI_i}{SI_{i+1} - SI_i}\,(\tau_{i+1} - \tau_i) \qquad \text{for } SI_i \le SI \le SI_{i+1}
public static double Interpolate(IReadOnlyList<SiteIndexAge> table, double siteIndex)
{
    var rows = table.OrderBy(row => row.SiteIndex).ToList();
    if (siteIndex <= rows[0].SiteIndex)
    {
        return rows[0].Years;
    }
    for (var i = 1; i < rows.Count; i++)
    {
        if (siteIndex <= rows[i].SiteIndex)
        {
            var (from, to) = (rows[i - 1], rows[i]);
            return from.Years + (siteIndex - from.SiteIndex) / (to.SiteIndex - from.SiteIndex) * (to.Years - from.Years);
        }
    }
    return rows[^1].Years;
}

This "table with straight lines between its rows, flat beyond the ends" is EcoVal's standard way of reading any published table. It appears again for the production table, the carbon price paths and the production level.

A range that runs backwards. The felling-age check counts hectares younger than the limit. A younger age puts more area below the limit, so the low age case gives the high result. The code says so explicitly rather than relying on Spanning to sort it out:

// Younger ages put more of the area below the limit: the low case of the age is the high case here.
low += older < minimum ? pixel.Hectares : 0;
central += best < minimum ? pixel.Hectares : 0;
high += younger < minimum ? pixel.Hectares : 0;

4. Stand phases

File: Features/Forest/Timber/StandPhaseCalculator.cs.

Each pixel is sorted into one of four phases by three comparisons. It is a decision tree, not a formula:

flowchart TD
    A{"Mean height<br/>below 10 m?"} -->|yes| Y["young"]
    A -->|no| B{"Age at or above the<br/>minimum felling age?"}
    B -->|yes| F["final felling"]
    B -->|no| C{"Basal area<br/>at least 20 m²/ha?"}
    C -->|yes| T["thinning"]
    C -->|no| G["growing"]
public static string Phase(PhasePixel pixel, double age, double minimumFellingAge, HarvestOptions harvest)
{
    if (pixel.HeightMetres < harvest.ThinningFromHeightMetres)
    {
        return StandPhaseCodes.Young;
    }
    if (age >= minimumFellingAge)
    {
        return StandPhaseCodes.FinalFelling;
    }
    return pixel.BasalArea >= harvest.ThinningBasalArea ? StandPhaseCodes.Thinning : StandPhaseCodes.Growing;
}

The age is uncertain (section 3.1), so each pixel is classified three times, and each phase's hectares become a range. The volume per phase is summed for the central age only:

var (younger, best, older) = pixel.Stand.Age;
double[] ages = [younger, best, older];
for (var i = 0; i < ages.Length; i++)
{
    var phase = Phase(pixel, ages[i], minimumAge, harvest);
    hectares[phase][i] += pixel.Hectares;
    if (i == 1)
    {
        volume[phase] += pixel.VolumePerHectare * pixel.Hectares;
    }
}

The phase with the most hectares in the central case becomes the suggested measure, and the volume in the thinning phase feeds the thinning's value in section 6.5.


5. Species mix

File: Features/Forest/Timber/SpeciesMixReader.cs.

The species maps give each pixel's shares per species. The polygon's mix is a weighted mean of the pixels' shares, where the weight is how much wood the pixel holds: its hectares times the laser-measured volume at its centre. Each pixel's shares qp,kq_{p,k} are first scaled to add up to 1.

sharek=∑pwp qp,k∑pwpwp=hp⋅vp\text{share}_k = \frac{\sum_p w_p\,q_{p,k}}{\sum_p w_p} \qquad w_p = h_p \cdot v_p

Weighting by volume matters: a pixel of dense old spruce should count for more than a pixel of sparse young birch when the result is used to price timber. If no pixel has volume, the weight falls back to hectares alone.

var volumeWeighted = valid.Any(pixel => pixel.Hectares * pixel.VolumePerHectare > 0);
double[]? sums = null;
var weights = 0.0;
foreach (var pixel in valid)
{
    var weight = volumeWeighted ? pixel.Hectares * pixel.VolumePerHectare : pixel.Hectares;
    var shares = fractions(pixel.Shares);
    sums ??= new double[shares.Length];
    for (var i = 0; i < sums.Length; i++)
    {
        sums[i] += weight * shares[i];
    }
    weights += weight;
}
return (sums!.Select(sum => sum / weights).ToArray(), volumeWeighted);

The species map and the volume raster have different pixel sizes (12.5 m and 10 m), so the volume is not read as a grid but sampled at each species pixel's centre (tile.Sample(xs, ys, …)).


6. Timber value

File: Features/Forest/Timber/TimberValueCalculator.cs. The value is a one-off net: what a final felling today would bring in, less what it costs.

flowchart LR
    V["Standing volume V<br/>m³sk"] -->|"× (1 − r)<br/>retention left standing"| F["Felled<br/>m³sk"]
    F -->|"× k<br/>bark and tops off"| S["Sold<br/>m³fub"]
    S -->|"× p<br/>net price per m³fub"| I["Income less harvesting<br/>kr"]
    I -->|"− A·(1 − r)·G<br/>regeneration"| N["Net timber value T<br/>kr"]

6.1 The formula

T=V⋅(1−r)⋅k⋅p  −  A⋅(1−r)⋅GT = V \cdot (1 - r) \cdot k \cdot p \;-\; A \cdot (1 - r) \cdot G
Symbol Meaning Unit
VV Standing volume m³sk
rr Share of the area left standing as retention patches 0–1
kk Conversion from standing volume to sold volume (bark and tops removed) m³fub per m³sk
pp Net price per sold cubic metre, after harvesting cost kr/m³fub
AA Forest land in the polygon ha
GG Cost of regenerating a felled hectare kr/ha

The net price mixes three assortments. With bb the broadleaf share, ss the sawlog share of the conifer volume, the three prices PP and the harvesting cost CC:

p=(1−b) [s Psaw+(1−s) Ppulp]+b Pbroadleaf−Cp = (1 - b)\,\bigl[s\,P_{\text{saw}} + (1 - s)\,P_{\text{pulp}}\bigr] + b\,P_{\text{broadleaf}} - C

Broadleaf volume is priced as pulpwood only, because the price statistics have no broadleaf sawlog price.

private static double PerM3fub(PriceMix prices, double sawlogShare, decimal cost) =>
    (1 - prices.BroadleafShare) * (sawlogShare * (double)prices.Sawlog + (1 - sawlogShare) * (double)prices.ConiferPulpwood)
    + prices.BroadleafShare * (double)prices.BroadleafPulpwood
    - (double)cost;
private static FellingCase Felling(/* … */)
{
    var felledVolume = volumeM3sk * (1 - retention);
    var felledHectares = forestHectares * (1 - retention);
    var sold = felledVolume * k;
    var regeneration = felledHectares * regenerationPerHectare;
    return new FellingCase(felledVolume, felledHectares, sold, regeneration, sold * PerM3fub(prices, sawlogShare, harvestingCost) - regeneration);
}

Prices are decimal in the database and the contract (they are published figures, and decimal keeps them exact), and are cast to double only inside the arithmetic.

6.2 The sawlog share: a ramp on diameter

How much of a stand becomes sawlogs depends on how thick the trees are. EcoVal uses a simple ramp on the mean diameter dd: nothing below d0=12d_0 = 12 cm, rising in a straight line to smax⁡=0.7s_{\max} = 0.7 at d1=32d_1 = 32 cm.

s(d)=smax⁡⋅clamp⁡ ⁣(d−d0d1−d0, 0, 1)slow,high=clamp⁡(s(d)∓u, 0, 1)s(d) = s_{\max} \cdot \operatorname{clamp}\!\left(\frac{d - d_0}{d_1 - d_0},\ 0,\ 1\right) \qquad s_{\text{low,high}} = \operatorname{clamp}\bigl(s(d) \mp u,\ 0,\ 1\bigr)

with u=0.1u = 0.1. clamp⁡(x,0,1)\operatorname{clamp}(x, 0, 1) holds xx between 0 and 1.

var ramp = Math.Clamp((diameter - options.NoSawlogsBelowCm) / (options.FullShareFromCm - options.NoSawlogsBelowCm), 0, 1);
var central = ramp * options.MaxShare;
return new ParameterRange(
    Math.Clamp(central - options.Uncertainty, 0, 1),
    central,
    Math.Clamp(central + options.Uncertainty, 0, 1));
Sawlog share from the stand's mean diameter

The options class calls this a placeholder, to be replaced with an assortment table. It is a modelling assumption, not something fitted to data.

6.3 The sawlog price by species

When the species mix is known and the statistics publish pine and spruce sawlog prices separately, the sawlog price is their mean weighted by each species' share of the conifer volume:

Psaw=qpine Ppine+qspruce Pspruceqpine+qspruceP_{\text{saw}} = \frac{q_{\text{pine}}\,P_{\text{pine}} + q_{\text{spruce}}\,P_{\text{spruce}}}{q_{\text{pine}} + q_{\text{spruce}}}
var conifer = species.PineShare + species.SpruceShare;
var bySpecies = conifer > 0 && market.PineSawlogPrice is not null && market.SpruceSawlogPrice is not null;
var sawlog = bySpecies
    ? (decimal)Math.Round(
        (species.PineShare * (double)market.PineSawlogPrice!.Value
            + species.SpruceShare * (double)market.SpruceSawlogPrice!.Value) / conifer)
    : market.SawlogPrice;

Every step has a fallback (??, or the all-species price), because the statistics leave cells empty for some regions and quarters.

6.4 Pairing the cases: which low goes with which

Four inputs are uncertain: kk, the sawlog share, the retention share and the regeneration cost. They do not all push the same way. A low net value comes from a low kk and a low sawlog share but a high retention and a high regeneration cost. The pairing is written out, with a comment, so nobody has to work it out again:

// The low net pairs the low k and sawlog share with the most left standing and the dearest regeneration
// (cleaning too); the high net the opposite, with scarification only.
var low = Felling(volumeM3sk, forestHectares, k.Low, s.Low, retention.High, regeneration.High, prices, market.HarvestingCost);
var central = Felling(volumeM3sk, forestHectares, k.Central, s.Central, retention.Central, regeneration.Central, prices, market.HarvestingCost);
var high = Felling(volumeM3sk, forestHectares, k.High, s.High, retention.Low, regeneration.Low, prices, market.HarvestingCost);

The regeneration range is built from which measures are assumed: scarification only (low cost), plus planting (central), plus cleaning (high cost).

The results are rounded to hundreds of kronor. The breakdown shown to the user is built from the rounded net, so its lines add up exactly:

// Rounded to hundreds like the net, so the lines add up to it.
net.Central + harvestingSek + regenerationSek,

6.5 Thinning and continuous-cover harvests

A partial harvest takes a share θ\theta of a stand's volume, with its own kk and its own cost CmC_m, and regenerates nothing:

Tpartial=Vstand⋅θ⋅km⋅p(sm,Cm)T_{\text{partial}} = V_{\text{stand}} \cdot \theta \cdot k_m \cdot p(s_m, C_m)

A thinning takes the smaller trees, so its sawlog share is read from the same ramp at 0.8 of the stand's diameter (ThinningDiameterRatio), and it applies only to the volume in the thinning phase (section 4).

double Net(double share, double conversion, double sawlogs) =>
    standVolume * share * conversion * PerM3fub(prices, sawlogs, cost.SekPerM3fub);

6.6 What the state would pay to protect it

ProtectionPaymentCalculator puts two reference amounts next to the timber value. They are not values of the forest and are not added to anything.

A nature conservation agreement pays a fixed share per year of the stand's net stumpage value TstumpT_{\text{stump}} (the net before regeneration), for the years of the agreement. A negative net gives no payment:

agreement=max⁡(0, Tstump)⋅(share per year×years)\text{agreement} = \max(0,\ T_{\text{stump}}) \cdot (\text{share per year} \times \text{years})

Biotope protection is taken as the region's average payment per hectare, pooled over the published years as total compensation over total hectares (not as a mean of the yearly averages, which would let a year with few hectares count as much as a year with many):

per hectare=∑ycompensationy∑yhectaresy\text{per hectare} = \frac{\sum_y \text{compensation}_y}{\sum_y \text{hectares}_y}
var pooled = region.Sum(year => year.CompensationThousandSek) * 1000 / region.Sum(year => year.LandHectares);
var perHectare = new ValueRange(
    Thousands(region.Min(year => year.SekPerHectare)), Thousands(pooled), Thousands(region.Max(year => year.SekPerHectare)));

7. The growth model

File: Features/Forest/Growth/GrowthCalculator.cs. This is the most model-heavy part of the forest page. It answers: how much does this forest grow a year, and how would it grow over the next hundred years if kept, or if felled and regrown?

The polygon is treated as one average stand. The model has five steps:

flowchart LR
    A["Site index<br/>(raster)"] --> B["Production B and rotation R<br/>(published table)"]
    B --> C["× production level<br/>(by latitude, fitted)"]
    C --> D["Yield curve V(t)<br/>calibrated to B and R"]
    D --> E["Year-by-year simulation:<br/>stocking, old-forest floor, mortality"]

7.1 Production and rotation from the site index

The site index (H100: how tall the dominant trees are at 100 years) says how good the ground is. SiteProductivityTable.Lookup turns it into a production BB (m³sk per hectare and year, averaged over a rotation) and a rotation RR (years), by linear interpolation between the table's even site indices:

var upper = Array.FindIndex(rows, row => row.SiteIndex >= siteIndex);
var (below, above) = (rows[upper - 1], rows[upper]);
var t = (siteIndex - below.SiteIndex) / (above.SiteIndex - below.SiteIndex);
return new SiteProduction(
    Lerp(below.Production[column], above.Production[column], t),
    Lerp(below.Rotation[column], above.Rotation[column], t));

The table is a static readonly array in the source, not an option: it is a published table, transcribed once, with the transcription notes in the class comment.

7.2 The production level by latitude

The National Forest Inventory measures more growth in the north than the production table predicts. The table's BB is therefore multiplied by a level λ\lambda that depends on the polygon's northing yy: straight lines between four regional centres, flat beyond them, and ±10 % for low and high.

B′=λ(y)⋅BB' = \lambda(y) \cdot B
// ProductionLevelOptions.At, in Features/Forest/ValuationOptions.cs
var share = (km - points[i - 1].NorthingKm) / (points[i].NorthingKm - points[i - 1].NorthingKm);
level = points[i - 1].Level + share * (points[i].Level - points[i - 1].Level);
// …
return new ParameterRange(level * (1 - Uncertainty), level, level * (1 + Uncertainty));
Production level by latitude

The four values are fitted to inventory data; section 7.7 explains how.

7.3 The yield curve: Chapman–Richards

A stand's volume by age follows an S-shaped curve: slow at first, fastest in middle age, levelling off. EcoVal uses the Chapman–Richards function, a standard growth curve in forestry:

V(t)=Vmax⁡ (1−e−κt)pV(t) = V_{\max}\,\bigl(1 - e^{-\kappa t}\bigr)^{p}

Vmax⁡V_{\max} is the volume the curve levels off at, κ\kappa sets how fast it gets there and p=3p = 3 sets the shape. (The code calls the rate Rate and the shape Shape; κ\kappa is used here to keep it apart from the volume conversion kk of section 6.)

Calibrating the curve to B and R. The curve has two unknowns, Vmax⁡V_{\max} and κ\kappa, and the production table gives two facts that pin them down:

  1. Mean annual growth V(t)/tV(t)/t peaks at the rotation RR. That is what a rotation is: the age at which felling gives the most wood per year.
  2. At that peak, mean annual growth equals BB, so V(R)=B⋅RV(R) = B \cdot R.

Mean growth V(t)/tV(t)/t peaks where its derivative is zero, which is where t V′(t)=V(t)t\,V'(t) = V(t). Differentiating the curve and writing x=κtx = \kappa t, this becomes

p x e−x=1−e−xp\,x\,e^{-x} = 1 - e^{-x}

which has no closed-form solution, so it is solved numerically (for p=3p = 3, x∗≈1.90x^{*} \approx 1.90). The two parameters then follow:

κ=x∗RVmax⁡=B⋅R(1−e−x∗)p\kappa = \frac{x^{*}}{R} \qquad V_{\max} = \frac{B \cdot R}{\bigl(1 - e^{-x^{*}}\bigr)^{p}}
public static YieldCurve Calibrate(double production, double rotationYears, double shape)
{
    var x = PeakOfMeanGrowth(shape);
    return new YieldCurve(production * rotationYears / Math.Pow(1 - Math.Exp(-x), shape), x / rotationYears, shape);
}

Solving for x* by bisection. Bisection finds where a function crosses zero by halving an interval that is known to contain the crossing. Balance(x) is the left side minus the right side of the equation above: positive for small xx, negative for large xx.

double Balance(double x) => shape * x * Math.Exp(-x) - (1 - Math.Exp(-x));
var (low, high) = (1e-9, 50.0);
for (var i = 0; i < 200; i++)
{
    var middle = (low + high) / 2;
    if (Balance(middle) > 0)
    {
        low = middle;      // still on the positive side: the crossing is further right
    }
    else
    {
        high = middle;     // on the negative side: the crossing is to the left
    }
}
return (low + high) / 2;

Each step halves the interval, so 200 steps is far more than a double can resolve; the loop simply runs to machine precision. This is the same idea as the golden-section search in part 1, section 6.3: a robust one-dimensional method with no derivatives.

The yield curve of one site

The year's growth is the curve's difference over one year, not its derivative, because the simulation steps in whole years:

ΔV(t)=V(t+1)−V(t)\Delta V(t) = V(t + 1) - V(t)
public double Volume(double age) => age <= 0 ? 0 : MaxVolume * Math.Pow(1 - Math.Exp(-Rate * age), Shape);
public double Growth(double age) => Volume(age + 1) - Volume(Math.Max(age, 0));

7.4 How the standing forest grows

A real stand is not on the curve. It may be thinner than the curve says (understocked), or far older than the rotation, and some of what grows dies. Three corrections are applied in order, each year.

1. Stocking. If the stand's measured volume VV is below the curve's volume at its age, it has fewer trees to grow on. Growth falls in proportion below a threshold σ\sigma (0.5), and stays at the curve's growth above it:

g1=min⁡ ⁣(1, V/Vcurve(a)σ)⋅ΔV(a)g_1 = \min\!\left(1,\ \frac{V / V_{\text{curve}}(a)}{\sigma}\right) \cdot \Delta V(a)

2. The old-forest floor. The curve alone would let a very old stand stop growing, which the inventory does not show. Past the rotation the growth is at least a share of B′B' that falls in a straight line from 1 at RR to φ\varphi (0.5) at 2R2R and stays there:

g2=max⁡(g1, f(a))f(a)={0a<RB′[1−(1−φ) min⁡ ⁣(1, aR−1)]a≥Rg_2 = \max\bigl(g_1,\ f(a)\bigr) \qquad f(a) = \begin{cases} 0 & a < R \\ B'\left[1 - (1 - \varphi)\,\min\!\left(1,\ \dfrac{a}{R} - 1\right)\right] & a \ge R \end{cases}

3. Natural mortality. Part of the gross growth dies. The share ss is a small background s0s_0 plus a crowding term that grows steeply as the standing volume nears a cap (a share cc of the curve's maximum):

s=s0+(1−s0)(Vc⋅Vmax⁡)qg=g2⋅max⁡(0, 1−s)s = s_0 + (1 - s_0)\left(\frac{V}{c \cdot V_{\max}}\right)^{q} \qquad g = g_2 \cdot \max(0,\ 1 - s)

with q=4q = 4. At the cap s=1s = 1: the stand stops gaining volume.

Natural mortality by how full the stand is

In code the three corrections are three lines of the simulation loop:

var age = standAge + year;
var curveVolume = curve.Volume(age);
var stocking = curveVolume < 1 ? 1 : keepVolume / curveVolume;
var keepGrowth = Math.Min(1, stocking / p.FullGrowthStocking) * curve.Growth(age);   // 1. stocking
keepGrowth = Math.Max(keepGrowth, FloorGrowth(age, p));                              // 2. old-forest floor
keepGrowth = mortality.Net(keepGrowth, keepVolume);                                  // 3. mortality
private static double FloorGrowth(double age, PathParameters p) =>
    age < p.Rotation ? 0 : p.Production * (1 - (1 - p.GrowthFloor) * Math.Min(1, age / p.Rotation - 1));

private sealed record Mortality(double Cap, double Background, double Exponent)
{
    public double Net(double grossGrowth, double volume)
    {
        var lost = Background + (1 - Background) * Math.Pow(Math.Max(0, volume / Cap), Exponent);
        return grossGrowth * Math.Max(0, 1 - lost);
    }
}

The first year's value of keepGrowth is the page's "growth this year".

7.5 From cubic metres to tonnes of CO₂

Growth in m³sk becomes CO₂ with the polygon's own ratio: its CO₂ stock (section 2.2) divided by its volume.

γ=CO2 stockV(t CO₂ per m³sk)uptake=g⋅A⋅γ\gamma = \frac{\text{CO}_2\ \text{stock}}{V} \quad \text{(t CO₂ per m³sk)} \qquad \text{uptake} = g \cdot A \cdot \gamma

Using the polygon's own ratio keeps the stock and the uptake consistent with each other. Only when the polygon has no standing volume does a national default (1.375 t/m³sk) take over:

var co2PerM3sk = ownRatio
    ? new ParameterRange(co2.Low / forest.VolumeM3sk, co2.Central / forest.VolumeM3sk, co2.High / forest.VolumeM3sk)
    : growth.Co2PerM3sk;

7.6 Three consistent parameter sets

The growth model has about ten uncertain parameters. Taking each one's low and high independently would not give a meaningful range, so the model is run three times with three sets that each hang together: a slow-growing forest, a central one and a fast-growing one. The low set takes the slower species, the older age model and the low parameters, except for the two parameters that slow growth as they rise, where it takes the high end.

// Low is the slower-growing case throughout: the less productive species, the older age, the low parameters,
// and the high stocking threshold and background mortality (the two that slow growth as they rise).
PathParameters Set(SiteProduction production, double age, Func<ParameterRange, double> pick, Func<ParameterRange, double> opposite) => new(
    production.M3skPerHectareYear * pick(productionLevel),
    production.RotationYears,
    age,
    opposite(growth.FullGrowthStocking),
    pick(growth.SelfThinningCap),
    opposite(growth.BackgroundMortality),
    // …
var low = Simulate(Set(slower, Math.Max(site.SpruceAgeYears, site.PineAgeYears), range => range.Low, range => range.High), /* … */);
var central = Simulate(Set(mean, (site.SpruceAgeYears + site.PineAgeYears) / 2, range => range.Central, range => range.Central), /* … */);
var high = Simulate(Set(faster, Math.Min(site.SpruceAgeYears, site.PineAgeYears), range => range.High, range => range.Low), /* … */);

Passing pick and opposite as functions is a neat way to say "the same construction, three times, with a different end of every range" without three near-identical blocks. Every output is then read across the three runs:

ValueRange Across(Func<PathResult, double> value, int digits = 1) =>
    ValueRange.Spanning(value(low), value(central), value(high), digits);

7.7 Where the growth parameters come from: fitted to the forest inventory

Four of the model's parameters were fitted to data: the production level λ\lambda, the background mortality s0s_0, the crowding exponent qq and the old-forest floor φ\varphi.

Kind of fit: calibration by grid search with a least-squares error, the same kind as the excursion and fishing fits in part 1. It differs in one practical way: the fit is not in EcoVal.Calibration but in a Python script, scripts/review/growth/fit-mortality.py, written during the November 2026 review. The script re-implements the growth model (the same curve, stocking, floor and mortality as section 7.4) and holds the inventory's published tables as constants. Its results were copied into GrowthOptions by hand.

The data is SLU's Skogsdata 2026: growth, standing volume and natural mortality by region and age class.

Mortality (s0s_0 and qq). For each candidate pair, the script computes what share of growth the model says dies in each of the four regions' managed forest, and in protected forest nationally, and compares with the measured shares:

E(s0,q)=∑r=14[m^r(s0,q)−mr]2+4 [m^prot(s0,q)−mprot]2E(s_0, q) = \sum_{r=1}^{4} \bigl[\hat{m}_r(s_0, q) - m_r\bigr]^2 + 4\,\bigl[\hat{m}_{\text{prot}}(s_0, q) - m_{\text{prot}}\bigr]^2

The protected figure gets a weight of 4 so that it counts as much as the four regional figures together.

def fit_mortality():
    """s0 and p by least squares on the four managed shares and the national protected share (weighted as four)."""
    managed, national = targets()
    best = None
    for s0 in [i / 200 for i in range(0, 41)]:
        for p in [1 + i / 20 for i in range(0, 81)]:
            err = sum((managed_share(r, s0, p) - managed[r]) ** 2 for r in REGIONS)
            err += 4 * (protected_national(s0, p) - national) ** 2
            if best is None or err < best[0]:
                best = (err, s0, p)
    return best[1], best[2]

The floor (φ\varphi) and the level (λ\lambda). Both are fitted on growth by age class, minimising the squared log ratio of the model's net growth n^\hat{n} to the measured nn (the log ratio treats "20 % too high" and "20 % too low" alike, as in part 1):

E=∑classes[ln⁡n^n]2E = \sum_{\text{classes}} \left[\ln\frac{\hat{n}}{n}\right]^2

The floor uses the age classes past the rotation, all regions together. The level is fitted per region, on the classes from 21 years. The four regional levels are then turned into a function of latitude: values at the regions' centres are adjusted, by repeated correction, until each region's forest-weighted mean equals its fitted level.

Storing the result. The stored values are rounded, and the range around them is a judgement that the options comment explains (for example, the high background mortality covers bark-beetle years):

public ParameterRange BackgroundMortality { get; set; } = new(0.06, 0.10, 0.18);
public double CrowdingExponent { get; set; } = 4;
public ParameterRange OldForestGrowthFloor { get; set; } = new(0.4, 0.5, 0.6);

The other growth parameters (the stocking threshold, the self-thinning cap, the curve's shape, the thinning ages) are set from the literature or by reasoning, and several are marked "to verify" in their comments.

Because the fit lives in a script with the data typed in, re-fitting after a new inventory means updating the script's tables, running it, and editing the options. If the C# model changes, the script's copy of it must change too, or the fit no longer matches what the app computes.


8. The three carbon paths

Still in GrowthCalculator.cs. The simulation follows three futures for the same land, year by year for 100 years:

  • Keep: the forest stands and grows as in section 7.4.
  • Forestry: everything is felled now; a new stand is planted, thinned, felled again at RR, and so on.
  • Left to grow: everything is felled now; the new stand is then left alone.
CO₂ held over 100 years in the three paths

8.1 The simulation loop

The loop is a plain time-stepping simulation: at each year, record the state, then advance it. Two Regrowth objects carry the felled paths' state.

var forestry = new Regrowth(curve, p, growth, hectares, fellAgain: true, mortality);
var leftToGrow = new Regrowth(curve, p, growth, hectares, fellAgain: false, mortality);
forestry.Fell(0, volumePerHectare, p.SawlogShareNow);
leftToGrow.Fell(0, volumePerHectare, p.SawlogShareNow);
// …
for (var year = 0; year <= horizon; year++)
{
    // … the standing forest's growth, section 7.4 …
    keepStock[year] = keepVolume * co2PerHectareM3;
    keepUptake[year] = keepGrowth * co2PerHectareM3;
    keepVolume += keepGrowth;
    forestry.Step(year, co2PerHectareM3);
    leftToGrow.Step(year, co2PerHectareM3);
}

In formulas, the kept forest's stock in year tt is

K(t)=Vt⋅A⋅γVt+1=Vt+gtK(t) = V_t \cdot A \cdot \gamma \qquad V_{t+1} = V_t + g_t

8.2 The regrowing stand

Regrowth is a small state machine. Its age starts negative, at minus the regeneration delay (10 years), so nothing grows until the age reaches 0:

private double _age = -growth.RegenerationDelayYears;
// …
public void Step(int year, double co2PerHectareM3)
{
    var grown = _age >= 0 ? curve.Growth(_age) : 0;
    if (!fellAgain)
    {
        grown = Math.Max(grown, FloorGrowth(_age, p));
    }
    grown = mortality.Net(grown, _volume);

    _trees[year] = _volume * co2PerHectareM3;
    _products[year] = _sawnwood + _paper;
    _uptake[year] = grown * co2PerHectareM3;

    _volume += grown;
    _age++;
    _sawnwood *= _sawnwoodRetained;
    _paper *= _paperRetained;
    // … forestry only: thin at the thinning ages, fell at the rotation and start over …
}

In the forestry path, a thinning removes a share θ\theta (0.30) of the volume, and at the rotation everything is felled and the age is reset:

if (_age >= p.Rotation)
{
    Fell(year + 1, _volume, p.RotationSawlogShare);
    _volume = 0;
    _age = -growth.RegenerationDelayYears;
}
else if (p.Thinnings.FirstOrDefault(thinning => thinning.AgeYears == _age) is { } thinning)
{
    var taken = _volume * p.ThinningRemoval;
    Deliver(taken, thinning.SawlogShare, p.ThinningProductCo2PerM3sk);
    _volume -= taken;
}

8.3 Wood products: what the felled stems still hold

Felled wood is not released at once. The stems that are sold become sawn wood and paper, which hold their carbon for a while. Branches, tops, stumps and roots count as released at felling.

The CO₂ in the delivered wood per m³sk felled is the sold volume (kk) times the wood's dry density ρ\rho times the carbon fraction, converted to CO₂:

π=k⋅ρ⋅0.5⋅4412(t CO₂ per m³sk felled)\pi = k \cdot \rho \cdot 0.5 \cdot \frac{44}{12} \quad \text{(t CO₂ per m³sk felled)}

A delivery of D=Vfelled⋅A⋅πD = V_{\text{felled}} \cdot A \cdot \pi tonnes is split by the sawlog share ss and the sawmill's yield yy (the share of a sawlog that becomes sawn wood):

sawn wood+=D⋅s⋅ypaper+=D⋅(1−s)\text{sawn wood} \mathrel{+}= D \cdot s \cdot y \qquad \text{paper} \mathrel{+}= D \cdot (1 - s)

The remaining D⋅s⋅(1−y)D \cdot s \cdot (1 - y) (chips and sawdust, mostly burnt for energy) counts as released.

private void Deliver(double volume, double sawlogShare, double co2PerM3sk)
{
    var delivered = volume * hectares * co2PerM3sk;
    _sawnwood += delivered * sawlogShare * p.SawnwoodYield;
    _paper += delivered * (1 - sawlogShare);
}

Decay with a half-life. Each pool decays exponentially. A half-life hh means half is left after hh years, so the share retained from one year to the next is

δ=(12)1/hpoolt+1=δ⋅poolt\delta = \left(\tfrac{1}{2}\right)^{1/h} \qquad \text{pool}_{t+1} = \delta \cdot \text{pool}_t

With IPCC's defaults, sawn wood (h=35h = 35 years) keeps 98.0 % a year and paper (h=2h = 2 years) keeps 70.7 %.

private readonly double _sawnwoodRetained = Math.Pow(0.5, 1 / growth.SawnwoodHalfLifeYears);
private readonly double _paperRetained = Math.Pow(0.5, 1 / growth.PaperHalfLifeYears);

The factor is computed once in the field initialiser and multiplied in every year, which is cheaper and clearer than recomputing an exponential of elapsed time for each delivery.

The forestry path taken apart into trees and wood products

A felled path's total in year tt is its trees plus its products:

F(t)=trees(t)+sawn wood(t)+paper(t)F(t) = \text{trees}(t) + \text{sawn wood}(t) + \text{paper}(t)

8.4 What is read off the paths

Two summary years come from the central run by scanning for the first year a condition holds:

UptakeCrossoverYear: FirstYear(horizon, year => path(central).Uptake[year] > central.KeepUptake[year]),
ParityYear: FirstYear(horizon, year => year > 0 && path(central).Total(year) >= central.KeepStock[year]),

The crossover year is when the new forest starts taking up more CO₂ a year than the old one would have. The parity year is when the felled path has caught up with the kept forest in total, if it ever does within the horizon (null otherwise).


9. Carbon value

File: Features/Forest/Growth/CarbonValueCalculator.cs. This puts a price on the gap between keeping and felling.

9.1 The price paths

Three published prices per tonne of CO₂ are used, each a series of points by calendar year. A price for any year is read with the usual rule (straight lines between points, flat beyond them):

P(y)=Pi+(Pi+1−Pi) y−yiyi+1−yiP(y) = P_i + (P_{i+1} - P_i)\,\frac{y - y_i}{y_{i+1} - y_i}
public static double At(IReadOnlyList<CarbonPricePoint> points, int year)
{
    // …
    for (var i = 1; i < sorted.Count; i++)
    {
        var (before, after) = (sorted[i - 1], sorted[i]);
        if (year <= after.Year)
        {
            return before.PerTonne + (after.PerTonne - before.PerTonne) * (year - before.Year) / (after.Year - before.Year);
        }
    }
    return sorted[^1].PerTonne;
}

The paths are published in different currencies and price years, so each gets one conversion factor to kronor at the common price year (2025): the exchange rate if it is in euro, times the consumer price index ratio from its own price year.

factor=exchange rate⋅KPI2025KPIprice year\text{factor} = \text{exchange rate} \cdot \frac{\text{KPI}_{2025}}{\text{KPI}_{\text{price year}}}
return Money.Indexed(exchange, options.ConsumerPriceIndex, path.PriceYear, options.PriceYear, "Valuation:CarbonPrice");

Money.Indexed throws with the name of the configuration section if the index lacks a year, so a missing number fails loudly instead of silently pricing at 1.

The three carbon price paths

The three price cases are then built year by year: low is the lowest of the three paths that year, central is ASEK's, high is the highest. A case is not one path: in the chart above, the high case follows Umweltbundesamt in the first years and ASEK afterwards.

return new PriceCases(
    Enumerable.Range(0, horizonYears + 1).Select(year => series.Min(prices => prices[year])).ToArray(),
    Prices(options.Asek, startYear, horizonYears, options),
    Enumerable.Range(0, horizonYears + 1).Select(year => series.Max(prices => prices[year])).ToArray());

9.2 The present value of the gap

Let D(t)D(t) be the gap in year tt: the CO₂ held if the forest is kept minus the CO₂ held on the felled path (trees and wood products).

D(t)=K(t)−F(t),D(−1)=0D(t) = K(t) - F(t), \qquad D(-1) = 0

The value prices each year's change in the gap at that year's price, and discounts it to today at the rate rr (3.5 %):

PV=∑t=0HP(t) [D(t)−D(t−1)](1+r)tPV = \sum_{t=0}^{H} \frac{P(t)\,\bigl[D(t) - D(t-1)\bigr]}{(1 + r)^{t}}

Why the change and not the gap itself? Because CO₂ matters when it is emitted or taken up. The first term, D(0)−0D(0) - 0, is the release at felling, priced today and not discounted. Later terms are each year's difference in uptake and decay between the two paths: negative when the felled path is catching up. A gap still open at the horizon simply stays in the sum, which means it counts as kept for good.

public static double PresentValue(double[] keepStock, double[] pathStock, double[] prices, double discountRate)
{
    var total = 0.0;
    var previous = 0.0;
    for (var year = 0; year < keepStock.Length; year++)
    {
        var difference = keepStock[year] - pathStock[year];
        total += prices[year] * (difference - previous) / Math.Pow(1 + discountRate, year);
        previous = difference;
    }
    return total;
}

The discount factor 1/(1+r)t1 / (1 + r)^t is what makes distant years count for little: at 3.5 %, a tonne in 50 years counts 18 % of a tonne today, and in 100 years 3 %. That is why the value is dominated by the release at felling and the first decades.

9.3 The range: every combination of growth and price

There are three growth runs (slow, central, fast) and three price cases. Which combination gives the lowest value is not obvious in advance: a fast-growing forest closes the gap sooner, but also has more to lose. So all nine are computed, and the range is their smallest and largest:

PVlow=min⁡g, c PV(g,c)PVcentral=PV(central growth, ASEK)PVhigh=max⁡g, c PV(g,c)PV_{\text{low}} = \min_{g,\,c}\ PV(g, c) \qquad PV_{\text{central}} = PV(\text{central growth},\ \text{ASEK}) \qquad PV_{\text{high}} = \max_{g,\,c}\ PV(g, c)
ValueRange Value(Func<Stocks, double[]> path)
{
    var all = runs
        .SelectMany(run => new[] { low, central, high }.Select(prices => PresentValue(run.Keep, path(run), prices, rate)))
        .ToList();
    return new ValueRange(
        RoundToHundreds(all.Min()),
        RoundToHundreds(PresentValue(runs[1].Keep, path(runs[1]), central, rate)),
        RoundToHundreds(all.Max()));
}

This is a different way of building a range from section 7.6. There the three cases are constructed to be slow, central and fast. Here the extremes are found by trying everything, because no single pairing is "the low one".

9.4 Splitting the value by period

The page shows how much of the value comes from the felling itself, from years 1–20, 21–50 and 51 onwards. Since the present value is a sum over years, each period's part is just the terms of its years, and the parts add up to the whole by construction:

PV=∑periods j ∑t∈jP(t) [D(t)−D(t−1)](1+r)tPV = \sum_{\text{periods } j}\ \sum_{t \in j} \frac{P(t)\,\bigl[D(t) - D(t-1)\bigr]}{(1 + r)^{t}}
private static readonly int[] PartStarts = [0, 1, 21, 51];
// …
for (var year = from; year <= to; year++)
{
    var previous = year == 0 ? 0 : keepStock[year - 1] - pathStock[year - 1];
    sek += prices[year] * (keepStock[year] - pathStock[year] - previous) / Math.Pow(1 + discountRate, year);
}

10. Everyday comparisons

File: Features/Forest/Growth/CarbonComparisonCalculator.cs. Tonnes of CO₂ mean little to most people, so the API sends a few conversion factors and the frontend divides the tonnes by them. They are plain ratios of published national figures, each with its year and source in ComparisonOptions:

one car’s emissions per year=emissions from all passenger carscars in trafficcost of capture per tonne=state aid awardedtonnes to be stored\text{one car's emissions per year} = \frac{\text{emissions from all passenger cars}}{\text{cars in traffic}} \qquad \text{cost of capture per tonne} = \frac{\text{state aid awarded}}{\text{tonnes to be stored}}
CarTonnesPerYear: Math.Round(options.CarEmissionsTonnes / options.CarsInTraffic, 3),
// …
var auctions = options.BeccsAuctions
    .Select(auction => (Auction: auction, PerTonne: auction.AidSek / auction.StoredTonnes))
    .OrderBy(entry => entry.PerTonne)
    .ToList();
var (cheapest, dearest) = (auctions[0], auctions[^1]);

The comparisons re-express the same tonnes. They are never a value of their own and are never added to the carbon value.


Summary: what kind of calculation each section is

Section Kind Fitted to data?
Forest stock Zonal sums and unit conversions No
Stand age, old forest, felling age Counting pixels against thresholds; table interpolation No (legal and published tables)
Stand phases Decision tree per pixel No (thresholds from guides)
Species mix Volume-weighted mean No
Timber value Algebraic formula with published prices No (the sawlog ramp is an assumption)
Growth model Calibrated growth curve plus a yearly simulation Yes: level, mortality and floor, by grid search in a Python script
Carbon paths Time-stepping simulation with exponential decay Uses the growth model's parameters
Carbon value Discounted sum over years; range over nine combinations No (published prices and discount rate)
Comparisons Ratios of published figures No