Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,66 @@
# Changelog

## Unreleased — m0 and m1 are compared per compiled block, about each block's own start

The against-tree check compared each axis's m0 and m1 over the whole sequence, with m1 referenced
to `t = 0`. Registration moves a stored shape's area by `δm0`, so a legal waveform placed at `t`
moved the absolute m1 by `t·δm0`: a compressible shape that compiled at 0 s was refused at 1, 10
and 100 s, by a message that blamed "a gradient plays at the wrong time" and printed two
equal-looking numbers. No tolerance alone fixed that without hiding a 4.5 1/m blip played one
raster late far into a sequence.

m0 and m1 are now compared per compiled block and axis, each about the block's own start, in two
stages:

- **compile** — the tree's placed events, restricted exactly to each block, against the ready
blocks emission hands PyPulseq, within SeqCraft's own float, its endpoint snap, and a tick where
a knot's time can land one off;
- **registration** — those ready blocks, measured before emission, against what PyPulseq stored,
within its storage precision: compression rounding, and the six-digit key it deduplicates events
by.

The whole-sequence m0 and m1 refusals are retired. The sequence's moments are sums of the block
ones, so they add nothing a block-wise check misses
([ADR-007](docs/adr/007-against-tree-moments-per-block.md)). A refusal names its stage, block, start
time, difference and tolerance. Duration and label addresses are checked as before. The comparison
changes no emitted waveform, and the one compiler change below moves interpolated values by float
roundoff only.

What changes in verdicts, on the controls in `tests/compiler/test_local_moments.py`:

- **Accepted now:** the compressible shapes at 1, 10 and 100 s; the dense low-duty shape the
traversed-area tolerance refused, whose strict `xfail` is gone; and two trapezoids at 100000.0
and 100000.4 Hz/m that share PyPulseq's six-digit key. The second still plays 100000.0, which is
PyPulseq's precision rather than SeqCraft's.
- **Refused now, missed before:** area moved across a block boundary, which leaves the whole m0
unchanged.
- **Still refused:** lost area, and a piece one raster late, at every placement from 0 to 100 s.
So is a centre-sampled gradient of four samples or fewer, which PyPulseq stores without its last
half raster; it is now refused at registration, the stage where the area is lost.

**Resampled blocks** are reported by legalization as data. The compile stage compares each one
with the tree resampled onto the raster the same way, on its own axis, including stretches whose
ends are sloped.

**Known limitations:**

- m0 and m1 are two numbers per block, not waveform fidelity. A change that keeps every block's area
and centroid is invisible, and so is anything below the tolerance.
- The registration stage allows for PyPulseq's six-digit deduplication, so it cannot see a stored
change within about `1e-5` of a block's `|g|` integral.
- The endpoint snap, which zeroes a superposed block's edge value below `1e-6·max_grad`, is
modelled in the compile tolerance, not removed. It stays because PyPulseq's timing check refuses an
end above 1e-9 Hz/m that the next block does not continue, and the snap keeps a summed end that
cancels to nearly zero from being refused.
- Event time parameters and shape lengths must stay below `1e6` gradient rasters, where `%.6g`
prints them exactly.

**`superpose` interpolates in ticks from each block's start.** At absolute float seconds, a value
at a cut or at another piece's knot carried an error that grew with the block's position. On two
controls a block's area moved by up to 1.5e-10 1/m at 100 s and 1.2e-9 at 1000 s, against 1.1e-14
at 0 s. The same block now superposes to the same knots, bit for bit, wherever it sits, and the
compile stage's tolerance loses its only term that grew with placement.

## Unreleased — a rosette readout

`sc.modules.RosetteReadout` plays whole petals of the analytic rosette
Expand Down
66 changes: 66 additions & 0 deletions docs/adr/007-against-tree-moments-per-block.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# ADR-007: The against-tree moments are compared per compiled block, in two stages

- Status: Accepted (proposed 2026-10-26, accepted with its merge on 2026-11-05)
- Date: 2026-10-26
- Amends: the m0 and m1 invariants of the always-on verification reviewed in
[`refactor/phase6_verification_time_audit.md`](../refactor/phase6_verification_time_audit.md).
The duration and label-address invariants are unchanged, and verification stays always on.

## Context

`verify_against_tree` compared each axis's m0 and m1 over the whole sequence, with m1 referenced
to `t = 0`, and read the sequence PyPulseq had registered. Registration is not exact. A
compressible shape is stored as differences rounded to `1e-7` of its peak, and an event whose
parameters print like an earlier one's under `%.6g` is stored as that one. A registration error
`δm0` in a shape placed at `t` moves the absolute m1 by `t·δm0`, so a legal waveform that compiled
at 0 s was refused at 1 s. A tolerance wide enough to absorb that at 10 s, 3e-4 s/m, would hide a
4.5 1/m blip played one raster late, 4.5e-5 s/m. One tolerance also had to cover two unrelated
error sources: SeqCraft's compile and PyPulseq's storage.

## Decision

Compare m0 and m1 **per compiled block and axis, each about the block's own start**, in two
stages.

1. **Compile.** The tree's placed events, restricted exactly to each block, against the ready
blocks that emission hands PyPulseq, measured before registration. The tolerance is SeqCraft's
own arithmetic, each term a stated bound: float summation, the float of superposing pieces, the
endpoint snap, and a tick where a knot's time can land one from where the other side puts it.
2. **Registration.** Those ready blocks against what PyPulseq stored, read back block by block.
The tolerance is PyPulseq's storage precision: compression rounding, bounded by its first-sample
edge case at 1.5 quanta of the peak, and the six-digit deduplication key. That allowance belongs
to this stage alone.

The whole-sequence m0 and m1 refusals are retired. For any partition, `M0 = Σ m0_k` and
`M1 = Σ (m1_k + a_k·m0_k)`. A whole-sequence comparison that tolerated every block's error could
therefore never fire, and a narrower one would bring the translated term `a_k·δm0_k` back.

A block-axis that legalization resampled onto the raster is reported as data
(`LegalizationResult.resampled`), never inferred from warning text. The compile stage compares it
with the tree resampled onto the gradient raster from the block's start. Merging a resampled
stretch's inner seams was considered and rejected: it is exact only where both ends of the stretch
are flat, since a sloped end keeps a boundary term of about `r²·g′/8`, and it coarsens the check
inside the stretch.

## Consequences

- A correct waveform compares the same wherever it sits. A refusal names its stage, block, start
time, difference and tolerance.
- Area moved across a block boundary is refused, which the whole-sequence m0 could not see.
- What stays global is exact: the registered block grid must equal the handed one in ticks, and
duration and label addresses are checked as before. With the grid exact, the whole-sequence
moments are the sums in the decision above, so comparing them again would only re-test the block
moments, within either the sum of their tolerances or a narrower one that brings back
`a_k·δm0_k`.
- A storage fault is refused at the stage where it happens. A centre-sampled gradient of four
samples or fewer, which PyPulseq stores without its last half raster, is refused at
registration.
- PyPulseq's six-digit deduplication is accepted as its precision. An event that shares a key with
an earlier one still plays the earlier one's values.
- m0 and m1 remain two linear functionals per block, not waveform fidelity.
- `superpose` interpolates in ticks from the block's start, in a commit of its own with the
tolerance term it makes unnecessary.
- The endpoint snap, which zeroes a superposed block's edge value below `1e-6·max_grad`, stays and
is modelled. Narrowing it to float residue was tried and reverted: PyPulseq's timing check refuses
an end above 1e-9 Hz/m that the next block does not continue, and the snap is what keeps a summed
end that cancels to nearly zero from being refused.
52 changes: 36 additions & 16 deletions docs/api_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1909,9 +1909,12 @@ Properties: `kinds`, and `summary()`.
class LegalizationResult:
blocks: tuple[PulseqReadyBlock, ...]
notes: tuple[tuple[str, tuple[str, ...]], ...]
resampled: tuple[tuple[int, str], ...] = ()
```

`notes` is explicit immutable stage output: emission neither discovers nor mutates warnings.
`resampled` names each `(block index, axis)` whose gradient was resampled onto the raster, as data,
because the against-tree check compares those with the tree resampled the same way.

| Name | What it is |
|---|---|
Expand Down Expand Up @@ -1950,7 +1953,7 @@ address.
| Function | Does |
|---|---|
| `superpose(pieces, a, b) -> (rel_ticks, amps)` | The exact PWL superposition over `[a, b]`, in integer ticks |
| `axis_gradient(axis, pieces, a, b, opts, notes, block_index)` | The single gradient event for one axis over one interval, or `None` |
| `axis_gradient(axis, pieces, a, b, opts, notes, block_index, *, resampled=None)` | The single gradient event for one axis over one interval, or `None`; a resample is appended to `resampled` |
| `check_limits(events, opts, block_index, origin, notes, *, start=0.0) -> None` | Raise `HardwareLimitError` on a per-axis violation; append norm findings to `notes` |
| `required_duration(events, opts) -> float` | The shortest block that can hold `events`, by PyPulseq's rules |
| `common_path(paths) -> tuple[str, ...]` | The longest tag path common to everything in a block |
Expand Down Expand Up @@ -1982,29 +1985,42 @@ access to placed events, boundaries, label targets, the scanner limits, or trans
| `check_rf_amplitude(seq, opts, origins=()) -> None` | Raise `HardwareLimitError` if any RF event's peak exceeds `opts.max_b1` |
| `check_label_addresses(seq) -> None` | Raise `CompileError` if two imaging ADCs write the same k-space address |
| `expected_addresses(placed, targets) -> list[dict[str, int]]` | Fold the tree's labels the way the interpreter will |
| `verify_against_tree(placed, targets, *, duration_s, tree_duration_s, moments, label_states) -> None` | The four semantic invariants |
| `handed_gradients(blocks) -> HandedGradients` | m0 and m1 of the ready blocks per block and axis, about each block's start, measured before emission, with PyPulseq's storage allowance |
| `stored_gradients(seq) -> BlockMoments` | The same for what PyPulseq stored, read back block by block |
| `verify_against_tree(placed, targets, *, duration_s, tree_duration_s, handed, stored, resampled, grad_raster, snap, label_states) -> None` | The four semantic invariants |

**The self-check** asserts four invariants after emission, each catching a class of compiler bug no
individual test case would:

1. **Total duration** matches the tree's — guards a boundary merge that dropped time.
2. **m0 per axis** matches the sum over flattened events — a split that lost a tail changes it.
3. **m1 per axis**, referenced to the sequence start — m0 survives a *time shift*, so it cannot see a
gradient that plays at the wrong moment; m1 can, because area `A` displaced by `dt` changes it by
`A·dt`.
2. **m0 per compiled block and axis**, about the block's own start — a split that lost a tail, a
merge that dropped a piece, or area moved from one block to the next changes it.
3. **m1 per compiled block and axis**, about the block's own start — m0 survives a *time shift*, so
it cannot see a gradient that plays at the wrong moment; m1 can, because area `A` displaced by
`dt` changes it by `A·dt`. With the block as reference, the lever arm is at most a block long, so
a correct waveform compares the same wherever it sits.
4. **Label addresses** match the fold of the tree's labels — a duplicate-address check only fires on
a *collision*, but an addressing shifted by one and still unique passes it.

All four are measured before anything is raised, because one mistimed stage usually breaks several
axes and the pattern is the diagnosis.

Tolerances scale with the total, because they must: float64 resolves about 4 ns at 20 000 s, and the
moment tolerance is scaled by total area *traversed* rather than the net, since a readout and its
prephaser nearly cancel.

`_sequence_moments(seq, order)` is the compiled-side integrator. It is private and deliberately
**not** shared with `analysis.moments`, which walks the tree: a self-check that calls the same code
as the thing it checks compares a number with itself.
m0 and m1 are compared in two stages, each against its own input. **Compile**: the tree's events,
restricted exactly to each block, against the ready blocks emission hands PyPulseq, within
SeqCraft's own float, its endpoint snap, and a tick where a knot can land one off; a block-axis
legalization resampled is compared with the tree resampled onto the raster. **Registration**: those ready blocks against what PyPulseq stored,
within its storage precision — compression rounding, and the six-digit key it deduplicates events
by. The sequence's whole m0 and m1 are sums of the per-block ones, so they need no check of their
own. All four invariants are measured before anything is raised, because one mistimed stage
usually breaks several axes and the pattern is the diagnosis.

m0 and m1 are not waveform fidelity: two numbers per block cannot see a change that keeps every
block's area and centroid, nor anything below the tolerance. [`compiler.md`](compiler.md) states
each tolerance's domain.

`BlockMoments(edges, m0, m1, error0, error1, overrun)` holds one side's per-block moments and the
float error bound of each; `HandedGradients` adds `storage0` and `storage1`, the registration
allowance. `_sequence_moments(seq, order)` integrates the whole built sequence at absolute times;
the check no longer uses it, and the baseline tool does. It is private and deliberately **not**
shared with `analysis.moments`, which walks the tree: a self-check that calls the same code as the
thing it checks compares a number with itself.

`ContractViolation(location, message)` is the finding type; `CompilerContractError(name, violations)`
is the exception.
Expand Down Expand Up @@ -2056,6 +2072,7 @@ at import.
| `ADDRESS_KEYS` | `design.events` | constant |
| `AXES` | `design.events` | constant |
| `BARRIER` | `design.logic` | constant |
| `BlockMoments` | `compiler.verification` | class |
| `CartesianLine` | `modules` | class |
| `CompileError` | `compiler.errors` | exception |
| `CompilerContractError` | `compiler.verification` | exception |
Expand All @@ -2077,6 +2094,7 @@ at import.
| `GRE3DTR` | `modules` | class |
| `IRPrep` | `modules` | class |
| `HANDLED_KINDS` | `design.events` | constant |
| `HandedGradients` | `compiler.verification` | class |
| `HardwareLimitError` | `compiler.errors` | exception |
| `INDIVISIBLE_KINDS` | `compiler.model` | constant |
| `Item` | `design.logic` | type alias |
Expand Down Expand Up @@ -2138,6 +2156,7 @@ at import.
| `format_error` | `errors` | function |
| `from_scanner` | `scanner.opts` | function |
| `from_ticks` | `design.timing` | function |
| `handed_gradients` | `compiler.verification` | function |
| `in_block_delay` | `compiler.model` | function |
| `interval_duration` | `compiler.model` | function |
| `knots_of` | `design.events` | function |
Expand All @@ -2159,6 +2178,7 @@ at import.
| `sample` | `analysis` | function |
| `spoiler` | `modules` | function |
| `span` | `design.logic` | function |
| `stored_gradients` | `compiler.verification` | function |
| `superpose` | `compiler.legalization` | function |
| `synthetic_hardware` | `scanner.hardware` | function |
| `time_at_or_before` | `compiler.model` | function |
Expand Down
Loading
Loading