# Model and algorithms

The Energy Flow Observatory asks a capacity question: after a specified loss of export availability or bilateral route capacity, how much of the measured annual import volume can still be supplied, and how would the remaining flows be allocated?

The answer is conditional on an observed trade panel and two explicit flexibility assumptions. The first allows unaffected exporters to supply additional volume. The second allows recorded bilateral links to expand. A separate complete-route calculation removes the restriction to recorded links while retaining the supply limits, import targets, self-pair exclusion, and any specified corridor restriction.

The browser solves a continuous transportation problem in three ordered stages. It first serves as much aggregate demand as possible. Holding that total fixed, it protects the least-served importer in proportional terms. Holding both priorities fixed to numerical tolerance, it chooses flows closest to the baseline. This document defines that calculation and explains the algorithms used in [the solver](../dist/solver.js). [Sensitivity and interpretation](03-sensitivity-and-interpretation.md) defines the quantities displayed around the solution.

## 1. What is being modeled

One solve concerns one commodity and one annual baseline. The shipped application has crude oil and LNG panels for 2021 and 2025. The data snapshot and scope are recorded in [energy-data.json](../dist/data/energy-data.json).

Crude volumes are physical crude barrels. LNG volumes are liquid LNG barrels. Every numerical quantity inside the solver is expressed in millions of the relevant barrels. The two products are solved separately. A liquid LNG barrel is a volume unit, not a barrel of oil equivalent, and the application does not add crude and LNG into one energy balance.

An importer target is its measured bilateral import total in the selected panel. An exporter supply base is its measured exports to those modeled importers. Neither quantity is national consumption or global production. A country can appear in both roles, but the model treats its exporter and importer copies as separate nodes. It has no constraint that transfers an import received by a country into that country's exports. Re-exports, domestic production, storage, and internal consumption therefore do not form an inferred physical balance.

The map combines these two roles into one country symbol for readability. The optimization retains the role distinction.

## 2. Notation

| Symbol | Meaning |
| --- | --- |
| $I$ | Active exporter roles in the selected panel |
| $J$ | Modeled importer roles in the selected panel |
| $B_{ij}$ | Numerical reference flow from exporter $i$ to importer $j$ |
| $K_{ij}$ | Indicator that the baseline pair has a usable observed quantity |
| $S_i=\sum_j B_{ij}$ | Exporter $i$'s measured baseline supply to the panel |
| $D_j=\sum_i B_{ij}$ | Importer $j$'s measured baseline import target |
| $Y=\sum_i S_i=\sum_j D_j$ | Total measured baseline volume |
| $H\subseteq I$ | Selected exporters in a supplier shock |
| $q_i\in[0,1]$ | Fraction of exporter $i$'s baseline availability removed |
| $k\in I$, $T\subseteq J$ | Exporter and destinations selected for a corridor shock |
| $q\in[0,1]$ | Fraction of selected corridor capacity removed |
| $h\geq0$ | Replacement supply allowance for exporters eligible for headroom |
| $r\geq0$ | Expansion allowance on unrestricted existing links |
| $A$ | Admissible exporter-importer arcs |
| $\bar S_i$ | Exporter capacity after the scenario is applied |
| $U_{ij}$ | Capacity of an admissible bilateral arc |
| $x_{ij}\geq0$ | Reallocated flow on an admissible arc |
| $y_j=\sum_i x_{ij}$ | Import volume served to importer $j$ |
| $F=\sum_{ij}x_{ij}$ | Aggregate served volume |
| $F^*$ | Maximum aggregate served volume |
| $\alpha^*$ | Best minimum importer service fraction at $F^*$ |
| $C(x)=\sum_{ij}|x_{ij}-B_{ij}|$ | Absolute departure from the numerical reference flows |

The asterisk denotes an optimized quantity. Volumes have units of million barrels. The parameters $q_i$, $q$, $h$, $r$, and $\alpha$ are fractions. For example, a displayed 25% route expansion means $r=0.25$.

The website allows $h$ from 0% to 50% and $r$ from 0% to 100%. The exported solver accepts nonnegative $h$ and $r$ up to 10, or 1,000%, to support external experiments. Those broader numerical limits are not statements about plausible physical spare capacity.

### Observed zeros and numerical zeros

The numerical matrix must contain finite, nonnegative values. Some zero entries correspond to known absence of recorded trade within the eligible reporting scope. Other zero entries stand in for pairs whose observed quantity is unknown. The separate mask $K$ preserves this distinction.

Existing-route mode admits only $B_{ij}>0$. Complete-route mode may admit a pair with $K_{ij}=0$. Such a pair is a hypothetical candidate whose observed baseline remains unknown. Its numerical reference is zero for the allocation objective. A positive allocation there is consequently penalized as a departure from the measured reference network, but it is not described as a measured increase from an observed zero. The matrix, tables, tooltips, and exports retain the distinction.

The [country-pair module](../dist/pairs.js) controls whether a direct pair shock can be launched from the website. It requires distinct country identities, active source and buyer roles, and a known baseline quantity. A known-zero pair can be selected, but its direct baseline exposure is zero. An unknown pair cannot be assigned a measured direct exposure.

## 3. Constructing a scenario

### 3.1 Supplier availability cuts

A supplier shock removes a specified fraction of the selected exporter's measured supply to the panel. Selected suppliers do not receive the replacement supply allowance. Every other exporter does:

$$
\bar S_i=
\begin{cases}
(1-q_i)S_i, & i\in H,\\
(1+h)S_i, & i\notin H.
\end{cases}
$$

For a joint shock, each selected exporter may have its own cut. A 50% US cut and a 25% Qatar cut therefore impose two separate capacities. The main scenario solve retains those separate values.

The direct volume removed before any reallocation is

$$
A_{\mathrm{direct}}=\sum_{i\in H}q_iS_i.
$$

The corresponding proportional no-adjustment allocation is $x_{ij}=(1-q_i)B_{ij}$ for selected suppliers and $x_{ij}=B_{ij}$ for the others. It serves $Y-A_{\mathrm{direct}}$ and is feasible under the scenario assumptions. Optimization can improve on that allocation by reallocating available supply.

Selection matters even at a zero cut. A selected exporter with $q_i=0$ has capacity $S_i$, whereas an unselected exporter has capacity $(1+h)S_i$. The selected exporter is being stressed, rather than being treated as a reserve supplier. Baseline service is still feasible at a zero cut.

### 3.2 Bilateral and regional corridor cuts

A corridor shock restricts exports from one source $k$ to one or more destinations $T$. It does not directly remove the exporter's total availability. Every exporter, including $k$, receives supply headroom:

$$
\bar S_i=(1+h)S_i.
$$

For every affected pair, the route capacity is replaced by

$$
U_{kj}=(1-q)B_{kj},\qquad j\in T.
$$

This replacement overrides the usual route capacity in both existing-route and complete-route mode. A full closure gives $U_{kj}=0$. At $q=0$, the selected route has capacity $B_{kj}$, not $(1+r)B_{kj}$. This convention makes the slider a reduction from the recorded baseline capacity of the selected corridor.

The direct exposure is

$$
A_{\mathrm{direct}}=q\sum_{j\in T}B_{kj}.
$$

The exporter may redirect its remaining capacity to other destinations. Other exporters may replace part of the affected imports. A country-pair shock is the special case $T=\{j\}$. The regional preset uses the EU27 and UK destination identities present in the panel.

The current solver accepts either supplier cuts or a corridor restriction in a single scenario. It rejects an input that combines the two. A simultaneous loss of national output and an embargo on one destination group requires an explicit extension to the capacity construction.

## 4. Existing routes and complete candidates

### 4.1 Existing-route mode

The admissible set is

$$
A_{\mathrm{existing}}=\{(i,j): B_{ij}>0\}.
$$

An unrestricted arc receives capacity

$$
U_{ij}=(1+r)B_{ij}.
$$

The row capacity $\bar S_i$ still applies. Increasing every bilateral capacity by 25% does not create 25% additional supply. It only relaxes where existing supply may be sent.

A source that serves several destinations must divide its available volume among them. The model captures competition for replacement supply through shared exporter capacities and competition for routes through the bilateral capacities.

### 4.2 Complete-route mode

The candidate set contains every exporter-importer combination with distinct country identities:

$$
A_{\mathrm{complete}}=\{(i,j)\in I\times J:\operatorname{code}(i)\neq\operatorname{code}(j)\}.
$$

For an unrestricted arc, the implementation uses

$$
U_{ij}=\min\{(1+h)S_i,D_j\}.
$$

This arc limit is redundant with the row and column limits because $\bar S_i\leq(1+h)S_i$ in every supported scenario. Its purpose is to represent unrestricted bilateral access without introducing unnecessarily large numerical capacities. A selected corridor still receives the stricter $(1-q)B_{ij}$ cap.

The parameter $r$ has no effect in complete-route mode. The same supply and import totals remain in place. Complete routes add possible destinations for available supply, not additional barrels.

The complete-route calculation is an optimistic routing benchmark. It does not establish terminal compatibility, shipping feasibility, regulatory permission, contract availability, vessel capacity, or a willingness to trade. It also does not impute a missing observed baseline. Its question is whether the remaining volume could be allocated if bilateral access were as flexible as the candidate construction assumes.

### 4.3 Why complete service is at least as large

For any existing-route solution, each bilateral flow is already bounded by the relevant exporter capacity and importer target. It is therefore feasible on the corresponding complete candidate arc. The corridor restrictions and self-pair exclusion are the same. Thus

$$
\mathcal F_{\mathrm{existing}}\subseteq\mathcal F_{\mathrm{complete}},
$$

where $\mathcal F$ denotes the set of feasible allocations. It follows that

$$
F^*_{\mathrm{complete}}\geq F^*_{\mathrm{existing}}.
$$

This is a property of the model construction. It does not depend on a particular observed country ranking.

## 5. The feasible flow set

For either route choice, feasible flows satisfy

$$
0\leq x_{ij}\leq U_{ij},\qquad (i,j)\in A,
$$

$$
\sum_{j:(i,j)\in A}x_{ij}\leq\bar S_i,\qquad i\in I,
$$

$$
\sum_{i:(i,j)\in A}x_{ij}\leq D_j,\qquad j\in J.
$$

Exporter capacity can remain unused. Importers cannot receive more than their baseline target. No importer demand is increased to accommodate redirected exports.

The demand caps are a substantive modeling choice. The model preserves the annual baseline as its service target. It does not estimate a new demand curve after a price shock, or allow one country's imports to grow beyond baseline while another country's imports fall. A historical comparison can show that growth, but the scenario optimization answers a different, fixed-target question.

All flow variables are continuous. No indivisible ship, cargo, terminal-opening, or contract decision is represented. The three objectives can be solved using linear and network-flow methods without integer variables. Adding integer decisions would change the economic question and would require additional data.

## 6. Stage 1: maximum aggregate service

The first objective is

$$
F^*=\max_{x\in\mathcal F}\sum_{(i,j)\in A}x_{ij}.
$$

The network has a super-source $s$, one node for each exporter role, one node for each importer role, and a super-sink $t$:

- An arc $s\to i$ has capacity $\bar S_i$.
- An arc $i\to j$ has capacity $U_{ij}$.
- An arc $j\to t$ has capacity $D_j$.

A feasible $s$-$t$ flow is exactly a feasible transportation allocation. Its value is the aggregate import service. The implementation uses a level-graph augmenting-flow algorithm in `Dinic`, called by `maximumService`.

### Minimum-cut interpretation

For any set of nodes $W$ containing $s$ and excluding $t$, define its cut capacity by the capacities of arcs leaving $W$:

$$
C(W)=\sum_{(u,v):u\in W,\ v\notin W}c_{uv}.
$$

Every feasible flow must pass through that cut, so $F\leq C(W)$. After the augmenting algorithm has no residual path to $t$, the nodes still reachable from $s$ identify a cut whose capacity equals the computed flow value. The solver returns this cut as a certificate:

$$
F^*=C(W^*).
$$

The returned cut identifies supplier, route, and buyer arcs. Supplier arcs point to available-volume restrictions. Route arcs point to bilateral access restrictions. Buyer arcs may simply reflect saturated import targets. A saturated route need not be the only obstacle, and several different minimum cuts may coexist. Reading one cut as a unique causal explanation would overstate what the certificate establishes.

The website exports the cut in the scenario JSON. It is useful for diagnosing why an aggregate service result cannot be improved under the current capacities.

## 7. Stage 2: protect the least-served importer

Maximum aggregate service usually leaves many possible country allocations. The second stage chooses the largest common service fraction:

$$
\alpha^*=\max_{x,\alpha}\alpha
$$

subject to $x\in\mathcal F$ and

$$
\sum_{ij}x_{ij}=F^*,
$$

$$
\sum_i x_{ij}\geq\alpha D_j,\qquad j\in J,
$$

$$
0\leq\alpha\leq1.
$$

This rule compares importers proportionally. A country with a target of 100 and a country with a target of 10 both receive a floor of 80% when $\alpha=0.8$. Their guaranteed volumes are 80 and 8.

The rule maximizes the worst service fraction. It does not require every importer to have the same fraction, and it is not a full leximin ordering of all importer fractions. Once the worst achievable fraction is fixed, the third stage selects among the remaining feasible allocations using proximity to the baseline.

The aggregate service objective has strict priority. The solver does not deliberately reduce total service to obtain a more equal distribution.

### Feasibility search

For a proposed $\alpha$, the importer-to-sink arc is given lower bound $\alpha D_j$ and upper bound $D_j$. A fixed return flow of $F^*$ from $t$ to $s$ turns the problem into a circulation with lower bounds.

The implementation eliminates lower bounds, records the induced node balances, introduces a super-source and super-sink for those balances, and tests whether all required balancing flow can be sent. Feasibility is monotone in $\alpha$: if a fraction is feasible, every smaller fraction is feasible.

`bestFairness` therefore searches the interval

$$
0\leq\alpha\leq\min\{1,F^*/Y\}.
$$

It first tests the upper bound. Otherwise, it uses at most 43 bisection iterations and stops when the search interval is at most $10^{-12}$. This avoids introducing a general linear-programming dependency into the browser.

## 8. Stage 3: minimum absolute flow change

With aggregate service and the proportional floor fixed, the final objective is

$$
\min_{x\in\mathcal F}\sum_{ij}|x_{ij}-B_{ij}|
$$

subject to

$$
\sum_{ij}x_{ij}=F^*,\qquad
\sum_i x_{ij}\geq\max\{0,\alpha^*-10^{-9}\}D_j.
$$

The small relaxation of the fraction is explicit in the implementation. It prevents roundoff in the feasibility search from making the final minimum-cost problem numerically infeasible. It is a numerical tolerance, not a policy weight.

The objective prefers retaining the measured bilateral pattern when throughput and the worst service fraction permit it. It has no distance, price, emissions, preference, or transport-cost interpretation. An unweighted change of one million barrels contributes the same objective amount on every link.

### Piecewise-linear cost construction

For a given route, the derivative of $|x-B_{ij}|$ is $-1$ below $B_{ij}$ and $+1$ above it. The solver replaces the route by up to two parallel arcs:

| Segment | Capacity | Unit cost |
| --- | --- | --- |
| Baseline segment | $\min\{B_{ij},U_{ij}\}$ | $-1$ |
| Additional segment | $\max\{0,U_{ij}-B_{ij}\}$ | $+1$ |

The total segment cost equals $|x_{ij}-B_{ij}|-B_{ij}$. Since $\sum_{ij}B_{ij}=Y$ is constant, minimizing segment cost is equivalent to minimizing absolute change.

The same lower-bound circulation reduction enforces throughput and importer floors. `MinCostFlow` then sends the required balancing flow using shortest residual paths. Residual reverse arcs allow earlier decisions to be revised when a later augmentation finds a better allocation. The initial forward network is acyclic, so its negative baseline-segment costs do not form an initial negative-cost cycle.

### A useful accounting identity

Let

$$
R^+=\sum_{ij}\max\{x_{ij}-B_{ij},0\},\qquad
R^-=\sum_{ij}\max\{B_{ij}-x_{ij},0\}.
$$

Because the baseline total is $Y$ and the final total is $F^*$,

$$
R^- - R^+=Y-F^*=L.
$$

Hence

$$
C(x)=R^++R^-=L+2R^+.
$$

At fixed aggregate loss $L$, minimizing absolute flow change is equivalent to minimizing gross additions above the numerical baseline. This explains why the third stage avoids unnecessary rerouting while retaining the first two priorities.

The identity concerns numerical reference values. If complete candidates include unknown observed baselines, $R^+$ on those candidates measures modeled additions relative to the reference network, not an observed trade increase.

### Remaining ties

The third stage does not guarantee a unique matrix $x$. Several allocations may have the same total service, the same best minimum service fraction, and the same absolute change. Another correct implementation may return different bilateral flows while agreeing on those objective values.

The returned matrix is one selected optimal allocation. Its individual links should not be treated as uniquely predicted trades. The distinction is especially relevant when complete candidates create many equivalent substitution paths.

## 9. Country allocation ranges

The website also calculates the range of service that each importer could receive while preserving maximum aggregate service. These ranges are computed before the fairness and minimum-change choices.

Define the maximum-service face

$$
\mathcal F^*=\left\{x\in\mathcal F:\sum_{ij}x_{ij}=F^*\right\}.
$$

For importer $j$, the quantities of interest are

$$
y_j^{\min}=\min_{x\in\mathcal F^*}\sum_i x_{ij},\qquad
y_j^{\max}=\max_{x\in\mathcal F^*}\sum_i x_{ij}.
$$

The implementation uses the transportation structure to obtain these bounds without solving two generic programs per importer.

Let $F^*_{-j}$ be the maximum flow when importer $j$'s sink capacity is set to zero. Then

$$
y_j^{\min}=\max\{0,F^*-F^*_{-j}\}.
$$

The lower bound follows because all other importers together can receive at most $F^*_{-j}$. It is attainable: a maximum flow to the other importers can be extended, after restoring $j$, to a maximum total flow without reducing their aggregate terminal service.

For the upper endpoint, the most that can be sent to $j$ alone is

$$
y_j^{\max}=\min\left\{D_j,F^*,\sum_{i:(i,j)\in A}\min\{\bar S_i,U_{ij}\}\right\}.
$$

Each exporter is bounded by its own capacity and its arc to $j$. A feasible flow serving that standalone maximum can be augmented to a maximum total flow while retaining the flow already entering $j$'s terminal arc. This establishes attainability on $\mathcal F^*$.

The displayed shortfall interval reverses the service endpoints:

$$
\left[100\left(1-\frac{y_j^{\max}}{D_j}\right),
100\left(1-\frac{y_j^{\min}}{D_j}\right)\right].
$$

Each interval is a separate country calculation. The favorable endpoint for every country need not be attainable in one common allocation. These are structural allocation bounds. They are neither statistical confidence intervals nor bounds conditional on retaining the stage-2 fairness rule.

## 10. Numerical tolerances and returned diagnostics

The algorithm uses double-precision arithmetic. The scale-dependent residual tolerance is

$$
\varepsilon=\max\{10^{-12},Y\times10^{-14}\}
$$

in million barrels. Residual arcs below that threshold are treated as exhausted.

| Calculation | Implemented tolerance or guard |
| --- | --- |
| Snap near-full service to baseline | $|F-Y|<Y\times10^{-12}$ |
| Flow-cut agreement | $\max\{10^{-6},Y\times10^{-9}\}$ million barrels |
| Lower-bound feasibility | $\max\{20\varepsilon,Y\times10^{-12}\}$ million barrels |
| Fairness search | At most 43 iterations, interval no wider than $10^{-12}$ |
| Fairness floor in final allocation | Relaxation of $10^{-9}$ in the service fraction |
| Final constraint and throughput acceptance | $\max\{10^{-6},Y\times10^{-9}\}$ million barrels |
| Shortest-path relaxation comparison | Improvement greater than $10^{-10}$ in path cost |
| Path-search guard | Fewer than 1,000,000 queued entries per shortest-path search |
| Augmentation guard | Fewer than 100,000 augmentations |

One millionth of a million barrels is one barrel. The volume acceptance tolerance therefore has a one-barrel floor and can be larger for a large panel. It is an algorithmic acceptance threshold, not a measurement-accuracy claim. UN Comtrade quantity quality and conversion assumptions are separate issues.

The final allocation is checked against route bounds, exporter capacities, importer targets, importer floors, and its required aggregate throughput. The scenario output includes the maximum constraint violation and fairness relaxation. An infeasible or nonconvergent calculation raises an error rather than returning an apparently successful allocation.

The reported worst-buyer loss uses $100(1-\alpha^*)$. Individual displayed shortfalls come from the final allocation, which allows the stated fractional relaxation. Their maximum can differ by a very small numerical amount.

## 11. Execution and performance

The principal calculation runs in [a Web Worker](../dist/worker.js), so solving does not block the browser's main interface thread. The worker exposes five operations: scenario allocation, severity curve, headroom grid, supplier ranking, and country envelopes.

The solver caches normalized panel totals in a `WeakMap`. The worker caches up to 60 results, keyed by operation, product, year, options, and operation settings. This cache is appropriate for the application's immutable bundled panels. An external caller that replaces a matrix without changing its product and year should clear or replace the worker rather than expecting the cache key to detect changed data.

The expensive fairness and minimum-change stages are needed for the selected scenario's country and route allocation. The grid, supplier rankings, and most sensitivity calculations require aggregate service only and therefore call the primary maximum-flow calculation. A single-source severity curve uses the exact hinge formula derived in [the sensitivity document](03-sensitivity-and-interpretation.md).

If $m=|I|$, $n=|J|$, and $e=|A|$, the primary network has $m+n+2$ nodes and $m+n+e$ forward arcs, plus their residual reverses. Existing-route construction keeps the optimization sparse. Complete-route construction can contain up to $mn$ candidate arcs before self-pair exclusions. The problem size grows with the measured source and buyer roles, rather than with the full country-directory square when most identities are outside the selected panel.

The interface gives each request an identifier and checks the current scenario version before displaying a result. A result for earlier slider values cannot replace the current calculation. The full pair directory and graphical display filters are separate from the optimization. Displaying only the largest 60 changes does not solve a 60-link approximation.

## 12. What this model establishes

For its supplied annual panel and capacities, the model establishes a feasible aggregate service limit, one allocation respecting the stated priorities, and sensitivity to specified changes in those capacities. The maximum-flow cut and the final constraint checks support that computational claim.

The model does not establish how countries would bargain, how prices would clear, how inventories would be drawn down, or which cargoes would arrive at a particular port. It has no timing, voyage, quality, liquefaction, regasification, pipeline, or storage constraints. Replacement supply and route expansion are scenario assumptions rather than estimated physical capacities.

A historical disruption can motivate a scenario or help assess an expanded model. Matching an observed episode after adjusting assumptions is calibration. Demonstrating predictive performance requires a separate evaluation with targets, observations, and parameters kept distinct. The browser demonstration should be read as a transparent capacity stress test throughout that evaluation.

## Implementation map

| Mathematical object | Implementation |
| --- | --- |
| Panel totals and residual scale | `normalisePanel` in [solver.js](../dist/solver.js) |
| Scenario capacities and admissible arcs | `buildProblem` in [solver.js](../dist/solver.js) |
| Maximum service and cut | `maximumService` and `Dinic` |
| Best minimum service fraction | `bestFairness` and `fairFeasible` |
| Minimum absolute change | `minimumChangeAllocation` and `MinCostFlow` |
| Selected scenario output | `solveScenario` |
| Separate importer extrema | `countryEnvelopes` |
| Coverage and direct-pair eligibility | [pairs.js](../dist/pairs.js) |
| Background operations and result cache | [worker.js](../dist/worker.js) |
| Controls, visualizations, and exports | [app.js](../dist/app.js) |
