Even flow: shape first, level second

An even-flow target constrains the shape of a harvest profile; a separate floor constrains its level. Together they find the highest flat profile a forest can sustain, without the level ever being specified. This notebook runs the two stages on a generated estate and shows the before and after.

This one mixes both paths: it runs commands and imports the library where the objective is the interesting part.

A generated estate

400 blocks, ages 0 to 120, on the two-strata recipe that ships with the repository. Any compiled dataset works; this one is small, so the notebook stays quick.

[1]:
import subprocess


def run(command: str) -> None:
    """Run a WS4 command, printing what it printed."""
    result = subprocess.run(command, shell=True, text=True, capture_output=True)
    print((result.stdout or result.stderr).strip())
    result.check_returncode()

[2]:
from pathlib import Path

import numpy as np
import pandas as pd
from ws4.build.compiler import build_canonical_dataset

work = Path("tmp/examples/even-flow")
work.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(7)
count = 400
fragments = work / "fragments.csv"
pd.DataFrame(
    {
        "BLOCK": np.arange(1, count + 1),
        "AREA_HA": np.round(rng.uniform(2.0, 20.0, count), 1),
        "F_AGE": rng.integers(0, 120, count),
        "AU": rng.choice(["A", "B"], count),
        "IFM": rng.choice(["managed", "unmanaged"], count),
        "RETENTION": rng.choice([0.0, 0.0, 0.25], count),
    }
).to_csv(fragments, index=False)
dataset = build_canonical_dataset("tests/fixtures/matrix/recipe.xml", fragments, work / "compiled")
print(dataset)
tmp/examples/even-flow/compiled

Stage 1: a floor, and nothing else

A flow term divides by a balance — the reference period for even flow — so while that balance is zero the term is infinite. The procedure is to prime it first: run with a linear floor so every period carries wood, and only then switch the shape term on.

[3]:
import random

from ws4.opt.engine import OptimizeConfig, Optimizer
from ws4.opt.incremental import IncrementalObjective
from ws4.opt.objective import Target, flow_penalty
from ws4.opt.solvers import solve_sa_delta

VOL, PERIOD, YEARS = "product.Harvested.CC", 10, 100
PERIODS = YEARS // PERIOD
optimizer = Optimizer.from_dataset(dataset, OptimizeConfig(years=YEARS, iterations=20_000))
candidates = optimizer.candidates()
level = [Target(VOL, period * PERIOD, minimum=30_000, period_width=PERIOD) for period in range(PERIODS)]

def profile(evaluator, schedule):
    probe = IncrementalObjective(evaluator.optimizer, evaluator.targets, ())
    probe.reset(schedule)
    return [
        sum(probe.totals.get((year, VOL), 0.0) for year in range(begin, begin + PERIOD))
        for begin in range(0, YEARS, PERIOD)
    ]

def show(title, values):
    print(title)
    print("  " + "  ".join(f"{value:,.0f}" for value in values))

def solve(evaluator, initial=None):
    best, objective = solve_sa_delta(
        evaluator, random.Random(1), iterations=20_000, temperature=1000.0, cooling=0.99,
        candidates=candidates, registry=optimizer.registry, initial=initial,
    )
    return best, objective
[4]:
evaluator = IncrementalObjective(optimizer, level)
primed, _ = solve(evaluator)
before = profile(evaluator, primed)
show("floor only:", before)
print(f"  spread {max(before):,.0f} to {min(before):,.0f}")
floor only:
  82,186  36,562  34,452  32,622  31,503  31,601  30,632  35,787  41,461  57,139
  spread 82,186 to 30,632

A ragged profile with a floor under it: the search harvested what it liked where it liked. The term it never had to satisfy is the shape.

Stage 2: add the band

Zero, plus or minus one percent, with a high non-linear weight, and continue from the primed schedule.

[5]:
flow = Target(
    VOL, 0, flow="even", period_width=PERIOD, minimum=-1.0, maximum=1.0,
    min_weight=10_000.0, max_weight=10_000.0, shape="non_linear",
)
flowed = IncrementalObjective(optimizer, level + [flow])
even, _ = solve(flowed, initial=primed)
after = profile(evaluator, even)
show("with the +-1% band:", after)
print(f"  spread {max(after):,.0f} to {min(after):,.0f}")
probe = IncrementalObjective(optimizer, level)
probe.reset(even)
print(f"  flow penalty {flow_penalty(probe.totals, flow, YEARS):,.1f}")
with the +-1% band:
  38,212  38,130  37,626  38,180  38,105  37,929  37,767  37,463  38,007  37,840
  spread 38,212 to 37,463
  flow penalty 0.0

Flat to within a percent — and note which percent. even compares every period with the reference period, the last one by default, not with the mean. The spread above is wider than one percent of the mean and still costs nothing, because every period is within one percent of the reference. flow_reference names another period to compare with.

What the pair bought

  • The band fixed the shape without being told a level.

  • The floor pulled the level up; the band then held the periods together as it climbed.

  • Neither target names a harvest level, which is why the same pair works on another estate.

For the closing-inventory variant, use flow="ndy" on a standing account: each period is compared with the one before it, so the same band tolerates a one-percent decline.