EcoVal Changelog v0.5.0

How the calculations are built, part 4: the river network and the dam

This part moves from the forest page to the water page. A user picks a barrier or a dam on a river, and the page shows what lies upstream of it, what power the dam makes, and what salmon, sea trout and eel it costs or would gain with a fishway or without the dam.

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

Contents


1. A different kind of calculation

The forest page works on pixels: sums over a raster inside a polygon. The water page works on a graph: river segments joined end to end, with barriers sitting on them. The questions are graph questions ("what can a fish reach from here?"), and the answers come from walking the graph.

flowchart LR
    DB["Database: watercourse segments,<br/>barriers, subcatchments"] --> N["RiverNetwork<br/>(in memory, built once)"]
    N --> W["Walks: upstream stretch, way to the sea,<br/>salmon habitat"]
    W --> D["DamValuationCalculator<br/>(pure): three scenarios"]
    O["Options: survival rates, prices, costs"] --> D
    C["Calibrations (part 1, section 5):<br/>smolts per km, sea trout model"] --> D

The network is loaded once and kept as a singleton, like the fitted models of part 1, section 5. All of Sweden's rivers fit in memory, and a walk then takes milliseconds.


2. The network as a data structure

File: Network/RiverNetwork.cs.

A segment is one stretch of river, drawn in the direction of flow from a FromNode to a ToNode. Two segments are connected when one's ToNode is the other's FromNode. A barrier sits on a segment at a fraction of its length: 0 at the upstream end, 1 at the downstream end.

public sealed record NetworkSegment(int Id, int FromNode, int ToNode, double LengthMetres, /* … */);

public sealed record NetworkBarrier(int Id, int SegmentId, double Fraction, bool Blocks, /* … */);

/// <summary>A point on the network: a segment and the fraction of its length from its upstream start.</summary>
public sealed record NetworkPosition(int SegmentId, double Fraction);

/// <summary>Part of a segment, from one fraction of its length to another (0 upstream, 1 downstream).</summary>
public sealed record SegmentPiece(int SegmentId, double From, double To);

Describing positions as "segment plus fraction" has a useful consequence: the length of any piece is simple arithmetic, with no geometry involved.

length of a piece=(to−from)⋅Lsegment\text{length of a piece} = (\text{to} - \text{from}) \cdot L_{\text{segment}}

The constructor builds lookup tables once so that the walks never search:

this.segments = segments.Where(segment => !segment.IsSea).ToDictionary(segment => segment.Id);
endingAt = this.segments.Values.ToLookup(segment => segment.ToNode);       // who flows INTO this node
startingAt = this.segments.Values.ToLookup(segment => segment.FromNode);   // who flows OUT of this node

endingAt[node] answers "which segments are upstream of this node?" and startingAt[node] answers "where does the water go next?". Both are ILookup, a dictionary from a key to many values, so each question is one hash lookup. The barriers are stored per segment, sorted by fraction, so "the first barrier above this point" is a scan of a short sorted array.


3. Which barriers stop fish

The source registers describe each barrier with a kind (dam, culvert, natural fall), sometimes a surveyor's judgement of whether trout can pass, and sometimes a note of a fishway. BarrierRules turns those into decisions. They are rules, not models: each is a small pure function of a few fields, written as a switch expression.

3.1 The trout rule

public static bool BlocksTrout(string? passabilityTrout, string kind, bool salmonidFishway, string? status) =>
    passabilityTrout switch
    {
        "Impassable" => true,
        "Partial" or "Passable" => false,
        _ => kind == "Dam" && status != "Former" && !salmonidFishway,
    };

Read top to bottom: a surveyor's judgement wins when there is one. Without it, a standing dam stops trout unless a fishway is recorded, and anything else (a culvert, a natural fall nobody judged) does not.

3.2 The salmon rule: five outcomes, not two

For salmon a yes or no is not enough, because a fishway lets some adults through and a natural waterfall means the river above was never salmon water. The rule returns one of five values:

SalmonPassage Meaning Effect on a walk
Open Passes freely Walked through
Fishway A fishway, or judged partly passable Walked through; adults pass with the fishway efficiency
ImpassableSurvey Judged impassable, man-made Stops the walk
DamWithoutFishway A dam nobody judged, no fishway recorded Stops the walk
Natural Judged impassable and natural Stops the walk; nothing above is valued
return passabilityTrout switch
{
    "Impassable" when kind == "Dam" && salmonidFishway => SalmonPassage.Fishway,
    "Impassable" => natural == true || kind == "NaturalBarrier" ? SalmonPassage.Natural : SalmonPassage.ImpassableSurvey,
    "Partial" => SalmonPassage.Fishway,
    "Passable" => kind == "Dam" && salmonidFishway ? SalmonPassage.Fishway : SalmonPassage.Open,
    _ when kind == "Dam" => salmonidFishway ? SalmonPassage.Fishway : SalmonPassage.DamWithoutFishway,
    _ => SalmonPassage.Open,
};

The order of the arms matters: the first arm ("Impassable" when …) catches a dam that was judged impassable but has a fishway, before the general "Impassable" arm. A switch expression takes the first arm that matches.

3.3 One dam site, one judgement

A power station appears in the registers as several structures: an intake dam, a spillway, sometimes more. A fish needs only one way past. The ingest groups such structures into a dam site (EcoVal.Ingest/Water/DamSites.cs: dams within 250 m on connected segments, or with names like "Granö A" and "Granö B"), and AsSites gives every dam of a site the site's best judgement:

var blocks = dams.All(dam => dam.Blocks);                    // stopped only if EVERY dam stops them
SalmonPassage? salmon =
    dams.Any(dam => dam.Fishway) ? SalmonPassage.Fishway
    : dams.Any(dam => dam.Salmon == SalmonPassage.Open) ? SalmonPassage.Open
    : dams.Any(dam => dam.Salmon == SalmonPassage.Fishway) ? SalmonPassage.Fishway
    : null;
var hydropower = dams.Any(dam => dam.Hydropower);            // turbines if ANY dam is for power

Note the asymmetry between All and Any: blocking needs every structure to block, but one turbine is enough for the site to have turbines. The walks then count a site once, however many of its dams they meet, by collecting site ids in a HashSet<int>.

3.4 A culvert that is not really on the river

The ingest snaps every barrier to the nearest river line within 150 m. Many surveyed culverts sit on brooks too small to be in the network, and where such a brook meets a river, its culvert gets snapped onto the river and would stop every walk there. One rule removes them: a culvert or road crossing that lies more than 30 m from the line of a watercourse with at least 100 km² flowing through it is taken to be on a side brook.

public static bool BesideARiver(string kind, double snapDistanceMetres, double throughAreaKm2, double snapMetres, double riverKm2) =>
    kind is "Culvert" or "RoadCrossing" && snapDistanceMetres > snapMetres && throughAreaKm2 >= riverKm2;

The comment on this method lists the real rivers where the problem was found. It is a good example of a data-quality rule that exists because of specific observed failures, and says so.


4. Walking the network

Walking upstream from a dam

Going upstream the river branches, so the walk must explore every branch. Upstream is a breadth-first search: a queue holds the segments still to visit, and a set of visited ids makes sure none is visited twice.

var visited = new HashSet<int> { start.SegmentId };
var queue = new Queue<NetworkSegment>();
// … the first segment, from the start point up …

while (queue.TryDequeue(out var segment))
{
    var onSegment = BarriersOn(segment.Id, ignore).ToList();
    // Coming from downstream, the first barrier met is the one furthest down the segment.
    var blocker = onSegment.LastOrDefault(stops);
    var top = blocker?.Fraction ?? 0;
    pieces.Add(new SegmentPiece(segment.Id, top, 1));
    length += (1 - top) * segment.LengthMetres;
    // …
    if (blocker is not null)
    {
        ends.Add(blocker);        // the walk stops on this branch
    }
    else
    {
        Enqueue(segment);         // carry on to the segments flowing into this one
    }
}

A detail that is easy to get wrong: barriers are sorted from the upstream end (fraction 0) to the downstream end (fraction 1), but the walk arrives from downstream. The first barrier it meets is therefore the last one in the sorted list that stops fish, hence LastOrDefault. The piece walked is from that barrier's fraction to 1.

Enqueue adds the segments that end at this segment's start node, and counts a source when there are none:

void Enqueue(NetworkSegment segment)
{
    var upstream = endingAt[segment.FromNode].ToList();
    if (upstream.Count == 0)
    {
        headwaters++;
    }
    foreach (var next in upstream.Where(next => visited.Add(next.Id)))
    {
        queue.Enqueue(next);
    }
}

visited.Add(id) returns false if the id was already there, so using it inside Where both tests and marks in one step. It protects against loops in the data (a river that splits around an island and rejoins).

The method takes the stopping rule as a function, Func<NetworkBarrier, bool> stops, so the same walk serves trout (barrier => barrier.Blocks) and young eel (barrier => barrier.BlocksYoungEel). The selected dam itself is passed in ignore, so the walk starts at it without being stopped by it.

4.2 Downstream: follow the water

Going downstream there is no branching: water from one segment goes to one next segment. The walk is a simple loop that follows Next until the network ends at the sea:

while (visited.Add(segment.Id))
{
    var onSegment = BarriersOn(segment.Id, ignore).Where(barrier => barrier.Fraction > from).ToList();
    barriers.UnionWith(onSegment.Select(barrier => barrier.Site));
    blocking.UnionWith(onSegment.Where(barrier => barrier.Blocks).Select(barrier => barrier.Site));
    lengthToSea += (1 - from) * segment.LengthMetres;
    // …
    if (Next(segment) is not { } next)
    {
        break;
    }
    (segment, from) = next;
}

SalmonToSea is the same loop with a different tally: how many fishways, hydropower dams, blocking barriers and natural barriers lie between the point and the sea. Those four counts drive the salmon formula in section 8.

4.3 Salmon habitat: a walk with a size limit

Salmon grow up in rivers, not brooks. Habitat is the upstream walk with one more stopping rule: a branch is not entered when less than 100 km² drains through it.

foreach (var next in upstream.Where(next => visited.Add(next.Id)))
{
    if (AreaAtOutlet(next.Id) is { } area && area < minUpstreamAreaKm2)
    {
        ends.Add(new HabitatEnd(StretchEndReasons.HabitatLimit, null));
    }
    else
    {
        queue.Enqueue(next);
    }
}

Every end of the walk is recorded with a reason code (natural_barrier, impassable_survey, dam_without_fishway, habitat_limit), so the page can show exactly why the habitat stops where it does.


5. How much land drains through a point

Several rules need the catchment area at a point: the salmon size limit, the stream width model (part 1, section 5.1), the power model's flow. The published data gives the area upstream of each subcatchment's outlet, not at arbitrary points.

5.1 A point inside a subcatchment

For a point part-way through a subcatchment, the subcatchment's own area is shared out in proportion to river length. With AoutA_{\text{out}} the area upstream of the outlet, AcA_c the subcatchment's own area, and σ\sigma the share of the subcatchment's river length that lies upstream of the point:

A(point)=Aout−Ac⋅(1−σ)σ=river length in the subcatchment above the pointall river length in the subcatchmentA(\text{point}) = A_{\text{out}} - A_c \cdot (1 - \sigma) \qquad \sigma = \frac{\text{river length in the subcatchment above the point}}{\text{all river length in the subcatchment}}

At the outlet σ=1\sigma = 1 and the formula gives AoutA_{\text{out}}; at the top it gives what flows in from other subcatchments.

var share = Math.Clamp(above / total, 0, 1);
return Math.Max(0, upstreamArea - catchment.AreaKm2 * (1 - share));

5.2 The area at every segment's end: recursion without recursion

A segment's area should be at least that of the segments flowing into it. That makes the area of a segment depend on the areas of everything upstream, which is naturally recursive:

Aend(s)=max⁡(Aown(s), max⁡u ∈ upstream of sAend(u))A_{\text{end}}(s) = \max\Bigl(A_{\text{own}}(s),\ \max_{u \,\in\, \text{upstream of } s} A_{\text{end}}(u)\Bigr)

A recursive C# method would overflow the call stack: a long river is thousands of segments deep. The code does the same work with an explicit stack, visiting each segment twice: once to push its upstream segments, and once, after they are done, to compute its own value. This is a post-order traversal.

// Post-order over the segments upstream, without recursion: rivers can be thousands of segments long.
var stack = new Stack<(int Id, bool Expanded)>([(segmentId, false)]);
// …
while (stack.TryPop(out var item))
{
    // …
    if (!item.Expanded)
    {
        stack.Push((item.Id, true));                 // come back to this one later
        foreach (var next in upstream.Where(/* not yet known */))
        {
            stack.Push((next.Id, false));            // but do its upstream segments first
        }
        continue;
    }
    var own = UpstreamAreaKm2(new NetworkPosition(item.Id, 1));
    var above = upstream.Select(next => areaAtOutlet.GetValueOrDefault(next.Id)).Where(area => area is not null).Max();
    areaAtOutlet[item.Id] = own is null ? above : above is null ? own : Math.Max(own.Value, above.Value);
}

The results are cached in a ConcurrentDictionary, so each segment is computed once for the lifetime of the process. This pattern (a recursive definition, an explicit stack, a cache) is called memoisation, and is the standard way to compute something over a deep tree.


6. The dam's three scenarios

File: Dam/DamValuationCalculator.cs. Everything about a dam is computed for three scenarios, in one loop:

Scenario Power Fish going up Fish going down
Kept (as it is) Full As the dam is today Through the turbines
Fishway Loses the water the fishway takes With the fishway's efficiency Through the turbines
Removed None Freely Freely
foreach (var kind in new[] { DamScenarioKinds.Kept, DamScenarioKinds.Fishway, DamScenarioKinds.Removed })
{
    var sameAsKept = kind == DamScenarioKinds.Fishway && fishwayExists;
    // … power, salmon, sea trout, eel, cost and net for this scenario …
}

If the dam already has a fishway, the fishway scenario equals the kept one and is flagged sameAsKept.

6.1 A small toolkit for low, central and high

This calculator has dozens of formulas, each needing three cases, and some parameters work in reverse (a higher cost gives a lower net). It handles that with a tiny set of helpers built on an enum:

private enum Case { Low, Central, High }

private static double Pick(ParameterRange range, Case c) => c switch
{
    Case.Low => range.Low,
    Case.High => range.High,
    _ => range.Central,
};

/// <summary>The opposite case, for a parameter that lowers the result when it rises.</summary>
private static Case Flip(Case c) => c switch
{
    Case.Low => Case.High,
    Case.High => Case.Low,
    _ => Case.Central,
};

private static ValueRange Range(Func<Case, double> compute, int digits) =>
    ValueRange.Spanning(compute(Case.Low), compute(Case.Central), compute(Case.High), digits);

A formula is then written once, as a function of the case, and Range runs it three times:

smolts = Range(c => Smolts(inputs, salmon, kind, c), 0);

and a parameter that works in reverse is picked with Flip(c):

Math.Max(0, Pick(price, c) - Pick(power.OperatingCostOrePerKwh, Flip(c)))   // the low case pays the high cost

This does the same job as the hand-written pairing in the timber value (part 2, section 6.4), but scales to many formulas without repeating each three times.


7. Power

7.1 Production: three sources, best first

How much electricity a plant makes a year is taken from the best source available, in this order:

flowchart TD
    A{"Yearly production<br/>published?"} -->|yes| P["Use it"]
    A -->|no| B{"Capacity (MW)<br/>published?"}
    B -->|yes| C["capacity × full-load hours"]
    B -->|no| D{"Hydropower dam with<br/>a known fall and flow?"}
    D -->|yes| M["Model it from physics"]
    D -->|no| N["No value, with a status code saying why"]

From capacity: a plant of PP megawatts running the equivalent of hh hours a year at full power makes

E=P⋅h1000GWh a yearE = \frac{P \cdot h}{1000} \quad \text{GWh a year}

From physics: water of density ρ\rho falling a height HH at a flow QQ releases power ρgHQ\rho g H Q. A turbine turns a share η\eta of that into electricity, and only a share cc of the mean flow can be used (floods spill past). Over the 8,760 hours of a year:

E=η⋅ρ⋅g⋅H⋅Q⋅c⋅8760109GWh a yearE = \frac{\eta \cdot \rho \cdot g \cdot H \cdot Q \cdot c \cdot 8760}{10^{9}} \quad \text{GWh a year}

with ρ=1000\rho = 1000 kg/m³ and g=9.81g = 9.81 m/s². The product ρgHQ\rho g H Q is in watts; times hours gives watt-hours, and 10910^9 of those make a gigawatt-hour.

private const double WaterDensity = 1000, Gravity = 9.81, HoursPerYear = 8760;

/// <summary>E = η ρ g H Q c × 8,760 h, in GWh a year.</summary>
public static double ModelledGigawattHours(double headMetres, double meanFlowM3s, double efficiency, double usableShare) =>
    efficiency * WaterDensity * Gravity * headMetres * meanFlowM3s * usableShare * HoursPerYear / 1e9;

The Production method returns a status code alongside the value (Published, FromCapacity, Modelled, NoHead, NoFlow, NotHydropower), so the page can say which source it is showing.

7.2 The price: mean or capture

The yearly mean price per bidding zone is the default. A plant with water stored behind it can choose when to run, and runs when prices are high. Such a plant is priced at hydropower's capture price: the price weighted by how much hydropower actually produced in each hour.

pcapture=∑hqh⋅ph∑hqhp_{\text{capture}} = \frac{\sum_h q_h \cdot p_h}{\sum_h q_h}

with qhq_h the zone's hydropower production and php_h the price in hour hh. This is a production-weighted mean, the same construction as the volume-weighted species mix in part 2, section 5.

It is computed offline by scripts/power-market.py from open hourly data and pasted into PowerOptions as a table per zone and year. It is a computed statistic, not a fitted model: nothing is estimated, only averaged.

Mean and capture price per bidding zone
var storage = inputs.RegulationDegreePercent >= options.StorageMinRegulationPercent;
// …
var price = captureYears is null ? mean : YearRange(captureYears, 1);

The range across years is the cheapest year, the mean and the dearest year:

private static ValueRange YearRange(IReadOnlyDictionary<int, double> byYear, int digits) =>
    new(Math.Round(byYear.Values.Min(), digits), Math.Round(byYear.Values.Average(), digits), Math.Round(byYear.Values.Max(), digits));

7.3 Revenue and its present value

Yearly revenue is the energy times the price less the running cost oo, never below zero (a plant that could not cover its running costs would stand still). EE is in GWh, so E⋅106E \cdot 10^6 is kWh, and prices in öre are divided by 100 to give kronor:

R=E⋅106⋅max⁡(0, p−o)100R = E \cdot 10^{6} \cdot \frac{\max(0,\ p - o)}{100}
var revenue = energy is not null && powerValuation.PriceOrePerKwh is { } price
    ? Range(c => Pick(energy, c) * 1e6 * Math.Max(0, Pick(price, c) - Pick(power.OperatingCostOrePerKwh, Flip(c))) / 100, digits: 0)
    : null;

The present value over the horizon (H=30H = 30 years, r=3.5 %r = 3.5\,\%) sums the yearly value from year 1:

PV=∑t=1HR(1+r)tPV = \sum_{t=1}^{H} \frac{R}{(1 + r)^{t}}
// Money.cs
public static double PresentValue(Func<int, double> valueInYear, double discountRate, int horizonYears, int fromYear = 1)
{
    var total = 0.0;
    for (var year = Math.Max(1, fromYear); year <= horizonYears; year++)
    {
        total += valueInYear(year) / Math.Pow(1 + discountRate, year);
    }
    return total;
}

The value in a year is passed as a function, so the same method handles a constant flow (_ => value) and one that changes over time (the fish ramp in section 8.3).

In the fishway scenario the energy is reduced by the share of the flow the fishway takes; in the removed scenario it is zero. A plant with storage also earns a payment for keeping capacity in reserve, valued per megawatt and ended by removal.


8. Salmon

8.1 Smolts reaching the sea

A smolt is a young salmon on its way to the sea. The number that reach it from the habitat above the dam is a chain of multiplications:

S=L⋅d⋅u⋅w⋅ε nf⋅μ nhS = L \cdot d \cdot u \cdot w \cdot \varepsilon^{\,n_f} \cdot \mu^{\,n_h}
Symbol Meaning
LL Salmon habitat above the dam, km (the walk of section 4.3)
dd Smolts per km (calibrated, part 1, section 5.3)
uu Share of spawning adults that get up past this dam
ww Share of smolts that get down past this dam
ε\varepsilon A fishway's efficiency (0.20, 0.37, 0.60)
nfn_f Fishways between the dam and the sea
μ\mu A smolt's survival past one hydropower dam (0.75, 0.88, 0.95)
nhn_h Hydropower dams between the dam and the sea

The scenario changes only uu and ww:

var up = kind == DamScenarioKinds.Removed ? 1 : inputs.Passage switch
{
    SalmonPassage.Open => 1,
    SalmonPassage.Fishway => fishway,
    _ => kind == DamScenarioKinds.Fishway ? fishway : 0,       // blocked today: 0 kept, the efficiency with a fishway
};
var down = kind != DamScenarioKinds.Removed && inputs.Hydropower ? damSurvival : 1;
var toSea = inputs.ToSea!;
var below = Math.Pow(fishway, toSea.FishwayBarriers) * Math.Pow(damSurvival, toSea.HydropowerDams);
return habitatKm * density * up * down * below;

The exponents are why dams further down the river matter so much. Each one multiplies the share again:

The share that gets past several dams

8.2 From smolts to fish caught

From there the chain continues with survival at sea and the shares caught:

flowchart LR
    S["Smolts<br/>reaching the sea"] -->|"× post-smolt survival (0.10)<br/>× adult survival (0.92)"| A["Adults<br/>returning"]
    A -->|"× coastal harvest rate (0.15)"| C["Coastal catch<br/>(number)"]
    C -->|"× mean weight × price per kg"| K["Coastal catch<br/>(kr a year)"]
    A -->|"× (river catch rate + trolling rate)"| G["Anglers' catch"]
    G -->|"× spending per fish"| P["Anglers' spending"]
adults=S⋅spost⋅sadultcoastal catch (kr)=adults⋅hc⋅m⋅p\text{adults} = S \cdot s_{\text{post}} \cdot s_{\text{adult}} \qquad \text{coastal catch (kr)} = \text{adults} \cdot h_c \cdot m \cdot p
private static double CoastalSek(DamInputs inputs, SalmonOptions options, string kind, Case c) =>
    Smolts(inputs, options, kind, c) * Pick(options.PostSmoltSurvival, c) * options.AdultSurvival
    * Pick(options.CoastalHarvestRate, c) * options.MeanWeightKg * options.PricePerKg;

Every factor is an option with its source. The whole salmon side is a product of published rates and one calibrated density; there is no fitted model in it beyond that density.

8.3 The ramp-up: fish do not appear at once

A new fishway does not fill the river with salmon the next year: the first spawners' offspring must grow up, go to sea and return. The yearly catch therefore moves from today's value KK to the scenario's value NN in a straight line over T=10T = 10 years:

v(t)=K+(N−K)⋅min⁡ ⁣(1, tT)PV=∑t=1Hv(t)(1+r)tv(t) = K + (N - K) \cdot \min\!\left(1,\ \frac{t}{T}\right) \qquad PV = \sum_{t=1}^{H} \frac{v(t)}{(1 + r)^{t}}
fishPv = Range(c =>
{
    var kept = CoastalSek(inputs, salmon, DamScenarioKinds.Kept, c);
    var now = CoastalSek(inputs, salmon, kind, c);
    return PresentValue(year => kept + (now - kept) * Math.Min(1, year / (double)salmon.RampUpYears), power);
}, 0);
The ramp-up and the effect of discounting

The cast (double)salmon.RampUpYears is not decoration. year and RampUpYears are both int, and year / 10 in integer arithmetic is 0 for the first nine years. Without the cast the ramp would be a step.

8.4 A result that depends on something else

If a barrier further down the river stops salmon outright, no fish reach this dam whatever is done here. The calculator still computes the scenario, treating the barriers below as passable, and sets a flag (inputs.ToSea is { BlockingBarriers: > 0 }) so the page can say the result holds only if those are opened too. A natural barrier below is different: the river above was never salmon water, so the status is NaturalBarrierBelow and nothing is valued.

The statuses are decided with a switch over property patterns, which reads like a table of conditions:

var status = inputs switch
{
    { River: null } => SalmonStatuses.NotSalmonRiver,
    { OnNetwork: false } or { Habitat: null } or { ToSea: null } => SalmonStatuses.OffNetwork,
    { ToSea.NaturalBarriers: > 0 } => SalmonStatuses.NaturalBarrierBelow,
    { Density: null } => SalmonStatuses.NotSalmonRiver,
    _ => SalmonStatuses.Valued,
};

9. Sea trout

Sea trout use the same passage factors as salmon but a different starting point. Their habitat has no size limit (they spawn in small streams), and the number of young fish comes from the sea trout model of part 1, section 5: the stream's modelled width, times the density class of its district.

Strout=Y⋅k⋅u⋅w⋅ε nf⋅μ nhS_{\text{trout}} = Y \cdot k \cdot u \cdot w \cdot \varepsilon^{\,n_f} \cdot \mu^{\,n_h}

with YY the young trout the stretch holds and kk the calibrated smolts per young trout. The catch is then

caught=Strout⋅creared⋅fwild\text{caught} = S_{\text{trout}} \cdot c_{\text{reared}} \cdot f_{\text{wild}}

where crearedc_{\text{reared}} is the share of reared smolts reported caught (2.9 %, from tagging studies) and fwildf_{\text{wild}} a factor for how much better wild smolts do at sea (1, 3.7 or 4.5).

private static double SeaTroutCatchSek(DamInputs inputs, SalmonOptions salmon, SeaTroutOptions trout, string kind, Case c) =>
    SeaTroutSmolts(inputs, salmon, kind, c) * trout.ReportedCatchRate * Pick(trout.WildFactor, c) * trout.MeanWeightKg
    * Pick(trout.PricePerKg, c);

The wild factor shows how a gap in the data is handled: there is no Swedish figure for wild sea trout, so the range runs from "no better than reared" to the figure measured for salmon, and the options comment says exactly that.


10. Eel

Eel is handled differently, because the national eel assessment already estimates the tonnes of silver eel killed at each larger plant. EcoVal shows that figure for the plant and adds two things of its own.

10.1 Survival to the sea

A silver eel going down passes each plant's turbines with mortality mm (0.31, 0.70 or 0.90). Past nn plants:

survival=(1−m) n\text{survival} = (1 - m)^{\,n}
var survival = 1 - Pick(options.TurbineMortality, Flip(c));       // the low case takes the high mortality
var turbines = inputs.Hydropower || inputs.Eel?.Plant is not null;
var plants = (inputs.ToSea?.HydropowerDams ?? 0) + (turbines && kind != DamScenarioKinds.Removed ? 1 : 0);
return Math.Pow(survival, plants);

A fishway does not change this: fishways help fish go up, and the eels are killed going down.

10.2 From tonnes to a number of eels

"0.8 tonnes of eel" is hard to picture; a number of eels is not. To convert, the eel's mean weight is needed, and that comes from two published relations, used with their coefficients as given (borrowed regression, as in part 3).

First, a silver eel's mean length rises with latitude, as a straight line:

ℓ(φ)=70+5 (φ−56)cm, with φ the latitude in degrees north\ell(\varphi) = 70 + 5\,(\varphi - 56) \quad \text{cm, with } \varphi \text{ the latitude in degrees north}

Second, weight follows length as a power law, the usual form of a length–weight relation in fish biology:

W=a⋅ℓ bg,a=0.000559, b=3.297W = a \cdot \ell^{\,b} \quad \text{g}, \qquad a = 0.000559,\ b = 3.297

The exponent is close to 3 because weight grows with volume, and volume with the cube of length.

public sealed record SilverEelLength(double Central, double PerDegree, double AtLatitude)
{
    public double At(double latitude) => Central + PerDegree * (latitude - AtLatitude);
}

public sealed record LengthWeight(double A, double B)
{
    public double Grams(double lengthCm) => A * Math.Pow(lengthCm, B);
}

The number of eels is then tonnes over grams, rounded to two significant figures, because the weight is a national mean and more digits would claim more than is known:

n=tonnes⋅106Wn = \frac{\text{tonnes} \cdot 10^{6}}{W}
public static double EelCount(double tonnes, double grams)
{
    var count = tonnes * 1_000_000 / grams;
    if (count < 1) return Math.Round(count, 1);
    var scale = Math.Pow(10, Math.Floor(Math.Log10(count)) - 1);
    return Math.Round(count / scale) * scale;
}

Math.Floor(Math.Log10(count)) is the number of digits before the decimal point, minus one. Dividing by a power of ten one less than that leaves two digits to round, and multiplying back restores the size: 6,843 becomes 6,800.


11. Costs, the net and willingness to pay

11.1 What a fishway or a removal costs

Published costs are given per metre of head (the height the water falls). The one-off cost of a fishway is

Conce=H⋅cper metre⋅KPIprice yearKPIcost year+CstudyC_{\text{once}} = H \cdot c_{\text{per metre}} \cdot \frac{\text{KPI}_{\text{price year}}}{\text{KPI}_{\text{cost year}}} + C_{\text{study}}

with a different cost per metre for large and small plants, and a yearly upkeep on top. The present value adds the upkeep's present value to the one-off cost:

oneOff = Range(c => Index(head * Pick(perMetre, c), year, costs) + study, 0);
upkeep = Range(c => Index(Pick(costs.FishwayUpkeepSekPerYear, c), costs.FishwayStudyPriceYear, costs), 0);
// …
var presentValue = Combine(oneOff, upkeep, (once, yearly) => once + PresentValue(_ => yearly, power), 0);

The removal cost comes from a study of small dams. For a dam outside what that study covered (a head above 7 m or a mean flow above 30.2 m³/s), the calculator returns the status OutsideSourceRange and no cost, instead of applying the per-metre figure where it was never measured:

if (removal && (head > costs.RemovalMaxHeadMetres || inputs.MeanFlowM3s > costs.RemovalMaxMeanFlowM3s))
{
    return new DamCost(DamCostStatuses.OutsideSourceRange, basis, Math.Round(head, 1), headSource, null, null, null, null);
}

This is the same principle as the caps in part 3: a number is not stretched beyond the data behind it.

11.2 The net

The net adds power, reserves and the fish catch, and subtracts the cost. The cost is paired the other way round: the low net takes the high cost.

netlow=PVlowpower+PVlowfish−Chigh\text{net}_{\text{low}} = PV^{\text{power}}_{\text{low}} + PV^{\text{fish}}_{\text{low}} - C_{\text{high}}
return ValueRange.Spanning(
    powerSide.Low + fish.Low - costSide.High,
    powerSide.Central + fish.Central - costSide.Central,
    powerSide.High + fish.High - costSide.Low,
    0);

If the power cannot be told (a hydropower dam with no known head, say), there is no net at all (null). A net that silently left out the power would be worse than no net.

11.3 Willingness to pay: a value that stops at the survey's edge

Two surveys asked Swedes what they would pay for a specific increase in wild salmon: about 1,000 more spawners in a river. That gives a total for that increase, not a price per fish.

The calculator computes the scenario's extra spawners and then decides which of three cases applies:

Extra spawners Code Value
Fewer than the surveyed increase (1,000) Below None
Within the surveyed range Within The survey's total
More than the largest surveyed (6,000) Above The survey's total, not more
value=total⋅clamp⁡ ⁣(extrasurveyed, 0, 1)for extra≥surveyed, else none\text{value} = \text{total} \cdot \operatorname{clamp}\!\left(\frac{\text{extra}}{\text{surveyed}},\ 0,\ 1\right) \quad \text{for extra} \ge \text{surveyed}, \text{ else none}
var scope = extra.Central < survey.SurveyedIncrease
    ? WillingnessToPayScopes.Below
    : extra.Central > survey.MaxSurveyedIncrease ? WillingnessToPayScopes.Above : WillingnessToPayScopes.Within;
var value = scope == WillingnessToPayScopes.Below
    ? null
    : Combine(extra, survey.TotalSek, (fish, total) => total * Math.Clamp(fish / survey.SurveyedIncrease, 0, 1), 0);

The scope is decided on the central case. The low and high cases then use their own number of extra spawners, so a low case that falls below the surveyed increase is scaled down by the clamp.

The comment in the source explains the choice: scaling the total down for a smaller increase would amount to a value per salmon, which neither survey supports. So below the surveyed increase the code returns null, and the page says the value is unknown.


12. The national plan

File: Dam/NationalPlanCalculator.cs. Sweden's national plan for hydropower sets, per river system, how much production may be given up for environmental measures (a guide value in TWh a year). The calculator shows how much of that a scenario would use:

share of the guide value=Ekept−Escenarioguide value⋅1000\text{share of the guide value} = \frac{E_{\text{kept}} - E_{\text{scenario}}}{\text{guide value} \cdot 1000}

(GWh over GWh; the 1000 turns the guide value's TWh into GWh.)

var gigawattHours = guideTerawattHours * 1000;
return ValueRange.Spanning(
    (kept.Low - now.Low) / gigawattHours,
    (kept.Central - now.Central) / gigawattHours,
    (kept.High - now.High) / gigawattHours,
    digits: 4);

The method takes today's date as a parameter (DateOnly today) to decide whether the dam's review date has passed. The endpoint gets it from TimeProvider, which keeps the calculator pure and lets a test fix the date.


13. Summary

Section Kind of calculation Regression or fitted model?
The network Graph of segments with lookup tables No
Which barriers stop fish Decision rules (switch expressions) No
Upstream, downstream, habitat Graph walks (breadth-first search; a loop following the flow) No
Area draining through a point Proportional sharing; a post-order traversal with a cache No
Power: production Published figure, capacity × hours, or the physics formula No
Power: capture price Production-weighted mean, computed offline by a script No (a computed statistic)
Salmon Product of survival rates and shares Uses EcoVal's calibrated smolts per km (part 1, section 5.3)
Sea trout The same product from a different start Uses EcoVal's width regression, density classes and smolt ratio (part 1, sections 5.1–5.2)
Eel survival A survival rate raised to the number of plants No
Eel count Length from latitude, weight from length Borrowed regression: SLU's linear length relation and power-law length–weight relation
Costs Cost per metre of head, indexed; refused outside the source's range No
Willingness to pay A survey total applied within the surveyed range only No
National plan A ratio No

The water page's dam is the clearest example in EcoVal of a process model: a chain of physical and biological steps, each a simple multiplication with a published rate. Its uncertainty comes from the rates, which is why almost every one is a ParameterRange, and why the code spends so much care on which low goes with which high.