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 sundriesgross_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 ewegross_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.
pub fn gross_margin(outputs: &[MarginLine], variable_costs: &[MarginLine], per: &str, units: f64, currency: &str) -> GrossMargin
| outputs | MarginLine[] | sales, subsidies tied to the enterprise, valuation change; may be empty |
| variable_costs | MarginLine[] | seed, fertiliser, sprays, feed, vet, contract work; not fixed costs |
| per | MarginBasis | hectare or head |
| units | float | hectares (taken to 0.0001 ha) or head (a whole number), more than zero |
| currency | string | every amount must be in it |
| returns | GrossMargin |
The types it declares, generated into your project
// MarginBasis is a string in Rust, one of: "hectare", "head".
// Parameters take it as &str and results hold it as String.
/// One named output or cost.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarginLine {
pub name: String,
pub amount: Money,
}
/// Totals and the same per hectare or head, each divided once from its total.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrossMargin {
pub output: Money,
pub variable_costs: Money,
pub gross_margin: Money,
pub output_per_unit: Money,
pub variable_costs_per_unit: Money,
/// total margin / units, not output per unit less costs per unit
pub gross_margin_per_unit: Money,
/// gross margin as a share of output, 10000 = 100%; null when output is zero
pub margin_basis_points: Option<i64>,
}
Your code names it in one line, in the file that uses it
fune!(agri.gross-margin@^1); // then call gross_margin(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::math_round_div::round_div; ← from math.round-div ^1.0.0 · built alongside by fune
use super::money_add::subtract_money; ← from money.add ^1.0.0 · built alongside by fune
use super::money_amount::{money, money_from_value, money_to_value, Money}; ← from money.amount ^1.0.0 · built alongside by fune
use super::money_sum::sum_money; ← from money.sum ^1.0.0 · built alongside by fune
const MAX_MINOR: i64 = 900_000_000_000;
/// 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.
///
/// # Panics
/// Panics on a bad basis or unit count, mixed currencies, or totals too large.
pub fn gross_margin(outputs: &[MarginLine], variable_costs: &[MarginLine], per: &str, units: f64, currency: &str) -> GrossMargin {
let (divisor, scale) = match per {
"hectare" => {
if !units.is_finite() || units <= 0.0 || units > 10_000_000.0 {
panic!("units must be a finite number of hectares greater than 0 and at most 10000000, received {}", units);
}
let d = (units * 10000.0 + 0.5).floor() as i64;
if d < 1 {
panic!("units must be at least 0.0001 hectares, received {}", units);
}
(d, 10000)
}
"head" => {
if units.fract() != 0.0 || units < 1.0 || units > 10_000_000.0 {
panic!("units must be a whole number of head from 1 to 10000000, received {}", units);
}
(units as i64, 1)
}
other => panic!("unknown basis \"{}\": use hectare or head", other),
};
let output_amounts: Vec<Money> = outputs.iter().map(|l| l.amount.clone()).collect();
let cost_amounts: Vec<Money> = variable_costs.iter().map(|l| l.amount.clone()).collect();
let output = sum_money(&output_amounts, currency);
let costs = sum_money(&cost_amounts, currency);
let margin = subtract_money(&output, &costs);
for m in [&output, &costs, &margin] {
if m.minor.abs() > MAX_MINOR {
panic!("totals must be within 900000000000 minor units either side of zero");
}
}
let per_unit = |m: &Money| money(round_div(m.minor * scale, divisor, "half-up"), currency);
GrossMargin {
output_per_unit: per_unit(&output),
variable_costs_per_unit: per_unit(&costs),
gross_margin_per_unit: per_unit(&margin),
margin_basis_points: if output.minor == 0 {
None
} else {
Some(round_div(margin.minor * 10000, output.minor, "half-up"))
},
output,
variable_costs: costs,
gross_margin: margin,
}
}
pub fn margin_line_from_value(v: &Value) -> MarginLine {
MarginLine {
name: v.get("name").as_str().to_string(),
amount: money_from_value(v.get("amount")),
}
}
pub fn gross_margin_to_value(g: &GrossMargin) -> Value {
Value::obj(vec![
("output", money_to_value(&g.output)),
("variableCosts", money_to_value(&g.variable_costs)),
("grossMargin", money_to_value(&g.gross_margin)),
("outputPerUnit", money_to_value(&g.output_per_unit)),
("variableCostsPerUnit", money_to_value(&g.variable_costs_per_unit)),
("grossMarginPerUnit", money_to_value(&g.gross_margin_per_unit)),
("marginBasisPoints", g.margin_basis_points.map_or(Value::Null, Value::Int)),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let outputs: Vec<MarginLine> = args[0].as_arr().iter().map(margin_line_from_value).collect();
let costs: Vec<MarginLine> = args[1].as_arr().iter().map(margin_line_from_value).collect();
gross_margin_to_value(&gross_margin(&outputs, &costs, args[2].as_str(), args[3].as_f64(), args[4].as_str()))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add agri.gross-margin
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./agri.gross-margin-1.0.0-rust.fune, or fetch it from a terminal with fune pull agri.gross-margin@1.0.0:rust.
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.
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Path | Bytes |
|---|---|
| README.md | 1,978 |
| impl/python.py | 2,638 |
| impl/rust.rs | 3,776 |
| impl/typescript.ts | 2,467 |
| vectors.json | 11,004 |