-- florilegium-species.lua -- species for florilegium: a plant sampled from a genome.
-- Copyright (c) 2026 Kevin Raymond. MIT License: see LICENSE or florilegium.sty.
--
-- A species is a table of traits drawn in a fixed order: the body plan first (which
-- fixes the clade, monocot or eudicot), then the pollination syndrome, then the
-- flower, its cluster, the leaf, the stem and the fruit. Each body plan gives every
-- trait a distribution, so the hard rules of botany hold by construction: a lily
-- has its parts in threes, a pea flower is two-sided, a cross of petals has four.
--
-- The same tables drive the TikZ library (tikzlibraryflorilegium.code.tex): M.tex()
-- writes them as TeX (tools/tikztables.lua), and both sides draw from pgf's generator
-- (ink.pgfrng), so one seed gives one species in either. Every choice is an integer
-- draw (pgf's random(a,b)), and a real-valued trait is the very number pgfmath computes
-- (florilegium-pgfmath.lua), so the organs that compare one (a stage from the phenology)
-- choose as the TikZ library does.
--
-- The botany follows the trait tables in Florilegium Genomes (2026, the author's
-- research notes): body plans and their bundles, the hard rules (e.g. variable petal
-- number only in radially symmetric flowers, after Damerval & Nadot 2007), and the
-- pollination syndromes of the U.S. Forest Service (public domain).

local ink = require("florilegium-ink")
local pm = require("florilegium-pgfmath")
local M = {}
M.version = "2.1.0"                 -- the release; florilegium.lua checks that every file has the same

local floor, fmt, concat = math.floor, string.format, table.concat

-- ---------------------------------------------------------------- distributions
-- W(v1, w1, v2, w2, ...) a weighted choice (integer weights); I(a, b) an integer;
-- R(a, b) a real number (drawing only); C(v) a constant (no draw); BY(trait, map)
-- the distribution in map[value of an earlier trait], or map._ ; maps may nest.
local function W(...) return { "w", ... } end
local function I(a, b) return { "i", a, b } end
local function R(a, b) return { "r", a, b } end
local function C(v) return { "c", v } end
local function BY(key, map) return { "by", key, map } end

-- ---------------------------------------------------------------- sampling
-- one draw from a distribution; rng is an ink.pgfrng; sp holds the traits drawn so far
local function draw(d, rng, sp)
  local kind = d[1]
  if kind == "c" then return d[2]
  elseif kind == "i" then return rng.random(d[2], d[3])
  elseif kind == "r" then
    -- as \flo@R{a}{b-a} computes it: \pgfmathparse{a+(b-a)*rnd}, to the scaled point
    local a, w = pm.sp(tostring(d[2])), pm.sp(tostring(d[3] - d[2]))
    return pm.add(a, pm.mulf(w, math.floor(rng.rnd() * 65536 + 0.5))) / 65536
  elseif kind == "w" then
    local total = 0
    for i = 3, #d, 2 do total = total + d[i] end
    local k = rng.random(1, total)
    for i = 2, #d, 2 do
      k = k - d[i + 1]
      if k <= 0 then return d[i] end
    end
  elseif kind == "by" then
    local v = sp[d[2]]
    local sub = d[3][tostring(v)] or d[3]._
    assert(sub, "florilegium: no distribution for " .. d[2] .. " = " .. tostring(v))
    return draw(sub, rng, sp)
  end
  error("florilegium: unknown distribution " .. tostring(kind))
end

-- Lehmer's generator answers seeds 1, 2, 3 ... with nearly proportional first values,
-- so the first two are thrown away (TikZ: \pgfmathgeneratepseudorandomnumber twice).
M.WARM = 2

-- ---------------------------------------------------------------- a family of genomes
-- The plants and the visitors are two families of one shape, and a third (a window of
-- tracery) adds its tables and nothing else. A family f has: traits, the draw order
-- (the first names the kind, a plant's body plan or a visitor's kind); kinds, each with
-- a name, a weight w, the roles it may fill, and d, its own distributions; derived, the
-- trait that follows from the kind (a plan's clade, a kind's group); fallback(k, trait),
-- the distribution a kind's own table leaves out; weight(k, role), its weight in a role,
-- or nil; roles, the role names (a role may also name a kind, for a specimen of it);
-- rolelist, the roles' order in the TeX tables; noun ("plant"), what the family samples;
-- refuse(kind, fix), an error for a fixed value that kind cannot draw, or nil; own(k, trait),
-- the distribution the kind really draws, for the values a fixed trait may take; tex, the
-- family's macro names in tikzlibraryflorilegium.tables.code.tex; violations(x) and
-- describe(x), the rules and the words. family(f) adds byname, dist, rolekinds, sample
-- and values.
local function family(f)
  f.byname = {}
  for i, k in ipairs(f.kinds) do f.byname[k.name] = k k.index = i end
  -- a trait's distribution for a kind: the kind's own, else the family's fallback
  function f.dist(kind, trait)
    local k = f.byname[kind]
    if f.derived and trait == f.derived then return C(k[f.derived]) end
    return k.d[trait] or f.fallback(k, trait)
  end
  -- the kinds a role may draw, as a W over their names (in f.kinds order); a role may
  -- also name one kind ("rose", "fern", "ladybird"), for a specimen of it. A role's own
  -- name comes first: "monocot" is the role (lily, iris or the generic monocot), not the
  -- plan of that name.
  function f.rolekinds(role)
    if f.byname[role] and not f.roles[role] then return W(role, f.byname[role].w) end
    local t = {}
    for _, k in ipairs(f.kinds) do
      local w = f.weight(k, role)
      if w then t[#t + 1] = k.name t[#t + 1] = w end
    end
    assert(#t > 0, "florilegium: no " .. f.noun .. " for the role " .. tostring(role))
    return W(table.unpack(t))
  end
  -- one of the family from a pgf seed (1 .. 2^31-2) for a role; log, if given, is a
  -- function(trait, value) called after every draw. Returns the sample and the generator,
  -- left where \florilegiumspecies leaves pgf's (organs go on from there). A real-valued
  -- trait is the number pgfmath computes, a multiple of 2^-16.
  -- fix, if given, is a table of traits fixed (M.fixes): each still takes its draw, then
  -- its value is the fixed one, and a trait that depends on it (BY) follows it; a fixed
  -- kind picks its own distributions. The traits drawn before a fixed one are as they
  -- would have been; those after it too, unless a trait that depends on it draws
  -- differently (a constant takes no draw, a range one), which moves every later draw along
  function f.sample(seed, role, log, fix)
    fix = fix or {}
    local rng = ink.pgfrng(seed)
    for _ = 1, M.WARM do rng.step() end
    local x = { seed = seed, role = role or "any" }
    local first = f.traits[1]
    x[first] = draw(f.rolekinds(x.role), rng, x)
    if fix[first] ~= nil then x[first] = fix[first] end
    if f.refuse then
      local refused = f.refuse(x[first], fix)
      if refused then error(refused, 0) end
    end
    if log then log(first, x[first]) end
    for i = 2, #f.traits do
      local t = f.traits[i]
      x[t] = draw(f.dist(x[first], t), rng, x)
      if fix[t] ~= nil then x[t] = fix[t] end
      if log then log(t, x[t]) end
    end
    return x, rng
  end
  f.own = f.own or function(k, trait) return f.dist(k.name, trait) end
  return f
end
M.FAMILIES = {}                      -- in the order of the TeX tables
function M.family(name)
  local f = M.FAMILIES[name]
  assert(f, "florilegium: no family of genomes named " .. tostring(name))
  return f
end

-- the order of the draws; every species draws them in this order
M.TRAITS = {
  "plan", "clade", "syndrome", "color", "form", "symmetry", "fused", "merosity", "merovar",
  "petalshape", "petalaspect", "apex", "petalmargin", "petalamp", "claw", "reflex", "overlap", "cup",
  "guides", "guidecount", "picotee", "corona", "spurs", "stamens", "orient",
  "inflo", "count", "rays", "depth", "openorder", "siderule", "coil", "size",
  "compound", "leaflets", "leafshape", "leafaspect", "leafmargin", "teeth", "dissection",
  "leafapex", "leafbase", "venation", "attachment", "stipules", "arrangement",
  "curl", "twist", "taper", "turns", "habit", "section", "hairy", "tendrils", "fruit", "phenology",
  -- a fern's own, last, so that the flowering plans (constants here: no draws) are as they were
  "division", "pinnae", "outline", "stipe", "sori", "dimorphic",
}

-- ---------------------------------------------------------------- defaults
-- for every plan, then for each clade; a plan overrides any of them
local COMMON = {
  syndrome = W("bee", 4, "butterfly", 2, "moth", 2, "bird", 1, "beetle", 1, "fly", 1),
  color = BY("syndrome", {
    bee = W("blue", 6, "violet", 3, "white", 3, "yellow", 2),
    butterfly = W("violet", 4, "pink", 3, "blue", 2, "red", 1, "orange", 1),
    moth = W("white", 6, "pink", 2, "yellow", 1),
    bird = W("red", 5, "orange", 3, "pink", 1),
    beetle = W("white", 5, "green", 2, "pink", 1),
    fly = W("white", 5, "yellow", 3, "violet", 1),
    wind = C("green"),
  }),
  symmetry = BY("form", { bilabiate = C("bilateral"), papilionaceous = C("bilateral"), orchid = C("bilateral"),
    _ = C("radial") }),
  fused = BY("form", { campanulate = C(1), urceolate = C(1), tubular = C(1), funnelform = C(1), salverform = C(1),
    bilabiate = C(1), rotate = W(0, 2, 1, 1), _ = C(0) }),
  merovar = C(0),
  petalshape = W("orbicular", 2, "obovate", 5, "spatulate", 2, "oblong", 2, "lanceolate", 2, "linear", 1),
  petalaspect = R(1.1, 2.2),
  apex = W("rounded", 12, "acute", 4, "acuminate", 2, "emarginate", 4, "bifid", 1, "fringed", 1),
  petalmargin = W("entire", 14, "undulate", 6, "crenate", 2, "fimbriate", 1, "laciniate", 1),
  petalamp = R(0.01, 0.06),
  claw = R(0, 0.1),
  reflex = R(-10, 30),
  overlap = R(0, 0.3),
  cup = R(0.2, 0.8),
  guides = BY("syndrome", {
    bee = W("lines", 6, "dots", 1, "eye", 1, "none", 2),
    butterfly = W("lines", 2, "eye", 1, "none", 3),
    fly = W("none", 3, "dots", 1),
    _ = C("none"),
  }),
  guidecount = I(2, 6),
  picotee = W(0, 9, 1, 1),
  corona = C("none"),
  spurs = C("none"),
  stamens = BY("syndrome", { bird = W("exserted", 3, "included", 1), moth = W("exserted", 2, "included", 1),
    _ = W("included", 3, "exserted", 1) }),
  orient = BY("form", {
    campanulate = W("nodding", 4, "horizontal", 1), urceolate = C("nodding"), tubular = W("horizontal", 1, "nodding", 1),
    bilabiate = C("horizontal"), papilionaceous = C("horizontal"), orchid = C("horizontal"), iris = C("erect"),
    head = C("erect"), rotate = W("erect", 3, "horizontal", 2), salverform = W("erect", 1, "horizontal", 1),
    _ = W("erect", 2, "horizontal", 2, "nodding", 1),
  }),
  count = BY("inflo", {
    solitary = C(1), raceme = I(5, 14), spike = I(10, 30), panicle = I(12, 30), corymb = I(8, 20),
    umbel = I(5, 14), cumbel = I(5, 12), dichasium = I(3, 15), monochasium = I(6, 16), head = I(15, 30),
    catkin = I(30, 80), thyrse = I(12, 30),
  }),
  rays = BY("inflo", { cumbel = I(8, 20), _ = C(0) }),
  depth = BY("inflo", { panicle = I(1, 2), dichasium = I(1, 3), thyrse = I(1, 2), _ = C(0) }),
  openorder = BY("inflo", {
    raceme = C("base"), spike = C("base"), panicle = C("base"), catkin = C("base"), thyrse = C("base"),
    corymb = C("outside"), head = C("outside"), umbel = W("outside", 3, "center", 1), cumbel = W("outside", 3, "center", 1),
    dichasium = C("center"), monochasium = C("center"), solitary = C("none"),
  }),
  siderule = BY("inflo", { monochasium = W("same", 2, "alternate", 1), _ = C("none") }),
  coil = R(0.4, 1.0),
  compound = W("simple", 8, "pinnate", 2, "palmate", 1, "trifoliate", 1),
  leaflets = BY("compound", { pinnate = I(2, 7), bipinnate = I(3, 8), palmate = I(5, 9), trifoliate = C(3), _ = C(1) }),
  leafaspect = BY("leafshape", {
    linear = R(8, 20), lanceolate = R(3.5, 6), elliptic = R(1.8, 3), ovate = R(1.4, 2.4), obovate = R(1.6, 2.6),
    oblong = R(2.2, 3.5), cordate = R(1.1, 1.6), orbicular = R(0.9, 1.15), reniform = R(0.6, 0.9),
    deltoid = R(1, 1.4), sagittate = R(1.5, 2.5), hastate = R(1.5, 2.5),
  }),
  teeth = BY("leafmargin", { serrate = I(10, 28), doubly = I(10, 22), dentate = I(6, 16), crenate = I(6, 14),
    lobed = I(3, 7), pinnatifid = I(4, 9), palmatelobed = I(3, 7), _ = C(0) }),
  dissection = BY("leafmargin", { entire = C(0), undulate = R(0, 0.05), serrate = R(0.04, 0.12),
    doubly = R(0.06, 0.14), dentate = R(0.06, 0.16), crenate = R(0.05, 0.12), lobed = R(0.3, 0.6),
    pinnatifid = R(0.6, 0.92), palmatelobed = R(0.35, 0.65) }),
  leafbase = BY("leafshape", { cordate = C("cordate"), reniform = C("cordate"), sagittate = C("auriculate"),
    hastate = C("auriculate"), _ = W("cuneate", 5, "rounded", 3, "truncate", 1, "oblique", 1) }),
  stipules = W("none", 4, "small", 1),
  curl = R(-0.3, 0.4),
  twist = R(0, 50),
  taper = R(0.4, 0.9),
  turns = W(0, 1, 1, 1),
  habit = W("erect", 6, "sprawling", 2, "climbing", 1),
  section = C("round"),
  hairy = W(0, 3, 1, 1),
  tendrils = C(0),
  phenology = R(-0.15, 0.15),
  division = C(0), pinnae = C(0), outline = C("none"), stipe = C(0), sori = C("none"), dimorphic = C(0),
}

local EUDICOT = {
  merosity = W(5, 70, 4, 22, 6, 5, 3, 3),
  -- leaflets of a compound leaf are oval or narrow, never heart- or arrow-shaped
  leafshape = BY("compound", {
    simple = W("lanceolate", 3, "elliptic", 3, "ovate", 4, "obovate", 1, "oblong", 1, "cordate", 2,
      "orbicular", 1, "reniform", 1, "deltoid", 1, "sagittate", 1, "hastate", 1),
    _ = W("elliptic", 4, "ovate", 3, "lanceolate", 2, "obovate", 1) }),
  leafmargin = W("entire", 4, "serrate", 5, "doubly", 1, "dentate", 2, "crenate", 2, "undulate", 1,
    "lobed", 2, "pinnatifid", 1, "palmatelobed", 1),
  leafapex = W("acute", 6, "acuminate", 3, "obtuse", 2, "rounded", 2, "emarginate", 1, "mucronate", 1),
  venation = BY("leafmargin", { palmatelobed = C("palmate"),
    _ = BY("leafshape", { orbicular = W("palmate", 2, "pinnate", 1), reniform = C("palmate"),
      cordate = W("palmate", 1, "pinnate", 1), _ = W("pinnate", 7, "arcuate", 2) }) }),
  -- a blade with basal lobes sits on a stalk (or clasps the stem), never flat on it; one
  -- draw either way, so the traits after it stay as they were
  attachment = BY("leafshape", { cordate = W("petiolate", 4, "clasping", 1), reniform = W("petiolate", 4, "clasping", 1),
    sagittate = W("petiolate", 4, "clasping", 1), hastate = W("petiolate", 4, "clasping", 1),
    _ = W("petiolate", 7, "sessile", 2, "clasping", 1) }),
  arrangement = W("alternate", 6, "opposite", 3, "whorled", 1),
}

local MONOCOT = {
  merosity = W(3, 98, 4, 2),
  compound = C("simple"),
  leafshape = W("linear", 6, "lanceolate", 3, "elliptic", 1),
  leafmargin = C("entire"),
  leafapex = W("acute", 6, "acuminate", 3),
  venation = C("parallel"),
  attachment = W("sheathing", 5, "sessile", 2, "clasping", 1),
  arrangement = W("alternate", 2, "distichous", 2, "rosette", 1),
  hairy = W(0, 9, 1, 1),
}

-- a fern bears no flowers: every flower trait is a constant (no draw); its fronds are
-- leaves of their own kind (compound "frond"), from a crown at the root
local FERN = {
  syndrome = C("none"), color = C("green"), form = C("none"), symmetry = C("none"), fused = C(0),
  merosity = C(0), petalshape = C("none"), petalaspect = C(1), apex = C("none"), petalmargin = C("none"),
  petalamp = C(0), claw = C(0), reflex = C(0), overlap = C(0), cup = C(0), guides = C("none"), guidecount = C(0),
  picotee = C(0), spurs = C("none"), stamens = C("none"), orient = C("erect"), inflo = C("none"), count = C(0),
  rays = C(0), depth = C(0), openorder = C("none"), siderule = C("none"), coil = C(0), size = C(0),
  compound = C("frond"), leaflets = C(0), leafaspect = C(1), teeth = C(0), dissection = C(0),
  leafbase = C("truncate"), venation = C("forked"), attachment = C("none"), stipules = C("none"),
  arrangement = C("crown"), twist = C(0), taper = C(1), habit = C("erect"), tendrils = C(0), fruit = C("spores"),
}
local CLADE = { monocot = MONOCOT, eudicot = EUDICOT, fern = FERN }

-- ---------------------------------------------------------------- body plans
-- w: weight in a pool; roles: which places on a page it can fill (hero: a big flower
-- at a stem's top; spray: small flowers that fill branches; monocot: the strap-leaved
-- plant). Report section 5b; sizes are the real flower (or head) diameter in mm.
M.PLANS = {
  { name = "lily", clade = "monocot", w = 8, roles = { hero = 1, monocot = 1 }, d = {
    syndrome = W("bee", 3, "butterfly", 3, "moth", 3, "bird", 1),
    form = C("lily"), merosity = C(3),
    petalshape = W("lanceolate", 4, "oblong", 2, "obovate", 1), petalaspect = R(2.5, 4.5),
    apex = W("acute", 4, "acuminate", 2, "rounded", 1), reflex = R(-80, 20), cup = R(0, 1),
    guides = W("dots", 3, "lines", 2, "none", 2),
    stamens = W("exserted", 4, "included", 1),
    inflo = W("solitary", 4, "raceme", 3, "umbel", 1),
    size = R(40, 90),
    leafshape = W("linear", 3, "lanceolate", 3, "elliptic", 1),
    arrangement = W("alternate", 3, "whorled", 1),
    fruit = C("capsule"),
  } },
  { name = "iris", clade = "monocot", w = 6, roles = { hero = 1, monocot = 1 }, d = {
    syndrome = W("bee", 8, "moth", 1, "bird", 1),
    form = W("iris", 5, "orchid", 3), merosity = C(3),
    petalshape = W("obovate", 3, "spatulate", 3, "oblong", 1), petalaspect = R(1.6, 3), claw = R(0.2, 0.45),
    guides = BY("syndrome", { bee = W("lines", 4, "blotch", 2, "dots", 1), _ = W("none", 2, "lines", 1) }),
    inflo = W("solitary", 4, "raceme", 3),
    size = R(40, 80),
    leafshape = BY("form", { iris = C("linear"), _ = W("elliptic", 2, "lanceolate", 2) }),
    arrangement = BY("form", { iris = C("distichous"), _ = W("rosette", 1, "alternate", 1) }),
    fruit = C("capsule"),
  } },
  { name = "rose", clade = "eudicot", w = 10, roles = { hero = 1 }, d = {
    syndrome = W("bee", 5, "beetle", 3, "fly", 1),
    form = W("rosaceous", 8, "rotate", 2), fused = C(0),
    merosity = W(5, 85, 4, 5, 6, 10), merovar = W(0, 4, 1, 1),
    petalshape = W("orbicular", 3, "obovate", 4), petalaspect = R(0.9, 1.5), claw = R(0, 0.05),
    overlap = R(0.1, 0.4),
    stamens = C("included"),
    inflo = W("solitary", 5, "corymb", 3),
    size = R(30, 70),
    compound = W("pinnate", 6, "simple", 2),
    leafmargin = W("serrate", 7, "doubly", 2),
    stipules = W("small", 1, "leafy", 1),
    arrangement = C("alternate"),
    section = W("round", 1, "prickly", 1),
    fruit = W("hip", 4, "pome", 1, "drupe", 1),
  } },
  { name = "mustard", clade = "eudicot", w = 8, roles = { spray = 1 }, d = {
    syndrome = W("bee", 4, "fly", 3, "butterfly", 3),
    form = C("cruciform"), merosity = C(4),
    petalshape = W("obovate", 3, "orbicular", 1, "spatulate", 1), apex = W("rounded", 3, "emarginate", 2),
    claw = R(0.3, 0.5),
    inflo = C("raceme"),
    size = R(8, 20),
    compound = C("simple"),
    leafmargin = W("entire", 2, "dentate", 2, "lobed", 3, "pinnatifid", 3),
    arrangement = W("alternate", 2, "rosette", 1),
    fruit = W("silique", 3, "silicle", 2),
  } },
  { name = "pea", clade = "eudicot", w = 8, roles = { spray = 1 }, d = {
    syndrome = W("bee", 9, "bird", 1),
    form = C("papilionaceous"), merosity = C(5),
    guides = W("lines", 3, "none", 1),
    inflo = W("raceme", 6, "head", 1, "solitary", 1),
    size = R(10, 22),
    compound = W("pinnate", 6, "trifoliate", 3),
    leafshape = W("elliptic", 3, "ovate", 2, "obovate", 2, "oblong", 1),
    leafmargin = W("entire", 5, "serrate", 1),
    stipules = W("leafy", 3, "small", 1),
    arrangement = C("alternate"),
    habit = W("climbing", 4, "erect", 2),
    tendrils = BY("compound", { pinnate = W(1, 3, 0, 1), _ = C(0) }),
    fruit = C("legume"),
  } },
  { name = "mint", clade = "eudicot", w = 8, roles = { spray = 1 }, d = {
    syndrome = W("bee", 8, "bird", 2),
    form = C("bilabiate"), merosity = C(5),
    guides = W("dots", 2, "lines", 2, "none", 1),
    inflo = W("spike", 4, "raceme", 2),
    size = R(8, 18),
    compound = C("simple"),
    leafshape = W("ovate", 3, "lanceolate", 2, "cordate", 1, "elliptic", 1),
    leafmargin = W("serrate", 5, "crenate", 3, "dentate", 2),
    attachment = W("petiolate", 2, "sessile", 1),
    arrangement = C("opposite"),
    section = C("square"),
    fruit = C("nutlets"),
  } },
  { name = "daisy", clade = "eudicot", w = 10, roles = { hero = 1, spray = 1 }, d = {
    syndrome = W("butterfly", 4, "fly", 3, "bee", 3),
    form = C("head"), merosity = I(8, 21),
    petalshape = W("linear", 4, "oblong", 3, "spatulate", 2), petalaspect = R(3, 6),
    apex = W("rounded", 3, "emarginate", 2, "bifid", 1, "acute", 1),
    guides = C("none"),
    inflo = W("solitary", 6, "corymb", 3),
    size = R(15, 45),
    compound = C("simple"),
    leafmargin = W("lobed", 3, "pinnatifid", 3, "dentate", 2, "serrate", 2, "entire", 1),
    arrangement = W("alternate", 4, "rosette", 2, "opposite", 1),
    fruit = W("pappus", 3, "achene", 2),
  } },
  { name = "umbellifer", clade = "eudicot", w = 8, roles = { spray = 1 }, d = {
    syndrome = W("fly", 5, "beetle", 3, "bee", 1),
    form = C("rotate"), fused = C(0), merosity = C(5),
    color = W("white", 6, "yellow", 2, "pink", 1),
    guides = C("none"),
    inflo = C("cumbel"),
    size = R(2, 4.5),
    compound = W("bipinnate", 5, "pinnate", 3),
    leafmargin = W("dentate", 3, "lobed", 2, "pinnatifid", 2),
    attachment = C("sheathing"),
    arrangement = C("alternate"),
    section = C("ribbed"),
    fruit = C("schizocarp"),
  } },
  { name = "heath", clade = "eudicot", w = 6, roles = { spray = 1 }, d = {
    syndrome = W("bee", 7, "bird", 2, "moth", 1),
    form = W("campanulate", 5, "urceolate", 5), merosity = W(5, 3, 4, 2),
    inflo = W("raceme", 6, "solitary", 2),
    size = R(5, 12),
    compound = C("simple"),
    leafshape = W("linear", 3, "elliptic", 2), leafmargin = C("entire"),
    arrangement = W("alternate", 2, "whorled", 2, "opposite", 1),
    fruit = W("berry", 3, "capsule", 1),
  } },
  { name = "borage", clade = "eudicot", w = 8, roles = { spray = 1 }, d = {
    syndrome = W("bee", 9, "butterfly", 1),
    form = W("rotate", 5, "salverform", 5), fused = C(1), merosity = C(5),
    guides = C("eye"),
    inflo = C("monochasium"),
    size = R(6, 20),
    compound = C("simple"),
    leafshape = W("lanceolate", 3, "elliptic", 2, "oblong", 1), leafmargin = C("entire"),
    arrangement = C("alternate"),
    hairy = C(1),
    fruit = C("nutlets"),
  } },
  { name = "catkin", clade = "eudicot", w = 3, roles = { spray = 1 }, d = {
    syndrome = C("wind"),
    form = C("none"), merosity = C(0),
    guides = C("none"), stamens = C("exserted"), orient = C("nodding"),
    inflo = C("catkin"),
    size = R(1, 2),
    compound = C("simple"),
    leafmargin = W("serrate", 4, "doubly", 2, "crenate", 1),
    arrangement = C("alternate"),
    habit = C("woody"),
    fruit = W("nut", 2, "samara", 1),
  } },
  { name = "columbine", clade = "eudicot", w = 5, roles = { hero = 1 }, d = {
    syndrome = W("bee", 4, "moth", 2, "bird", 3),
    form = C("spurred"), merosity = C(5), spurs = C("all"),
    petalshape = W("obovate", 2, "oblong", 2), stamens = W("exserted", 3, "included", 1),
    orient = W("nodding", 2, "horizontal", 1),
    inflo = W("solitary", 3, "panicle", 2, "raceme", 1),
    size = R(25, 50),
    compound = C("trifoliate"),
    leafshape = W("obovate", 2, "orbicular", 1), leafmargin = C("lobed"),
    arrangement = W("alternate", 1, "rosette", 1),
    fruit = C("follicle"),
  } },
  { name = "eudicot", clade = "eudicot", w = 10, roles = { hero = 1, spray = 1 }, d = {
    form = W("rotate", 4, "rosaceous", 3, "campanulate", 2, "funnelform", 2, "salverform", 2, "tubular", 1),
    merovar = BY("form", { rotate = W(0, 4, 1, 1), rosaceous = W(0, 4, 1, 1), _ = C(0) }),
    inflo = W("solitary", 3, "raceme", 2, "dichasium", 2, "corymb", 1, "panicle", 1, "umbel", 1, "thyrse", 1),
    size = BY("inflo", { solitary = R(25, 60), _ = R(8, 25) }),
    fruit = W("capsule", 4, "berry", 2, "follicle", 1, "samara", 1),
  } },
  { name = "monocot", clade = "monocot", w = 4, roles = { hero = 1, monocot = 1 }, d = {
    syndrome = W("bee", 3, "moth", 2, "butterfly", 2, "bird", 1),
    form = W("lily", 3, "rotate", 2, "tubular", 1, "campanulate", 1),
    corona = BY("form", { lily = W("none", 6, "cup", 2, "trumpet", 1), _ = C("none") }),
    inflo = W("solitary", 2, "raceme", 3, "spike", 2, "umbel", 2),
    size = BY("inflo", { solitary = R(30, 70), _ = R(8, 25) }),
    leafmargin = W("entire", 19, "undulate", 1),
    venation = W("parallel", 9, "arcuate", 1),
    fruit = W("capsule", 4, "berry", 1),
  } },
  -- a fern (report section 4d): fronds divided once to three times (pinnae, pinnules, their
  -- lobes), in an outline, on a bare stipe; spores in sori under the pinnae; in a dimorphic
  -- fern the fertile fronds are narrow and beaded. Only the role "fern" draws it (apart):
  -- a page's ferns grow at the root beside its four flowering plants. Leaf traits: the
  -- pinna's (or pinnule's) taper, tip and edge; curl: how far the fronds arch over
  { name = "fern", clade = "fern", w = 1, roles = {}, apart = true, d = {
    leafshape = W("lanceolate", 3, "oblong", 2), leafapex = W("acute", 3, "obtuse", 2, "rounded", 1),
    leafmargin = W("entire", 3, "crenate", 3, "serrate", 2),
    curl = R(0, 0.6), turns = W(0, 1, 1, 1), hairy = W(0, 1, 1, 1),
    division = W(1, 5, 2, 4, 3, 2),
    pinnae = BY("division", { ["1"] = I(14, 26), ["2"] = I(10, 16), _ = I(8, 13) }),
    outline = BY("division", { ["1"] = W("lanceolate", 4, "oblong", 3, "ovate", 1),
      _ = W("lanceolate", 4, "ovate", 2, "deltoid", 3, "oblong", 1) }),
    stipe = R(0.12, 0.4),
    sori = W("dots", 5, "lines", 2, "marginal", 2, "none", 1),
    dimorphic = W(0, 4, 1, 1),
  } },
}
-- the plants: a trait's distribution is the plan's own, else its clade's, else
-- everyone's; a role ("hero", "spray", "monocot", "any") draws its plans by their
-- weights, and "any" every flowering plan (not a plan set apart, the fern)
M.ROLES = { hero = true, spray = true, monocot = true, any = true }
local PLANT = family {
  name = "plant", noun = "plant", what = "a species", heading = "A species",
  traits = M.TRAITS, kinds = M.PLANS, derived = "clade", roles = M.ROLES,
  rolelist = { "hero", "spray", "monocot", "any" },
  fallback = function(p, trait) return CLADE[p.clade][trait] or COMMON[trait] end,
  weight = function(p, role) if (role == "any" and not p.apart) or p.roles[role] then return p.w end end,
  refuse = function(plan, fix) return M.refused(plan, fix) end,
  tex = { traits = "traits", role = "role", kind = "plan", T = "T", BY = "BY", d = "", ok = "ok" },
}
M.FAMILIES[1], M.FAMILIES.plant = PLANT, PLANT
local PLAN = PLANT.byname
M.dist, M.roleplans, M.sample = PLANT.dist, PLANT.rolekinds, PLANT.sample

-- ---------------------------------------------------------------- the rules
-- report section 5c; a species that breaks one is a bug in the tables
local FUSED = { campanulate = 1, urceolate = 1, tubular = 1, funnelform = 1, salverform = 1, bilabiate = 1 }
local SIDEWAYS = { bilabiate = 1, papilionaceous = 1, orchid = 1 }
function M.violations(sp)
  local v = {}
  local function check(ok, what) if not ok then v[#v + 1] = what end end
  local mono = sp.clade == "monocot"
  check(not mono or sp.merosity == 3 or sp.merosity == 6 or sp.merosity == 4, "monocot with parts not in threes")
  check(not mono or sp.merosity ~= 5, "monocot with five parts")
  check(not mono or sp.leafmargin == "entire" or sp.leafmargin == "undulate", "monocot with a toothed leaf")
  check(not SIDEWAYS[sp.form] or (sp.symmetry == "bilateral" and sp.orient == "horizontal"), "two-sided form not two-sided")
  check(sp.form ~= "papilionaceous" or (sp.merosity == 5 and sp.fruit == "legume"), "pea flower without five parts and a pod")
  check(not FUSED[sp.form] or sp.fused == 1, "fused form with free petals")
  check((sp.form ~= "rosaceous" and sp.form ~= "cruciform") or sp.fused == 0, "rose or cross form with fused petals")
  check(sp.form ~= "cruciform" or sp.merosity == 4, "cross of petals without four")
  check(sp.inflo ~= "catkin" or (sp.form == "none" and sp.syndrome == "wind"), "catkin with petals or a visitor")
  check(sp.syndrome ~= "wind" or sp.inflo == "catkin", "wind flower outside a catkin")
  check((sp.inflo ~= "cumbel" and sp.form ~= "head") or sp.form == "head" or sp.size <= 5, "umbel flowers too big")
  check(sp.merovar == 0 or sp.symmetry == "radial", "variable petal number in a two-sided flower")
  check(sp.spurs ~= "one" or sp.symmetry == "bilateral", "one spur on a radial flower")
  check(sp.tendrils == 0 or sp.compound == "pinnate", "tendrils without a pinnate leaf")
  local fern = sp.clade == "fern"
  check(fern == (sp.division > 0), "a flowering plant with fronds, or a fern without")
  check(fern or (sp.pinnae == 0 and sp.sori == "none" and sp.dimorphic == 0), "a frond's traits on a flowering plant")
  check(not fern or (sp.form == "none" and sp.inflo == "none" and sp.compound == "frond"), "a fern with flowers")
  check(not fern or (sp.pinnae >= 8 and sp.stipe > 0 and sp.outline ~= "none"), "a frond without pinnae or stipe")
  return v
end
PLANT.violations = M.violations

-- ---------------------------------------------------------------- in words
local NUM = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
  "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty-one",
  "twenty-two", "twenty-three", "twenty-four", "twenty-five", "twenty-six" }
local COLOR = { blue = "blue", violet = "violet", pink = "pink", red = "red", orange = "orange", yellow = "yellow",
  white = "white", green = "green" }
local FOR = { bee = "for bees", butterfly = "for butterflies", moth = "for moths at dusk", bird = "for birds",
  beetle = "for beetles", fly = "for flies and hoverflies", wind = "pollinated by the wind" }
local INFLO = {
  solitary = "alone on its stalk", raceme = "along a raceme", spike = "in a dense spike",
  panicle = "in branched panicles", corymb = "in a flat-topped cluster", umbel = "in an umbel",
  cumbel = "in a compound umbel", dichasium = "in forked cymes", monochasium = "in a coiled cyme that uncurls",
  head = "in a round head", catkin = "in hanging catkins", thyrse = "in a crowded thyrse",
}
local MARGIN = { entire = "smooth-edged", undulate = "wavy", serrate = "toothed", doubly = "doubly toothed",
  dentate = "coarsely toothed", crenate = "scalloped", lobed = "lobed", pinnatifid = "deeply cut",
  palmatelobed = "hand-lobed" }
local SHAPE = { linear = "strap-shaped", lanceolate = "narrow", elliptic = "oval", ovate = "egg-shaped",
  obovate = "spoon-shaped", oblong = "oblong", cordate = "heart-shaped", orbicular = "round",
  reniform = "kidney-shaped", deltoid = "triangular", sagittate = "arrow-shaped", hastate = "spear-shaped" }
local ARRANGE = { alternate = "", opposite = ", in pairs", whorled = ", in whorls", rosette = ", in a rosette at the foot",
  distichous = ", in two flat ranks" }
local FRUIT = { capsule = "capsules", berry = "berries", hip = "hips", pome = "small apples", drupe = "stone fruit",
  legume = "pods", silique = "long thin pods", silicle = "round flat pods", nutlets = "nutlets",
  pappus = "seeds with parachutes", achene = "small dry seeds", schizocarp = "paired ribbed seeds",
  follicle = "pods that split down one side", samara = "winged seeds", nut = "nuts" }

local function n_(k) return NUM[k] or fmt("%d", k) end
local function a_(word) return (word:match("^[aeiou]") and "an " or "a ") .. word end

local function flower_words(sp)
  local n, f = sp.merosity, sp.form
  local c = (sp.orient == "nodding" and f ~= "none" and "nodding " or "") .. COLOR[sp.color]
  local parts = sp.clade == "monocot" and 2 * n or n     -- a monocot's parts come in two whorls of n
  if f == "head" then return a_(c) .. " daisy head of " .. n_(n) .. " rays"
  elseif f == "lily" and sp.corona ~= "none" then        -- the narcissus' corona, short or long
    return a_(c) .. (sp.corona == "cup" and " narcissus of " or " daffodil of ") .. n_(2 * n) .. " tepals around a "
      .. (sp.corona == "cup" and "short cup" or "long trumpet")
  elseif f == "lily" then
    local shape = sp.reflex < -40 and "swept-back" or sp.cup > 0.6 and "trumpet" or sp.cup < 0.3 and "starry" or "cupped"
    return a_(c) .. " lily of " .. n_(2 * n) .. " " .. shape .. " tepals"
  elseif f == "iris" then return a_(c) .. " iris of three falls and three standards"
  elseif f == "orchid" then return a_(c) .. " orchid with a broad lip"
  elseif f == "papilionaceous" then return a_(c) .. " pea flower"
  elseif f == "bilabiate" then return a_(c) .. " two-lipped flower"
  elseif f == "cruciform" then return a_(c) .. " cross of four petals"
  elseif f == "spurred" then return a_(c) .. " flower with " .. n_(n) .. " spurs"
  elseif f == "campanulate" then return a_(c) .. " bell of " .. n_(parts) .. " lobes"
  elseif f == "urceolate" then return a_(c) .. " urn"
  elseif f == "tubular" then return a_(c) .. " tube"
  elseif f == "funnelform" then return a_(c) .. " trumpet"
  elseif f == "salverform" then return a_(c) .. " flat-faced tube of " .. n_(parts) .. " lobes"
  elseif f == "none" then return "tiny petal-less flowers"
  end
  local some = sp.merovar > 0 and "mostly " or ""
  if f == "rotate" and sp.fused == 1 then return a_(c) .. " wheel of " .. some .. n_(parts) .. " lobes" end
  return a_(some .. n_(parts) .. "-petaled " .. c) .. (f == "rosaceous" and " rose" or " wheel")
end

local function leaf_words(sp)
  local m, s = MARGIN[sp.leafmargin], SHAPE[sp.leafshape]
  local leaf
  if sp.compound == "pinnate" then leaf = "leaves of " .. n_(sp.leaflets) .. " pairs of " .. m .. " leaflets"
  elseif sp.compound == "bipinnate" then leaf = "finely twice-divided leaves"
  elseif sp.compound == "palmate" then leaf = "hand-shaped leaves of " .. n_(sp.leaflets) .. " " .. m .. " leaflets"
  elseif sp.compound == "trifoliate" then leaf = "leaves in threes of " .. m .. " leaflets"
  else leaf = (sp.hairy == 1 and "hairy, " or "") .. m .. ", " .. s .. " leaves" end
  if sp.venation == "parallel" then leaf = leaf .. " with parallel veins"
  elseif sp.venation == "palmate" then leaf = leaf .. " veined from the base" end
  return leaf .. ARRANGE[sp.arrangement]
end

-- a fern in words: its fronds, their pinnae, their stalk, where its spores are
local DIVIDED = { "once-divided", "twice-divided", "thrice-divided" }
local OUTLINE = { lanceolate = "lance-shaped", oblong = "narrow, parallel-sided", ovate = "egg-shaped",
  deltoid = "triangular" }
local SORI = { dots = "in round dots", lines = "in lines", marginal = "along the edges" }
local function fern_words(sp)
  local part = sp.division == 1 and MARGIN[sp.leafmargin] .. " pinnae"
    or "pinnae cut into " .. (sp.division == 3 and "lobed " or "") .. "pinnules"
  local s = "a fern of " .. DIVIDED[sp.division] .. ", " .. OUTLINE[sp.outline] .. " fronds of " .. n_(sp.pinnae)
    .. " pairs of " .. part .. " on " .. (sp.hairy == 1 and "a scaly" or "a bare") .. " stalk, unrolling from fiddleheads in spring"
  if sp.dimorphic == 1 then s = s .. "; the fertile fronds narrow and beaded" end
  s = s .. (sp.sori == "none" and "; its spores hidden" or "; spores " .. SORI[sp.sori] .. " beneath")
  return s .. (sp.turns == 1 and ", the fronds turning copper in autumn." or ".")
end

-- one sentence: what it looks like, how it flowers, who it is for, its leaves, its fruit
function M.describe(sp)
  if sp.clade == "fern" then local s = fern_words(sp) return s:sub(1, 1):upper() .. s:sub(2) end
  local s = flower_words(sp) .. " " .. INFLO[sp.inflo] .. ", " .. FOR[sp.syndrome] .. "; "
    .. leaf_words(sp) .. (sp.tendrils == 1 and ", climbing by tendrils" or "") .. "; then " .. FRUIT[sp.fruit] .. "."
  return s:sub(1, 1):upper() .. s:sub(2)
end
PLANT.describe = M.describe

-- ---------------------------------------------------------------- a document's plants
-- showy: flowers that can carry a page, one at a time or in a loose cluster, not a
-- raceme, spike, catkin or compound umbel of small ones (those make a page's sprays),
-- and painted in the ink: red and orange take the copper, which the margin keeps sparing
local SPRAYS = { cumbel = true, raceme = true, spike = true, panicle = true, thyrse = true, catkin = true, monochasium = true }
function M.showy(sp) return not SPRAYS[sp.inflo] and sp.color ~= "red" and sp.color ~= "orange" end

-- a pool of eight species for a document (docseed: \florilegiumseed, or 0), each with a
-- role, no body plan twice, both heroes showy; ink.rng streams, Lua only (TikZ draws
-- species by seed)
local SLOTS = { "hero", "hero", "spray", "spray", "monocot", "any", "any", "any" }
local pools = {}
function M.pool(docseed)
  docseed = docseed or 0
  if pools[docseed] then return pools[docseed] end
  local rng = ink.rng(docseed * 104729 + 307)
  local pool, used = {}, {}
  for i, role in ipairs(SLOTS) do
    local sp
    local tries = 0
    repeat
      sp = M.sample(1 + floor(rng.u() * 2147483645), role)
      tries = tries + 1
      assert(tries < 10000, "florilegium-species: no body plan left for the role " .. role)
    until not used[sp.plan] and (role ~= "hero" or M.showy(sp))
    used[sp.plan] = true
    sp.slot = i
    pool[i] = sp
  end
  pools[docseed] = pool
  return pool
end

-- the document's fern (docseed as for the pool): from a stream of its own, so the pool is
-- as it was; the pages that have ferns all have this one
local ferns = {}
function M.fern(docseed)
  docseed = docseed or 0
  if not ferns[docseed] then
    local rng = ink.rng(docseed * 104729 + 401)
    ferns[docseed] = M.sample(1 + floor(rng.u() * 2147483645), "fern")
  end
  return ferns[docseed]
end

-- the four that grow on one page (rng: the page's species stream), in the order of
-- the stems they grow on: the hero (main stem 1), a second showy plant (2: the other
-- hero, or a showy one of the rest), the monocot (3) and a spray (the footer)
function M.community(pool, rng)
  local hero = pool[1 + floor(rng.u() * 2)]
  local spray = pool[3 + floor(rng.u() * 2)]
  local mono = pool[5]
  local showy = {}
  for _, sp in ipairs(pool) do
    if sp ~= hero and sp ~= spray and sp ~= mono and M.showy(sp) then showy[#showy + 1] = sp end
  end
  local second = showy[1 + floor(rng.u() * #showy)]   -- never empty: the other hero is showy
  return { hero, second, mono, spray }
end

-- ---------------------------------------------------------------- visitors
-- A visitor is sampled as a plant is, from a genome of its own: its kind first (a
-- butterfly, a bumblebee, a damselfly ...), which fixes its group, then the traits the
-- report gives that kind (section 6), each a constant where the kind has no such thing.
-- size is the real animal's in mm (a wingspan for butterflies and moths, a body length
-- for the others, a shell's width for a snail); ground the wash it is painted in (the
-- ink, pale, dark or the copper, which takes orange, red and yellow); pose how it is seen.
-- The order of the draws; every visitor draws them in this order
M.VTRAITS = {
  "kind", "group", "size", "tone", "ground", "pose",
  -- wings of butterflies and moths: tip, edge, tails; the pattern systems of the nymphalid
  -- groundplan (bands near the body, a central band or spots with a discal spot, a border
  -- band, spots or eyespots with their rings and the arcs outside them, lunules at the edge;
  -- after Schwanwitsch 1924 and Süffert 1927), veins; the feelers
  "apex", "wingedge", "tails", "basal", "central", "discal", "border", "eyes", "rings", "parafocal",
  "lunules", "veins", "antenna",
  -- bees and hoverflies: abdomen bands, hair, pollen carried, width for length, a pale tail
  "bands", "hair", "pollen", "build", "paletail",
  -- dragonflies and damselflies: tinted wings, the dark spot near each tip
  "tint", "stigma",
  -- beetles and ladybirds: the wing cases' pattern and spots
  "pattern", "spots", "spotsize",
  -- caterpillars: stripes, hair tufts, a tail horn
  "stripes", "tufts", "horn",
  -- snails: whorls, how fast the coil widens, spire height for width, handedness, bands,
  -- a flared lip, how far the foot is out
  "whorls", "expansion", "spire", "hand", "shellbands", "lip", "extension",
  -- birds: the bill, a crest, the tail for the body's length
  "bill", "crest", "tail",
  -- snails' shells (the shells report, part A): the mouth's height for its width (Raup's S),
  -- how deep the suture runs, the sculpture and its ribs a whorl, a coil whose whorls part,
  -- and a snail withdrawn into its shell. Last, so no other visitor draws differently
  "aperture", "suture", "sculpture", "ribs", "opencoil", "withdrawn",
}
-- what a kind does not have: every trait a constant (no draw)
local VNONE = {
  pose = C("none"), apex = C("none"), wingedge = C("none"), tails = C(0), basal = C(0), central = C("none"),
  discal = C(0), border = C("none"), eyes = C(0), rings = C(0), parafocal = C(0), lunules = C(0), veins = C(0),
  antenna = C("none"), bands = C(0), hair = C(0), pollen = C(0), build = C(0), paletail = C(0), tint = C("none"),
  stigma = C(0), pattern = C("none"), spots = C(0), spotsize = C(0), stripes = C("none"), tufts = C(0), horn = C(0),
  whorls = C(0), expansion = C(0), spire = C(0), hand = C("none"), shellbands = C(0), lip = C(0), extension = C(0),
  bill = C("none"), crest = C(0), tail = C(0),
  aperture = C(0), suture = C(0), sculpture = C("none"), ribs = C(0), opencoil = C(0), withdrawn = C(0),
}
-- the wings of butterflies and moths: the groundplan's border system decides the spots
local BORDER_EYES = BY("border", { eyes = I(1, 6), spots = I(3, 7), _ = C(0) })
local BORDER_RINGS = BY("border", { eyes = I(1, 3), _ = C(0) })
local BORDER_ARCS = BY("border", { eyes = W(1, 1, 0, 1), _ = C(0) })
-- kinds: group; w, the weight among all kinds; roles, the weight in each role (a flower's
-- pollinator: bee, butterfly, moth, bird, beetle, fly; off the flowers: leaf, stem, perch)
M.VKINDS = {
  { name = "butterfly", group = "lepidoptera", w = 6, roles = { butterfly = 1 }, d = {
    size = R(30, 70), tone = R(0.26, 0.4), ground = W("ink", 5, "copper", 3, "pale", 2, "dark", 1),
    pose = W("open", 3, "closed", 2),
    apex = W("rounded", 4, "angular", 3, "falcate", 1), wingedge = W("smooth", 5, "scalloped", 3, "toothed", 1),
    tails = W(0, 7, 1, 2, 2, 1), basal = W(0, 1, 1, 1), central = W("none", 3, "band", 2, "spots", 1),
    discal = W(0, 1, 1, 1), border = W("eyes", 3, "spots", 2, "band", 1, "none", 2),
    eyes = BORDER_EYES, rings = BORDER_RINGS, parafocal = BORDER_ARCS, lunules = I(0, 2), veins = W(1, 3, 0, 1),
    antenna = C("clubbed"),
  } },
  { name = "moth", group = "lepidoptera", w = 3, roles = { moth = 3 }, d = {
    size = R(25, 60), tone = R(0.3, 0.5), ground = W("pale", 4, "dark", 3, "ink", 2, "copper", 1),
    pose = W("tent", 3, "flat", 2),
    apex = W("rounded", 3, "angular", 2), wingedge = W("smooth", 4, "scalloped", 1),
    basal = W(0, 1, 1, 1), central = W("band", 3, "spots", 1, "none", 1), discal = W(1, 3, 0, 1),
    border = W("band", 2, "spots", 2, "eyes", 1, "none", 1),
    eyes = BORDER_EYES, rings = BORDER_RINGS, parafocal = BORDER_ARCS, lunules = I(0, 2), veins = W(0, 2, 1, 1),
    antenna = W("thread", 3, "feathery", 2), hair = R(0.3, 0.8),
  } },
  -- a hawkmoth hovers at a long tube on narrow swept wings
  { name = "hawkmoth", group = "lepidoptera", w = 1, roles = { moth = 1 }, d = {
    size = R(40, 90), tone = R(0.3, 0.48), ground = W("dark", 2, "pale", 1, "copper", 1), pose = C("hover"),
    apex = C("pointed"), wingedge = C("smooth"), basal = W(0, 1, 1, 1), central = W("band", 2, "none", 1),
    discal = W(1, 1, 0, 1), border = W("band", 2, "none", 1), lunules = I(0, 1), veins = W(0, 2, 1, 1),
    antenna = C("thread"), bands = I(3, 6), hair = R(0.4, 0.8),
  } },
  { name = "honeybee", group = "bee", w = 3, roles = { bee = 3 }, d = {
    size = R(12, 15), tone = R(0.3, 0.42), ground = W("ink", 3, "copper", 1), pose = W("visit", 2, "fly", 1),
    antenna = C("elbowed"), bands = I(4, 6), hair = R(0.2, 0.4), pollen = W(1, 1, 0, 1), build = R(0.4, 0.45),
  } },
  { name = "bumblebee", group = "bee", w = 3, roles = { bee = 3 }, d = {
    size = R(14, 23), tone = R(0.28, 0.4), ground = W("ink", 3, "copper", 2), pose = W("visit", 2, "fly", 1),
    antenna = C("elbowed"), bands = I(1, 4), hair = R(0.7, 1), pollen = W(1, 1, 0, 1), build = R(0.5, 0.6),
    paletail = W(1, 2, 0, 1),
  } },
  { name = "solitarybee", group = "bee", w = 2, roles = { bee = 2 }, d = {
    size = R(6, 14), tone = R(0.34, 0.5), ground = W("dark", 3, "ink", 2, "copper", 1), pose = W("visit", 2, "fly", 1),
    antenna = C("elbowed"), bands = I(0, 3), hair = R(0.1, 0.4), pollen = W(1, 1, 0, 2), build = R(0.28, 0.34),
  } },
  { name = "hoverfly", group = "fly", w = 3, roles = { fly = 1 }, d = {
    size = R(8, 15), tone = R(0.3, 0.42), ground = W("ink", 3, "copper", 2), pose = W("hover", 2, "rest", 3),
    antenna = C("short"), bands = I(3, 4), hair = R(0, 0.3), build = R(0.3, 0.45),
  } },
  { name = "dragonfly", group = "odonate", w = 2, roles = { stem = 2 }, d = {
    size = R(40, 75), tone = R(0.28, 0.42), ground = W("ink", 4, "copper", 1, "dark", 1), pose = C("cross"),
    bands = I(0, 8), tint = W("clear", 4, "tinted", 1), stigma = W(1, 4, 0, 1),
  } },
  { name = "damselfly", group = "odonate", w = 2, roles = { stem = 2 }, d = {
    size = R(28, 45), tone = R(0.28, 0.42), ground = W("ink", 4, "copper", 1), pose = W("folded", 3, "spread", 1),
    bands = I(0, 8), tint = W("clear", 3, "tinted", 2), stigma = W(1, 3, 0, 1),
  } },
  { name = "beetle", group = "beetle", w = 2, roles = { beetle = 2 }, d = {
    size = R(6, 20), tone = R(0.3, 0.5), ground = W("dark", 3, "ink", 2, "copper", 1), pose = C("walk"),
    antenna = W("thread", 3, "clubbed", 1, "comb", 1), build = R(0.45, 0.7),
    pattern = W("plain", 3, "stripes", 2, "spots", 2), spots = BY("pattern", { spots = I(2, 8), _ = C(0) }),
    spotsize = BY("pattern", { spots = R(0.08, 0.16), _ = C(0) }),
  } },
  { name = "ladybird", group = "beetle", w = 2, roles = { beetle = 1, stem = 1 }, d = {
    size = R(4, 9), tone = R(0.3, 0.45), ground = W("copper", 5, "dark", 1), pose = C("walk"),
    antenna = C("clubbed"), build = R(0.8, 0.9), pattern = C("spots"),
    spots = W(2, 2, 7, 4, 10, 1, 14, 1, 22, 1, 0, 1), spotsize = R(0.08, 0.2),
  } },
  { name = "caterpillar", group = "larva", w = 2, roles = { leaf = 1 }, d = {
    size = R(20, 45), tone = R(0.28, 0.45), ground = W("ink", 3, "pale", 1, "copper", 1),
    pose = W("straight", 3, "loop", 2, "curl", 2), build = R(0.1, 0.15),
    stripes = W("none", 2, "side", 2, "back", 1), tufts = W(0, 3, 1, 1), horn = W(0, 3, 1, 1),
  } },
  -- most snail species coil to the right (dextral); report section 6d
  { name = "snail", group = "snail", w = 2, roles = { leaf = 1 }, d = {
    size = R(12, 30), tone = R(0.28, 0.42), ground = W("ink", 3, "pale", 1, "copper", 1), pose = C("glide"),
    whorls = R(3.5, 6), expansion = R(1.6, 3.2), spire = R(0.1, 1.2), hand = W("dextral", 19, "sinistral", 1),
    shellbands = W(0, 3, 5, 2, 1, 1, 2, 1, 3, 1), lip = W(0, 1, 1, 1), extension = R(0.4, 1),
    -- about half of land snails are smooth; ribs 12-24 a whorl; an open coil is rare (report A2)
    aperture = R(0.85, 1.3), suture = R(0.15, 0.8), sculpture = W("smooth", 5, "ribs", 3, "cords", 2),
    ribs = BY("sculpture", { ribs = I(12, 24), _ = C(0) }), opencoil = W(0, 99, 1, 1), withdrawn = W(0, 7, 1, 3),
  } },
  -- a perching bird with a seed-eater's short conical bill, or a nectar bird (a
  -- hummingbird or a sunbird) with a long thin one, hovering or perched at the flower
  { name = "bird", group = "bird", w = 1, roles = { perch = 1 }, d = {
    size = R(90, 140), tone = R(0.28, 0.42), ground = W("ink", 3, "dark", 1, "copper", 1), pose = C("perch"),
    bill = C("conical"), crest = W(0, 4, 1, 1), tail = R(0.3, 0.5),
  } },
  { name = "hummingbird", group = "bird", w = 1, roles = { bird = 1 }, d = {
    size = R(70, 110), tone = R(0.28, 0.42), ground = W("ink", 3, "copper", 2), pose = W("hover", 2, "perch", 1),
    bill = W("curved", 2, "straight", 1), crest = W(0, 5, 1, 1), tail = R(0.3, 0.45),
  } },
}
-- the visitors: what a kind's table leaves out it does not have (VNONE); a role draws
-- its kinds by the weights in their roles, "any" every kind by its weight; the TeX
-- tables are a namespace of their own (\flo@VT, \flo@VBY), since visitors and plants
-- share trait names. A visitor's values (M.values) are only what some kind draws itself:
-- a kind without a shell holds a placeholder that no drawing of a shell can take
M.VROLES = { bee = true, butterfly = true, moth = true, bird = true, beetle = true, fly = true, leaf = true,
  stem = true, perch = true, any = true }
local VISITOR = family {
  name = "visitor", noun = "visitor", what = "a visitor", heading = "A visitor",
  traits = M.VTRAITS, kinds = M.VKINDS, derived = "group", roles = M.VROLES,
  rolelist = { "bee", "butterfly", "moth", "bird", "beetle", "fly", "leaf", "stem", "perch", "any" },
  fallback = function(_, trait) return VNONE[trait] end,
  weight = function(k, role) return role == "any" and k.w or k.roles[role] end,
  own = function(k, trait) return k.d[trait] end,
  tex = { traits = "vtraits", role = "vrole", kind = "vkind", T = "VT", BY = "VBY", d = "vis@", ok = "vok" },
}
M.FAMILIES[2], M.FAMILIES.visitor = VISITOR, VISITOR
M.vdist, M.vrolekinds, M.vsample = VISITOR.dist, VISITOR.rolekinds, VISITOR.sample

-- ---------------------------------------------------------------- a genome of your own
-- Some traits fixed, the rest sampled (board #5109): "compound=palmate, leaflets=7". The
-- values a trait may take are those some plan (or kind) can draw: one of its names, or a
-- whole number or a real number within the range the genome draws from. clade and group
-- follow from the plan and the kind and are not fixed themselves.
local function collect(d, acc)
  local k = d[1]
  local function num(lo, hi, real)
    acc.lo = acc.lo and math.min(acc.lo, lo) or lo
    acc.hi = acc.hi and math.max(acc.hi, hi) or hi
    acc.real = acc.real or real
  end
  local function one(v)
    if type(v) == "number" then num(v, v, math.type(v) == "float") else acc.names[v] = true end
  end
  if k == "c" then one(d[2])
  elseif k == "i" then num(d[2], d[3], false)
  elseif k == "r" then num(d[2], d[3], true)
  elseif k == "w" then for i = 2, #d, 2 do one(d[i]) end
  elseif k == "by" then for _, sub in pairs(d[3]) do collect(sub, acc) end
  end
end
-- a family: the name of one (plant, visitor), or, as the first callers wrote it, true for
-- the visitors and false (or nothing) for the plants
local function famof(which)
  if which == true then return VISITOR elseif not which then return PLANT end
  return type(which) == "table" and which or M.family(which)
end
-- trait -> { names = {name = true}, lo, hi, real }: what fixing it may give, for a family
-- (f.own: the distributions a kind really draws)
function M.values(which)
  local f = famof(which)
  if f.VALUES then return f.VALUES end
  local out = {}
  for i, t in ipairs(f.traits) do
    local acc = { names = {} }
    for _, k in ipairs(f.kinds) do
      if i == 1 then acc.names[k.name] = true
      else
        local d = f.own(k, t)
        if d then collect(d, acc) end
      end
    end
    out[t] = acc
  end
  if f.derived then out[f.derived] = nil end
  assert(out[f.traits[1]])
  f.VALUES = out
  return out
end
-- A fixed value that the other kind of plant draws, but not this one: a name only the fern
-- draws (syndrome=none, inflo=none, compound=frond, ...) fixed on a flowering plant, or, on
-- a fern, a leaf tip, edge or outline that its frond has no table entry for (FROND). M.refused
-- gives the error for the first such trait, in draw order, or nil; M.sample raises it once
-- the plan is known, and the TikZ library (\flo@planfixcheck) refuses the same values from
-- the tables M.tex writes.
local FROND = { leafapex = true, leafmargin = true, outline = true }
local KINDVALUES
local function kindvalues()
  if KINDVALUES then return KINDVALUES end
  local fern, flowering = {}, {}
  for i = 2, #M.TRAITS do
    local t = M.TRAITS[i]
    local a, b = { names = {} }, { names = {} }
    for _, p in ipairs(M.PLANS) do collect(M.dist(p.name, t), p.clade == "fern" and a or b) end
    fern[t], flowering[t] = a.names, b.names
  end
  KINDVALUES = { fern = fern, flowering = flowering }
  return KINDVALUES
end
local function namelist(set)
  local names = {}
  for name in pairs(set) do names[#names + 1] = name end
  table.sort(names)
  return names
end
-- for M.tex: the traits that have names only the fern draws, those names and the flowering
-- plant's; the frond's own names for the traits it reads through tables
function M.kindvalues()
  local kv, fernonly, frond = kindvalues(), {}, {}
  for i = 2, #M.TRAITS do
    local t = M.TRAITS[i]
    local only = {}
    for name in pairs(kv.fern[t]) do if not kv.flowering[t][name] then only[name] = true end end
    if next(only) and t ~= "clade" then fernonly[#fernonly + 1] = { t, namelist(only), namelist(kv.flowering[t]) } end
    if FROND[t] then frond[#frond + 1] = { t, namelist(kv.fern[t]) } end
  end
  return fernonly, frond
end
function M.refused(plan, fix)
  local kv, fern = kindvalues(), PLAN[plan].clade == "fern"
  for i = 2, #M.TRAITS do
    local t, v = M.TRAITS[i], fix[M.TRAITS[i]]
    if type(v) == "string" then
      if fern and FROND[t] and not kv.fern[t][v] then
        return fmt("florilegium: %s=%s is a flowering plant's; a fern's %s is one of %s", t, v, t, concat(namelist(kv.fern[t]), ", "))
      elseif not fern and not kv.flowering[t][v] and kv.fern[t][v] then
        return fmt("florilegium: %s=%s is a fern's; a flowering plant's %s is one of %s", t, v, t, concat(namelist(kv.flowering[t]), ", "))
      end
    end
  end
end
-- "trait=value, ..." as a table of fixed traits, each value as the sampler holds it (a name,
-- a whole number, or a real number to the scaled point, as TeX reads it); an unknown trait
-- or a value the genome cannot draw is an error
function M.fixes(text, which)
  local f = famof(which)
  local fix, vals = {}, M.values(f)
  for item in tostring(text or ""):gmatch("[^,]+") do
    local t, v = item:match("^%s*([%w_]+)%s*=%s*(.-)%s*$")
    if not t then
      if item:match("%S") then error("florilegium: not trait=value: '" .. item .. "'", 0) end
    else
      local ok = vals[t]
      if not ok then error("florilegium: " .. f.what .. " has no trait '" .. t .. "'", 0) end
      -- as TeX reads it (\flo@fixcheck): pgfkeys takes one pair of braces off a value; a
      -- number is a plain decimal (a minus sign first or none, at most one point), compared
      -- with the range as TeX holds both, in sp
      v = v:match("^{(.*)}$") or v
      local n = v:match("^%-?%d*%.?%d*$") and v:match("%d") and tonumber(v)
      local s = n and ok.lo and n > -16384 and n < 16384 and pm.sp(v)
      if ok.names[v] then fix[t] = v
      elseif s and s >= pm.sp(tostring(ok.lo)) and s <= pm.sp(tostring(ok.hi)) and (ok.real or s % 65536 == 0) then
        fix[t] = ok.real and s / 65536 or s // 65536
      else
        local names = {}
        for name in pairs(ok.names) do names[#names + 1] = name end
        table.sort(names)
        local range = ok.lo and fmt("%s from %s to %s", ok.real and "a number" or "a whole number", ok.lo, ok.hi) or nil
        error(fmt("florilegium: %s=%s cannot be drawn; %s is %s", t, v, t,
          concat(names, ", ") .. (#names > 0 and range and ", or " or "") .. (range or "")), 0)
      end
    end
  end
  return fix
end
-- the visitor rules; a visitor that breaks one is a bug in the tables
local WINGED = { lepidoptera = 1 }
function M.vviolations(v)
  local out = {}
  local function check(ok, what) if not ok then out[#out + 1] = what end end
  local lep = WINGED[v.group]
  check(lep or (v.apex == "none" and v.border == "none" and v.tails == 0), "wing pattern on a visitor without scaled wings")
  check(v.kind == "butterfly" or v.tails == 0, "tails on a visitor other than a butterfly")
  check(v.kind ~= "butterfly" or v.antenna == "clubbed", "a butterfly without clubbed feelers")
  check(v.group ~= "lepidoptera" or v.kind == "butterfly" or v.antenna ~= "clubbed", "a moth with clubbed feelers")
  check(v.border == "eyes" or v.rings == 0, "eyespot rings without eyespots")
  check(v.kind ~= "ladybird" or v.pattern == "spots", "a ladybird without its spots")
  check(v.group == "beetle" or v.pattern == "none", "wing cases on a visitor that is no beetle")
  check((v.group == "snail") == (v.whorls > 0), "a shell on something not a snail, or a snail without one")
  check(v.group == "snail" or (v.aperture == 0 and v.sculpture == "none" and v.withdrawn == 0 and v.opencoil == 0),
    "a shell's mouth, sculpture or coil on something not a snail")
  check((v.sculpture == "ribs") == (v.ribs > 0), "ribs counted on a shell that is not ribbed, or a ribbed one without")
  check((v.group == "bird") == (v.bill ~= "none"), "a bill on something not a bird, or a bird without one")
  check(v.kind ~= "bird" or v.bill == "conical", "a perching seed-eater with a nectar bill")
  check(v.kind ~= "hummingbird" or v.bill ~= "conical", "a nectar bird with a seed-eater's bill")
  check(v.group ~= "odonate" or v.tint ~= "none", "a dragonfly or damselfly without its wings' tint")
  check(v.size > 0, "a visitor of no size")
  return out
end
VISITOR.violations = M.vviolations
-- a visitor in words, after "a" or "an": "butterfly with scalloped wings and a row of eyespots"
-- the ground in the words of the animal's own colors (the copper paints warm ones)
local GROUNDW = {
  lepidoptera = { ink = "blue ", pale = "white ", dark = "brown ", copper = "orange " },
  bee = { ink = "", dark = "dark ", copper = "golden " }, fly = { ink = "", copper = "yellow-banded " },
  odonate = { ink = "blue ", dark = "dark ", copper = "red " }, beetle = { ink = "blue ", dark = "black ", copper = "red " },
  larva = { ink = "", pale = "pale ", copper = "orange " }, snail = { ink = "", pale = "pale ", copper = "brown " },
  bird = { ink = "", dark = "dark ", copper = "russet " },
}
local KINDW = { butterfly = "butterfly", moth = "moth", hawkmoth = "hawkmoth", honeybee = "honeybee",
  bumblebee = "bumblebee", solitarybee = "solitary bee", hoverfly = "hoverfly", dragonfly = "dragonfly",
  damselfly = "damselfly", beetle = "beetle", ladybird = "ladybird", caterpillar = "caterpillar", snail = "snail",
  bird = "small bird", hummingbird = "nectar bird" }
function M.vdescribe(v)
  local k = v.kind
  local before, with, after = "", {}, ""
  local ground = GROUNDW[v.group][v.ground]
  if v.group == "lepidoptera" and k ~= "butterfly" and v.ground == "ink" then ground = "" end   -- a blue moth is rare
  if v.group == "lepidoptera" then
    if v.wingedge ~= "smooth" then with[#with + 1] = v.wingedge .. " wings" end
    if v.apex == "falcate" then with[#with + 1] = "hooked wingtips" end
    if v.tails > 0 then with[#with + 1] = v.tails == 1 and "a tail on each hind wing" or "thread tails" end
    if v.border == "eyes" then with[#with + 1] = "a row of eyespots"
    elseif v.border == "spots" then with[#with + 1] = "a row of spots along the edge" end
    if v.antenna == "feathery" then with[#with + 1] = "feathery feelers" end
    if v.pose == "closed" then after = ", resting with its wings closed"
    elseif v.pose == "tent" then after = ", resting with its wings folded like a tent"
    elseif v.pose == "hover" then before = "hovering " end
  elseif v.group == "bee" or v.group == "fly" then
    if v.pollen == 1 then with[#with + 1] = "pollen on its legs" end
    if v.paletail == 1 then with[#with + 1] = "a pale tail" end
    if v.pose == "hover" then after = ", hanging in the air" elseif v.pose == "fly" then after = ", in flight" end
  elseif v.group == "odonate" then
    if v.tint == "tinted" then with[#with + 1] = "tinted wings" end
    if v.pose == "folded" then after = ", its wings folded along its body" end
  elseif k == "ladybird" then
    ground = v.ground == "copper" and "red " or "black "
    if v.spots > 0 then with[#with + 1] = n_(v.spots) .. (v.ground == "copper" and " black spots" or " red spots")
    else ground = "plain " .. ground end
  elseif k == "beetle" then
    if v.pattern == "stripes" then with[#with + 1] = "striped wing cases"
    elseif v.pattern == "spots" then with[#with + 1] = "spotted wing cases" end
  elseif k == "caterpillar" then
    before = v.pose == "loop" and "looping " or v.pose == "curl" and "curled " or ""
    if v.stripes ~= "none" then with[#with + 1] = "stripes" end
    if v.tufts == 1 then with[#with + 1] = "tufts of hair" end
    if v.horn == 1 then with[#with + 1] = "a horn at its tail" end
  elseif k == "snail" then
    local adj = {}
    if v.spire >= 1 then adj[#adj + 1] = "high-spired" elseif v.spire <= 0.25 then adj[#adj + 1] = "flat" end
    if v.shellbands > 0 then adj[#adj + 1] = "banded" end
    if v.sculpture == "ribs" then adj[#adj + 1] = "ribbed" elseif v.sculpture == "cords" then adj[#adj + 1] = "corded" end
    local shell = v.opencoil == 1 and "open-coiled shell" or "shell"
    if #adj > 0 then shell = concat(adj, ", ") .. " " .. shell end
    with[#with + 1] = (shell:match("^[aeiou]") and "an " or "a ") .. shell
    if v.hand == "sinistral" then with[#with + 1] = "a coil to the left" end
    if v.withdrawn == 1 then after = ", withdrawn into it" end
  elseif v.group == "bird" then
    with[#with + 1] = v.bill == "conical" and "a short seed-eater's bill" or "a long thin bill"
    if v.crest == 1 then with[#with + 1] = "a crest" end
    if v.pose == "hover" then before = "hovering " end
  end
  local s = before .. ground .. KINDW[k]
  if #with == 1 then s = s .. " with " .. with[1]
  elseif #with > 1 then s = s .. " with " .. concat(with, ", ", 1, #with - 1) .. " and " .. with[#with] end
  return s .. after
end
VISITOR.describe = M.vdescribe

-- ---------------------------------------------------------------- tracery
-- A window of Gothic tracery sampled as a plant is (board #5235, the frames report, part
-- B). Its kind is what it is on the page: a window (a traceried arch), a headpiece (a
-- wide, shallow arch over a title), an arcade (bays under a straight top), a rose, or a
-- foil alone (a trefoil or quatrefoil as an ornament). The period then locks the
-- vocabulary as a body plan locks a plant: no ogee before 1310, no spherical triangle
-- after 1350. One number does most of the drawing, the arch's excess (its radius over
-- its span, after Havemann and Fellner 2004): 0.5 a round arch, 1 equilateral, more a
-- lancet, less a drop arch. Lengths are fractions of the span; the drawing is circles
-- struck from the springing points and the centers they give (the report's snap points).
M.TTRAITS = {
  "kind", "period", "masonry", "arch", "excess", "rise", "ogee", "shoulder", "jamb",
  "lights", "split", "branch", "depth", "setdown", "bar", "border", "transoms",
  "figure", "foils", "foilshape", "cusps", "cuspdepth", "orders", "hood", "spandrel",
  "spokes", "rings", "oculus", "tone", "accent",
}
-- for every kind; a kind overrides any of them
local TCOMMON = {
  -- plate tracery (openings cut through a slab) belongs to the earliest windows
  masonry = BY("period", { early_english = W("plate", 3, "bar", 1), _ = C("bar") }),
  arch = BY("period", {
    early_english = W("lancet", 3, "equilateral", 2),
    geometric = W("equilateral", 4, "lancet", 1, "drop", 1),
    curvilinear = W("equilateral", 3, "drop", 2, "ogee", 1),
    perpendicular = W("fourcentered", 3, "drop", 2, "equilateral", 1),
    rayonnant = C("equilateral"),
    flamboyant = W("equilateral", 2, "ogee", 2, "drop", 1),
  }),
  -- radius over span; a four-centered arch is set by its rise and shoulders instead
  excess = BY("arch", { round = C(0.5), segmental = R(0.52, 0.7), drop = R(0.6, 0.9), equilateral = C(1),
    lancet = R(1.1, 1.6), ogee = R(0.8, 1.1), _ = C(0) }),
  rise = BY("arch", { fourcentered = R(0.25, 0.4), _ = C(0) }),          -- rise over span
  ogee = BY("arch", { ogee = R(0.4, 0.7), _ = C(0) }),                  -- the reversal, as a fraction of the rise
  shoulder = BY("arch", { fourcentered = R(0.12, 0.25), _ = C(0) }),     -- the shoulder arcs' radius over span
  jamb = C(0),                                                          -- the jambs' height over span
  lights = C(0),
  -- how the lights group under sub-arches: in two halves, a center light with the rest
  -- each side, or not at all (Perpendicular mullions run to the arch)
  split = BY("period", { perpendicular = C("flat"), _ = BY("lights", {
    ["1"] = C("flat"), ["2"] = W("binary", 3, "flat", 1), ["3"] = W("center", 2, "flat", 2),
    ["4"] = W("binary", 3, "flat", 1), ["5"] = W("center", 2, "flat", 1), ["6"] = W("binary", 3, "flat", 1),
    ["7"] = W("center", 2, "flat", 1), _ = C("flat") }) }),
  -- the head's construction: sub-arches with a figure above, mullions forking in a Y,
  -- intersecting arcs, panels straight up to the arch, the lights' ogee heads repeated
  -- up the head as a net (reticulated), ogee heads with mouchettes and daggers flowing
  -- above them, or a headpiece's screen
  branch = BY("lights", { ["0"] = C("none"), ["1"] = C("none"), _ = BY("period", {
    early_english = C("subarch"), geometric = W("subarch", 4, "Y", 1, "intersecting", 1),
    curvilinear = W("subarch", 3, "intersecting", 1, "Y", 1, "reticulated", 2, "flowing", 2),
    perpendicular = W("panel", 3, "subarch", 1),
    rayonnant = C("subarch"), flamboyant = W("subarch", 2, "Y", 1, "flowing", 3, "reticulated", 1) }) }),
  depth = BY("branch", { subarch = BY("lights", { ["2"] = C(1), ["3"] = C(1), ["4"] = I(1, 2), ["5"] = I(1, 2),
    ["6"] = I(1, 2), ["7"] = I(1, 2), _ = I(1, 3) }), _ = C(0) }),
  setdown = BY("branch", { subarch = R(0, 0.12), _ = C(0) }),            -- the sub-arches' springing, below the main one
  bar = R(0.012, 0.03),                                                 -- a bar's half-width over span
  border = R(0.02, 0.06),                                               -- the main arch's bar, over span
  transoms = C(0),
  figure = BY("branch", { subarch = BY("period", {
    early_english = W("oculus", 3, "foiled", 2, "none", 1), geometric = W("foiled", 6, "triangle", 2, "oculus", 1),
    curvilinear = W("foiled", 2, "dagger", 2, "mouchettes", 3, "soufflet", 2, "triangle", 1),
    perpendicular = W("foiled", 2, "none", 1), rayonnant = W("foiled", 4, "oculus", 1),
    flamboyant = W("mouchettes", 4, "soufflet", 3, "dagger", 2) }), _ = C("none") }),
  foils = BY("figure", { foiled = W(3, 2, 4, 5, 5, 1, 6, 3, 8, 1), triangle = W(0, 1, 3, 2), soufflet = C(4), _ = C(0) }),
  foilshape = BY("period", { early_english = C("round"), geometric = W("round", 4, "pointed", 1), rayonnant = C("round"),
    curvilinear = W("pointed", 2, "round", 1), perpendicular = W("pointed", 3, "round", 1),
    flamboyant = W("pointed", 3, "round", 1) }),
  -- cusps in each light's head: two make a trefoiled head
  cusps = BY("period", { early_english = W(0, 2, 2, 1), geometric = W(2, 3, 0, 1), curvilinear = W(2, 3, 4, 1, 0, 1),
    perpendicular = W(2, 3, 4, 2), rayonnant = W(2, 2, 0, 1), flamboyant = W(2, 2, 4, 1) }),
  cuspdepth = R(0.12, 0.28),                                            -- a cusp's reach over the opening's width
  orders = I(1, 3),                                                     -- recessed rings round the arch
  hood = C("none"),                                                     -- the drip molding over the arch
  spandrel = C("blank"),                                                -- what fills the leftover corners
  spokes = C(0), rings = C(0), oculus = C(0),
  tone = R(0.3, 0.5),                                                   -- the wash in the openings
  accent = BY("hood", { stops = W("center", 2, "stops", 2, "none", 1), _ = W("center", 3, "none", 2) }),
}
-- kinds: w, the weight among all; roles, the weight in each place on the page
-- (headpiece: over a title; window: a pic or an initial's frame; rose; ornament)
M.TKINDS = {
  { name = "window", w = 4, roles = { window = 1, frame = 1 }, d = {
    period = W("early_english", 2, "geometric", 4, "curvilinear", 3, "perpendicular", 3, "rayonnant", 1, "flamboyant", 2),
    jamb = R(0.8, 2.2),
    lights = BY("period", { early_english = I(1, 3), geometric = I(2, 5), curvilinear = I(2, 5),
      perpendicular = I(3, 7), rayonnant = I(2, 4), flamboyant = I(2, 5) }),
    transoms = BY("period", { perpendicular = I(0, 2), _ = C(0) }),
    hood = W("none", 1, "plain", 2, "stops", 2),
    spandrel = BY("period", { early_english = C("blank"), geometric = W("blank", 2, "trefoil", 2),
      curvilinear = W("blank", 1, "trefoil", 1, "dagger", 2), perpendicular = W("blank", 2, "trefoil", 1),
      rayonnant = W("blank", 1, "trefoil", 1), flamboyant = W("dagger", 2, "blank", 1) }),
  } },
  -- a wide, shallow arch: segmental, four-centered, or an ogee depressed over shoulders
  { name = "headpiece", w = 3, roles = { headpiece = 3 }, d = {
    period = W("geometric", 3, "curvilinear", 2, "perpendicular", 4, "flamboyant", 2),
    arch = BY("period", { geometric = C("segmental"), curvilinear = W("ogee", 2, "segmental", 2),
      perpendicular = W("fourcentered", 4, "segmental", 2), flamboyant = W("ogee", 2, "fourcentered", 1, "segmental", 1) }),
    -- flat: a segmental arch struck from well below the springing, a four-centered or
    -- ogee arch rising a fifth of its span at most, over short jambs
    excess = BY("arch", { segmental = R(1, 1.6), _ = C(0) }),
    rise = BY("arch", { fourcentered = R(0.1, 0.16), ogee = R(0.11, 0.17), _ = C(0) }),
    shoulder = BY("arch", { fourcentered = R(0.04, 0.08), ogee = R(0.05, 0.08), _ = C(0) }),
    jamb = R(0.12, 0.18),
    lights = I(5, 8),
    orders = I(1, 2), border = R(0.015, 0.035),
    -- a screen: every light its own cusped head straight under the arch, small foils in
    -- the stone between the heads (no sub-arches, which would double the height)
    split = C("flat"), branch = BY("period", { perpendicular = W("panel", 1, "screen", 3), _ = C("screen") }),
    depth = C(0), setdown = C(0),
    figure = BY("branch", { screen = W("foiled", 5, "oculus", 1, "none", 1), _ = C("none") }),
    foils = BY("figure", { foiled = W(3, 3, 4, 3, 5, 1), _ = C(0) }),
    hood = W("plain", 2, "stops", 2, "none", 1),
    spandrel = W("foliage", 4, "trefoil", 2, "blank", 1),
  } },
  -- bays side by side under a straight molding, each a small window
  { name = "arcade", w = 2, roles = { headpiece = 2 }, d = {
    period = W("early_english", 1, "geometric", 2, "perpendicular", 4),
    arch = BY("period", { early_english = W("lancet", 2, "equilateral", 1, "round", 1),
      geometric = W("equilateral", 3, "drop", 1), perpendicular = W("fourcentered", 3, "drop", 1) }),
    jamb = R(0.3, 0.8),
    lights = I(5, 10),
    branch = C("none"), figure = C("none"), depth = C(0), setdown = C(0),
    hood = W("plain", 2, "none", 1),
    spandrel = W("trefoil", 2, "blank", 2, "foliage", 1),
  } },
  { name = "rose", w = 2, roles = { rose = 1, ornament = 1 }, d = {
    period = W("geometric", 3, "rayonnant", 3, "flamboyant", 2),
    masonry = C("bar"), arch = C("none"), cusps = C(0), orders = I(1, 2),
    spokes = W(6, 1, 8, 3, 12, 4, 16, 3), rings = I(1, 2), oculus = R(0.12, 0.3),
  } },
  -- a foiled circle alone, the margin's ornament
  { name = "foil", w = 2, roles = { ornament = 3 }, d = {
    period = W("early_english", 1, "geometric", 4, "perpendicular", 1, "flamboyant", 1),
    masonry = C("bar"), arch = C("none"), figure = C("foiled"),
    foils = W(3, 4, 4, 5, 5, 1, 6, 2, 8, 1), cusps = C(0), orders = I(1, 2),
  } },
}
M.TROLES = { headpiece = true, window = true, frame = true, rose = true, ornament = true, any = true }
local TRACERY = family {
  name = "tracery", noun = "tracery", what = "a window", heading = "A window of tracery",
  traits = M.TTRAITS, kinds = M.TKINDS, roles = M.TROLES,
  rolelist = { "headpiece", "window", "frame", "rose", "ornament", "any" },
  fallback = function(_, trait) return TCOMMON[trait] end,
  weight = function(k, role) return role == "any" and k.w or k.roles[role] end,
  tex = { traits = "ttraits", role = "trole", kind = "tkind", T = "TT", BY = "TBY", d = "tr@", ok = "tok" },
}
M.FAMILIES[3], M.FAMILIES.tracery = TRACERY, TRACERY
M.tdist, M.trolekinds, M.tsample = TRACERY.dist, TRACERY.rolekinds, TRACERY.sample

-- the rules of tracery (the report's T1-T8 and its period table); one broken is a bug
local LATE = { ogee = 1, dagger = 1, mouchettes = 1, soufflet = 1 }   -- curvilinear and later
local EARLY = { early_english = 1, geometric = 1, rayonnant = 1 }
local FOILED = { foiled = 1, soufflet = 1 }
function M.tviolations(w)
  local out = {}
  local function check(ok, what) if not ok then out[#out + 1] = what end end
  local early = EARLY[w.period]
  check(not early or not (LATE[w.arch] or LATE[w.figure]), "an ogee or a flowing figure before 1310")
  check(w.branch ~= "panel" or w.period == "perpendicular", "panel tracery outside the Perpendicular")
  check(w.figure ~= "triangle" or w.period ~= "perpendicular", "a spherical triangle in the Perpendicular")
  check(w.arch ~= "fourcentered" or w.period == "perpendicular" or w.period == "flamboyant", "a four-centered arch before 1350")
  check(w.masonry ~= "plate" or w.period == "early_english", "plate tracery after 1250")
  check((w.lights == 0) == (w.kind == "rose" or w.kind == "foil"), "lights on a rose or a foil, or a window without")
  check((w.arch == "none") == (w.kind == "rose" or w.kind == "foil"), "a rose or a foil with an arch, or a window without one")
  check(w.branch ~= "none" or w.depth == 0, "sub-arches without the construction")
  check(w.lights < 2 or w.depth <= math.floor(math.log(w.lights, 2)), "more sub-arches than lights")
  check(w.branch == "subarch" or w.depth == 0 and w.setdown == 0, "sub-arches set down under another head")
  check(w.figure == "none" or w.branch == "subarch" or w.branch == "screen" or w.kind == "foil", "a head figure with no sub-arches to sit on")
  check(w.branch ~= "screen" or w.kind == "headpiece", "a screen of lights that is not a headpiece")
  check((w.branch ~= "reticulated" and w.branch ~= "flowing") or w.period == "curvilinear" or w.period == "flamboyant",
    "reticulated or flowing tracery outside the curvilinear and flamboyant")
  check((w.foils > 0) == (FOILED[w.figure] ~= nil or (w.figure == "triangle" and w.foils == 3)), "foils without a foiled figure, or one without foils")
  check(w.foils == 0 or w.foils >= 3, "fewer than three foils")
  check((w.spokes > 0) == (w.kind == "rose"), "spokes on something not a rose, or a rose without")
  check(w.kind ~= "rose" or (w.rings > 0 and w.oculus > 0), "a rose without rings or an eye")
  check(w.accent ~= "stops" or w.hood == "stops", "copper on hood stops that are not there")
  check(w.arch ~= "round" or w.excess == 0.5, "a round arch with an excess other than a half")
  check(w.arch ~= "equilateral" or w.excess == 1, "an equilateral arch with an excess other than one")
  check(w.arch ~= "lancet" or w.excess > 1, "a lancet with its centers inside the span")
  check(w.arch ~= "drop" or (w.excess < 1 and w.excess > 0.5), "a drop arch with its centers outside the span")
  local shouldered = w.arch == "fourcentered" or (w.kind == "headpiece" and w.arch == "ogee")
  check(not shouldered or (w.rise > 0 and w.shoulder > 0), "a four-centered or depressed arch without rise or shoulders")
  check(shouldered or (w.rise == 0 and w.shoulder == 0), "rise or shoulders on an arch not four-centered")
  check((w.arch == "ogee") == (w.ogee > 0), "an ogee without its reversal, or a reversal on another arch")
  check(w.transoms == 0 or w.period == "perpendicular", "transoms outside the Perpendicular")
  check(w.kind ~= "foil" or w.figure == "foiled", "a foil that is not foiled")
  return out
end
TRACERY.violations = M.tviolations

-- a window in words: "a geometric window of three lights under a sexfoil, the lights
-- trefoiled, in two orders under a hood mold ending in stops"
local PERIODW = { early_english = "Early English", geometric = "geometric", curvilinear = "curvilinear",
  perpendicular = "Perpendicular", rayonnant = "rayonnant", flamboyant = "flamboyant" }
local ARCHW = { round = "round", segmental = "segmental", drop = "drop", equilateral = "equilateral", lancet = "lancet",
  fourcentered = "four-centered", ogee = "ogee" }
local FOILW = { [3] = "trefoil", [4] = "quatrefoil", [5] = "cinquefoil", [6] = "sexfoil", [8] = "multifoil" }
local FIGUREW = { oculus = "an oculus", triangle = "a spherical triangle", dagger = "a dagger",
  mouchettes = "a pair of mouchettes", soufflet = "a soufflet" }
local CUSPW = { [1] = "cusped", [2] = "trefoiled", [3] = "trefoiled", [4] = "cinquefoiled", [5] = "cinquefoiled" }
local function foilw(w)
  local name = FOILW[w.foils] or n_(w.foils) .. "-foiled circle"
  if w.foilshape == "pointed" then name = "pointed " .. name end
  return a_(name)
end
local function an_(word) return (word:match("^[aeiouAEIOU]") and "an " or "a ") .. word end
function M.tdescribe(w)
  local s
  local period = PERIODW[w.period]
  if w.kind == "foil" then
    s = foilw(w) .. " in the " .. period .. " manner"
  elseif w.kind == "rose" then
    s = an_(period .. " rose of " .. n_(w.spokes) .. " spokes") .. (w.rings > 1 and " in two rings" or "")
      .. " round " .. (w.oculus > 0.22 and "a wide eye" or "a small eye")
  else
    local arcade = w.kind == "arcade"
    local what = w.kind == "headpiece" and "headpiece" or arcade and "arcade" or "window"
    s = an_(period .. " " .. what .. " of " .. n_(w.lights) .. (arcade and " bays" or w.lights == 1 and " light" or " lights"))
    if w.figure == "foiled" then s = s .. " under " .. foilw(w)
    elseif FIGUREW[w.figure] then s = s .. " under " .. FIGUREW[w.figure]
    elseif w.branch == "Y" then s = s .. ", the mullions forking in a Y"
    elseif w.branch == "intersecting" then s = s .. ", the mullions crossing in the head"
    elseif w.branch == "panel" then s = s .. " paneled to the arch"
    elseif w.branch == "reticulated" then s = s .. ", the head reticulated"
    elseif w.branch == "flowing" then s = s .. ", mouchettes flowing in the head" end
    if w.branch == "screen" and w.figure ~= "none" then s = s .. " between the heads" end
    s = s .. ", in " .. (arcade and ARCHW[w.arch] .. " arches" or an_(ARCHW[w.arch] .. " arch"))
    if w.masonry == "plate" then s = s .. " cut through the slab" end
    if w.transoms > 0 then s = s .. " crossed by " .. (w.transoms == 1 and "a transom" or "two transoms") end
  end
  if w.orders > 1 then s = s .. " of " .. n_(w.orders) .. " orders" end
  if w.hood == "stops" then s = s .. " with a hood mold ending in stops"
  elseif w.hood == "plain" then s = s .. " with a hood mold" end
  if w.cusps > 0 and w.kind ~= "rose" and w.kind ~= "foil" then
    s = s .. ", the " .. (w.kind == "arcade" and "bays" or "lights") .. " " .. CUSPW[w.cusps]
  end
  if w.spandrel == "foliage" then s = s .. ", foliage in the spandrels"
  elseif w.spandrel == "trefoil" then s = s .. ", trefoils in the spandrels"
  elseif w.spandrel == "dagger" then s = s .. ", daggers in the spandrels" end
  s = s .. "."
  return s:sub(1, 1):upper() .. s:sub(2)
end
TRACERY.describe = M.tdescribe

-- ---------------------------------------------------------------- shells
-- A shell (board #5335, the shells report's part A) is sampled as a visitor is: its kind
-- first (an ammonite, a scallop, a whelk ...), which fixes its group, then the traits the
-- report gives that kind, each a constant where the kind has no such thing. Three groups:
-- planispirals coil flat and are seen from the side, down the axis (ammonites, the
-- nautilus); bivalves are drawn from the outline of one valve; gastropods are the sea
-- snails' empty shells, Raup's coiled tube with a spire, but for the cowrie, whose spire is
-- hidden and which is drawn from its outline too. The coil is Raup's (1966), its ring
-- placed as Okabe and Yoshimura place it (2017): expansion W (how many times the tube
-- widens in a turn), umbilicus D (the tube's inner edge over its outer, from the axis),
-- spire T (how far the tube slides along the axis in a turn, for its distance from it) and
-- aperture S (the mouth's height for its width); a shell without a coil has them all 0.
-- size is the real shell's in mm, its longest extent; ground the wash it is painted in;
-- preservation what shows of its surface: the shell, a mold (an ammonite whose shell has
-- worn away, its septa's suture lines showing), pyrite or nacre (both in the copper).
do
  M.SHTRAITS = {
    "kind", "group", "size", "tone", "ground", "pattern", "contrast", "view", "preservation",
    -- the coil: an ammonite's involution (how much each whorl hides the one before) first,
    -- since its W and D go together
    "involution", "whorls", "expansion", "umbilicus", "spire", "aperture", "hand",
    -- the surface: ribs (a whorl's, or a valve's from its beak), spiral cords, concentric
    -- ridges or layers
    "sculpture", "ribs", "cords", "ridges",
    -- an ammonite's keel, the suture lines of its septa on a mold, a broken last whorl
    "keel", "septa", "broken",
    -- an outline's width for its length (a valve's, a cowrie's), the beak's place along the
    -- hinge (0 at one end, 0.5 in the middle), a scallop's ears, how domed a valve is
    "aspect", "beak", "ears", "inflation",
    -- a gastropod's shoulder, how deep its suture runs, the canal, the lip, columella folds
    "shoulder", "suture", "canal", "lip", "folds",
  }
  -- what a shell does not have: every trait a constant (no draw)
  local SHNONE = {
    pattern = C("none"), preservation = C("shell"),
    involution = C("none"), whorls = C(0), expansion = C(0), umbilicus = C(0), spire = C(0), aperture = C(0), hand = C("none"),
    ribs = C(0), cords = C(0), ridges = C(0), keel = C("none"), septa = C("none"), broken = C(0),
    aspect = C(0), beak = C(0), ears = C("none"), inflation = C(0),
    shoulder = C("none"), suture = C(0), canal = C("none"), lip = C("none"), folds = C(0),
  }
  -- a pattern's strength, where there is one
  local CONTRAST = BY("pattern", { none = C(0), _ = R(0.35, 1) })
  -- each group's own, under its kinds' tables
  local SHGROUP = {
    planispiral = { tone = R(0.28, 0.42), contrast = CONTRAST, view = C("flank"), spire = C(0) },
    bivalve = { tone = R(0.28, 0.42), contrast = CONTRAST, view = W("outside", 3, "inside", 1), inflation = R(0.2, 0.6) },
    gastropod = { tone = R(0.28, 0.42), contrast = CONTRAST, view = W("mouth", 3, "back", 1), hand = C("dextral"),
      umbilicus = R(0, 0.06), suture = R(0.15, 0.7) },
  }
  -- kinds: group; w, the weight among all kinds and in its group's role; roles, the weight
  -- in the others (margin: lying on the margin's ground, the shapes that read small first;
  -- ornament: alone, as an ornament). A coil's whorls touch when W D <= 1 (McGhee 2015), so
  -- an ammonite's wide umbilicus comes with a slowly widening coil
  M.SHKINDS = {
    -- an ammonite: ribs simple, forking or knobbed; a mold shows the septa's suture lines,
    -- the frilled (ammonitic) ones of the Jurassic and Cretaceous most often
    { name = "ammonite", group = "planispiral", w = 3, roles = { margin = 3, ornament = 2 }, d = {
      size = R(30, 180), ground = W("ink", 3, "pale", 2),
      preservation = W("shell", 3, "mold", 3, "pyrite", 1, "nacre", 1),
      -- evolute: many slowly widening whorls, a wide umbilicus; involute: few, fast, hiding
      -- the ones before; W D stays under 1 in each
      involution = W("evolute", 3, "intermediate", 3, "involute", 2),
      whorls = BY("involution", { evolute = R(5, 8), intermediate = R(4, 6), _ = R(3.5, 5) }),
      expansion = BY("involution", { evolute = R(1.5, 1.9), intermediate = R(1.8, 2.3), _ = R(2.2, 3) }),
      umbilicus = BY("involution", { evolute = R(0.3, 0.45), intermediate = R(0.15, 0.3), _ = R(0.02, 0.15) }),
      sculpture = W("ribs", 4, "branching", 3, "tubercles", 2, "smooth", 1),
      ribs = BY("sculpture", { smooth = C(0), _ = I(18, 48) }),
      keel = W("none", 3, "keel", 2, "grooved", 1),
      septa = BY("preservation", { mold = W("ammonitic", 3, "ceratitic", 1, "goniatitic", 1), _ = C("none") }),
      broken = W(0, 4, 1, 1),
    } },
    -- the chambered nautilus: one wide whorl hiding the rest (W 3.4 and D 0.04, Raup 1967),
    -- a dimple at the center, flame stripes on its older half
    { name = "nautilus", group = "planispiral", w = 1, roles = { margin = 1, ornament = 2 }, d = {
      size = R(140, 220), ground = W("pale", 3, "ink", 1), pattern = C("flammules"),
      preservation = W("shell", 6, "nacre", 1),
      involution = C("involute"), whorls = R(3, 3.6), expansion = R(3.1, 3.6), umbilicus = R(0.02, 0.06),
      sculpture = C("smooth"),
    } },
    -- a scallop: a fan on a straight hinge with ears, strong ribs from the beak at its middle
    { name = "scallop", group = "bivalve", w = 3, roles = { margin = 3, ornament = 3 }, d = {
      size = R(40, 120), ground = W("ink", 3, "pale", 2, "dark", 1),
      pattern = W("none", 3, "bands", 1, "rays", 1, "zigzags", 1, "dots", 1),
      sculpture = C("ribs"), ribs = I(12, 24), aspect = R(0.9, 1.05), beak = C(0.5),
      ears = W("equal", 2, "unequal", 3),
    } },
    -- a cockle: round and domed, crowded ribs scalloping its edge
    { name = "cockle", group = "bivalve", w = 2, roles = { margin = 2 }, d = {
      size = R(25, 60), ground = W("pale", 3, "ink", 2), pattern = W("none", 3, "bands", 1),
      sculpture = C("ribs"), ribs = I(18, 34), aspect = R(0.85, 1), beak = R(0.42, 0.5), inflation = R(0.5, 0.8),
    } },
    -- a mussel: a dark wedge with its beak at the narrow end, nacre inside
    { name = "mussel", group = "bivalve", w = 2, roles = { margin = 1 }, d = {
      size = R(40, 100), ground = W("dark", 3, "ink", 1), sculpture = C("smooth"),
      aspect = R(0.4, 0.55), beak = R(0, 0.06),
    } },
    -- a clam: an oval with its beak off center, concentric ridges, often rayed
    { name = "clam", group = "bivalve", w = 2, roles = { margin = 1 }, d = {
      size = R(25, 70), ground = W("pale", 3, "ink", 2), pattern = W("none", 2, "rays", 2, "zigzags", 1),
      sculpture = W("ridges", 3, "smooth", 1), ridges = BY("sculpture", { ridges = I(6, 14), _ = C(0) }),
      aspect = R(0.65, 0.82), beak = R(0.25, 0.4),
    } },
    -- an oyster: lumpy, in layers, as often lying open on its pale inside as not
    { name = "oyster", group = "bivalve", w = 1, roles = { margin = 1 }, d = {
      size = R(50, 130), ground = W("pale", 2, "ink", 2), sculpture = C("layers"), ridges = I(4, 8),
      aspect = R(0.7, 1.2), beak = R(0.05, 0.25), view = W("outside", 1, "inside", 1),
    } },
    -- a whelk: a spindle drawn out into a canal, columella folds now and then (as a tulip
    -- shell's); the lightning whelk coils to the left
    { name = "whelk", group = "gastropod", w = 2, roles = { margin = 2, ornament = 1 }, d = {
      size = R(50, 180), ground = W("pale", 2, "ink", 2), pattern = W("none", 2, "bands", 2, "flammules", 2),
      whorls = R(5, 8), expansion = R(1.7, 2.1), spire = R(2, 3.2), aperture = R(1.3, 1.6),
      hand = W("dextral", 49, "sinistral", 1),
      sculpture = W("ribs", 2, "cords", 2, "cancellate", 1, "nodes", 2, "smooth", 1),
      ribs = BY("sculpture", { ribs = I(8, 14), cancellate = I(8, 14), nodes = I(7, 11), _ = C(0) }),
      cords = BY("sculpture", { cords = I(3, 7), cancellate = I(3, 6), _ = C(0) }),
      shoulder = W("none", 2, "rounded", 2, "angular", 2), canal = W("long", 2, "short", 2),
      lip = W("thick", 2, "plain", 2, "flared", 1), folds = W(0, 3, 2, 1, 3, 1),
    } },
    -- a turret shell: a tall screw of many slowly widening whorls (a high spire goes with a
    -- low W, Okabe and Yoshimura 2017); the triphorids coil to the left
    { name = "turret", group = "gastropod", w = 2, roles = { margin = 1 }, d = {
      size = R(25, 90), ground = W("ink", 2, "pale", 2, "dark", 1), pattern = W("none", 2, "bands", 1, "flammules", 1),
      whorls = R(9, 15), expansion = R(1.15, 1.3), spire = R(3, 5), aperture = R(0.95, 1.2),
      hand = W("dextral", 49, "sinistral", 1),
      sculpture = W("cords", 3, "ribs", 2, "cancellate", 1, "smooth", 1),
      ribs = BY("sculpture", { ribs = I(14, 24), cancellate = I(14, 22), _ = C(0) }),
      cords = BY("sculpture", { cords = I(2, 5), cancellate = I(2, 4), _ = C(0) }),
      shoulder = W("none", 3, "angular", 1), lip = C("plain"),
    } },
    -- a topshell: a cone on a flat base (a 60-70 degree apex is T about 2), now and then worn
    -- down to its nacre
    { name = "topshell", group = "gastropod", w = 2, roles = { margin = 1 }, d = {
      size = R(12, 35), ground = W("ink", 2, "pale", 1), pattern = W("flammules", 2, "bands", 1, "dots", 1, "none", 1),
      preservation = W("shell", 3, "nacre", 1),
      whorls = R(6, 9), expansion = R(1.5, 1.7), spire = R(1.8, 2.4), aperture = R(0.8, 0.95), umbilicus = R(0, 0.06),
      sculpture = W("cords", 3, "smooth", 2, "nodes", 1),
      ribs = BY("sculpture", { nodes = I(10, 16), _ = C(0) }), cords = BY("sculpture", { cords = I(3, 6), _ = C(0) }),
      shoulder = W("none", 3, "angular", 1), lip = C("plain"),
    } },
    -- a cowrie: a glossy egg, seen from above or from beneath with its toothed slit
    { name = "cowrie", group = "gastropod", w = 2, roles = { margin = 2, ornament = 1 }, d = {
      size = R(15, 80), ground = W("ink", 2, "dark", 1, "pale", 1), pattern = W("dots", 3, "bands", 1, "none", 1),
      view = W("back", 3, "mouth", 1), umbilicus = C(0), suture = C(0), sculpture = C("smooth"),
      aspect = R(0.55, 0.72), lip = C("toothed"),
    } },
  }
  M.SHROLES = { margin = true, ornament = true, planispiral = true, bivalve = true, gastropod = true, any = true }
  local SHELL = family {
    name = "shell", noun = "shell", what = "a shell", heading = "A shell",
    traits = M.SHTRAITS, kinds = M.SHKINDS, derived = "group", roles = M.SHROLES,
    rolelist = { "margin", "ornament", "planispiral", "bivalve", "gastropod", "any" },
    fallback = function(k, trait) return SHGROUP[k.group][trait] or SHNONE[trait] end,
    weight = function(k, role) if role == "any" or role == k.group then return k.w end return k.roles[role] end,
    -- a shell's values (M.values) are what its kind or group draws, never SHNONE's placeholders
    own = function(k, trait) return k.d[trait] or SHGROUP[k.group][trait] end,
    tex = { traits = "ktraits", role = "krole", kind = "kkind", T = "KT", BY = "KBY", d = "sh@", ok = "kok" },
  }
  M.FAMILIES[4], M.FAMILIES.shell = SHELL, SHELL
  M.shdist, M.shrolekinds, M.shsample = SHELL.dist, SHELL.rolekinds, SHELL.sample

  -- the rules of shells (the report's A6); one broken is a bug in the tables
  local RIBBED = { ribs = 1, branching = 1, tubercles = 1, cancellate = 1, nodes = 1 }
  local NACREOUS = { oyster = 1, mussel = 1 }                  -- a valve whose inside is nacre
  function M.shviolations(s)
    local out = {}
    local function check(ok, what) if not ok then out[#out + 1] = what end end
    local coiled = s.whorls > 0
    check(not coiled or s.group ~= "bivalve", "a coil on a bivalve")
    check(not coiled or (s.expansion > 1 and s.umbilicus >= 0 and s.umbilicus < 1 and s.spire >= 0),
      "a coil outside Raup's bounds (W > 1, 0 <= D < 1, T >= 0)")
    check(not coiled or s.expansion * s.umbilicus <= 1, "whorls that do not touch (W D > 1)")
    -- along the axis too: a ring sits T y0 (1 - 1/W) above the next one round, and each
    -- reaches S of its size up and down
    local y0 = coiled and (1 + s.umbilicus) / (1 - s.umbilicus) or 0
    check(s.group ~= "gastropod" or not coiled or s.spire * y0 * (s.expansion - 1) <= s.aperture * (s.expansion + 1),
      "whorls that part along the axis (T y0 (W - 1) > S (W + 1))")
    check(coiled or (s.expansion == 0 and s.umbilicus == 0 and s.spire == 0), "a coil's numbers on a shell without a coil")
    check(s.group ~= "planispiral" or (coiled and s.spire == 0), "a planispiral with a spire, or without a coil")
    check((s.involution ~= "none") == (s.group == "planispiral"), "an involution on a shell that is no planispiral, or one without")
    check((s.aperture > 0) == (s.group == "gastropod" and coiled), "a mouth's shape on a shell that is no coiled gastropod, or one without")
    check((s.suture > 0) == (s.group == "gastropod" and coiled), "a suture's depth on a shell that is no coiled gastropod, or one without")
    check(s.shoulder == "none" or (s.group == "gastropod" and coiled), "a shoulder on a shell that is no coiled gastropod")
    check((s.hand == "none") == (s.group ~= "gastropod"), "a handedness on a shell that shows none, or a gastropod without one")
    check(s.hand ~= "sinistral" or s.kind == "whelk" or s.kind == "turret", "a sinistral shell other than a whelk or a turret")
    check(s.canal == "none" or s.kind == "whelk", "a canal on a shell that is no spindle")
    check((s.lip == "toothed") == (s.kind == "cowrie"), "a toothed slit on a shell that is no cowrie, or a cowrie without one")
    check(s.lip == "none" or s.group == "gastropod", "a lip on a shell that is no gastropod")
    check(s.folds == 0 or s.kind == "whelk", "columella folds on a shell that is no spindle")
    check((s.preservation ~= "pyrite" and s.preservation ~= "mold") or s.kind == "ammonite", "pyrite or a mold on a shell other than an ammonite")
    check(s.preservation ~= "nacre" or s.kind == "ammonite" or s.kind == "nautilus" or s.kind == "topshell",
      "nacre showing on a shell that has none to show")
    check((s.septa ~= "none") == (s.preservation == "mold"), "suture lines on a shell, or a mold without them")
    check((s.view == "flank") == (s.group == "planispiral"), "a planispiral seen other than from the side")
    check((s.view == "outside" or s.view == "inside") == (s.group == "bivalve"), "a valve's view on a shell that is no bivalve")
    check((s.view == "mouth" or s.view == "back") == (s.group == "gastropod"), "a gastropod's view on a shell that is no gastropod")
    check((s.ribs > 0) == (RIBBED[s.sculpture] ~= nil), "ribs counted on a shell that has none, or a ribbed shell without a count")
    check((s.cords > 0) == (s.sculpture == "cords" or s.sculpture == "cancellate"), "cords counted on a shell without them, or one with them uncounted")
    check((s.ridges > 0) == (s.sculpture == "ridges" or s.sculpture == "layers"), "ridges counted on a shell without them, or one with them uncounted")
    check(s.ridges == 0 or s.group == "bivalve", "concentric ridges on a shell that is no bivalve")
    check(s.ears == "none" or s.kind == "scallop", "ears on a shell that is no scallop")
    check(s.keel == "none" or s.kind == "ammonite", "a keel on a shell that is no ammonite")
    check(s.broken == 0 or s.group == "planispiral", "a broken whorl on a shell that is no planispiral")
    check((s.aspect > 0) == (s.group == "bivalve" or s.kind == "cowrie"), "an outline's aspect on a shell drawn from its coil, or an outline without one")
    check((s.beak == 0 and s.inflation == 0) or s.group == "bivalve", "a beak or a dome on a shell that is no bivalve")
    check((s.contrast > 0) == (s.pattern ~= "none"), "a pattern without strength, or strength without a pattern")
    return out
  end
  SHELL.violations = M.shviolations
  -- a shell in the copper: pyrite, nacre worn through, or a valve lying open on its nacre
  function M.shcopper(s)
    return s.preservation == "pyrite" or s.preservation == "nacre" or (s.view == "inside" and NACREOUS[s.kind] ~= nil)
  end

  -- a shell in words: "a pyritized ammonite with forking ribs and a keel, its last whorl
  -- broken", "a sinistral whelk of six whorls with a long canal, knobbed on its shoulder"
  local SHKINDW = { ammonite = "ammonite", nautilus = "chambered nautilus", scallop = "scallop", cockle = "cockle",
    mussel = "mussel", clam = "clam", oyster = "oyster", whelk = "whelk", turret = "turret shell", topshell = "topshell",
    cowrie = "cowrie" }
  local PATTERNW = { bands = "banded", rays = "rayed", flammules = "flame-striped", zigzags = "zigzag-marked", dots = "spotted" }
  local SEPTAW = { goniatitic = "zigzag", ceratitic = "saw-toothed", ammonitic = "frilled" }
  -- a count in words, to ninety-nine (an ammonite has up to 48 ribs a whorl)
  local TENS = { [2] = "twenty", [3] = "thirty", [4] = "forty", [5] = "fifty", [6] = "sixty", [7] = "seventy",
    [8] = "eighty", [9] = "ninety" }
  local function count_(k)
    if k < 20 or k > 99 then return n_(k) end
    return TENS[k // 10] .. (k % 10 > 0 and "-" .. NUM[k % 10] or "")
  end
  -- the head ("a sinistral banded whelk"), what it is made of ("of seven whorls"), what it has
  -- ("with a long canal and spiral cords"), then the rest, each after a comma ("latticed",
  -- "its lip thickened")
  function M.shdescribe(s)
    local adj = {}
    if s.preservation == "pyrite" then adj[#adj + 1] = "pyritized" end
    if s.hand == "sinistral" then adj[#adj + 1] = "sinistral" end
    if PATTERNW[s.pattern] and s.kind ~= "nautilus" then adj[#adj + 1] = PATTERNW[s.pattern] end
    adj[#adj + 1] = SHKINDW[s.kind] .. (s.preservation == "mold" and " mold" or "")
    local of, has, rest = nil, {}, {}
    local function with(what) has[#has + 1] = what end
    local function also(what) rest[#rest + 1] = what end
    if s.group == "planispiral" then
      if s.sculpture == "ribs" then with(count_(s.ribs) .. " ribs a whorl")
      elseif s.sculpture == "branching" then with("forking ribs")
      elseif s.sculpture == "tubercles" then with("knobbed ribs") end
      if s.keel == "keel" then with("a keel") elseif s.keel == "grooved" then with("a keel between two grooves") end
      if s.kind == "nautilus" then with("flame stripes") end
      if s.septa ~= "none" then also("showing its " .. SEPTAW[s.septa] .. " suture lines") end
      if s.preservation == "nacre" then also("worn to its nacre") end
      if s.broken == 1 then also("its last whorl broken") end
    elseif s.group == "bivalve" then
      if s.ribs > 0 then of = "of " .. count_(s.ribs) .. " ribs" end
      if s.ears == "unequal" then with("unequal ears") elseif s.ears == "equal" then with("ears") end
      if s.sculpture == "ridges" then with(count_(s.ridges) .. " concentric ridges")
      elseif s.sculpture == "layers" then of = "in " .. count_(s.ridges) .. " layers" end
      if s.view == "inside" then also(NACREOUS[s.kind] and "lying open on its nacre" or "lying open") end
    else
      if s.whorls > 0 then of = "of " .. count_(floor(s.whorls + 0.5)) .. " whorls" end
      if s.canal ~= "none" then with("a " .. s.canal .. " canal") end
      if s.sculpture == "cords" then with("spiral cords") end
      local on = s.shoulder == "angular" and " on its angular shoulder" or ""
      if s.sculpture == "ribs" then also("ribbed" .. on)
      elseif s.sculpture == "cancellate" then also("latticed")
      elseif s.sculpture == "nodes" then also("knobbed" .. (on ~= "" and on or " on its shoulder")) end
      if s.lip == "flared" then also("its lip flared") elseif s.lip == "thick" then also("its lip thickened") end
      if s.preservation == "nacre" then also("worn to its nacre") end
      if s.kind == "cowrie" then also(s.view == "mouth" and "seen from beneath, its slit toothed" or "seen from above") end
    end
    local text = an_(concat(adj, " "))
    if of then text = text .. " " .. of end
    if #has > 0 then
      text = text .. " with " .. (#has == 1 and has[1] or concat(has, ", ", 1, #has - 1) .. " and " .. has[#has])
    end
    if #rest > 0 then text = text .. ", " .. concat(rest, ", ") end
    text = text .. "."
    return text:sub(1, 1):upper() .. text:sub(2)
  end
  SHELL.describe = M.shdescribe

  -- the document's cabinet (docseed as for the pool): four shells of role margin from a
  -- stream of their own, no kind twice, more than one group, at most one in the copper, so
  -- a page that lies one to three of them on its ground keeps the margin's copper sparse
  local cabinets = {}
  function M.cabinet(docseed)
    docseed = docseed or 0
    if cabinets[docseed] then return cabinets[docseed] end
    local rng = ink.rng(docseed * 104729 + 701)
    local cab, used, groups, copper, tries = {}, {}, {}, false, 0
    while #cab < 4 do
      local s = M.shsample(1 + floor(rng.u() * 2147483645), "margin")
      local ok = not used[s.kind] and not (copper and M.shcopper(s))
      if ok and #cab == 3 then
        local n = 0
        for _ in pairs(groups) do n = n + 1 end
        if n == 1 and groups[s.group] then ok = false end
      end
      if ok then
        used[s.kind], groups[s.group], copper = true, true, copper or M.shcopper(s)
        cab[#cab + 1] = s
      end
      tries = tries + 1
      assert(tries < 10000, "florilegium-species: no cabinet of shells for the document seed " .. docseed)
    end
    cabinets[docseed] = cab
    return cab
  end
end

-- ---------------------------------------------------------------- as TeX
-- the tables for tikzlibraryflorilegium.code.tex: one macro per plan that draws its
-- traits in M.TRAITS order, and one per role that draws a plan
local function key(v) return tostring(v) end
local function sorted_keys(t)
  local ks = {}
  for k in pairs(t) do ks[#ks + 1] = k end
  table.sort(ks)
  return ks
end
-- the TeX for a distribution; a BY map's entries become macros \flo@d@<name>@<value>,
-- appended to out; by is the family's BY macro, which looks the earlier trait up among its own
local function tex_dist(d, name, out, by)
  local kind = d[1]
  if kind == "c" then return "\\flo@C{" .. key(d[2]) .. "}"
  elseif kind == "i" then return fmt("\\flo@I{%d}{%d}", d[2], d[3])
  elseif kind == "r" then return "\\flo@R{" .. key(d[2]) .. "}{" .. key(d[3] - d[2]) .. "}"
  elseif kind == "w" then
    local parts, total = {}, 0
    for i = 2, #d, 2 do total = total + d[i + 1] parts[#parts + 1] = "{" .. key(d[i]) .. "}{" .. total .. "}" end
    return "\\flo@W{" .. total .. "}{" .. concat(parts) .. "}"
  elseif kind == "by" then
    for _, k in ipairs(sorted_keys(d[3])) do
      local sub = name .. "@" .. k
      local code = tex_dist(d[3][k], sub, out, by)
      out[#out + 1] = "\\expandafter\\def\\csname flo@d@" .. sub .. "\\endcsname{" .. code .. "}"
    end
    return "\\flo@" .. by .. "{" .. d[2] .. "}{" .. name .. "}"
  end
  error("florilegium: unknown distribution " .. tostring(kind))
end
-- a family's tables: \flo@<traits>, \flo@<role>@<role> draws a kind, \flo@<kind>@<name> its
-- traits with \flo@<T>; a kind's name is a role too unless a role has that name
local function tex_family(f, out)
  local x = f.tex
  out[#out + 1] = "\\def\\flo@" .. x.traits .. "{" .. concat(f.traits, ",") .. "}"
  local roles = {}
  for _, r in ipairs(f.rolelist) do roles[#roles + 1] = r end
  for _, k in ipairs(f.kinds) do if not f.roles[k.name] then roles[#roles + 1] = k.name end end
  for _, role in ipairs(roles) do
    out[#out + 1] = "\\expandafter\\def\\csname flo@" .. x.role .. "@" .. role .. "\\endcsname{"
      .. tex_dist(f.rolekinds(role), x.role, out, x.BY) .. "}"
  end
  for _, k in ipairs(f.kinds) do
    local body = {}
    for i = 2, #f.traits do
      local t = f.traits[i]
      body[#body + 1] = "\\flo@" .. x.T .. "{" .. t .. "}{" .. tex_dist(f.dist(k.name, t), x.d .. k.name .. "@" .. t, out, x.BY) .. "}"
    end
    out[#out + 1] = "\\expandafter\\def\\csname flo@" .. x.kind .. "@" .. k.name .. "\\endcsname{%\n  "
      .. concat(body, "%\n  ") .. "}"
  end
end
function M.tex()
  local out = {
    "%% tikzlibraryflorilegium.tables.code.tex -- generated by tools/tikztables.lua from",
    "%% florilegium-species.lua; do not edit. Copyright (c) 2026 Kevin Raymond. MIT License.",
  }
  for _, f in ipairs(M.FAMILIES) do tex_family(f, out) end
  -- a value the plan's kind of plant cannot draw (M.refused): the fern's plans; per trait,
  -- the names only the fern draws and the flowering plant's; the frond's own names
  local fernplans = {}
  for _, p in ipairs(M.PLANS) do if p.clade == "fern" then fernplans[#fernplans + 1] = p.name end end
  out[#out + 1] = "\\def\\flo@fernplans{," .. concat(fernplans, ",") .. ",}"
  local fernonly, frond = M.kindvalues()
  for _, x in ipairs(fernonly) do
    out[#out + 1] = fmt("\\expandafter\\def\\csname flo@fernonly@%s\\endcsname{{%s}{%s}}", x[1], concat(x[2], ","), concat(x[3], ","))
  end
  for _, x in ipairs(frond) do
    out[#out + 1] = fmt("\\expandafter\\def\\csname flo@fernok@%s\\endcsname{%s}", x[1], concat(x[2], ","))
  end
  -- what a fixed trait may be (\florilegiumspecies[...], \florilegiumvisitor[...]): its
  -- names, the range of a number (empty if none), 1 if that number is real
  for _, f in ipairs(M.FAMILIES) do
    local vals = M.values(f)
    for _, t in ipairs(f.traits) do
      local ok = vals[t]
      if ok then
        local names = {}
        for name in pairs(ok.names) do names[#names + 1] = name end
        table.sort(names)
        out[#out + 1] = fmt("\\expandafter\\def\\csname flo@%s@%s\\endcsname{{%s}{%s}{%s}{%d}}", f.tex.ok, t,
          concat(names, ","), ok.lo and key(ok.lo) or "", ok.hi and key(ok.hi) or "", ok.real and 1 or 0)
      end
    end
  end
  return concat(out, "\n") .. "\n"
end

-- ---------------------------------------------------------------- the traits, as Markdown
-- docs/traits.md: every trait in the order it is drawn and what it may be fixed to
function M.traitsdoc()
  local out = {
    "# Traits",
    "",
    "The traits a species, a visitor, a window of tracery and a shell are sampled with, in the order",
    "they are drawn, and what each may be fixed to: one of the names listed, or a number in the range",
    "given (a whole number where it says so). Fix them with `\\florilegiumspecies[...]`,",
    "`\\florilegiumvisitor[...]`, `\\florilegiumtracery[...]`, `\\florilegiumshell[...]` or a pic's `traits`",
    "key; [the TikZ library](tikz.md#a-genome-of-your-own) shows how. `clade` and `group` follow from",
    "the plan and the kind and are not fixed themselves.",
    "",
    "This page is written by `tools/tikztables.lua` from `florilegium-species.lua`.",
  }
  for _, f in ipairs(M.FAMILIES) do
    local vals = M.values(f)
    out[#out + 1] = ""
    out[#out + 1] = "## " .. f.heading
    out[#out + 1] = ""
    out[#out + 1] = "| trait | what it may be |"
    out[#out + 1] = "|---|---|"
    for _, t in ipairs(f.traits) do
      local ok = vals[t]
      if ok then
        local names = {}
        for name in pairs(ok.names) do names[#names + 1] = "`" .. name .. "`" end
        table.sort(names)
        local range = ok.lo and fmt("%s from %g to %g", ok.real and "a number" or "a whole number", ok.lo, ok.hi)
        local what = concat(names, ", ")
        if range then what = what ~= "" and what .. ", or " .. range or range end
        out[#out + 1] = fmt("| `%s` | %s |", t, what)
      end
    end
  end
  return concat(out, "\n") .. "\n"
end

return M
