Functional Weave
Code in Python

agri.gross-margin

Enterprise gross margin (output less variable costs), in total and per hectare or per head, in exact money.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 14 tests, run in TypeScript, Python and Rust.

What it does

The gross margin of a farm enterprise (a crop, a flock, a herd): its output less the variable costs that rise and fall with it, in total and per hectare or per head, with the margin as a share of output. Fixed costs (labour, machinery depreciation, rent, overheads) are deliberately not in it; that is what makes gross margins comparable between farms and against the published benchmarks.

`grossMargin(outputs, variableCosts, "hectare", 100, "GBP")` for 100 ha of wheat with £238,000 output and £52,000 variable costs is a £186,000 margin, £1,860 per hectare, 78.15% of output.

For example

  • gross_margin(outputs ×2, variable costs ×4, hectare, 100, GBP) → output £238,000.00, variable costs £52,000.00, gross margin £186,000.00, output per unit £2,380.00, variable costs per unit £520.00, gross margin per unit £1,860.00, margin basis … 100 ha of winter wheat: grain and straw less seed, fertiliser, sprays and sundries
  • gross_margin(outputs ×2, variable costs ×3, head, 500, GBP) → output £50,500.00, variable costs £17,500.00, gross margin £33,000.00, output per unit £101.00, variable costs per unit £35.00, gross margin per unit £66.00, margin basis points 6… a 500-ewe flock per ewe
  • gross_margin(outputs ×1, variable costs ×1, head, 3, GBP) → output £100.00, variable costs £50.00, gross margin £50.00, output per unit £33.33, variable costs per unit £16.67, gross margin per unit £16.67, margin basis points 50% the margin per head is the margin divided once (1667), not output per head less costs per head (1666)

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def gross_margin(outputs: Sequence[MarginLine], variable_costs: Sequence[MarginLine], per: MarginBasis, units: float, currency: str) -> GrossMargin
outputsMarginLine[]sales, subsidies tied to the enterprise, valuation change; may be empty
variable_costsMarginLine[]seed, fertiliser, sprays, feed, vet, contract work; not fixed costs
perMarginBasishectare or head
unitsfloathectares (taken to 0.0001 ha) or head (a whole number), more than zero
currencystringevery amount must be in it
returnsGrossMargin

The types it declares, generated into your project

MarginBasis = Literal["hectare", "head"]

@dataclass(frozen=True)
class MarginLine:
    """One named output or cost."""

    name: str
    amount: Money

@dataclass(frozen=True)
class GrossMargin:
    """Totals and the same per hectare or head, each divided once from its total."""

    output: Money
    variable_costs: Money
    gross_margin: Money
    output_per_unit: Money
    variable_costs_per_unit: Money
    #: total margin / units, not output per unit less costs per unit
    gross_margin_per_unit: Money
    #: gross margin as a share of output, 10000 = 100%; null when output is zero
    margin_basis_points: Optional[int]

Your code names it in one line, in the file that uses it

from fune.agri.gross_margin import gross_margin  # agri.gross-margin@^1
impl/python.py · 64 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import math
from typing import Sequence

from .agri_gross_margin_types import GrossMargin, MarginBasis, MarginLine
from .math_round_div import round_div  ← from math.round-div ^1.0.0 · built alongside by fune
from .money_add import subtract_money  ← from money.add ^1.0.0 · built alongside by fune
from .money_amount import Money, money  ← from money.amount ^1.0.0 · built alongside by fune
from .money_sum import sum_money  ← from money.sum ^1.0.0 · built alongside by fune

MAX_MINOR = 900000000000


def gross_margin(
    outputs: Sequence[MarginLine],
    variable_costs: Sequence[MarginLine],
    per: MarginBasis,
    units: float,
    currency: str,
) -> GrossMargin:
    """Gross margin: enterprise output less its variable costs, per hectare or head.

    Each per-unit figure is its own total divided once, half up. Taking output
    per head less costs per head instead can be a penny out: 3 head with 10000
    output and 5000 costs is 3333 - 1667 = 1666 that way, but 5000 / 3 = 1667.
    """
    if per == "hectare":
        if isinstance(units, bool) or not isinstance(units, (int, float)) or not math.isfinite(units) or units <= 0 or units > 10000000:
            raise ValueError("units must be a finite number of hectares greater than 0 and at most 10000000, received %r" % (units,))
        divisor = _round_half_away(units * 10000)
        if divisor < 1:
            raise ValueError("units must be at least 0.0001 hectares, received %r" % (units,))
        scale = 10000
    elif per == "head":
        if isinstance(units, bool) or not isinstance(units, int) or units < 1 or units > 10000000:
            raise ValueError("units must be a whole number of head from 1 to 10000000, received %r" % (units,))
        divisor = units
        scale = 1
    else:
        raise ValueError('unknown basis "%s": use hectare or head' % (per,))

    output = sum_money([line.amount for line in outputs], currency)
    costs = sum_money([line.amount for line in variable_costs], currency)
    margin = subtract_money(output, costs)
    for m in (output, costs, margin):
        if abs(m.minor) > MAX_MINOR:
            raise ValueError("totals must be within 900000000000 minor units either side of zero")

    def per_unit(m: Money) -> Money:
        return money(round_div(m.minor * scale, divisor, "half-up"), currency)

    return GrossMargin(
        output=output,
        variable_costs=costs,
        gross_margin=margin,
        output_per_unit=per_unit(output),
        variable_costs_per_unit=per_unit(costs),
        gross_margin_per_unit=per_unit(margin),
        margin_basis_points=None if output.minor == 0 else round_div(margin.minor * 10000, output.minor, "half-up"),
    )


def _round_half_away(x: float) -> int:
    # Math.round and f64::round agree with this for positive numbers.
    return int(math.floor(x + 0.5))

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add agri.gross-margin
Download for Python agri.gross-margin-1.0.0-python.fune · 20,660 bytes sha256 36bc6297502b732ea3da4cc376a9c0695dcf5b208c34afc78e42714755ee8a33

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./agri.gross-margin-1.0.0-python.fune, or fetch it from a terminal with fune pull agri.gross-margin@1.0.0:python.

The whole function, every language, is one file too: agri.gross-margin-1.0.0.fune, 27,146 bytes, sha256 01046e119ccab8b1635dcb534ab490eacc1e7554bb76ec17a2b96641c60934b3. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before agri.gross-margin

after — your function gets the result and the arguments, and returns the final result.

# fune: after agri.gross-margin

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace math.round-div in agri.gross-margin
# fune: replace money.add in agri.gross-margin
# fune: replace money.amount in agri.gross-margin
# fune: replace money.sum in agri.gross-margin

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show agri.gross-margin --steps.

# fune: step agri.gross-margin after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
100 ha of winter wheat: grain and straw less seed, fertiliser, sprays and sundries outputs ×2, variable costs ×4, hectare, 100, GBP → output £238,000.00, variable costs £52,000.00, gross margin £186,000.00, output per unit £2,380.00, variable costs per unit £520.00, gross margin per unit £1,860.00, margin basis …
a 500-ewe flock per ewe outputs ×2, variable costs ×3, head, 500, GBP → output £50,500.00, variable costs £17,500.00, gross margin £33,000.00, output per unit £101.00, variable costs per unit £35.00, gross margin per unit £66.00, margin basis points 6…
the margin per head is the margin divided once (1667), not output per head less costs per head (1666) outputs ×1, variable costs ×1, head, 3, GBP → output £100.00, variable costs £50.00, gross margin £50.00, output per unit £33.33, variable costs per unit £16.67, gross margin per unit £16.67, margin basis points 50%
a loss-making enterprise has a negative margin outputs ×1, variable costs ×1, hectare, 10, GBP → output £1,000.00, variable costs £1,500.00, gross margin -£500.00, output per unit £100.00, variable costs per unit £150.00, gross margin per unit -£50.00, margin basis points…
no output: margin share is null and a negative half penny rounds away from zero , variable costs ×1, hectare, 2, GBP → output £0.00, variable costs £0.05, gross margin -£0.05, output per unit £0.00, variable costs per unit £0.03, gross margin per unit -£0.03, margin basis points —
a part hectare area outputs ×1, variable costs ×1, hectare, 12.5, GBP → output £12,500.00, variable costs £2,500.00, gross margin £10,000.00, output per unit £1,000.00, variable costs per unit £200.00, gross margin per unit £800.00, margin basis point…
a negative output line (a clawback) reduces output outputs ×2, variable costs ×1, head, 10, GBP → output £19,000.00, variable costs £9,000.00, gross margin £10,000.00, output per unit £1,900.00, variable costs per unit £900.00, gross margin per unit £1,000.00, margin basis poi…
no lines at all is zero everywhere , , head, 1, EUR → output €0.00, variable costs €0.00, gross margin €0.00, output per unit €0.00, variable costs per unit €0.00, gross margin per unit €0.00, margin basis points —
a fractional head count is an error outputs ×1, , head, 2.5, GBP → error: units must be a whole number of head from 1 to 10000000
zero hectares is an error outputs ×1, , hectare, 0, GBP → error: units must be a finite number of hectares greater than 0
Show the other 4 tests
CaseArgumentsExpected
less than a square metre is an error outputs ×1, , hectare, 0, GBP → error: units must be at least 0.0001 hectares
an unknown basis is an error outputs ×1, , acre, 1, GBP → error: unknown basis "acre"
a cost in another currency is an error outputs ×1, variable costs ×1, head, 1, GBP → error: currency mismatch
totals beyond 900 billion minor units are refused outputs ×1, , head, 1, GBP → error: totals must be within 900000000000 minor units

More from the author

## How it is worked out

1. Outputs and variable costs are totalled exactly in minor units (`money.sum`); every line must be in `currency`. Lines may be negative (a clawback, a credit note). 2. The margin is output less variable costs, and may be negative. 3. Each per-unit figure is its own total divided once by the hectares or head, half up (away from zero for negatives, `math.round-div`). So the per-head margin is not always per-head output less per-head costs: with 3 head, 10000 output and 5000 costs, that shortcut gives 3333 - 1667 = 1666, where 5000 / 3 is 1667. 4. `marginBasisPoints` is the margin over output, half up, and null when output is zero.

Hectares are taken to 0.0001 ha (1 m²); head is a whole number.

## What it does not do

It does not decide what is a variable cost, value stock or home-grown feed, or split shared costs between enterprises: the caller brings the lines. It is arithmetic, not an assessment of the enterprise.

## Limits

More than 0 and at most 10,000,000 hectares or head; each total within ±900,000,000,000 minor units, which keeps every intermediate below 2^53 so that TypeScript stays exact.

## Source

The definition (enterprise output less variable costs, before fixed costs) is the standard one in UK farm management, e.g. the John Nix Farm Management Pocketbook and AHDB's Farmbench costings.

Files

PathBytes
README.md1,978
impl/python.py2,638
impl/rust.rs3,776
impl/typescript.ts2,467
vectors.json11,004