# SDK: Batches: the matrix

> A piece's matrix says which versions of it are made. Each version is a **combo**: one value per dimension and, when the piece has slots, a structure and one candidate per slot of it. Every combo renders in the piece's one format.

Source: https://allyhub.com/docs/reference/sdk/batches · AllyHub 0.10.0
Index of all docs: https://allyhub.com/llms.txt

## Dimensions

`matrix.dims` are dimensions and their values, crossed in full: `{ lang: ["en", "zh-cn"], audience: ["dev", "ops"] }` makes four combos.

- `lang` is the one dimension AllyHub reads: it picks the file of each item's script in that language and `assets/text/<lang>.json`, the first value being the default language. Its values are lowercase language tags (`en`, `zh-cn`). Without `lang`, a piece's languages are its script's and the shared text's, `allyhub.config.ts`'s `locales` first.
- Other dimensions are the piece's: its parts function reads them from `ctx.combo`.
- A name starts with a lowercase letter (then letters, digits, `_`, `-`); a value is letters, digits, `.`, `_`, `-`, each listed once. `size`, `format`, `piece`, `output`, `token`, `structure` and `id` name no dimension or slot. A wrong name or value is AK-M001.
- A combo's **key** is its names sorted, each `name=value`, joined with commas: `audience=dev,lang=en` (`default` when there are none). It filters commands' `--combo` (`--combo lang=zh-cn`); the rendered files carry its values, after the name of the piece's folder (`.allyhub/out/launch/launch.dev.en.mp4`).

## Slots

An ad is a structure of **slots** (a hook, a demo, a call to action), each with **candidates**. The matrix chooses which slot combinations to make; each chosen one is crossed with every combo of the dimensions.

```ts file=ads/tidyform/tidyform.ts

  format: "9x16",
  maxDuration: 30,
  matrix: {
    dims: { lang: ["en"] },
    slots: {
      hook: [{ name: "price", tags: ["price"] }, "reaction", "question"],
      demo: { pool: "./pool/demos" },
      cta: ["trial", { name: "sale", tags: ["discount"] }],
    },
    structures: { classic: ["hook", "demo", "cta"], short: ["hook", "cta"] },
    pick: 6,
    seed: 1,
    differ: { slots: 2, first: ["hook"] },
    rules: [{ if: { hook: "#price" }, require: { cta: "#discount" } }],
  },
  parts: ({ s, combo, pool }) => {
    const hook = part({
      key: "hook",
      speech: say(s(`ads.tidyform.hook.${combo["hook"] ?? ""}`)),
    });
    const cta = part({
      key: "cta",
      speech: say(s(`ads.tidyform.cta.${combo["cta"] ?? ""}`)),
    });
    if (combo["structure"] === "short") return [hook, cta];
    return [
      hook,
      part({ key: "demo", dur: 4, layers: [footage(pool("demo"))] }),
      cta,
    ];
  },
});
```

| Field | Type | Default | What it is |
| --- | --- | --- | --- |
| `slots` | `{ slot: candidates }` | none | Names, `{ name, tags }`, or a pool `{ pool, tags? }` ([below](#pools)) |
| `structures` | `{ name: slots[] }` | one structure of every slot, in order | Orders of slots. With it, `combo.structure` names a combo's structure. Every slot is in some structure |
| `pick` | 1 to 10000 | every combination the rules allow | How many slot combinations sampling chooses |
| `seed` | number or string | 1 | Decides between equally good choices |
| `differ` | `{ slots?, first? }` | none | Any two chosen combos differ in at least `slots` slots (another structure counts as one); `first`: their openings differ, the first n slots of each structure, or these slots |
| `rules` | `[{ if?, require?, exclude? }]` | none | Over slots, dimensions and `structure`; a value is a name, `#tag` or a list of either. When every `if` holds, every `require` must hold and no `exclude` may. Each has a `require` or an `exclude` |
| `combos` | `Combo[]` | none: sampled | The slot combinations to make, chosen by the agent ([below](#the-agents-own-combos)). Not with `pick` or `seed` |

- A rule's condition on a slot a combo's structure lacks never holds. A condition on a dimension is kept when the slot combinations are crossed with the dimensions: a crossing it rules out is not made.
- A candidate's tags are what `#tag` matches. A part's own `tags` are labels for people and tools; rules do not read them.

### Pools

`{ pool: "./pool/demos", tags? }` makes one candidate per media file (video, audio or picture) directly in the folder, named by the file's stem. The folder is relative to the piece's file (`/` first: from the project's root). `tags` go to every file; a file's `<stem>.meta.json` adds its own:

```json
{ "tags": ["inbox", "short"] }
```

`ctx.pool(slot)` is the file the slot picked in this combo, as a path from the project's root that `footage()` and `ctx.asset()` take. A pool outside the project, an empty pool, two files with one stem, or a stem that cannot be a name is AK-X001.

## Sampling

Without `combos`, sampling chooses `pick` slot combinations, the same for the same definition. Greedy, best first, it prefers combinations that:

1. keep `differ` against every earlier pick;
2. use the most candidates (and structures) no pick uses yet, so every candidate appears once when it can;
3. use the candidates used least so far;
4. make the most pairs of candidates not yet seen together;
5. differ most from the nearest earlier pick;
6. then the seed decides.

Each pick keeps a reason in a few words. Sampling looks at no more than 100,000 slot combinations before the rules; more is AK-X002.

## The agent's own combos

`combos` names the slot combinations to make, in order: each names `structure` when the piece declares structures, and one candidate per slot of it, never a dimension. Nothing is sampled.

```ts file=ads/chosen/chosen.ts

  format: "1x1",
  matrix: {
    dims: { lang: ["en", "zh-cn"] },
    slots: { hook: ["a", "b"], cta: ["trial", "sale"] },
    combos: [
      { hook: "a", cta: "trial" },
      { hook: "b", cta: "sale" },
    ],
  },
  parts: ({ combo }) => [
    part({ key: "hook", dur: 2, title: `Hook ${combo["hook"] ?? ""}` }),
    part({ key: "cta", dur: 2 }),
  ],
});
```

This makes `c01-en`, `c01-zh-cn`, `c02-en` and `c02-zh-cn`. Each combo is checked against the slots (AK-X001), the rules (AK-X002) and `differ` (AK-X004; the same combo twice too).

## Combo ids

- The chosen slot combinations are `c01`, `c02`, … in order (with as many digits as the count needs: `c001` when there are 100 or more). With more than one combo of the dimensions, an id adds their values: `c01-en`, `c01-zh-cn`.
- A piece with slots names its files by id (`.allyhub/out/launch/launch.c01-en.mp4`), and `--combo c03` names one.
- A piece with dimensions only has no ids: its combos are named by their keys.

## In the parts function

- `ctx.combo.<slot>` is the candidate's name, `ctx.combo.structure` the structure, `ctx.combo.<dimension>` the dimension's value.
- `ctx.pool(slot)` is a pool slot's file; a slot that is not a pool throws.
- A part whose `key` is a slot's name fills that slot; `part({ slot })` names the slot a part with another key fills.

**Each part renders once.** A rendered part is kept and reused in every combo that has the same part; the sound is mixed for each whole combo. So a part's layers read from their `ctx.combo` only the dimensions and their own part's slot: reading another slot's pick, or the structure, is AK-X005. Choose in the parts function and pass the result to the layer. A transition on a slot's part is rendered once per pair of parts it joins.

The check loads only a few combos that between them hold every candidate, and puts the others together from their parts: each combo's length against `maxDuration` (AK-X006), and as facts the speech's loudness at each join (`join-loudness`), the music's length (`music-length`) and the generated media each combo uses. `matrix-coverage` lists each candidate with the combos that use it.

## Rules

| Rule | What is wrong |
| --- | --- |
| AK-X001 | A slot, structure, rule, pool or combo names something that does not exist, or a combo lacks a slot of its structure |
| AK-X002 | The rules leave no combination to make (or the slots make more than sampling looks at), or rule out a combo `combos` names |
| AK-X004 | Two chosen combos are the same, or more alike than `differ` allows |
| AK-X005 | A part reads another slot's pick, so one render of it cannot serve every combo |
| AK-X006 | A combo is longer than its video's `maxDuration` |

## Commands

- `allyhub inspect combos` prints each piece's slots, rules, the chosen combos with why, and what rendering them costs in part renders, without a browser.
- `allyhub render <piece> --type csv` writes the batch's table of ads, `<piece>.ads.csv`: a row per ad with its combo, picks, length, file, name and the generated media it uses.
- `allyhub render` renders every combo; `--combo` narrows it.
