{ "cells": [ { "cell_type": "markdown", "id": "553f9610", "metadata": {}, "source": [ "# Even flow: shape first, level second\n", "\n", "An even-flow target constrains the *shape* of a harvest profile; a separate floor constrains\n", "its level. Together they find the highest flat profile a forest can sustain, without the level\n", "ever being specified. This notebook runs the two stages on a generated estate and shows the\n", "before and after.\n", "\n", "This one mixes both paths: it runs commands and imports the library where the objective is the interesting part.\n" ] }, { "cell_type": "markdown", "id": "4d09fd0f", "metadata": {}, "source": [ "## A generated estate\n", "\n", "400 blocks, ages 0 to 120, on the two-strata recipe that ships with the repository. Any\n", "compiled dataset works; this one is small, so the notebook stays quick." ] }, { "cell_type": "code", "execution_count": 1, "id": "0dee8b2c", "metadata": { "execution": { "iopub.execute_input": "2026-10-17T20:20:55.374392Z", "iopub.status.busy": "2026-10-17T20:20:55.373958Z", "iopub.status.idle": "2026-10-17T20:20:55.383024Z", "shell.execute_reply": "2026-10-17T20:20:55.381450Z" } }, "outputs": [], "source": [ "import subprocess\n", "\n", "\n", "def run(command: str) -> None:\n", " \"\"\"Run a WS4 command, printing what it printed.\"\"\"\n", " result = subprocess.run(command, shell=True, text=True, capture_output=True)\n", " print((result.stdout or result.stderr).strip())\n", " result.check_returncode()\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "4b2d4a1a", "metadata": { "execution": { "iopub.execute_input": "2026-10-17T20:20:55.387445Z", "iopub.status.busy": "2026-10-17T20:20:55.387008Z", "iopub.status.idle": "2026-10-17T20:20:55.832885Z", "shell.execute_reply": "2026-10-17T20:20:55.831732Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tmp/examples/even-flow/compiled\n" ] } ], "source": [ "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from ws4.build.compiler import build_canonical_dataset\n", "\n", "work = Path(\"tmp/examples/even-flow\")\n", "work.mkdir(parents=True, exist_ok=True)\n", "rng = np.random.default_rng(7)\n", "count = 400\n", "fragments = work / \"fragments.csv\"\n", "pd.DataFrame(\n", " {\n", " \"BLOCK\": np.arange(1, count + 1),\n", " \"AREA_HA\": np.round(rng.uniform(2.0, 20.0, count), 1),\n", " \"F_AGE\": rng.integers(0, 120, count),\n", " \"AU\": rng.choice([\"A\", \"B\"], count),\n", " \"IFM\": rng.choice([\"managed\", \"unmanaged\"], count),\n", " \"RETENTION\": rng.choice([0.0, 0.0, 0.25], count),\n", " }\n", ").to_csv(fragments, index=False)\n", "dataset = build_canonical_dataset(\"tests/fixtures/matrix/recipe.xml\", fragments, work / \"compiled\")\n", "print(dataset)" ] }, { "cell_type": "markdown", "id": "fb6d72a8", "metadata": {}, "source": [ "## Stage 1: a floor, and nothing else\n", "\n", "A flow term divides by a balance — the reference period for even flow — so while that balance\n", "is zero the term is infinite. The procedure is to prime it first: run with a linear floor so\n", "every period carries wood, and only then switch the shape term on." ] }, { "cell_type": "code", "execution_count": 3, "id": "20655528", "metadata": { "execution": { "iopub.execute_input": "2026-10-17T20:20:55.836247Z", "iopub.status.busy": "2026-10-17T20:20:55.836077Z", "iopub.status.idle": "2026-10-17T20:20:56.133084Z", "shell.execute_reply": "2026-10-17T20:20:56.131921Z" } }, "outputs": [], "source": [ "import random\n", "\n", "from ws4.opt.engine import OptimizeConfig, Optimizer\n", "from ws4.opt.incremental import IncrementalObjective\n", "from ws4.opt.objective import Target, flow_penalty\n", "from ws4.opt.solvers import solve_sa_delta\n", "\n", "VOL, PERIOD, YEARS = \"product.Harvested.CC\", 10, 100\n", "PERIODS = YEARS // PERIOD\n", "optimizer = Optimizer.from_dataset(dataset, OptimizeConfig(years=YEARS, iterations=20_000))\n", "candidates = optimizer.candidates()\n", "level = [Target(VOL, period * PERIOD, minimum=30_000, period_width=PERIOD) for period in range(PERIODS)]\n", "\n", "def profile(evaluator, schedule):\n", " probe = IncrementalObjective(evaluator.optimizer, evaluator.targets, ())\n", " probe.reset(schedule)\n", " return [\n", " sum(probe.totals.get((year, VOL), 0.0) for year in range(begin, begin + PERIOD))\n", " for begin in range(0, YEARS, PERIOD)\n", " ]\n", "\n", "def show(title, values):\n", " print(title)\n", " print(\" \" + \" \".join(f\"{value:,.0f}\" for value in values))\n", "\n", "def solve(evaluator, initial=None):\n", " best, objective = solve_sa_delta(\n", " evaluator, random.Random(1), iterations=20_000, temperature=1000.0, cooling=0.99,\n", " candidates=candidates, registry=optimizer.registry, initial=initial,\n", " )\n", " return best, objective" ] }, { "cell_type": "code", "execution_count": 4, "id": "1258a5db", "metadata": { "execution": { "iopub.execute_input": "2026-10-17T20:20:56.136632Z", "iopub.status.busy": "2026-10-17T20:20:56.136387Z", "iopub.status.idle": "2026-10-17T20:20:57.467256Z", "shell.execute_reply": "2026-10-17T20:20:57.466018Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "floor only:\n", " 82,186 36,562 34,452 32,622 31,503 31,601 30,632 35,787 41,461 57,139\n", " spread 82,186 to 30,632\n" ] } ], "source": [ "evaluator = IncrementalObjective(optimizer, level)\n", "primed, _ = solve(evaluator)\n", "before = profile(evaluator, primed)\n", "show(\"floor only:\", before)\n", "print(f\" spread {max(before):,.0f} to {min(before):,.0f}\")" ] }, { "cell_type": "markdown", "id": "1bc9bc18", "metadata": {}, "source": [ "A ragged profile with a floor under it: the search harvested what it liked where it liked. The\n", "term it never had to satisfy is the shape." ] }, { "cell_type": "markdown", "id": "f1ffe50f", "metadata": {}, "source": [ "## Stage 2: add the band\n", "\n", "Zero, plus or minus one percent, with a high non-linear weight, and continue from the primed\n", "schedule." ] }, { "cell_type": "code", "execution_count": 5, "id": "04c57a46", "metadata": { "execution": { "iopub.execute_input": "2026-10-17T20:20:57.470472Z", "iopub.status.busy": "2026-10-17T20:20:57.470312Z", "iopub.status.idle": "2026-10-17T20:20:59.156287Z", "shell.execute_reply": "2026-10-17T20:20:59.155091Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "with the +-1% band:\n", " 38,212 38,130 37,626 38,180 38,105 37,929 37,767 37,463 38,007 37,840\n", " spread 38,212 to 37,463\n", " flow penalty 0.0\n" ] } ], "source": [ "flow = Target(\n", " VOL, 0, flow=\"even\", period_width=PERIOD, minimum=-1.0, maximum=1.0,\n", " min_weight=10_000.0, max_weight=10_000.0, shape=\"non_linear\",\n", ")\n", "flowed = IncrementalObjective(optimizer, level + [flow])\n", "even, _ = solve(flowed, initial=primed)\n", "after = profile(evaluator, even)\n", "show(\"with the +-1% band:\", after)\n", "print(f\" spread {max(after):,.0f} to {min(after):,.0f}\")\n", "probe = IncrementalObjective(optimizer, level)\n", "probe.reset(even)\n", "print(f\" flow penalty {flow_penalty(probe.totals, flow, YEARS):,.1f}\")" ] }, { "cell_type": "markdown", "id": "f65e5eee", "metadata": {}, "source": [ "Flat to within a percent — and note **which** percent. ``even`` compares every period with the\n", "**reference period**, the last one by default, not with the mean. The spread above is wider than\n", "one percent of the mean and still costs nothing, because every period is within one percent of\n", "the reference. ``flow_reference`` names another period to compare with." ] }, { "cell_type": "markdown", "id": "a9a8d410", "metadata": {}, "source": [ "## What the pair bought\n", "\n", "* The **band** fixed the shape without being told a level.\n", "* The **floor** pulled the level up; the band then held the periods together as it climbed.\n", "* Neither target names a harvest level, which is why the same pair works on another estate.\n", "\n", "For the closing-inventory variant, use ``flow=\"ndy\"`` on a standing account: each period is\n", "compared with the one before it, so the same band tolerates a one-percent decline." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "python", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }