SHC vNext QR proof of concept

cycle-log: wire format

Rendered from codecs/cycle-log/FORMAT.md in the repository.

This document specifies the bytes of a cycle-log card (the codec input that follows the codec reference). Together with model.ts (what a card can say) and MAPPING.md (the Bundle it stands for), it is meant to be enough to write an independent encoder and decoder that agree bit for bit with cycle-log.wasm. The reference implementation is rust/core/src/ (walk.rs is the format as code, shared by encoder and decoder; rc.rs is the range coder; cm.rs holds the 2-level KT chains, Elias integer coder and LZ77 UTF-8 text model).

v2 codec architecture notes: Compared with the initial prototype, cycle-log.wasm (~370 KiB, zero imports, zero floats, link-time zero-panic) replaces multi-level Bayesian mixtures and cycle-phase prediction with three small integer primitives and four structural improvements:

  1. Dominant grid + per-value onGrid bit (for both numeric series and times of day): selects a dominant grid when ≥ 75% of values lie on it instead of collapsing to GCD = 1 on a single outlier.
  2. Per-entry seconds bit: a single non-zero :SS entry in a series no longer forces uni(60) on every other entry.
  3. Circular midnight-safe clock (mod 1440): time-of-day habit tracking wraps cleanly across 23:59 → 00:01 via signed deltas in [−720, +719].
  4. Script-neutral LZ77 shared UTF-8 text model: compresses repeated codes, free-text labels and non-Latin strings without English-only assumptions. It also adds compact coding for TempEntry exclusion flags/reasons (bbt and skinTemp) and optional MedDose quantities on medications.

Everything is integer arithmetic. Unless stated otherwise:

  • integers are unsigned;
  • >> on signed values is an arithmetic shift (floor);
  • / truncates;
  • min, max, clamp are the usual operations.

1. What is coded

1.1 The card

The card is the output of one binary range coder (section 2). There is no header byte, version or length. The first coded decision is the mode (section 5.2). Then follows the walk of section 4, a fixed sequence of binary decisions that describes the normalized model.

1.2 The model that is coded

The coded model is always normalize(m) of model.ts, re-implemented in check.rs:

  • daily series are uniform flat arrays of { date, ... } entries using FHIR DateTime (YYYY-MM-DD or YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)), intervals carry CalendarDate bounds (YYYY-MM-DD), and answers carry DateTime. Internally the codec derives a date span (start, days in 1..10,000) from the earliest to latest recorded date across all daily series, intervals and answers (a card with no dated facts at all has has_span = 0 and omits the span); there is no start/days/DayIndex field in JSON and no tracking-window Observation in FHIR;
  • concepts use readable built-in keywords (SymptomKind, MedicationKind, ConditionKind, Mucus, Sex, Mood, Energy, ProcedureKind, IntervalKind, ExcludeReason, coded Answer values) in built-in slots, and standard FHIR R4 CodeableConcept objects ({ coding: [{ system, code, display? }], text? } or text-only { text }) everywhere else and as escapes. For built-in concepts, coding[0].display is stripped canonically and text is forbidden. For any non-built-in escape concept (including SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URIs), both coding[0].display and text (≤ 128 code points each) are preserved and must agree across all occurrences of the same (system, code). Text-only { text } concepts carry plain text directly without requiring a synthetic system URI;
  • optional exportedAt (FhirInstant, mapped to FHIR Bundle.timestamp), with Z normalized to +00:00 and :00 seconds omitted in canonical form;
  • natural decimals in JSON: bbt and skinTemp values (up to 2 decimal places) are parsed directly into exact integer hundredths; MedDose values and custom quantities (up to 6 decimal places) are parsed directly into exact integers at their smallest exact internal scale (0..6), with zero floating-point arithmetic in the WASM codec;
  • each series array sorted by date (and within each date in canonical order: date-only entries first, then by UTC instant, then by local time, then by value/concept); for a set series (symptoms, medications, custom coded), each item's first occurrence on a date is in the date's wire set (in canonical concept order) and repeats are further entries;
  • escape CodeableConcept values that equal a built-in keyword (SymptomKind, MedicationKind, ConditionKind, ProcedureKind, IntervalKind, ExcludeReason, coded series levels, coded answers) written as the readable keyword;
  • built-in interval pairs written as kind (including "breastfeeding"), and built-in procedure concepts written as ProcedureKind;
  • intervals of one state that overlap or touch merged into one, then sorted by (start, kind, code, value, end), and unified procedures ({ date: FhirDateTime, code: ProcedureKind | CodeableConcept }) sorted by (date, code), where dates of any precision (YYYY, YYYY-MM, YYYY-MM-DD, or full timestamp) sort chronologically/canonically;
  • conditions in canonical concept order with the built-in condition table first;
  • answers whose value equals one of the question's answer codes written as the answer name, sorted by (date, question);
  • empty custom series dropped, custom series sorted by code;
  • in a components series (entries: [{ date, components: [{ code, value }] }]): components recorded in no entry dropped, the rest sorted by code (canonical concept order); each entry carries at least one recorded component;
  • absent and empty optional fields omitted in canonical JSON (reduced omitted when false; empty patient, bbt, and skinTemp omitted when empty);
  • times of day: Z normalized to +00:00 and :00 seconds omitted in canonical DateTime / FhirDateTime / FhirInstant.

Concepts are interned (concepts.rs). The built-in concepts are interned first, always in the order given by vocab::all_builtins(), so their ids are the same on both sides:

  • the 21 OBS codes: the 18 of the first version, then volume, skin-temperature deviation and nightly skin temperature;
  • 5 flow values;
  • the level values of the seven coded series;
  • 35 symptoms, then 7 medications;
  • 15 interval values;
  • 13 procedure codes;
  • 15 conditions;
  • for each of the 7 questions, its LOINC code followed by its answer codes.

Duplicates keep their first id. Call their number NB. (The observation-category concept vital-signs is also a built-in for the model's purposes, so it may not carry a label, but it is not interned in advance: a card that uses it spells it out.)

Canonical concept order (compareAnyConcept):

  1. built-in table position, where a table applies (symptoms, medications, conditions);
  2. then coded concepts before text-only { text } concepts:
    • SNOMED CT ids numerically (by length, then digits);
    • then other coded concepts by system|code in UTF-8 byte order;
  3. then text-only { text } concepts by their text in UTF-8 byte order.

The decoder computes it once per card as a rank (Concepts::ranks): one merge sort, with the systems ranked first by uri|. Every later comparison is then an integer comparison.

2. The range coder (rc.rs)

This is the LZMA range coder with 16-bit probabilities, without LZMA's constant leading zero byte.

2.1 Encoder

State:

  • low: 64 bits, starts at 0;
  • range: 32 bits, starts at 0xFFFFFFFF;
  • cache: one byte, starts at 0;
  • cache_size: starts at 1;
  • a flag first.

A decision is a bit b with probability p0 = P(b = 0) in units of 1/65536, 1 <= p0 <= 65535:

bound = (range >> 16) * p0
if b == 0: range = bound
else:      low += bound; range -= bound
while range < 2^24: range <<= 8; shift_low()

shift_low():
  if (low mod 2^32) < 0xFF000000 or low >= 2^32:
     carry = low >> 32
     emit(cache + carry); then (cache_size - 1) times emit(0xFF + carry)   (bytes mod 256)
     cache_size = 0; cache = (low >> 24) & 0xFF
  cache_size += 1
  low = (low & 0x00FFFFFF) << 8

The very first byte emit produces is the LZMA leading zero. It is always 0, because the coded value lies in [0, 1), so it is dropped.

2.2 Termination (canonical)

After the last decision, let hi = low + range. For j = 4, 3, 2, 1, in that order:

  • let m = 2^(8j) − 1 and x = (low + m) & ~m;
  • at the first j with x < hi, set low = x and stop.

A suitable j ≥ 3 always exists, because range ≥ 2^24. Then call shift_low() five times, and remove all trailing 0x00 bytes from the output. The card is what remains; it may be empty.

2.3 Decoder

  • Start with range = 0xFFFFFFFF and code = the first four card bytes, big-endian. Bytes past the end of the card read as 0.
  • A card whose first four bytes are FF FF FF FF is refused.
  • A decision:
bound = (range >> 16) * p0
if code < bound: range = bound; b = 0
else:            code -= bound; range -= bound; b = 1
while range < 2^24: range <<= 8; code = (code << 8) | next_byte()

2.4 Uniform values

uni(n, v) codes 0 <= v < n with no model:

  • Let w = bit length of n − 1. Code the bits of v from bit w − 1 down to bit 0.
  • Before each bit b, let base be the value of the bits decided so far, and:
    • c0 = min(n, base + 2^b) − base;
    • c1 = max(0, min(n, base + 2^(b+1)) − (base + 2^b)).
  • If c1 == 0, the bit is 0 and nothing is coded.
  • Otherwise code the bit with p0 = c0·65536 / (c0 + c1), clamped to [1, 65535].
  • uni(1) codes nothing.

A flag is a decision at p0 = 32768.

2.5 Canonical form, and how the decoder checks it

A card is accepted only if encoding the decoded model gives exactly the card. The decoder checks this in three steps.

  1. Record. While decoding, it records each decision's probability p0 (16 bits), in chunks that grow with the card.
  2. Re-encode. After validating and normalizing the decoded model, it walks that model again in encode mode, in the card's mode.
    • The walk derives every coded quantity from the model exactly as the encoder does: onsets from bleeding, the grid from the values, concept-reference choices, prefix lengths, and so on.
    • It codes each decision with the recorded probability.
    • It requires the walk to use exactly the recorded number of decisions, and the output bytes to equal the card.
    • For a modelled card, a second range encoder codes the same decisions in plain mode alongside: every decision not from uni at 32768, and the mode flag as 1. The plain card's length must not be smaller than the card's.
  3. Plain cards. If the card is plain, the decoder runs the full modelled encoder, abandoned as soon as it is certain to be longer. That length must be greater than the card's.

Why step 2 is the encoder.

  • Same decisions, same state. All model state (counts, mixture weights, predictor state, vocabularies, seen lists) is a deterministic function of the decisions made so far and of the values the walk has read. If every decision of the encode-mode walk equals the decoded one, both walks are in the same state before each decision, so their probabilities are equal. The output is then exactly the encoder's.
  • A different decision cannot go unnoticed. Suppose the k-th decision differs. Up to k both walks used the same probabilities, so the two codings split the same interval into its two disjoint parts at step k. Every later step stays inside its part, so the final values differ, and so do the bytes.

So the decisions themselves need not be recorded. Only their probabilities are, which replaces a second full model pass. As an independent check, the test suite re-encodes every card the fuzzer gets accepted with the full encoder, through the TypeScript fromBundle.

3. Probability models (cm.rs)

3.1 Counts and the KT chain

A context counter is a pair (n0, n1) of 16-bit counts, initially (0, 0).

A chain is a list of levels, root first. Each level selects one counter by its context index. The probability is computed down the chain:

root:   p = (4·n0·65536 + 4·32768) / (4·(n0+n1) + 4)          (Krichevsky–Trofimov)
level:  p = (4·n0·65536 + alpha·q) / (4·(n0+n1) + alpha)      (q = the parent's p)
  • In the mixture (section 3.3) the same formulas are computed as ((n0 << 18) + a·q) / (4·(n0+n1) + a) in 32 bits. This is exact because n0 ≤ 8191.
  • The final probability is clamped to [pmin, 65536 − pmin].
  • After the decision, every level's counter is updated: the observed count increases by 1, and if n0 + n1 > limit, both are replaced by (n + 1) >> 1.
  • Context indices outside a table select nothing: the counter reads as (0, 0) and is not updated.

Defaults: alpha = 8 (two counts of prior from the parent), limit = 255, pmin = 16.

3.2 Symbols

A symbol 0 <= s < k is coded as a path in a balanced binary tree:

  • Start with lo = 0, hi = k, node = 1.
  • While hi − lo > 1:
    • let mid = lo + (hi − lo)/2;
    • code the bit [s ≥ mid] with tree node node;
    • set lo or hi accordingly;
    • set node = 2·node + bit.

Each tree node has its own counters in every context (tables have 2·nextpow2(k) node slots per context).

3.3 Mixtures

A mixture has up to 8 levels forming a tree. Each level has a parent level, or the root prior. Each level has its own counters, and up to 4 of the levels are candidates.

  • Every level's p is computed as in section 3.1, from its counter and its parent's p.
  • Each candidate i keeps a code length Li in 1/256 bits, initially 0.
  • The mixed probability is p = Σ wi·pi / Σ wi, where wi = POW2[di mod 256] >> (di / 256) and di = Li − min L.
    • wi = 0 when di ≥ 24·256.
    • POW2[k] = round(65536 · 2^(−k/256)) (table in cm.rs).
    • Each pi is first clamped to [pmin, 65536 − pmin], and the mixture is clamped again.
  • After the decision:
    • each Li += COST[(pi_of_actual_bit) >> 4], where COST[i] = 256·(16 − log2(16i + 8)), computed by the integer squaring algorithm in build_cost;
    • min L is subtracted from all Li;
    • every level's counter is updated.

The sequence then costs at most the best candidate's own code length plus log2(candidates) bits (up to table rounding).

The mixtures used (level: contexts, parent; candidates marked *):

namelevels
adherence REC (1 node)0 root*; 1 prev (2) ←0; 2 (prev, activity) (6) ←1 *; 3 (prev, phase) (2·P) ←1 *; 4 (prev, prev2) (4) ←0; 5 (prev, prev2, activity) (12) ←4; 6 (…, phase) (12·P) ←5 *
categorical value VAL0 root*; 1 previous value (K+1) ←0 *; 2 phase (P) ←0 *; 3 (previous value, phase) ←1 *
set item ITEM (1 node)0 root; 1 (prev state, count so far) (9) ←0 *; 2 (slot, prev state, count) (9·S) ←1 *; 3 (slot, prev state) (3·S) ←0; 4 (slot, prev state, phase) (3·S·P) ←3 *
bleeding in an episode EP (7 symbols)0 root; 1 yesterday (8) ←0 *; 2 (yesterday, period day) (56) ←1 *; 3 previous period, same day (9) ←0; 4 (+ period day) (63) ←3 *; 5 all three (504) ←2 *

Here P is the number of phase buckets (11, section 4.6), S the scan width (24), and K the number of symbols.

Single chains (section 3.1) are used elsewhere, with their levels given at each use below.

3.4 Integers

The integer coders use one shared IntCm with a context per use (constants IC_* in walk.rs).

uint(v, maxbits) codes v ≥ 0. Let n = v + 1 and nb = bit length of n (1..64), with nb ≤ maxbits.

  1. Length, in unary. For len = 1, 2, …: while len < maxbits, code the bit [nb > len] with node len − 1, and stop after a 0.
  2. Mantissa. Code the bits of n below its leading 1, from high to low:
    • the first two use node 64 + (len − 1)·4 + prefix, where prefix starts at 1 and appends each coded bit;
    • the rest are flags.
  3. The table has two levels: the root, and the use's context.

sint(v) codes v as follows:

  • a nonzero bit (node 0 of a 2-node chain with the same two levels);
  • if nonzero, a sign bit (node 1);
  • then uint(|v| − 1).

4. The walk (walk.rs)

The sections come in this order:

  1. header (derived date span if any dated facts exist, optional exportedAt instant, reduced flag, and flags for times of day and further entries)
  2. patient
  3. source
  4. conditions
  5. intervals
  6. procedures (unified list, full or partial FhirDateTime)
  7. answers
  8. bleeding and flow
  9. measured volume
  10. pain
  11. symptoms
  12. BBT
  13. skin temperature
  14. mucus, ovulation test, progesterone (PdG) test, pregnancy test, sex, mood, energy
  15. sleep
  16. pill log
  17. medications
  18. custom series
  19. further entries (section 4.12)
  20. times of day (section 4.11)

Presence. Every optional part starts with a present decision: one chain with only a root, shared by all of them, so a card that leaves most parts empty learns to code "absent" cheaply. These are:

  • the derived-span flag (has_span), the exportedAt flag, the reduced flag, the flags for times and further entries (sections 4.11, 4.12), and the patient and source flags;
  • the count of conditions, intervals, procedures, answers and custom series: count(n) codes present = [n > 0], then uint(n − 1) in the count's own context;
  • the used flag of each per-day built-in series: if 0, the series is entirely unrecorded and nothing else of it is coded. The BBT and skin-temperature flags precede their headers. Custom series have no used flag, because they are never empty.

Dated events. Answers (and full-date procedures within the derived span) are coded relative to the derived date span using event_day:

  • after the first event of the list, a modelled flag "same date as the previous event" (chain: root only, one per list);
  • otherwise uni(days − lo, day − lo), where lo is 0 for the first event and the previous event's offset + 1 after it.

4.1 Header

  • has_span: a present decision (1 = the card has at least one dated fact in a daily series, interval or answer). When 1, the internal date span derived from the earliest to latest dated fact is coded as:
    • uni(36525, start − 2000-01-01) (days)
    • uni(10000, days − 1) (When has_span is 0, no date span is coded and all per-day series, intervals and answers are empty. No tracking-window Observation is emitted in either case.)
  • has_exported_at: a present decision; when 1, the exportedAt FhirInstant (calendar date 2000-01-01..2099-12-31, minute of day, optional non-zero seconds, and quarter-hour UTC offset) is coded and emitted as FHIR Bundle.timestamp.
  • the reduced flag: one present decision (1 = the sender left out data to fit a size, reduced: true).
  • the flags for times of day and further entries: present decisions indicating whether any fact on the card carries a time of day or any date of any series has more than one entry.

4.1b Patient

  1. Present (above). If 0, the section ends.
  2. A flag: family name present; if 1, the name follows as text.
  3. uni(4, number of given names), then each given name as text.
  4. uni(4, birth date form): 0 none, 1 YYYY, 2 YYYY-MM, 3 YYYY-MM-DD. Then:
    • form ≥ 1: year in 1900..2150;
    • form ≥ 2: uni(12, month − 1);
    • form 3: uni(31, day − 1).

Names are text (section 4.3) in the label family, each front-coded against the previous name, with at most 256 bytes. Validation (section 5) rejects impossible Gregorian dates.

4.1c Source and conditions

Source. Present (above). If present: the name as text (label family, not front-coded, ≤ 256 bytes); a flag "has a version"; if set, the version as text (label family, not front-coded, ≤ 128 bytes).

Dates of some precision (pdate, used for patient birth dates, condition onsets and procedure dates):

  • the form: for an optional date 4 symbols (none, YYYY, YYYY-MM, YYYY-MM-DD), otherwise 3 (YYYY, YYYY-MM, YYYY-MM-DD); a chain with only a root, one per list;
  • year in 1900..2150 coded relative to the reference year;
  • form ≥ YYYY-MM: uni(12, month − 1); form YYYY-MM-DD: uni(31, day − 1). Validation (section 5) rejects years outside 1900..2150 and impossible Gregorian dates.

Conditions. count(n, IC_COND_COUNT, 16). Then for each condition in canonical order:

  1. a concept reference (slot kind: condition) with the 15 built-in conditions as its table;
  2. the status: 3 symbols (not stated, active, resolved), chain root only;
  3. the onset: an optional pdate (IC_COND_YEAR).

4.2 Concept references

A concept slot is coded with a choice symbol, using a chain (root, kind of slot: 11 kinds: symptom, medication, escape value, custom code, custom value, interval, procedure, condition, answer, component code, component value). It has 4 symbols when the slot has a built-in table (symptoms, medications, conditions) and 3 symbols otherwise:

  • table (choice 0): uni(table size, position).
  • seen: uni(number of concepts seen so far on this card, position in first-appearance order).
  • built-in: uni(NB, id).
  • new: spelled out (below).

The encoder takes the first choice that applies, in this order: table, seen, built-in, new. The decoder rejects:

  • a "seen" reference to a table entry;
  • a "built-in" reference to a seen or table concept;
  • a spelling of a known concept.

After any reference the concept counts as seen.

Spelling. First the system choice (for a coded concept) or text-only form ({ text }):

choicemeaningwhat follows
0SNOMED CTnothing
1another well-known systemits index among the 7 others (LOINC, RxNorm, UCUM, cycle-log, ATC, ICD-10-CM, NDC), as a 7-symbol tree
2a system declared earlier on this carduni(count, index)
3a new systemits URI as text: URI family, front-coded against the previous URI, ≤ 255 bytes
text-onlyno coding, plain { text } onlythe text string in the label family (≤ 128 code points)

Then, for coded concepts, the code:

  • SNOMED CT. A partition flag (modelled, root only: 0 = "00", 1 = "10"), then uint(item − 100, IC_SNOMED, 50 bits). The id is item ‖ partition ‖ Verhoeff check digit.
  • Other systems. First the code form: 3 symbols, chain (root, system class: LOINC, RxNorm, other well-known, declared).
    • number if the code matches 0|[1-9][0-9]{0,17}: uint(value, IC_NUM, 60).
    • digits-check if it matches [1-9][0-9]{0,14}-[0-9]:
      • uint(digits − 1, IC_DASH, 50);
      • a modelled flag: the check digit equals the Luhn/LOINC mod-10 digit of the digits;
      • if not, uni(9, (check − luhn − 1) mod 10).
    • text otherwise: front-coded against the previous text code of the same system, ≤ 512 bytes.

For any non-built-in coded escape concept (regardless of whether its system is well-known or an app URI), optional coding[0].display and optional CodeableConcept.text flags follow; when set, each string is coded in the label family (≤ 128 code points, up to 512 distinct escape labels per card). Built-in concepts carry neither display nor text on the wire.

4.3 Text

There are three text families: codes (also used for units), URIs, and labels (also used for patient names and the source). Each family has two chains, allocated on first use:

  • end: 1 node; levels root, previous-byte class (9), class·8 + length bucket (72);
  • byte: a 256-symbol tree; levels root, previous-byte class (9), previous byte (256).

The byte tree's root level does not start from 1/2: its prior at tree node n is BYTE_PRIOR[n], the share of the lower half of the node's leaves under fixed byte weights, with weight 64 (16 counts) instead of the root's usual 4. That is, the root computes (4·n0·65536 + 64·BYTE_PRIOR[n]) / (4·(n0+n1) + 64), and the deeper levels take it as their parent's p as usual. The byte weights (byte_weight in cm.rs) are English letter frequencies (per mille ×10: a 820, b 150, c 280, d 430, e 1270, f 220, g 200, h 610, i 700, j 15, k 80, l 400, m 240, n 670, o 750, p 190, q 10, r 600, s 630, t 910, u 280, v 100, w 240, x 15, y 200, z 7) for a–z, and: space 1500; - 600; . and / 300; : and _ 150; ( and ) 100; each digit 300; each of A–Z 120; any other printable ASCII 60; each byte ≥ 0x80 8; every other byte 1. BYTE_PRIOR[n] = ⌊65536 · (weight of the lower half) / (weight of the node)⌋, clamped to [64, 65472]; node n at depth d covers the leaves from (n − 2^d)·2^(8−d). So a short text such as an app name costs about 6 bits a character from the start instead of 8.

The byte classes are: start, a–z, A–Z, 0–9, -, _./:, space, other ASCII, ≥ 0x80. The length buckets are 0, 1, 2, 3–4, 5–8, 9–16, 17–32, 33+.

If there is a previous string, uint(lcp, IC_LCP, 11) comes first. Here lcp is the longest common prefix, in bytes, with the previous string. The prefix is copied, and the lcp is counted as work (section 5.3). Then, for each further byte:

  • an end flag;
  • if not at the end, the byte.

At the maximum length the end is implicit. The decoder checks the result later: it must be valid UTF-8 and pass the model's code and label rules.

4.4 Intervals, procedures and answers

Intervals. count(n, IC_IV_COUNT, 9) (≤ 256). Then, for each interval in canonical order:

  • uint(startOffset − previous startOffset, IC_IV_START, 10) (offset from the derived span start);
  • the kind: 16 symbols (15 kinds, 15 = custom), chain (root, previous kind);
  • for a custom interval, two concept references (slot kind: interval);
  • a modelled flag "ends on the last date of the span"; if not, uint(endOffset − startOffset, IC_IV_LEN, 10).

Procedures. Unified list count(n, IC_PR_COUNT, 10) (≤ 512). Each procedure ({ date: FhirDateTime, code: ProcedureKind | CodeableConcept }) in canonical order (date, code) carries:

  • its date part (YYYY, YYYY-MM, or YYYY-MM-DD) via pdate;
  • the kind: 14 symbols (13 kinds, 13 = custom), chain root only; a custom kind is followed by a concept reference (slot kind: procedure). (Procedures whose FhirDateTime includes a time of day carry that time in section 4.11.)

Answers. count(n, IC_ANS_COUNT, 15) (≤ 20,000; a question may be answered more than once a day, at different times). Then, for each in canonical order:

  • event_day;
  • the question: 7 symbols, chain (root, previous question + 1 when on the same day as the previous answer, else 0);
  • the value:
    • a coded question: (answers + 1) symbols, the last one an escape, chain (root, question); an escape is followed by a concept reference (slot kind: answer);
    • an integer question: uni(hi − lo + 1, value − lo) over its range.

4.5 Bleeding and flow

Onsets.

  • A bleed day has a value in {bleeding, light, moderate, heavy}.
  • An onset is a bleed day with no bleed day in the gap = 7 days before it.
  • The onsets are coded first:
    1. A flag "any onset" (chain: root, context 0). If set, uint(first onset, IC_ONSET0, 10) follows.
    2. Then, repeatedly: a flag "another onset", with context 1 if there is no prediction yet, 2 if the predicted next onset falls inside the derived span, 3 if outside.
    3. If set, the cycle length L:
      • for the first length, uint(L − gap − 1, IC_LEN0, 10);
      • after that, sint(L − P, IC_RESID0 + min(lengths so far, 3), 12).

The prediction P is the median of the last three lengths. With one length it is that length; with two, (a + b + 1)/2.

Days. Then, for every day:

  • Onset day. The value is one of 4 bleed values. The chain is (root, previous onset's value: 5 states).
  • Other days.
    • First a recorded flag: chain (root, prev·2 + prev2, (prev·2 + prev2)·2 + in-episode). In-episode means a bleed day falls within the gap days before.
    • If in-episode: one of the 7 values, mixture EP. Its contexts are:
      • yesterday's value (0 = unrecorded);
      • the day of the period, min(day − onset, 7) − 1;
      • the value on the same day of the previous period, or 8 if there is none.
    • Otherwise: one of {no-bleeding, flow-none, spotting}. The chain is (root, previous such value: 4 states).

The encoder derives the onsets from the values, so the onset list and the values always agree. A decoded card where they disagree fails the canonical check.

4.6 Cycle features

After bleeding, every day gets a phase bucket:

bucketcondition
0–3inside a period: from its onset to its last bleed day, by day of period 1, 2, 3, 4+
4next onset in 1–3 days
5next onset in 4–7 days
6next onset in 8–12 days
7next onset in 13–16 days
8next onset in 17+ days
9overdue (the predicted onset has passed)
10unknown
  • "Next onset" is the actual next onset, or after the last one, last onset + P.
  • The BBT class is luteal for buckets 4–6, overdue for 9, unknown for 10, and follicular otherwise.
  • The day's activity is the number of series already coded as recorded on that day.

4.7 Per-day categorical series

This covers pain (11 values), the seven coded series (their levels plus 1 for escape), the pill log (2) and custom boolean series (2). For each day:

  • A recorded flag, mixture REC, contexts:
    • prev / prev2: recorded on the previous one / two days;
    • activity: min(activity, 2);
    • phase.
  • If recorded, the symbol, mixture VAL. Its contexts are the last recorded symbol (0 = none yet) and the phase.

An escape symbol is followed by:

  • if this series has had escapes before: a modelled flag "new escape", and if not new, uni(count, index);
  • if new, a concept reference (slot kind: escape value).

4.8 Numeric series

This covers measured volume, BBT, skin temperature, sleep and custom quantities.

  • BBT header: a unit flag (0 = Cel). (Its times of day are coded with every other series' in section 4.11.)
  • Skin temperature header: a kind flag (0 = deviation, 1 = absolute), then a unit flag (0 = Cel).
  • Every day: the recorded flag, mixture REC (as in section 4.7). For measured volume the activity context is replaced by the day's bleeding state (0 = not recorded, 1–7), so REC has 8 values instead of 3 in that position: whether a volume is measured follows the bleeding.
  • First recorded value:
    • uint(g, IC_GRID, 56), where g is the gcd of |v − v0| over all values, and 0 when all values are equal;
    • then v0: uni(hi − lo + 1, v0 − lo) for the ranged series: volume 0..500, BBT (Cel 3400..4200, °F 9300..10760), skin temperature (deviation Cel −500..500, °F −900..900; absolute Cel 2500..4000, °F 7700..10400) and sleep (0..1440); sint(v0, IC_V0, 56) for custom quantities.
  • Later values when g = 0: nothing; the value is v0.
  • Later values otherwise: the value is q = (v − v0)/g, coded as the residual q − pred with sint in a per-series chain (root, activity bucket = min(bitlen(A), 15)).

The prediction is chosen among four candidates, all in fixed point × 256:

  1. the last q;
  2. a running level;
  3. the level of the day's first key;
  4. the level of the day's second key.

The keys are, for measured volume, the day's bleeding state b (0–7) and b·4 + min(phase, 3) (bleeding state and day of the period); for every other series, the day's BBT class (section 4.6) and its weekday, (start + day) mod 7. So the volume of a heavy day is predicted from earlier heavy days, and especially from earlier heavy days at the same point of a period.

The candidate with the smallest error memory E wins; ties go to the lowest index. Then pred = (candidate + 128) >> 8.

Updates after each value, with qf = q·256:

  • E_i += |qf − cand_i| − (E_i >> decay);
  • each level moves by (qf − level) >> ema; a level's first sample sets it;
  • A += (|res|·16 − A) >> 3.

Defaults: ema = 3, decay = 4. The first value initialises all levels to 0, because q0 = 0.

4.9 Set series

This covers symptoms (table: 35 built-ins), medications (table: 7, each item with a taken/missed status) and custom coded series.

Each set series keeps a vocabulary: its concepts in first-appearance order. For each day:

  • A nonempty flag, mixture REC.
  • If nonempty:
    1. Scanned slots. For each of the first S = 24 vocabulary slots, a present flag, mixture ITEM. Its contexts are:
      • the slot;
      • its state yesterday (absent, present/taken, missed);
      • count so far today: min(·, 2);
      • phase.
    2. Status. For medications, a present item has a missed flag, chain (root, previous state, slot·3 + previous state). Items beyond the scan, and new items, use the contexts (0, S·3).
    3. Other known concepts. If the vocabulary is longer than S: uint(count, 15), then each one's vocabulary index in increasing order, as uni(remaining range, gap).
    4. New concepts:
      • uint(count − 1, 15) if nothing else is present today, otherwise uint(count, 15) (15 bits since a day has no cap; a count below 127 costs what the former 7-bit width did);
      • then each new concept's reference in canonical order;
      • each is appended to the vocabulary.

A day holds any number of items (the 20,000-fact limit bounds them). The decoder stores items in coding order and sorts each day canonically after the walk.

4.10 Custom series

count(n, IC_CUSTOM_COUNT, 6) (≤ 32). Then, for each series in canonical order:

  1. the code (concept reference, slot kind: custom code);
  2. the valueType: 4 symbols ("boolean", "coded", "quantity", "components"), chain root only;
  3. for "quantity": the unit as text (code family, front-coded against the previous unit, ≤ 64 bytes), then uni(7, scale) where scale ∈ 0..6 is the smallest internal scale derived from the natural JSON decimal values (no scale field appears in JSON);
  4. for "components": uni(16, count − 1), then for each component in canonical order its code (concept reference, slot kind: component code), its valueType (3 symbols: "boolean", "coded", "quantity"; chain root only, shared by the card's components series) and, for a "quantity", its unit and derived internal scale as in 3;
  5. the values: section 4.7 ("boolean"), 4.9 ("coded"), 4.8 ("quantity") or below ("components"), without a used flag.

Readings with components. For every day:

  • a recorded flag, mixture REC (section 4.7);
  • if recorded, for each component k in order:
    • a present flag, chain (root, k·3 + state), the state being 0 before the component's first value, 1 if it was present in the previous reading, 2 if not. The last component's flag is not coded when no earlier component was present (a reading has at least one value);
    • if present, the value:
      • quantity: the component's own numeric stream (section 4.8: grid, first value, predictor and residual chain), with the BBT class and weekday as its keys;
      • boolean: a flag, chain (root, k·3 + previous value of this component: 0 none, 1 false, 2 true);
      • coded: if the component had a value before, a flag "same as its previous value" (chain: root, k); otherwise, or if not the same, a flag "new" (chain: root, k) when the component has values seen before, then uni(seen, index) into its own first-appearance list, or for a new value a concept reference (slot kind: component value).

The chains are per series. A component's value is not predicted from its siblings': measured on synthetic blood pressure with correlated systolic and diastolic values (about 150 readings a year), a sibling-residual context made the series 0.05 bits a reading longer, because the extra contexts do not learn in a year.

4.11 Times of day

Only when the card has times of day (section 4.1). The blocks come in a fixed order: the built-in per-day series (bleeding, volume, pain, symptoms, BBT, skin temperature, mucus, ovulation test, progesterone (PdG) test, pregnancy test, sex, mood, energy, sleep, pill, medications), then the custom series in canonical order, then the screening answers, then the procedures with full YYYY-MM-DD dates. A block exists only for a series with at least one fact. Its facts, already known to the decoder, come date by date: the date's first entry (a set series: its items, in canonical concept order, an order the decoder knows before it sorts the set), then the date's further entries (section 4.12) in order; answers and full-date procedures in canonical order. Each entry has its own time.

Per block:

  1. has: a flag, chain root only: does any fact of the series have a time? If 0, the block ends.
  2. shared: a flag, chain root only: every fact has the same time (minutes, seconds and offset).
  3. secs: a flag, chain root only: some time has seconds other than 00.
  4. Shared: one time (below, with no previous time), applied to every fact.
  5. Otherwise: the grid, uint(g − 1, IC_TGRID, 11), the gcd of the timed facts' minutes of day (1 when that gcd is 0); a decoded g over 1,440 is refused. Then for each fact: a has-time flag, chain (root, previous fact's flag: 0, 1, or 2 at the block's start), and if set, one time.

Each fact has a class: 0 for the first fact of its day in the block, 1 for a later one (a second reading, a later item). The series keeps a previous time and a level per class, so a habitual second reading is predicted from earlier second readings.

One time. With m the minutes of day on the grid (q = m / g):

  • kind: 4 symbols, chain (root, 2 × the previous kind in the block (4 at its start) + the class):
    • 0: the same minute as one of the day's references: the distinct minutes of times coded for that day by earlier blocks (the most recent four; those on the grid). With more than one reference, uni(count, position) names it;
    • 1: the same as the class's previous time;
    • 2: near the class's level: a sign flag (root only), then uint(|q − level|, IC_TDELTA, 7), at most 60 / g steps (more is refused);
    • 3: uni(1439 / g + 1, q). The encoder takes the first kind that applies (the first matching reference). The level is the class's running mean of minutes, ×16: set to the class's first time, then level += (16·m − level) / 4 (arithmetic shift); it is rounded to steps as ((level + 8) >> 4) / g.
  • seconds: uni(60, s) when the block's secs flag is set; otherwise 0.
  • offset: the offset index = sign·60 + hours·4 + quarter (index 60, "−00:00", and indices ≥ 120 are refused). The predicted offset is that of the nearest earlier or same day that has a coded time on this card, else the last offset coded. If there is a prediction, a flag (root only) "same as predicted", and if not, uni(120, index); with no prediction, uni(120, index).

A block adds its day's minutes to the day's references once it has coded all of that day's facts (a shared block: its one time to every day it covers); every coded time sets its day's offset.

Cost. A card with neither times nor further entries pays the flag only: about 0.42 bits on every sample record (a presence decision late in the shared chain). Measured on synthetic times added to the tuning sample power-tracker (2,525 timed facts in 14 series; each symptom and medication is a fact):

timesbits per timed factcard
one time per series across the window, one offset0.03 (11–22 bits per series)+9 B
habitual, every minute, sd 15 min around a per-series mean, one DST change6.31+1,983 B
habitual, sd 30 min7.52+2,367 B
habitual, sd 30 min, on a 5-minute grid5.37+1,687 B
one sitting a day (all series at one varying time, sd 40 min), BBT separate, DST2.50+785 B
BBT only, sd 10 min, DST6.05+229 B
BBT only, sd 10 min, with seconds11.92+453 B
uniform random times (BBT and sleep)10.77+845 B
each symptom at its own time (morning or evening habit)10.86+444 B

Blood pressure added to power-tracker (85354-9, about 310 days with a reading): the morning reading at a habitual time costs 6.5 bits; twice daily, 6.9 bits a reading. Coding without the class (one previous time and level for all of a series' facts) cost 10.5 bits a reading on the twice-daily data, so the class saves about 3.7 bits per reading. A heart rate logged with the morning reading costs 1.15 bits a reading with the day's four references, 6.1 bits with only the last time coded that day as reference.

4.12 Further entries

Only when the card has further entries (section 4.1). For each series in the order of section 4.11 that has at least one day with an entry:

  1. has: a flag, chain root only: does the series have a day with more than one entry? If 0, the series is done.
  2. Otherwise, for each day with a first entry: the count c of further entries as flags "another entry?" (chain: root, series × 9 + 3 × min(entries coded that day − 1, 2) + min(c on the series' previous day with entries, 2)), stopping at 0 (or at 20,000 entries); then each further entry's value:
    • categorical (bleeding, pill, coded series, custom boolean): one symbol over the series' values (a coded series: its levels and an escape, which a concept reference follows; slot kind: escape value), chain (root, series × 16 + the previous entry's symbol);
    • numeric (volume, pain, BBT, skin temperature, sleep, custom quantity): sint(v − previous, IC_EXV, 56), the previous entry's value (the first entry's for the first further one); a value outside the series' range is refused;
    • set (symptoms, medications, custom coded): uni(n, i), the repeated item's place i among the day's n items in canonical concept order; for a medication then a flag (root only) "not taken";
    • reading with components: per component a present flag, chain (root, 2 × component + whether the previous reading had it), and if present its value: a quantity sint(v − previous, IC_EXC, 56) (the previous reading's value of the component, 0 when it had none), a boolean flag (chain: root, previous value), a coded value as a concept reference (slot kind: component value). A reading with no component is refused.

The first entry of each day is the one the per-day sections code (sections 4.5 to 4.10), so every per-day prediction (bleeding today, cycle day, the previous value) uses it, and a card whose days have one entry each is coded exactly as before. The further entries of a day are in canonical order (MODEL.md §8): the decoder checks this by re-encoding (section 2.5). Repeats are separate facts and never merged: an entry identical to another (same value, same time or both untimed) is coded as a further entry like any other, and entries that disagree (two bleeding states at one time, a medication taken and not taken) are coded as recorded; no further entry changes the day's predictions, which use the first. Measured on bp-twice-daily: one untimed reading repeated adds 2 bytes; the same reading repeated at its own time 14 bytes; an untimed pain score, symptom or bleeding state repeated 1–2 bytes. Dropping every blood-pressure time from bp-twice-daily (547 readings on 306 days, now valid without times) takes the card from 1,798 to 1,522 bytes.

Cost, on synthetic blood pressure added to power-tracker: a second reading costs about 10 bits (count and value) against 10.8 bits for a first; when every day has two, the count costs 0.13 bits a day; when a random 30% of days have two, about 1 bit a day. The held-out sample records: bp-twice-daily pays 10.4 bits per second reading (241 of them), timestamped 5.5 bits per further entry (43: second pain scores, evening flow, repeated cramps and ibuprofen).

5. Limits, modes and bounds

5.1 What the encoder refuses

conditionstatus
validateJson (and so validate) rejects the modelMALFORMED, with validate's field path
the card would exceed 4,096 bytes (no QR code holds more)LIMIT

Nothing else is refused. In particular, the encoder never refuses a model because its Bundle is large or because it would be slow to decode: those are warnings for tools (section 5.4).

The encoder abandons a coding pass as soon as its output is certain to exceed 4,096 bytes. So the cost of encoding a very large model is bounded by the model, not by the card.

5.2 Modes, and the worst-case bound on card size

The first decision is the mode flag: 0 for modelled, 1 for plain.

  • A plain card codes every modelled decision at p0 = 32768.
  • uni decisions keep their exact probabilities in both modes.

The encoder produces both cards and emits the shorter, choosing the modelled one on a tie.

So a card is never longer than the plain coding of the same walk. The plain coding is a fixed-cost representation:

  • one bit per adherence flag, per tree level of a symbol, and per scanned set slot;
  • log2(n) per uniform value;
  • 2·bitlen + 1 bits per integer;
  • 9 bits per text byte.

The cy_sizes export reports both sizes. Measured with sizes.ts: on the random-model generator the card is a median 0.67 of the plain size (maximum 1.00, where plain mode was chosen). It is 0.72 on uniform noise in every series and 0.12 on alternating extremes. For data with no exploitable structure, the card falls back to the plain coding.

5.3 Termination and the true worst cases

Every decode terminates, by the model's own limits:

  • Every loop runs over something the model bounds: days (≤ 10,000), series (15 built-in + ≤ 32 custom; 16 built-ins for times and entries), entries per series per day (≤ the facts), components per reading (≤ 16), items per set per day (≤ 64), facts in total (≤ 20,000, which also bounds conditions and answers), answers (≤ 20,000, as facts), intervals (≤ 256), procedures (≤ 512), distinct concepts (≤ 21,504) and code systems (≤ the concepts), string lengths (code 512, URI 255, label 800, name 256, source name 256 and version 128 bytes), and integer widths (≤ 64 bits).
  • A decoded count beyond its limit is refused as soon as it is read. There is no recursion; JSON skipping uses an explicit stack ≤ 128 deep. All indexing is checked.
  • The module contains no panic path: the panic handler calls an undefined symbol, so a build in which any panic survives optimisation fails to link.

The 4,096-byte card bounds the number of decisions. Counts are halved at 255, so no adaptive decision can be more certain than about 255.5/256, and each costs at least about 0.0028 bits. A 32,768-bit card therefore holds at most about 12 million decisions. Text copied by common prefixes adds at most the model's string bytes, about 17 M. A decision costs at most about 1,400 WebAssembly instructions and a copied byte a few, so no card can cost more than about 17 billion instructions, about 1.5 s on a desktop.

Worst cards constructed. These were built under the model's limits and sized to just fit 4,096 bytes; all measured on this build, at opt-level 3. Bun and Node times are the best of four decodes in one process (Node after compiling the module), on one desktop:

cardcard BworkinstructionsBunNodememoryBundle
2,006 concepts, each in its own 255-character system4,0964.54 M5.2 G0.24 s0.26 s25 MiB1.2 MB
1,083 new concepts, 128-code-point codes spelled byte by byte4,0954.86 M4.6 G0.22 s0.23 s23 MiB0.9 MB
1,024 component values, each a new concept with a 128-code-point code (readings of 16 coded components)4,0954.60 M4.4 G0.28 s0.21 s23 MiB0.7 MB
804 conditions with 128-code-point codes4,0933.63 M3.5 G0.17 s0.17 s14 MiB0.7 MB
20,000 facts (the model's limit), every coding long and labelled7780.46 M0.45 G0.07 s0.09 s71 MiB66.6 MB
20,000 facts as readings of 16 components, every coding long and labelled2,9270.21 M0.20 G0.10 s0.04 s69 MiB65.6 MB
34 set series scanning a 24-item vocabulary on all 400 days8480.34 M0.48 G0.04 s0.03 s10 MiB3.7 MB
19,600 facts, every one with a time of day (48 series on all 400 days, a random time and offset each day)9900.13 M0.18 G0.02 s–11 MiB5.7 MB
8,150 timed pain scores, 50 a day4,0890.12 M0.17 G0.02 s–8 MiB3.4 MB
20,000 facts as 32 coded series whose item repeats at two times every day2,6030.15 M0.30 G0.03 s–13 MiB5.8 MB
20,000 untimed entries of one quantity series on one day220.08 M0.24 G0.03 s–18 MiB6.0 MB
7,200 timed symptom entries on one day (5 symptoms repeated)2,7020.06 M0.14 G0.01 s–12 MiB2.8 MB
the heaviest sample (wellness-diary)1,85925 k33 M5 ms7 ms7 MiB0.76 MB

The times-of-day, entries and wellness-diary rows were measured on this build; the other rows were measured on an earlier build and not rebuilt, since times and entries add only one flag to them. Neither moves the bounds: every entry is a fact (at most 20,000), costs at least a count flag and its value, and the 4,096-byte card bounds the decisions as before.

Components do not move the bounds: each recorded component value counts as one fact toward the 20,000, so the largest Bundle stays about the same.

The worst rejected input is a worst card with one byte appended. It decodes fully, then fails the canonical check: 4.6 G instructions and 0.2 s.

The largest Bundle the model allows is 20,000 facts, each with two codings of a 255-character system, a 128-code-point code and a 128-code-point display (the wire format bounds raw label UTF-8 bytes at 800). That is tens of megabytes.

Memory. The module declares a maximum of 1 GiB (16,384 pages). Structures grow with the card. Memory is dominated by the Bundle: 71 MiB for the largest one, under 26 MiB for every other worst card, and 2–7 MiB for the samples.

5.4 Warnings for tools

cy_cost(card or model) in the tools module reports:

  • the work and decisions of the decode;
  • facts, Bundle bytes and memory (for a model, memory includes encoding it);
  • estInstructions = 1,400·work + 4·bundleBytes + 6,000·facts + 5 M, an upper envelope of every measurement above (the facts term covers ordering, checking and rendering each day's entries).

Recommended thresholds for an "unusually costly to decode" warning, each about 30–100 times the heaviest realistic sample:

figureheaviest samplewarn at
estInstructions43 M (wellness-diary; 30 M counted)4,000,000,000 (≈ 90×, about 0.4 s on a desktop)
bundleBytes1.15 MB (power-tracker)32 MiB (≈ 30×)
memoryBytes6.6 MiB (own-vocabulary)256 MiB (≈ 40×)

5.5 Decoder totality

All of section 5.3 holds for every input, including random bytes and hostile cards. The test suite fuzzes 35,000 inputs with a generous per-call time limit that would still catch a hang.

6. Model constants and why

The constants are structural; none were fitted to particular samples. Their sensitivity is in sizes.ts; the README lists the results.

constantvaluereason
text priorEnglish letter frequencies and fixed class weights, worth 16 countsa short text (an app name, a label) is mostly lowercase words; the prior saves about 2 bits a character until the adaptive model has learned the card's own text
presenceone shared contexta card that leaves most optional parts empty learns that quickly
volume keysbleeding state; bleeding state and day of periodmeasured volume follows the flow level and falls over a period
KT root prior½ count eachminimax-optimal for an unknown binary source
parent prior alpha2 countsan unseen context starts at its parent; two observations of its own outweigh it
halving limit255keeps about the last 128–255 observations per context: years of daily data stay adaptive to habit changes
pmin16/65536caps a surprise at about 12 bits
episode gap7 daysbleeding separated by less than a week is one episode; cycles shorter than about two weeks are not physiological
cycle predictormedian of 3robust to one unlogged or skipped period
phase buckets1–3, 4–7, 8–12, 13–16, 17+ days before onsetthe luteal phase is 12–14 days, so ovulation is ~14 days before onset; premenstrual symptoms cluster in the last week
level tracker1/8about one week of memory
predictor memory1/16about two weeks
scan width24covers the built-in-sized vocabularies; larger vocabularies are coded by index
time level1/4a habit drifts over weeks; tracks it within a few logged days
"near" a time±60 minutesa habitual time rarely moves further; anything else is coded uniformly
times gridgcd of the minutesapps that round to 5 or 15 minutes pay for the grid's steps only
time classfirst entry of a day / latera habitual second reading has its own previous time and level
day referencesthe 4 most recent distinct minutes of the dayseveral series logged in one sitting share a time
count contextsentries so far that day (0, 1, 2+), the previous day's count (0, 1, 2+)a habit of two a day makes the count nearly free

7. Worked example

A five-day date span starting 2026-03-01 (2026-03-01..2026-03-05): bleeding moderate, heavy, light, (omitted), no-bleeding; pain 4 and a menstrual cramp on 2026-03-01. Illustrative trace (cy_trace):

  1.00 bits  coding mode: modelled
 23.80 bits  derived span: 2026-03-01, 5 days
  1.00 bits  card not marked as reduced
  0.42 bits  no times of day and one entry per series per day on this card
  0.27 bits  no patient identity
  0.20 bits  no source app
  0.15 bits  number of reported conditions: 0
  0.11 bits  number of intervals: 0
  0.18 bits  number of procedures: 0
  0.07 bits  number of screening answers: 0
  2.00 bits  first period starts on day 0
  2.00 bits  no further period onset in the window
  2.00 bits  day 0 bleeding (period starts): moderate
  4.00 bits  day 1 bleeding: heavy (period day 2, yesterday moderate)
  3.93 bits  day 2 bleeding: light (period day 3, yesterday heavy)
  3.76 bits  day 3 bleeding: not recorded
  4.42 bits  day 4 bleeding: no-bleeding (period day 5)
  0.07 bits  volume: series not used (nothing recorded in window)
  4.59 bits  pain: series used
  5.00 bits  day 0 pain: 4 (period day 1)
  4.94 bits  days 1–4 pain: not recorded
  3.12 bits  symptoms: series used
  9.13 bits  day 0 symptoms: SNOMED CT 431416001 (period day 1)
  4.65 bits  days 1–4 symptoms: not recorded
  0.29 bits  bbt: series not used (nothing recorded in window)
  0.27 bits  skinTemp: series not used (nothing recorded in window)
  0.25 bits  mucus: series not used (nothing recorded in window)
  0.23 bits  ovulationTest: series not used (nothing recorded in window)
  0.22 bits  progesteroneTest: series not used (nothing recorded in window)
  0.21 bits  pregnancyTest: series not used (nothing recorded in window)
  0.20 bits  sex: series not used (nothing recorded in window)
  0.18 bits  mood: series not used (nothing recorded in window)
  0.18 bits  energy: series not used (nothing recorded in window)
  0.17 bits  sleep: series not used (nothing recorded in window)
  0.16 bits  pill: series not used (nothing recorded in window)
  0.15 bits  medications: series not used (nothing recorded in window)
  0.15 bits  number of custom series: 0
sum 83.6 bits; card 80 bits

Reading it:

  • The coder chose modelled mode; the plain coding of the same walk needs the same 10 bytes, and a tie goes to modelled.
  • The window start is uni(36525) and the length uni(10000): 15.2 + 13.3 = 28.5 bits.
  • Each empty optional part costs its present decision only. They share one chain, so after the first few each "absent" is cheaper: the times-and-entries flag 0.42 bits, the patient 0.27, the last unused series 0.15.
  • The onset list is: "any onset" and the first onset uint(0) (2 bits together), then "another onset?" = 0 (2 bits).
  • Day 0 is an onset, so no recorded flag is coded. Its value is one of 4 symbols, giving "moderate".
  • Days 1–2 are in-episode, with one of 7 values; day 3 is not recorded; day 4 is in-episode, "no-bleeding".
  • The cramp is a symptom given by table position: choice symbol, then uni(35, 0).
  • The ideal costs add up to 83.6 bits; the terminated card is 80 bits (section 2.2).

8. The trace (tools module)

cy_trace(card) decodes the card and returns JSON:

{"bytes": n,
 "symbols": [{"cat", "day", "days"?, "what", "cost"}...],
 "categories": {...},
 "modelledBits256", "cardBits256", "terminationBits256",
 "mode"}
  • Costs are in 1/256 bits, computed as 256·(16 − log2 p) of each decision.
  • Runs of "not recorded" days are merged into one symbol with days.
  • Declarations of new concepts are their own symbols, in the category declarations.
  • Every symbol stands alone: its what describes that symbol only.

The categories, in the order of the categories object: header, intervals, procedures, bleeding, pain, symptoms, bbt, mucus, ovulationTest, progesteroneTest, pregnancyTest, sex, mood, energy, sleep, pill, medications, custom, declarations, termination, patient, source, conditions, answers, volume, skinTemp, times. termination collects nothing from the walk; the coding-mode decision belongs to header.

  • The reduced flag is its own symbol in header, right after the window: "card reduced: values may be coarsened and series left out to fit a size" or "card not marked as reduced".
  • A components series is described in custom: its declaration "custom series (reading with components: , )", then one symbol per day, "day d custom reading: , …" listing the recorded components in order (quantities with their unit), or "day d custom reading: not recorded" (merged into runs like other unrecorded days).
  • Times of day are in times: first the card's flag (below); then one symbol per block (a series with facts), " times of day: none" or " times of day: N of M facts", with ", all at HH:MM±HH:MM" when one time is shared by all of them. A custom series is named "custom "; answers and procedures are "answers" and "procedures". So the cost of times is reported separately per series.
  • Further entries are in the series' own category: one symbol per series, ": one entry a day" or ": N further entries on M days". The card-level flag is in times: "no times of day and one entry per series per day on this card", "times of day on this card", "days with several entries on this card" or "times of day and days with several entries on this card".