Every public name in src/seqcraft, by layer. Signatures are the ones the code has; every code
block below is executed by tools/check_api_reference.py, so this document cannot drift from the
package without CI noticing.
Read §0 first — the rest is reference.
- 0. The whole package in one page
- 1.
design/— what you build - 2.
scanner/— what you build against - 3.
compiler/— the transform - 4.
analysis— measuring a tree - 5.
display— looking at a tree - 6.
errors— the exception hierarchy - 7. Compiler internals
- 8. Migration
- 9. Index
Three things you write, one function that transforms them, one toolbox that measures them.
import numpy as np
import pypulseq as pp
import seqcraft as sc
opts = pp.Opts(max_grad=40, grad_unit='mT/m', max_slew=150, slew_unit='T/m/s',
rf_dead_time=100e-6, rf_ringdown_time=30e-6, adc_dead_time=10e-6)
gx = pp.make_trapezoid('x', flat_area=64 * 4.0, flat_time=3.2e-3, system=opts)
adc = pp.make_adc(num_samples=64, duration=3.2e-3, delay=gx.rise_time, system=opts)
tr = sc.LogicBlock('tr') # 1. a tree of events
tr.add(0.0, gx, adc) # anything may overlap anything
seq = sc.compile(tr, opts) # 2. legal pulseq blocks, or an exception
assert type(seq).__module__.startswith('pypulseq') # it is a pypulseq.Sequence
m = sc.moments(tr) # 3. measure the tree
assert round(m['x']) == 258 # 256 of flat area, plus what the two ramps contribute| Layer | Module | You use it to |
|---|---|---|
| design | logic module events timing units |
say what you mean |
| scanner | opts hardware |
say what the machine can do |
| compiler | compile() |
turn meaning into legal pulseq blocks |
| analysis | sample moments kspace sequence_kspace pns b_value |
measure a tree |
| display | plot_block |
look at a tree |
The central contract. sc.compile(tree, opts) returns a pypulseq.Sequence and nothing else.
If the tree cannot become a legal sequence, it raises. If the compiler had to change a waveform
to make it legal, it warns. There is no report object to inspect and no result wrapper to unpack.
Everything reachable as sc.<name>. This is the whole of what __init__.py re-exports.
| Name | Kind | Section |
|---|---|---|
compile, compile_sequence |
function | 3.1 |
LogicBlock, Node, Item |
class, class, type alias | 1.1 |
flatten, span, barrier |
function | 1.2 |
Module |
class | 1.3 |
events |
module | 1.4 |
timing, Raster |
module, class | 1.5 |
units, convert |
module, function | 1.6 |
scanner, opts, hardware |
module | 2 |
analysis, sample, moments, kspace, sequence_kspace, pns, b_value |
module, function | 4 |
display, plot_block |
module, function | 5 |
SeqCraftError, ConfigurationError, MissingExtraError |
exception | 6 |
CompileError, HardwareLimitError, DefinitionConflict |
exception | 6 |
RasterError, UnknownFieldError, CompilerContractError |
exception | 6 |
SeqCraftWarning |
warning | 3.3 |
__version__ |
str | — |
display is resolved on first access, so import seqcraft does not pull matplotlib in through
seqcraft. Everything else is eager.
Nothing here knows what a pulseq block is. A logic block lets anything overlap anything, a raster quantises a time, a unit converts a number — and none of them has an opinion about where the boundaries will fall.
A tree of pulseq events with relative start times. Two attributes, one method.
class LogicBlock:
tag: str # optional label; becomes the provenance path and appears in errors
nodes: list[Node] # Node(start: float, item: Event | LogicBlock)Node.start is measured from this block's own start, so a block does not know where it sits.
That is what lets the same block be reused at three different times in one sequence.
Two call shapes, one meaning. Returns self, so calls chain.
lb = sc.LogicBlock('excitation')
lb.add(0.0, gx) # one item at one instant
lb.add(4.0e-3, gx, adc) # two items at one instant
lb2 = sc.LogicBlock('table') # the table form, for a computed schedule
lb2.add([[0.0, gx],
[5.0e-3, gx, adc]])
assert len(lb2) == 3 # three nodes: every item gets its own, whatever the row shapeRows are appended in the order given and never sorted by time. Insertion order is what
flatten and the compiler's tie-breaking rely on, so two events at the same instant keep the order
you wrote.
add validates: anything that is neither a pypulseq event nor a LogicBlock raises
ConfigurationError naming the type it got. You therefore cannot construct a malformed tree.
try:
sc.LogicBlock('bad').add(0.0, 42)
except sc.ConfigurationError as err:
assert 'int' in str(err)Measured from the nodes: max(start + span(item)). A block cannot advertise a length that
disagrees with what it plays.
spoil = sc.LogicBlock('spoil').add(0.0, pp.make_trapezoid('z', area=500.0, system=opts))
assert round(spoil.duration * 1e3, 2) == 0.57To make a block longer, add a delay — which is how you lengthen a block in pulseq anyway:
spoil.add(0.0, pp.make_delay(10e-3))
assert round(spoil.duration * 1e3, 3) == 10.0| Call | Does |
|---|---|
lb.nodes[2].start += 40e-6 |
move the third child later |
del lb.nodes[0] |
remove the first |
for node in lb: |
__iter__ yields Nodes |
len(lb) |
number of direct children |
lb.copy() |
a new block with a new node list, sharing the same items — see below |
lb.describe(indent=0) |
indented text view of the whole tree |
repr(lb) |
LogicBlock(tag, n nodes, d ms) |
tree = sc.LogicBlock('tr').add(0.0, sc.LogicBlock('inner').add(0.0, gx))
assert len(tree) == 1 # one direct child, which is a block
assert 'inner' in tree.describe()
variant = tree.copy()
variant.nodes[0].start = 1e-3 # the node list is new: this is safe
assert tree.nodes[0].start == 0.0
assert variant.nodes[0].item is tree.nodes[0].item # but the *items* are sharedcopy() is one level deep. It gives you a new node list over the same items, which is what you
want when adding one block object at many times: 1700 references to one spoiler rather than 1700
copies. Reordering, retiming or deleting nodes on the copy leaves the original alone; reaching
through a node into a nested block does not. For an independent sub-tree, copy that block too.
class Node:
start: float # seconds, from the enclosing block's own start
item: Item # a pypulseq event, or a nested LogicBlockA frozen-in-spirit pair; start is writable, which is how you move a child.
Item is the type alias SimpleNamespace | LogicBlock.
| Absent | Where the job went |
|---|---|
marks / anchors |
Whatever produced the block. A block cannot know where it sits, so it cannot know when its echo occurs — readout.time_to_echo is a property of the readout. |
a labels field |
A pulseq label is an event: lb.add(t, pp.make_label('LIN', 'SET', k)). |
a declared duration |
Measured, so there is no second source of truth. |
then / over / chain |
add is shorter than any algebra and needs nothing learned. |
Walks the whole tree and yields every event (never a block) with its absolute time from the root and its provenance path — the chain of non-empty tags enclosing it.
inner = sc.LogicBlock('spoiler').add(0.0, gx)
outer = sc.LogicBlock('tr').add(2e-3, inner)
assert [(round(t, 5), p) for t, _, p in sc.flatten(outer)] == [(0.002, ('tr', 'spoiler'))]This is the function every measurement is built on. Use it, not lb.nodes, whenever you need the
events themselves — a component that nests would otherwise have its actual events skipped and your
check would pass vacuously.
t0 and path are the recursion's own accumulators; callers pass neither.
The duration of an event or a block, in seconds. For an event this is pypulseq's own
calc_duration logic; for a block it is block.duration.
assert sc.span(gx) == pp.calc_duration(gx)
assert sc.span(spoil) == spoil.durationA zero-duration marker event. Adding one forces the compiler to place a block boundary at that instant:
long_g = pp.make_trapezoid('x', area=2000.0, duration=4e-3, system=opts)
split = sc.compile(sc.LogicBlock('t').add(0.0, long_g).add(2e-3, sc.barrier('mid')), opts)
assert len(split.block_events) == 2Use it when a boundary must fall somewhere the compiler would not otherwise choose — for instance so that a trigger lands at the start of its own block, or so a later reconstruction step can find a known seam.
seqcraft.design.logic.BARRIER is the type string these carry ('seqcraft_barrier'). It is in
HANDLED_KINDS and is not a pypulseq type.
The standard shape for a reusable component. A convention, not a gate: the compiler takes a
LogicBlock and never asks what produced it, so a plain function is a component too.
class Module(ABC):
def __init__(self, *, opts: pp.Opts, tag: str | None = None) -> None
def __call__(self, *args, **kwargs) -> LogicBlock # what callers use
@abstractmethod
def build(self, *args, **kwargs) -> LogicBlock # what you writeFour members, each earning its place:
optsis required, not defaulted. pypulseq falls back to the process-globalOpts.default, so a module designing against that makes a sequence depend on import order.tagis identity and becomes the provenance path. An untagged block returned bybuildis named after the class.__call__is the single place the framework checks and names what came back. It rejects abuildthat returned the wrong type, with your class in the message.buildis abstract, because a subclass that does not produce a block is not a module.
class PhaseEncode(sc.Module):
def __init__(self, *, opts, fov_m, matrix, duration_s, tag=None):
super().__init__(opts=opts, tag=tag)
self.matrix = matrix
# Design once, in __init__: the *shape* is fixed, only the amplitude varies per line.
self.blip = pp.make_trapezoid('y', area=1.0 / fov_m, duration=duration_s, system=opts)
def build(self, line: int) -> sc.LogicBlock:
k = line - self.matrix // 2 # signed index about k = 0
scaled = sc.events.derive(self.blip, amplitude=self.blip.amplitude * k)
return sc.LogicBlock().add(0.0, scaled)
pe = PhaseEncode(opts=opts, fov_m=0.22, matrix=64, duration_s=600e-6)
assert pe(line=17).tag == 'PhaseEncode' # named after the class
assert PhaseEncode(opts=opts, fov_m=0.22, matrix=64,
duration_s=600e-6, tag='ky')(line=17).tag == 'ky'The rule that matters: build must not mutate self. Note sc.events.derive above rather than
self.blip.amplitude = ... — see §1.4. The compiler cannot check this: it validates a tree and
never sees the second call, so a module that mutates itself hands it a perfectly legal tree every
time. The three-line check is in writing_a_module.md.
Three things Module does not do, so do not look for them: declare a duration — the block
measures itself — check units, or scrape __dict__ for provenance.
_finalize(block) is the private hook __call__ runs: it type-checks and names. Tests call it
directly; nothing else should.
seqcraft does not wrap pypulseq events. They are SimpleNamespace objects and stay that way, so
interop with the rest of the pulseq ecosystem is free. Event is an alias for SimpleNamespace,
not a class. What this module adds is the arithmetic the compiler needs and one safe way to copy.
The only sanctioned way to modify a pypulseq event.
flipped = sc.events.derive(gx, amplitude=-gx.amplitude)
assert gx.amplitude == -flipped.amplitudeTwo properties of pypulseq 1.5 make ad-hoc copying dangerous:
Sequence.set_blockwrites a registration cache onto the event object (event._pypulseq_sequence_event_cache), keyed byid(sequence). Acopy.deepcopycarries that stale key along, and CPython reuses addresses — so a copied event can be silently mistaken for a registered one in a different sequence.- Assigning to a shared event mutates it for every tree that holds it.
derive strips id, shape_IDs and _pypulseq_sequence_event_cache, then applies your changes to
a fresh namespace. Never write event.amplitude = x.
It raises AttributeError for a name the event does not already have, so a typo is caught rather
than silently adding a field:
try:
sc.events.derive(gx, amplitide=1.0) # note the typo
except AttributeError as err:
assert 'amplitide' in str(err)Waveform arrays are shared by reference on purpose — they are never mutated in place, and sharing is what lets pypulseq's per-event registration cache hit for repeated events.
The exact-gradient primitive. A gradient is piecewise linear; this returns its corner points in absolute time.
For an arbitrary gradient the samples sit at raster centres, so first and last appear as
two extra knots half a raster outside them. For an extended trapezoid tt already reaches both
edges, so they coincide with existing knots and are not duplicated. Getting that wrong is what makes
an arbitrary gradient appear to lose amplitude.
Integrates the polyline analytically. order 0 gives area (1/m), 1 the first moment (s/m), 2 the
second (s²/m).
t, a = sc.events.knots_of(gx)
assert round(sc.events.pwl_moment(t, a, 0)) == 258 # area, 1/m: flat top plus rampsUse these, never raster sampling, for any arithmetic. An arbitrary gradient's samples sit at raster centres and an extended trapezoid's knots are not uniformly spaced, so interpolating onto a uniform grid costs percent-level amplitude error on a spiral. The compiler uses knots throughout; so should you. See §4.5.
Moments are linear in the waveform, which is why the compiler can sum per-piece moments whether the pieces overlap (in a tree, where they superpose) or abut (in compiled blocks, where they concatenate). No union of knots needs building.
The closed form matters: g(t) * t is quadratic between knots, so the trapezoidal rule is wrong
for order >= 1.
A curve suitable for plotting or interpolating — not a uniform raster. A trap is sampled onto
raster; a grad event carries its own sample times and they come back unchanged.
Never assume the returned times are uniform; use the t that comes back. check_limits once did
not, and divided by raster where it should have divided by diff(t) — on an EPI train's extended
trapezoid that overstated the slew by 26×.
t, g = sc.events.waveform_of(gx, opts.grad_raster_time)
assert bool(np.allclose(np.diff(t), opts.grad_raster_time)) # a trapezoid: uniformA stable sha256 of an event's numeric content, excluding registration state. This is what makes mutation detectable:
before = sc.events.content_hash(pe.blip)
pe(line=17)
assert sc.events.content_hash(pe.blip) == before, 'build() mutated a stored event'Amplitude and slew against opts, per axis and as a vector norm. Each entry is
(kind, where, value, limit), where kind is one of grad, slew, grad_norm, slew_norm.
strong = {'amplitude': 0.9 * opts.max_grad, 'duration': 1e-3, 'system': opts}
sx, sy = pp.make_trapezoid('x', **strong), pp.make_trapezoid('y', **strong)
assert [k for k, *_ in sc.events.check_limits([sx], opts)] == [] # legal alone
assert 'slew_norm' in [k for k, *_ in sc.events.check_limits([sx, sy], opts)]Pass starts= whenever the events do not all begin at zero. Two lobes of a bipolar pair are both
on one axis; without their start times they are taken to play simultaneously and sum to zero, which
hides a real violation.
The _norm entries are informational for a tree: the vector norm across simultaneous axes routinely
exceeds the per-axis limit and is legal on real amplifiers. The compiler treats per-axis violations
as errors and reports norm violations as warnings.
Classifications of pulseq's own type strings, kept here because they describe what an event is:
| Constant | Members |
|---|---|
GRADIENT_KINDS |
trap, grad |
POINT_KINDS |
labelset, labelinc, trigger, output |
LABEL_KINDS |
labelset, labelinc |
HANDLED_KINDS |
every type the compiler can place: the above plus rf, adc, delay, seqcraft_barrier |
AXES |
('x', 'y', 'z') |
ADDRESS_KEYS |
('SLC', 'LIN', 'PAR', 'AVG', 'REP', 'SEG', 'ECO', 'SET') — together they address a k-space location |
The two genuinely compiler constants — what may not be cut, what may not share a block — live in
compiler/model.py instead, because they are block-format policy rather than event identity.
events.trapzis a numpy-compat alias (np.trapezoidon numpy ≥ 2,np.trapzbelow), kept so the declarednumpy>=1.24floor is real. Deliberately absent from__all__: it is numpy's function under a compatibility name, not seqcraft API.
Pulseq quantises time on four rasters, every one supplied by the scanner. Floating point is not good
enough here: 1.5e-3 / 1e-5 is 149.99999999999997 and 250 * 1e-7 is not 2.5e-5. Both errors
propagate into ADC dwells and off-raster block durations.
The raster as an object. All arithmetic goes through integer ticks (10¹² per second) internally.
r = sc.Raster(opts.grad_raster_time, 'gradient')
assert r.holds(1.5e-3) # is this a multiple?
assert r.ceil(1.5049e-3) == 0.00151 # round up to the raster
assert r.floor(1.5049e-3) == 0.0015
assert r.nearest(1.5049e-3) == 0.0015
assert r.count(1.5e-3) == 150 # how many rasters is this?
assert r.at(150) == 0.0015 # the time of raster 150
assert repr(r) == 'Raster(gradient, 10 us)'require(t, *, what='duration') raises RasterError naming the value and the raster:
try:
r.require(1.505e-3)
except sc.RasterError as err:
assert str(err).startswith('duration 1.505000 ms is not a multiple of the 10.0 us gradient raster')Nothing here assumes 10 µs. Siemens' 10 µs, GE's 4 µs and Philips' 6.4 µs are all just numbers
read from the Opts at each call site.
Integer-tick arithmetic, for when a sum of times must land exactly on a raster:
t = 0.0 # what a TR loop does
for _ in range(1000):
t += 1.997e-3
assert t != 1.997 # and it has drifted by 23 fs
assert sc.timing.exact_sum([1.997e-3] * 1000) == 1.997 # ticks do not
terms = [1e-5] * 121 # all exact multiples of 10 us
assert sum(terms) != 0.00121
assert sc.timing.exact_sum(terms) == 0.00121
assert sc.timing.exact_diff(3e-3, 1e-3) == 0.002
assert sc.timing.to_ticks(1.5e-3) == 1_500_000_000
assert sc.timing.from_ticks(1_500_000_000) == 0.0015The accumulating loop is the honest demonstration, and it is the shape the real bug had: a plain subtraction of absolute times produced an RF delay of 129.9999999986 µs at 39 s into a sequence, which pypulseq rejects.
Do not demonstrate this with a short
sum(). CPython 3.12 gavesum()Neumaier compensated summation, sosum([1.3e-4, 5.0e-4, 3.7e-4, 2.1e-4])is exactly0.00121there and drifts on 3.11 — a claim that flips between interpreters.+=gets no such compensation, which is both why the loop above is stable and why the accumulation in real code is the thing to worry about.
| Constant | Value | Meaning |
|---|---|---|
EPS |
1e-9 |
the compiler's time tolerance — one nanosecond, well below any raster |
TICKS_PER_SECOND |
10**12 |
one tick is a picosecond; float64 holds integers exactly to 2.5 hours of them |
RasterError is defined here, with the only code that raises it, and re-exported as
sc.RasterError.
convert(value, from_unit, to_unit=None, *, gamma=GAMMA_1H, f0=None) -> floatEleven dimensions, both directions, the shape pypulseq.convert uses. Scales are exact Fractions,
so convert(4200, 'us', 's') is 0.0042 and not 0.004200000000000001.
assert sc.convert(220, 'mm', 'm') == 0.22
assert sc.convert(40, 'mT/m', 'Hz/m') == 1703040.0 # at the proton gamma
assert round(sc.convert(20, 'uT', 'Hz'), 2) == 851.52 # B1, carried in hertz
assert sc.convert(220, 'mm') == 0.22 # to_unit=None -> the SI base unitUse it so a module never spells out a factor.
| Helper | Returns |
|---|---|
dimension_of(unit) |
the dimension a unit belongs to, e.g. 'gradient' for 'mT/m' |
known_units(dimension=None) |
every unit, or every unit of one dimension |
dimensions() |
('angle', 'bvalue', 'frequency', 'gradient', 'kspace', 'kspace_area', 'kspace_rate', 'length', 'ratio', 'slew', 'time') |
GAMMA_1H |
42576000.0 Hz/T |
assert sc.units.dimension_of('mT/m') == 'gradient'
assert 'ms' in sc.units.known_units('time')
assert len(sc.units.dimensions()) == 11An unknown unit raises ConfigurationError listing what is available.
The scanner is a pypulseq.Opts. Not a seqcraft class wrapping one. The compiler reads eight
fields of it, and the same object configures pp.make_trapezoid. Build it the ordinary way:
opts = pp.Opts(max_grad=40, grad_unit='mT/m', max_slew=150, slew_unit='T/m/s', B0=3.0,
rf_dead_time=100e-6, rf_ringdown_time=30e-6, adc_dead_time=10e-6)Set the dead times. pypulseq defaults
rf_dead_time,rf_ringdown_timeandadc_dead_timeto zero. A sequence built on those zeros compiles cleanly and validates cleanly, so nothing here will tell you they are unset. They are properties of your installation rather than of a scanner model, and the PulseqSystems lookup does not carry them.
The eight fields the compiler reads:
opts.max_grad opts.rf_ringdown_time opts.gamma
opts.max_slew opts.rf_raster_time opts.adc_dead_time
opts.grad_raster_time opts.adc_raster_time (and opts.block_duration_raster)
Because deriving one Opts from another by hand loses the rest of it — Opts fills every argument
you omit from the process-global Opts.default, so the hand-written version silently returns to
zero dead times, pypulseq's rasters and a foreign gamma.
soft = sc.opts.derate(opts, grad=0.85, slew=0.70) # design a diffusion lobe against this
assert soft.max_grad == 0.85 * opts.max_grad
assert soft.rf_dead_time == opts.rf_dead_time # the hand-written version loses this
assert pp.Opts(max_grad=opts.max_grad * 0.85).rf_dead_time == 0.0derate copies all eighteen fields and changes only what it was asked to. **overrides sets any
other Opts field; an unknown one raises UnknownFieldError with a spelling suggestion.
The finished sequence is still compiled against the full opts — the derated one is a design
constraint, not a validation ceiling.
from_scanner(manufacturer, model, gradient=None, *,
rf_dead_time, rf_ringdown_time, adc_dead_time, max_b1, **overrides) -> OptsLooks max_grad, max_slew and B0 up in
PulseqSystems so they need not be copied off a spec
sheet. The four site constants are required keyword arguments because get_pulseq_specs
does not return them — they belong to the installation.
opts = sc.opts.from_scanner(
'Siemens', 'Prisma', 'XR',
rf_dead_time=100e-6, rf_ringdown_time=30e-6, adc_dead_time=10e-6,
max_b1=sc.convert(20, 'uT', 'Hz'),
)Raises UnknownFieldError for an override that is not an Opts field, and MissingExtraError if
the systems extra is not installed.
UnknownFieldError is defined here and re-exported as sc.UnknownFieldError.
pp.Opts() defaults max_b1 to 851.52 Hz — 20 µT — so the limit is live whether or not anyone
set it. SeqCraft enforces it, which makes the default worth knowing about: an ordinary 1 ms 90°
sinc peaks at 130 % of it.
| every RF module checks its own pulse | Excitation, Refocusing, IRPrep and SaturationPrep raise ConfigurationError at construction, naming what to change |
| the compiler checks the emitted sequence | HardwareLimitError, naming the block and its origin. This catches a raw pypulseq RF event added straight to a LogicBlock |
max_b1 = +inf disables both |
and only +inf does. Zero, a negative, NaN and an absent limit are each refused as unusable rather than silently treated as unlimited — NaN because every comparison against it is False, and None because pp.Opts(max_b1=None) falls back to the 20 µT default rather than to no limit. Zero is not pypulseq's convention here either: unlike adc_samples_limit, make_sinc_pulse compares rf_amplitude > system.max_b1 unconditionally, so a zero limit warns at inf % there |
The remedy depends on the pulse family, which is why each module supplies its own rather than sharing one.
| family | how the peak responds | what the refusal says |
|---|---|---|
| sinc, or gauss pinned by a time–bandwidth product | envelope stretches, so exactly 1 / duration |
the duration that fits, as a floor |
| SLR | the filter is recomputed, so scaling is not guaranteed | the same number, as a starting point to re-check |
SaturationPrep |
bandwidth_hz is fixed, so TBW moves with the duration |
likewise a starting point |
hypsec |
set by the sweep; bandwidth does nothing, and nor does duration |
beta, mu or adiabaticity via pulse_opts |
wurst |
sqrt(bandwidth / duration), so duration helps only as 1/sqrt |
bandwidth or adiabaticity via pulse_opts |
Lowering adiabaticity is not free — it is what B1 robustness is bought with — and the messages
say so.
from_scanner requires max_b1 for the same reason it requires the dead times: it belongs to the
transmit chain and the coil loading, so the PulseqSystems lookup does not carry it. Take it from the
reference voltage the scanner reports, and keep a margin.
A hardware model is not a limit. Opts says how hard the amplifier may be driven; this
describes how the body responds — three exponential time constants per axis, a stimulation
threshold, and the forbidden acoustic-resonance bands. Nothing on the compile path reads it;
sc.pns(tree, opts, hw) takes it as a third argument.
hw = sc.hardware.synthetic_hardware()
assert hw.is_synthetic is True
assert 'NOT a real scanner' in repr(hw)
synthetic_hardware()is not a real scanner. It is an illustrative stand-in so PNS checks can run without a vendor file: shaped likepypulseq.utils.siemens.asc_to_hw's output, and derived field for field from pypulseq's publicsafe_example_hw()rather than kept as a second copy of it. It must never be used to clear a human scan.It is illustrative, not conservative — not an upper bound, not a worst case, and not representative of any particular scanner. A site model may differ from it in the absolute peak, in which axis dominates, and in how it ranks one waveform against another, so use the site's own descriptor for anything scanner-specific.
The caveat travels with the object:
is_synthetic=Trueand areprthat says so.
SeqCraft does not bundle, discover or implicitly locate vendor hardware files. Using a
.asc descriptor is an explicit opt-in: you pass the path, seqcraft reads the file, and nothing
about its location is retained. path is
an ordinary string or Path, resolved the way Python resolves any other — the runtime does not
police where it points. Keeping vendor descriptors outside the repository is policy, enforced by
.gitignore rather than by this function.
The returned model carries .source, a provenance string of the form
'<basename> sha256:<12 hex>' — the file's name and hash only, never its directory and never
its contents. A missing path raises ConfigurationError, and the message points at
synthetic_hardware() for the case where there is no file to pass.
hw = sc.hardware.load_hardware('/path/to/scanner.asc')Also spelled sc.compile_sequence, for callers who would rather not shadow the builtin.
seq = sc.compile(tr, opts, name='gre', definitions={'TE': 8e-3, 'TR': 20e-3})
assert seq.definitions['TE'] == 8e-3
assert seq.definitions['Name'] == 'gre'
assert 'TotalDuration' in seq.definitionsReturns a pypulseq.Sequence. Yours to use directly — seq.write(path), seq.plot(),
seq.block_events, seq.duration()[0] are all pypulseq's own. The definitions you passed are
already set on it, along with Name and TotalDuration, so nothing has to survive until write time.
A logic block lets anything overlap anything. A pulseq block holds at most one RF, one ADC and one gradient per axis, must last a whole number of block rasters, must leave the RF dead time before a pulse and the ringdown after it, and must have gradients that join continuously across boundaries. The compiler finds boundaries satisfying all of that and combines whatever lands inside each one.
Boundaries come from two independent properties, which the reservation model keeps apart:
- Indivisible — no boundary may fall strictly inside it. An RF's dead time and ringdown, an ADC's window and trailing dead time, a trigger's pulse: each is one hardware action, so splitting it is meaningless.
- Exclusive — a block may hold at most one, so a boundary is required between two. RF and ADC
only. Triggers are
TRIGGERSextensions and pulseq accepts several per block.
Putting a boundary somewhere in the gap between each pair of consecutive exclusive reservations guarantees at most one RF and one ADC per block by construction, with nothing left to check.
| Case | Behaviour | Why |
|---|---|---|
| Gradients on different axes | silent | A phase-encode blip beside a slice rewinder beside a readout prephaser is the normal way to build a sequence. Warning would teach people to ignore warnings. |
| Gradients on the same axis | warned, then summed | Summing is almost always what was meant — a rewinder sharing time with a prephaser. But it is the one place the compiler changes a waveform, so it says so. |
| Two RF or two ADC overlapping | raises | You cannot transmit twice at once, sample twice at once, or transmit and receive at once. |
Two individually legal gradients on one axis can sum to an illegal one, and no module can see that in isolation: adding an area-100 and an area-200 trapezoid on a 40 mT/m, 150 T/m/s system reaches 93 % of the amplitude limit but 189 % of the slew limit. So amplitude and slew are measured on the compiled waveform, which is the only place the truth is visible.
Pulseq's own vocabulary, exactly as it will be written — FOV, SliceThickness, kSpaceCenterLine,
TE, TR, and anything else your acquisition wants recorded. Merged with the sequence name under a
collision check: passing Name with a value different from name/root.tag raises
DefinitionConflict rather than one silently winning.
try:
sc.compile(tr, opts, name='gre', definitions={'Name': 'something_else'})
except sc.DefinitionConflict as err:
assert 'gre' in str(err) and 'something_else' in str(err)There is no geometry argument. FOV, matrix and slice order are decisions about the scan you are
running; the compiler turns a tree into legal blocks and is indifferent to why the tree looks the way
it does. salvage/geometry.py holds a Geometry dataclass with a definitions() method if you want
one.
Every legality failure raises. There is no report to forget to check.
| Exception | Raised when | Fix |
|---|---|---|
CompileError |
Two RF or two ADC overlap; an absolute start is negative; a gradient starts off the gradient raster; no boundary can be cut in the gap between two exclusive events; a block boundary would fall inside a gradient an ADC is sampling; two ADCs write the same k-space address; an unsupported or unknown event type; check_timing fails |
Fix the tree — the message names the event, its provenance path, and usually two concrete remedies |
HardwareLimitError |
The summed waveform exceeds max_grad or max_slew on an axis; an RF event's peak exceeds max_b1; an ADC or RF event exceeds the interpreter's per-event sample limit |
Lengthen the lobe or the pulse, derate the design, or split the readout into several ADCs |
DefinitionConflict |
name= and definitions['Name'] disagree |
Pass one or the other |
CompilerContractError |
The compiled sequence does not match the tree: total duration, m0, m1 or a label address drifted; or a stage broke an IR contract | A compiler bug. Report it with the tree that produced it |
ConfigurationError |
add() got something that is not an event or a block; a unit is unknown; an Opts is unusable |
Fix the call |
RasterError |
A time does not land on a raster it must | sc.Raster(opts.grad_raster_time).ceil(t) where the time is computed |
Every message follows one shape, so it is scannable and testable:
HardwareLimitError: slew 189% of the 150 T/m/s limit on axis x.
from : tr.readout.prephaser
at : 2.340 ms (block 117)
reached: 283.5 T/m/s
fix
lengthen the lobe, or lower the readout bandwidth
or design that part against sc.opts.derate(opts, slew=0.52)
Catching them:
big = pp.make_trapezoid('x', amplitude=0.6 * opts.max_grad, duration=2e-3, system=opts)
try:
sc.compile(sc.LogicBlock('tr').add(0.0, big, big), opts)
except sc.HardwareLimitError as err:
assert str(err).startswith('gradient 120% of the 40 mT/m limit on axis x.')All exception classes are re-exported at the package root — sc.CompileError,
sc.HardwareLimitError, and so on — regardless of which submodule defines them.
Things the compiler did rather than refused. These are SeqCraftWarning, a UserWarning
subclass, emitted through the standard warnings machinery.
| Category | Meaning |
|---|---|
merge |
Two or more gradients on one axis were summed |
resample |
A gradient was resampled onto the raster to join a boundary continuously; the message gives how far it moved the waveform, k, m0 and m1 |
resample_total |
One axis was resampled in more than one block: the net m0, and the summed magnitudes of the k and m1 changes |
snap |
An RF or ADC reservation was snapped to the block raster |
orphan_label |
A label has no ADC after it, so its placement is undefined |
norm |
The vector norm across simultaneous axes exceeds the per-axis limit — normal for multi-axis gradients, and legal on real amplifiers |
One aggregated warning per category, at the end of the compile. Python's default filter shows a warning once per source line, so one warning per merge would show the first and swallow the rest. Instead you get a single line naming the count and the sites, with identical sites counted rather than repeated:
SeqCraftWarning: 8 same-axis gradient merges: tr.rewinder+tr.prephaser (axis x) x8
Handle them the standard way:
import warnings
gentle = {'duration': 2e-3, 'rise_time': 400e-6, 'system': opts}
merged = sc.LogicBlock('m').add(0.0, pp.make_trapezoid('x', area=100.0, **gentle),
pp.make_trapezoid('x', area=200.0, **gentle))
with warnings.catch_warnings(record=True) as caught: # inspect them
warnings.simplefilter('always')
sc.compile(merged, opts)
assert any('same-axis gradient merge' in str(w.message) for w in caught)
try: # or make them fatal
with warnings.catch_warnings():
warnings.simplefilter('error', sc.SeqCraftWarning)
sc.compile(merged, opts)
raise AssertionError('should have raised')
except sc.SeqCraftWarning:
passIn a test, pytest.warns(sc.SeqCraftWarning, match='merge') is the positive form; for the negative —
no warning of a kind — use catch_warnings(record=True), because pytest.warns has no clean
negative.
One entry shape: give it a tree, get numbers back. You should not have to know that PNS needs a
compiled sequence while moments do not. The one exception is sequence_kspace, for a sequence that
already exists: compiled, or read back from a .seq file, which is what a reconstruction has.
The tree on a uniform gradient raster.
grid, grads, marks = sc.sample(spoil, opts)
# grid : ndarray of times, seconds, spaced by opts.grad_raster_time
# grads : {'x': ndarray, ...} in Hz/m, summed per axis, only axes in use
# marks : [(kind, start, end, label), ...] for each RF, ADC and barrier
assert sorted(grads) == ['z'] and marks == []
assert bool(np.allclose(np.diff(grid), opts.grad_raster_time))marks entries are ('rf' | 'adc' | 'barrier', start, end, label), in tree order; a barrier has
start == end.
It samples the tree, not the compiled sequence — deliberately. It shows what you meant, before
the compiler chose block boundaries, which is what you want when the question is "did I place this
correctly". Use seq.plot() to see what the compiler made of it.
Typical uses beyond plotting:
slew = {ax: np.diff(g) / opts.grad_raster_time for ax, g in grads.items()} # slew per axis
gaps = grid[np.flatnonzero(np.abs(grads['z']) < 1e-9)] # find dead time
sampleis lossy on purpose. The grid is uniform; an arbitrary gradient's samples sit at raster centres and an extended trapezoid's knots are not uniformly spaced at all, so both are interpolated onto the grid. For a moment, a split or a sum usemoments, orknots_of+pwl_moment, which are exact. See §4.5.
Whole-tree gradient moment per axis, integrated from exact knots. Takes no opts and does no
compile — a moment is a property of the waveform, not of the scanner.
assert round(sc.moments(spoil)['z'], 6) == 500.0 # m0, in 1/m
assert 'z' in sc.moments(spoil, 1) # m1, in s/morder |
Quantity | Unit | Reads on |
|---|---|---|---|
| 0 | area — k-space displacement | 1/m | Is my readout balanced? Did the spoiler survive? |
| 1 | first moment | s/m | Flow/motion sensitivity; whether a bipolar pair is truly nulled |
| 2 | second moment | s²/m | Acceleration sensitivity |
A worked check — is this diffusion pair nulled at the echo?
m1 = sc.moments(tr, 1)
assert all(isinstance(v, float) for v in m1.values())Because it does no compile, it works on a tree the compiler would refuse:
off_raster = sc.LogicBlock('t').add(5e-6, gx) # 5 us is off the gradient raster
assert round(sc.moments(off_raster)['x']) == 258 # still measurableThe nominal k-space trajectory, in 1/m: the exact integral of the gradients from each excitation's
RF effective centre, conjugated at each refocusing pulse's, at the true ADC sample times rather
than on a raster. kspace takes a tree and compiles it. sequence_kspace takes a
pypulseq.Sequence that already exists, such as one read back from a .seq file;
kspace(tree, opts) is sequence_kspace(compile(tree, opts)).
k = sc.kspace(tr, opts)
assert set(k) == {'k_adc', 't_adc', 'k', 't_k', 't_excitation', 't_refocusing'}
assert k['k_adc'].shape[0] == 3 # (3, n_samples)
assert k['k_adc'].shape[1] == k['t_adc'].size
k_seq = sc.sequence_kspace(sc.compile(tr, opts)) # or a Sequence read back from a file
assert np.allclose(k_seq['k_adc'], k['k_adc'], atol=1e-9)| Key | Meaning |
|---|---|
k_adc |
(3, n_samples) at the ADC sample times |
t_adc |
their times |
k, t_k |
the dense trajectory and its timebase, with NaN just before each excitation |
t_excitation, t_refocusing |
RF centre times |
Use
sequence_kspace, notseq.calculate_kspace(). In the pinned PyPulseq that method samples the gradients on the raster and sums rectangles, which biases k by about half a raster of gradient.pypulseq_dependency.mdhas the detail.Why the return is named: the backend,
calculate_kspacePP, returns its tuple in a different order fromcalculate_kspace, and getting that wrong silently swaps the trajectory for its timebase — a wrong answer with no error.
Peripheral-nerve-stimulation prediction. Compiles internally, then delegates to pypulseq's SAFE model implementation.
r = sc.pns(spoil, opts, sc.hardware.synthetic_hardware())
assert set(r) == {'ok', 'peak', 'norm', 'components', 't'}
assert isinstance(r['ok'], bool) and r['peak'] >= 0.0| Key | Meaning |
|---|---|
ok |
True if the model predicts the sequence stays under the stimulation threshold |
peak |
Peak stimulation as a fraction of the limit — 0.63 is 63 % |
norm |
The full time-resolved stimulation curve |
components |
Per-axis contributions |
t |
Timebase for norm and components |
The full return matters. When ok is False, peak tells you how much but norm and t
tell you where, which is what you need to fix it:
if not r['ok']:
worst_at = r['t'][int(np.argmax(r['norm']))]
print(f'peak stimulation at {worst_at * 1e3:.1f} ms')It delegates to pypulseq's SAFE implementation rather than reimplementing it. dG/dt
convolved with three exponentials is about sixty lines and looks reachable from sample, but it
is a safety calculation, and a second implementation that can disagree with the first is the
wrong thing to own.
It is a model-based prediction, not a measurement: what comes back depends on the response model you supply as much as on the waveform.
Never used to clear a human scan with a synthetic model. See §2.3.
The diffusion b-value per axis, in s/mm², from (2π)² ∫ k(t)·k(t) dt over the emitted
gradients. Bernstein, King & Zhou §9.1, Eqs. 9.5–9.7.
g = pp.make_trapezoid('x', amplitude=25e-3 * 42.576e6, rise_time=200e-6,
flat_time=10e-3, system=opts)
b = sc.b_value(sc.LogicBlock('mono').add(0.0, g), opts)
assert set(b) == {'x', 'total'}
assert round(b['total'], 1) == 16.3The contract, in four parts:
| it integrates the whole tree | b is a property of every gradient on the axis — slice lobes, crushers and readout prephasers all contribute — so a nominally unweighted acquisition generally returns a small non-zero value |
| the phase origin is the excitation | integration runs from the first use='excitation' pulse's effective centre, with k measured relative to its value there |
refocusing pulses conjugate k |
every use='refocusing' pulse applies k → k − 2k(t_ref) from its effective centre onwards, in time order. Both instants are event.delay plus pp.calc_rf_center |
end_s chooses which instant's b |
for the nominal centre-echo b of a spin-echo DWI, pass the spin echo. A later endpoint includes the weighting accumulated after it |
Scope. Sign handling follows the excitation/refocusing pathway encoded by Pulseq use labels:
one excitation, then zero or more refocusing pulses. Stimulated echoes and more general coherence
pathways are outside what this models. Cross terms are not computed, so the return is the trace of
the b-matrix rather than the matrix.
examples/dwi_se_epi_2d/02
compares it with a Bloch simulation.
The single most important thing to get right in this module:
| Function | Basis | Exact? |
|---|---|---|
sample |
uniform raster grid, interpolated | No — for looking, and for approximate numeric work |
moments |
knots_of + pwl_moment over flatten(tree) |
Yes — never routed through sample |
kspace |
compiled, then sequence_kspace |
Yes, at true ADC sample times |
sequence_kspace |
the sequence's own gradients, through calculate_kspacePP() |
Yes, at true ADC sample times |
pns |
compiled, then calculate_pns() |
Not an exactness question — a model-based prediction, via pypulseq's SAFE implementation |
b_value |
sample, then the running integral on its raster grid |
No — numerical integration; how close depends on the waveform |
moments looks like it could be built on sample now that they sit together. It must not be — and
the reason is subtler than "sampling is lossy". Linear interpolation errs antisymmetrically about
each knot, so the halves cancel under the integral and m0 comes back bit-identical while the peak
is visibly rounded off:
w = np.sin(np.pi * np.linspace(0.0, 1.0, 13)) * 0.1 * opts.max_grad
lobe = pp.make_arbitrary_grad('x', waveform=w, first=0.0, last=0.0, system=opts)
lobe_tree = sc.LogicBlock('lobe').add(0.0, lobe)
grid, grads, _ = sc.sample(lobe_tree, opts)
peak_exact = float(np.max(np.abs(sc.events.knots_of(lobe, 0.0)[1])))
peak_sampled = float(np.max(np.abs(grads['x'])))
assert (peak_exact - peak_sampled) / peak_exact > 0.01 # the peak is visibly lost
assert abs(float(sc.events.trapz(grads['x'], grid))
- sc.moments(lobe_tree)['x']) < 1e-6 # the area is notSo a moments built on sample would look correct on every test anyone would think to write, and
the compiler's own self-check would be comparing two differently-wrong numbers.
tests/analysis/test_analysis.py asserts both halves.
Everything above is the tree, the compiler and the contract, and none of it knows what a slice is.
sc.modules is the other half: MR physics with its arithmetic attached, one class per thing.
gre = sc.modules.GRE2D(opts=opts, fov_mm=220.0, matrix=(64, 64), thickness_mm=5.0)
seq = sc.compile(gre(lines=range(64)), opts, name='gre_2d')Re-exported flat, so no import path names a folder:
| Name | What |
|---|---|
Excitation |
an RF pulse and, when selective, its selection gradient and rephaser |
Refocusing |
a 180 and its crusher pair, as one waveform symmetric about the pulse's effective centre in time and area |
PhaseEncode |
one Cartesian phase-encode blip, designed once and scaled per line |
VelocityEncode |
a bipolar pair that encodes velocity along one axis: net area zero, so stationary spins are untouched, and a first moment set by venc_m_s. Emitted one toggle at a time — polarity is the sign of the first moment, and the phase difference between the two toggles is what a reconstruction subtracts |
CartesianLine |
prephaser, readout gradient and ADC as one design — prephase=False drops the prephaser, which is the spin-echo readout; echoes/polarity read the same line more than once, which is a multi-echo gradient echo; and it can reshape the prephaser into two lobes that null the first gradient moment at the echo as well as the zeroth, which is velocity compensation — reached through the repetition-level augmentation API rather than a parameter here. oversampling takes that many ADC samples per reconstructed pixel at an unchanged bandwidth per pixel, the convention EPI2D uses; the default of 1 is the readout it has always emitted |
RadialReadout |
one radial spoke: prephaser, readout gradient and ADC, already oriented, with the trajectory geometry a caller would otherwise reverse-engineer |
SpiralReadout |
one reversible spiral arm and the four ways to traverse it — out, in, in-out, out-in. The arm is at rest at both ends, which is what makes them one family |
RosetteReadout |
whole petals of the analytic rosette k_max sin(ω1 t) e^{iω2 t}, played on the gradient raster and at rest at both ends, with a crossing report that keeps ideal instants, closest approaches and nearest samples apart |
WaveReadout |
a CartesianLine plus a sine and a cosine on the other two axes while the ADC samples: the Wave-CAIPI corkscrew. Integer cycles over the ADC dwell window, amplitude_mT_m a prescription or 'max', centering='sinzero' or 'sinctr'. The line, the CAIPI pattern, flow compensation and reconstruction are the caller's |
EPI2D |
the whole echo-planar train: prephasers, alternating lobes, blips on the zero crossings, one ADC per echo, and the labels a reconstruction reads back |
ContinuousEPI2D |
the same train sampled by one ADC window, from the first lobe's start to the last lobe's end — ramps, turnarounds and blips included — with every sample's k and time reported. The window has to fit the configured opts.adc_samples_limit, and is never split |
spoiler |
a gradient winding n turns of phase across a voxel — a function, not a class |
IRPrep |
an inversion pulse and its crusher, with the effective centre TI is measured from |
SaturationPrep |
a spectrally selective pulse and the spoiler that destroys what it made — the chemical-shift offset is the contract, and its sign is the failure that looks fine |
T2Prep |
a T2-weighting preparation: tip down, an MLEV-4 composite refocusing train, tip up, spoil. prep_time_s is the transverse interval between two RF centres, and what survives is scaled by exp(-prep_time_s / T2). tip_up names which realisation of the tip-up to build — 'simple' by default — and changes none of that |
GRE2DTR |
one repetition of a spoiled 2D gradient echo |
GRE2D |
the complete scan |
GRE3DTR |
one repetition of a 3D Cartesian gradient echo — a sibling of GRE2DTR, owning the z axis where a slab's rephasing and a partition's encoding become one gradient |
bSSFP2DTR |
one balanced repetition of a 2D Cartesian bSSFP acquisition: zero net gradient area on every axis over the RF-centre-to-RF-centre interval, with TE = TR/2 as the default realisation rather than as the definition. Every declared time is measured from the RF effective centre, which time_to_rf_center() reports. It claims a balanced waveform and never a magnetisation in steady state. flow_comp adds echo-time first-moment compensation, which is narrower than the between-excitations condition the bSSFP flow literature uses |
bSSFP3DTR |
one balanced repetition of a 3D Cartesian bSSFP acquisition — a sibling of bSSFP2DTR, where z carries slab selection, its balancing and the partition encoding. Each repetition discharges its own partition moment, so the RF-to-RF balance does not depend on which partition the successor acquires and the caller owns the view order. The selection-side lobes share one window, which is what keeps the symmetric realisation whose first moment vanishes at kz = 0 |
TSEShot |
one excitation and its train of refocused Cartesian readouts — the crusher window three axes share, and the moment balance around every refocusing pulse |
FSE2D |
the complete turbo-spin-echo scan: shots, and which lines each one acquires |
DiffusionSEPrep |
a diffusion-weighted spin echo: the excitation, the refocusing pulse, and two equal same-polarity lobes either side of it. b_s_per_mm2 in; the lobe width, the amplitude and the echo time out |
The folders behind that table are taxonomy, and each has a rule: rf/ is rf.use in
{excitation, refocusing}, preparation/ is the rest of rf.use — everything played before the
imaging train — encoding/ is gradients with no ADC, readout/ contains an ADC, kernel/
composes more than one leaf folder, imaging/ composes kernels, and the top level holds what is
not an sc.Module subclass. tests/modules/test_layout.py asserts all of it, including that
nothing in preparation/ emits an excitation or a refocusing.
Classes in preparation/ end in Prep — IRPrep, SaturationPrep and T2Prep — because for
that folder the rf.use value alone does not identify the physics, so the name carries both
parts.
DiffusionSEPrep carries the suffix too and lives in kernel/, because the folder rule is about
what a class composes: it owns an excitation and a refocusing pulse as well as its own
gradients.
sc.FlowCompensation and sc.VelocityEncoding are not modules and are not in sc.modules.
They take no opts, build nothing, and constructing one commits to nothing: they are values that
say what physics is wanted, handed to a repetition that decides whether and how it can be done.
tr = sc.modules.GRE3DTR(
opts=opts, fov_mm=(220.0, 220.0, 120.0), matrix=(128, 128, 16),
flow_comp=sc.FlowCompensation(axis='y'),
velocity_encode=sc.VelocityEncoding(venc_m_s=1.5, axis='z'),
)FlowCompensation(axis=...) |
the common-mode first moment is zero at the echo on that axis. axis may name several — ('y', 'z') — which is two independent requirements, spelled as spoil_axis already is |
VelocityEncoding(venc_m_s=..., axis=...) |
the first moment differs between two acquired states by 1 / (2 venc). .states is (+1, -1), and .delta_m1_s_per_m reads the relation from VelocityEncode.delta_m1_for, so the two paths cannot disagree |
Three things follow, and each is a refusal rather than a surprise:
Which axes work is the repetition's answer, not the intent's, and the two intents do not have the same answer:
x |
y |
z |
|
|---|---|---|---|
FlowCompensation on bSSFP2DTR |
yes | yes | yes |
FlowCompensation on GRE2DTR |
yes | yes | yes |
FlowCompensation on GRE3DTR |
yes | yes | yes |
VelocityEncoding on GRE2DTR |
no | yes | yes |
VelocityEncoding on GRE3DTR |
no | yes | yes |
A PhysicalDesignScope carries either on whichever axes its axes lists, and refuses the rest.
Flow compensation works on every axis because each one keeps the zeroth-moment job it already had
— k = 0 on the readout, the line's own k on the phase encode, a rephased slice — and gains the
first-moment one on top.
On a multi-echo acquisition it means every acquired echo, not the first one only, and there is
no option to ask for less. On any axis that is silent across the train — the phase-encode and
slice axes of a 2D gradient echo both are — that costs nothing, because a first moment about a
fixed origin stops accruing where the gradient is zero. On the readout axis it costs echo spacing,
because the condition has to be carried from one echo to the next by the waveform between the
lobes, and min_echo_spacing_s on the readout reports what it came to. A monopolar train reshapes
the fly-back it already has; a bipolar train's lobes abut, so it has to make room for a transition
and pays considerably more.
Velocity encoding needs more than that. It asks for a first moment that differs between two acquisitions, and the readout axis is realised by a solve that nulls its first moment rather than aiming it at a value. That is the current realisation's scope, not a claim that readout-axis velocity encoding is impossible; extending it would need no change to the routing.
The table is about ownership, not feasibility: an axis listed here, or in a scope's axes,
still refuses a particular request that no schedule can realise within the scanner's limits.
The same FlowCompensation value can therefore be honoured by one repetition and refused by
another, which is why the check cannot live on the value.
A state is required exactly when velocity encoding is present. tr(line=..., encoding_state=s)
for one of venc.states, and passing one where nothing generates a pair is refused too — an
ignored state would hand you two identical repetitions and show up as a subtraction that comes
back zero.
Flow compensation is the common mode, not a per-state zero. Alone, the common mode is the one
acquired state and it reads as m1 = 0. Beside a velocity encoding it fixes the mean of the two
states while the encoding fixes their difference, so they come out at ±Δm1/2 — derived, not
asked for, which is what lets the two compose without a precedence rule.
venc = sc.VelocityEncoding(venc_m_s=1.5, axis='z')
tr = sc.modules.GRE3DTR(opts=opts, fov_mm=(220.0, 220.0, 120.0), matrix=(64, 64, 8),
velocity_encode=venc)
scan = sc.LogicBlock()
at = 0.0
for partition in range(8):
for line in range(64):
for state in venc.states:
scan.add(at, tr(line=line, partition=partition, encoding_state=state))
at += tr.tr_sOrdering the states is the caller's: innermost minimises the time between the two acquisitions that get subtracted, outermost minimises the difference in their eddy-current history. This is a protocol decision and the library does not make it.
The keywords above are the convenience surface for a packaged kernel. A composition you wrote
yourself — Excitation, a readout and a spoiler, assembled in your own code — reaches the same
designer through sc.PhysicalDesignScope, without becoming a module first.
import numpy as np
exc = sc.modules.Excitation(opts=opts, flip_deg=15.0, thickness_mm=5.0, duration_s=1e-3)
arm = sc.modules.SpiralReadout(opts=opts, fov_mm=240.0, matrix=64, shots=8,
dwell_s=4e-6, variant='in')
angles = tuple(2.0 * np.pi * i / 8 for i in range(8))
scope = sc.PhysicalDesignScope(
origin_s=exc.time_to_center(), # the semantic origin of the pathway
before=exc(rephase=False), # what plays before the designed region
after=lambda angle: arm(angle_rad=angle, prephase=False), # and after it
echo_in_after_s=arm.time_to_echo(0) - arm.prephaser_duration_s,
axes=('x', 'y', 'z'), # which axes it may use inside the region
states=angles, # what your repetition varies over
min_window_s=arm.prephaser_duration_s,
)
design = scope.design(opts=opts, flow_comp=sc.FlowCompensation(axis=('x', 'y', 'z')))
scan = sc.LogicBlock('spiral')
for index, angle in enumerate(angles):
scan.add(index * 30e-3, design.build(angle))Three concepts, and they divide like this:
FlowCompensation, VelocityEncoding |
what physics is wanted — the first moment |
PhysicalDesignScope |
where it applies, and where k should be at the echo |
design.build(state) |
one state's block, built once from the finished design |
It is opt-in, and it is not a layer. Events, modules and functions into a LogicBlock and
then sc.compile needs none of this. Nor is it a different designer: a packaged kernel and a
scope end at the same internal machinery, which stays internal.
What the designed region is asked for. On each axis it owns it leaves k where k_at_echo
says at the echo, plus whatever the intents add. The default is zero — what a prephaser, a winder
and a slice rephaser all do. A family that encodes with the region it owns says so:
pe = sc.modules.PhaseEncode(opts=opts, fov_mm=220.0, matrix=32, axis='y')
ro = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=32, bandwidth_hz_px=500.0,
prephase=False) # the scope designs the prephaser
encoding = sc.PhysicalDesignScope(
origin_s=exc.time_to_center(),
before=exc(),
after=ro(),
echo_in_after_s=ro.time_to_echo(), # this block has no prephaser in it
axes=('y',),
states=tuple(range(32)),
design_states=(0, 31), # a signed pair bounds a linear encode
k_at_echo=lambda line, axis: pe.k_per_m(line),
)
encoded = encoding.design(opts=opts, flow_comp=sc.FlowCompensation(axis='y'))That is the zeroth moment of the whole scope at the echo, in 1/m. The first moment is what the
physical intents are for, which keeps the two kinds of requirement in separate places.
Handing a region over is explicit. before=exc(rephase=False) is you saying the slice
rephasing belongs to the designer now — the same seam CartesianLine(prephase=False) and
SpiralReadout(prephase=False) offer. Nothing inspects a finished block and rewrites it.
One rule is worth stating twice, because getting it wrong does not raise: what you declare must
describe the configuration you emit. A module reports its timings for its own block, and if you
asked it to leave a region out, that region's duration is still in the number it reports.
SpiralReadout.time_to_echo is measured from a block containing its own prephaser, so a scope
designing that prephaser subtracts prephaser_duration_s from echo_in_after_s.
design.at(te_s=...) redesigns the same family at a longer echo time — it does not stretch
what exists. The request goes back through the same search as an explicit TE, so the designer may
keep the region it had and let the extra time become fill in front of it rather than spending all
of it on a wider region. The achieved te_s is never shorter than the one asked for: a request
between two legal instants comes back at the first one at or above it. This is how a protocol
holding two families harmonises them.
design_states on the scope is a hint about which states will size the schedule, not a
promise. Every state is realised and checked before a schedule is accepted, so a poor hint costs
search time and never correctness.
Every module here was extracted from a working example rather than designed in the abstract.
examples/gre_2d/01_build.ipynb builds the same sequence
three ways — raw pypulseq, the leaves composed inline, and the composition as a module — which is
the shortest route to seeing what each one is for.
LogicBlock.duration is measured, so a module never declares one. What a module does answer is
the questions a tree of events cannot:
Excitation.time_to_center() |
to the RF's effective centre — for a minimum-phase pulse, nowhere near the midpoint |
Excitation.time_to_rephaser() |
where the slice rephaser begins, so another axis can start there |
Refocusing.time_to_center() |
to the conjugation instant — where calculate_kspacePP flips the sign of k, and what every echo time in a spin echo is measured from |
Refocusing.time_to_crusher() |
where the trailing crusher window begins, so the readout block can start inside the refocusing block. Worth 1.4 ms per echo |
CartesianLine.time_to_echo(echo=0) |
to k = 0, which is not the middle of the ADC window. The no-argument call is the first echo, which is what TE means in a multi-echo protocol |
CartesianLine.te_s |
k = 0 per echo, len == echoes. The only sanctioned source of echo times — a bipolar train's are not uniformly spaced, and dividing a phase difference by echo_spacing_s instead is a 0.75 % scale error in every voxel of a two-point field map |
CartesianLine.echo_spacing_s / min_echo_spacing_s |
the seam-to-seam period, and the shortest legal one. Not the spacing between echo times; see te_s |
CartesianLine.polarity_of(echo) / echo_sample(echo) |
+1/-1, and which ADC sample carries k = 0 — pre_echo_samples forward, num_samples - 1 - pre_echo_samples reverse. The wrong branch is a mirrored echo, which against a symmetric phantom looks correct |
CartesianLine.flyback_area_per_m / flyback_duration_s |
the monopolar fly-back. Minus the lobe's total area, not -area_to_echo_per_m, which is half of it and is a number the module already exposes |
CartesianLine.area_to_echo_per_m |
what the readout accumulates by the echo — minus the prephaser when there is one, and the number a spin echo's crusher pair is balanced around when there is not |
EPI2D.echo_sample(echo) |
which ADC sample of that echo carries k = 0 — pre_echo_samples forward, its mirror reverse. One line of arithmetic whose wrong branch is an N/2 ghost |
EPI2D.polarity(echo) |
+1 or -1, counted across the whole train. echo is an offset from the first imaging echo, so -navigator_echoes … -1 are the navigators and range(-navigator_echoes, len(lines)) walks the file's readouts in order |
EPI2D.k_read_per_m |
where a forward lobe's samples land in k, per sample. With ramp sampling that is not dk times an index, and nothing outside the module can derive it |
EPI2D.time_to_center_line(lines) |
to the acquisition of center_line, which the ordering decides. This is TE, and it is not the first echo |
ContinuousEPI2D.time_to_echo(echo) / time_to_center_line(lines) |
the midpoint of a lobe, which is where its kx = 0 is — an instant, on a sample only when samples_per_echo is odd. The second is TE's endpoint, where kx and ky are zero together |
ContinuousEPI2D.k_per_m(lines) / sample_times_s(lines) |
every sample of the one window: where in k, integrated from the emitted lobes and blips, and when, read off the ADC event. Sample j is lobe j // samples_per_echo |
SpiralReadout.origin_crossing_samples / origin_crossing_times |
where the trajectory passes through k = 0, as a sequence — out-in crosses twice and the others once, so a scalar would change meaning when it arrived |
SpiralReadout.k_per_m(angle_rad=…) |
the sample positions, integrated from the emitted knots rather than from the design pass. A NUFFT is told where the samples are, so a trajectory one raster out is a blur and a wrong field map |
SpiralReadout.limits() |
the peak gradient and slew this readout actually emits, measured rather than inferred from the traversal's constraints |
SpiralReadout.echo_spacing_s |
derived from the realised trajectory, None when there is one crossing |
RosetteReadout.origin_crossing_ideal_s |
the formula's P + 1 crossing instants, on the gradient raster. Beside them, origin_crossing_closest_s and origin_crossing_residual_per_m are where and how near the designed trajectory comes to k = 0, and origin_crossing_samples the nearest samples. Never merged into one number, and no scalar TE |
RosetteReadout.k_per_m(angle_rad=…) / core_samples |
every sample's position, padding included, integrated from the designed knots; core_samples is the slice taken on the analytic core |
RosetteReadout.departure_per_m / limits() |
the core's largest vector departure from the analytic curve, as an upper bound, and the peak vector gradient and slew. Measured on the designed knots |
WaveReadout.sample_times_s() / k_per_m() |
the ADC sample times, adc.delay + (n + ½)·dwell on the block clock, and the (3, N) positions on them, relative to the encoding target — integrated from the emitted knots, the same for either prephase. Under prephase=False this is the nominal contract trajectory, with the caller's prephaser_area_per_m assumed delivered, not the bare block compiled from k = 0 |
WaveReadout.prephaser_area_per_m(axis) / echo_offset_per_m(axis) |
the moment the centring needs in place before the block, stated whatever prephase is, and what a PhysicalDesignScope adds to k_at_echo (non-zero only on the sine axis under 'sinctr') |
WaveReadout.area_after_echo_per_m(axis) |
what the block plays after the echo sample, for the rewinder or spoiler that follows |
IRPrep.time_to_center() |
to the inversion's effective centre — 5.1 ms into a 10 ms hyperbolic secant, and what an inversion time is measured from |
SaturationPrep.time_to_center() |
the same question, the same origin, so a timeline can add them |
SaturationPrep.offset_hz |
the chemical shift converted once: shift_ppm × 1e-6 × B0 × γ. Negative is below water. A test traces it as far as the compiled sequence, because a sign error here is legal Pulseq that saturates the wrong tissue |
SaturationPrep.band_edge_hz |
hertz from water to the near edge of the excited band; the module refuses a pulse whose band reaches water, and this is the margin |
GRE2D.time_to_center_line(lines=…, dummies=…) |
to the readout of center_line, which depends on the ordering and on the dummy count, so it takes the same arguments build does |
GRE2DTR.min_te_s / min_tr_s |
feasibility, known at design time; a shorter request raises |
Those four compose by addition only because every one of them is measured from the start of the
block that module's build returns. An inversion time is
inv.time_to_center() + ti_s - gre.time_to_center_line(lines=segment) from the start of a shot to
the start of its train, and a term measured from anywhere else would be wrong in a way no other
number in the sequence could contradict.
The winder is three gradients on three axes playing at once — the slice rephaser on z, the
phase-encode blip on y, the readout prephaser on x. Each leaf reports its minimum and accepts
an override; GRE2DTR takes the maximum and passes it down. Stretching the short ones keeps TE at
its minimum, which inserting a delay would not.
Spoiling is more than one axis, for a different reason. spoil_axis defaults to ('x', 'z'),
because a gradient dephases only along its own direction: winding cycles on z alone leaves the
residual coherent in x, and what survives reaches the next readout carrying a ky that does not
belong to it — a ghost along the phase-encode direction rather than anything that reads as a
spoiling problem. The readout axis is the one most often missed, because after the echo only half
the readout's area is left on kx — half a cycle across one voxel. Naming 'y' adds a spoiler
beside the rewinder rather than instead of it, so the net is a fixed dephasing rather than one
that depends on the line just acquired. Cycles are counted per axis across that axis's own voxel,
which GRE2DTR.voxel_mm(axis) answers.
A refocusing pulse conjugates k, and that is a third coupling. Between consecutive refocusing
centres each axis's gradient area before the echo must equal its area after it, and the balance
point is the RF's effective centre rather than the middle of anything. Refocusing owns the
selection axis — both its crushers straddle its own pulse, so it symmetrises the plateau about the
centre and then solves the two amplitudes by integration. It cannot own the readout axis: the lobe
after readout n and the lobe before readout n+1 are the pair that has to balance, and they live
in two different readout blocks, so the caller places those and area_to_echo_per_m is the number
it balances them around.
Those readout-axis lobes are a balance, not a crusher. Their common area is cancelled by the
conjugation, so it has no k-space consequence and examples/se_2d/ sets it to zero — the crusher
belongs on the slice axis, where Refocusing puts it. Their difference is gx.area − 2 · area_to_echo_per_m, one half-dwell's worth of readout area, and that part is not optional.
refoc = sc.modules.Refocusing(opts=opts, thickness_mm=6.25, crush_voxel_mm=5.0)
line = sc.modules.CartesianLine(opts=opts, fov_mm=256.0, matrix=128,
bandwidth_hz_px=200.0, prephase=False)
assert abs(refoc.area_to_center_per_m - refoc.area_from_center_per_m) < 1e-9
assert abs(refoc.time_to_center() - refoc().duration / 2) < 1e-12 # the time half of it
skew = (float(line.gx.area) - 2 * line.area_to_echo_per_m) / 2 # the two lobes differ by 2*skew
crush_s = max(refoc.min_crush_duration_s, # one window, three axes
sc.modules.PhaseEncode(opts=opts, fov_mm=256.0, matrix=128).min_duration_s)echoes and polarity turn one Cartesian line into a multi-echo gradient echo. polarity has
no default and is required above one echo: the two modes produce files that differ in the
dwell, the echo times, the k ordering of every second echo and the block count, and look identical
in a protocol printout.
one = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=128, bandwidth_hz_px=500.0)
# eight echoes, one k grid, uniform echo times, a fly-back between each pair
mono = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=128, bandwidth_hz_px=500.0,
echoes=8, polarity='monopolar')
# eight echoes, no fly-back, every second echo reversed
bipolar = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=128, bandwidth_hz_px=500.0,
echoes=8, polarity='bipolar')
# a requested period rather than the shortest one
slower = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=128, bandwidth_hz_px=500.0,
echoes=6, polarity='monopolar', echo_spacing_s=3.0e-3)
# a multi-echo spin echo: the caller places the winders, as examples/se_2d/ does
spin = sc.modules.CartesianLine(opts=opts, fov_mm=220.0, matrix=128, bandwidth_hz_px=500.0,
echoes=4, polarity='monopolar', prephase=False)
# `echoes=1` is the module that shipped before the train existed, byte for byte
assert sc.events.content_hash(mono.gx) == sc.events.content_hash(one.gx)
assert (mono.dwell_s, mono.num_samples) == (one.dwell_s, one.num_samples)
# monopolar echo times are uniform; bipolar ones alternate by two dwells about the period
import numpy as np
assert float(np.ptp(np.diff(mono.te_s))) < 1e-12
assert abs(float(np.ptp(np.diff(bipolar.te_s))) - 2 * bipolar.dwell_s) < 1e-12
assert bipolar.echo_spacing_s < mono.echo_spacing_s
assert [bipolar.polarity_of(n) for n in range(4)] == [1, -1, 1, -1]Three things change with a second echo, and each is a place where the obvious implementation compiles, passes every k-space extent check and produces a plausible image:
| the lobe | A trapezoid is symmetric about its own midpoint, so a reverse lobe samples the forward lobe's grid only if the window is exactly centred — T == 2*guard + num_samples*dwell, with equality. The flat-top rounding that is correct for a single line puts the two polarities 0.2051 Δk apart, which is a linear phase ramp between odd and even echoes and therefore a wrong number in a field map rather than an artefact. 'bipolar' redesigns the lobe; 'monopolar' reuses the shipped one unchanged, because every lobe in it is that same lobe |
| the dwell | The guard is the ADC's delay, and pypulseq's timing check divides those by rf_raster_time, not the ten-times-finer adc_raster_time. So num_samples * dwell_s must be an even number of RF rasters, and under 'bipolar' the dwell is snapped up onto that quantum — 500 ns at 128 samples. The same request therefore gives 500.8 Hz/px monopolar and 488.3 bipolar, and bandwidth_hz_px reads back what was achieved |
| the fly-back | Minus the lobe's total area, ramps included. -area_to_echo_per_m is the pre-echo part alone — 294.638695 against 585.664336 1/m at the reference protocol — and each echo would then start half a k-space further along than the last |
ECO and REV are emitted on every acquired echo of a train, including echo 0 and including
monopolar, because pulseq labels are stateful: a skipped SET inherits rather than defaults, and a
monopolar train that inherits REV = 1 from an EPI train elsewhere in the file is mirrored by the
reconstruction. At echoes=1 neither is emitted, which is what keeps that case byte-identical.
acquire=False suppresses both with the ADC.
GRE2DTR and GRE2D forward echoes, polarity and echo_spacing_s and gain no arithmetic:
the winder coupling, min_te_s, min_tr_s, build and the spoiler all take a longer readout
without an edit, because each of them measures the block rather than predicting it. So there is
no MEGRE2D — a multi-echo gradient echo is GRE2D with two more arguments, and
examples/megre_2d/ is the one example directory that defines no class.
megre = sc.modules.GRE2D(opts=opts, fov_mm=220.0, matrix=(128, 128), thickness_mm=3.0,
flip_deg=15.0, bandwidth_hz_px=500.0, tr_s=40e-3,
echoes=8, polarity='monopolar')
assert len(megre.tr.ro.te_s) == 8The receiver is phase-locked to the transmitter. GRE2DTR gives the same phase_deg to the
excitation and to the readout. Moving one and not the other writes the RF-spoiling schedule's
quadratic phase into ky, which scatters a point source across the phase-encode direction while
the readout direction stays perfectly correct.
gre(lines=range(ny)) # fully sampled
gre(lines=sorted(acs | set(range(0, ny, 3)))) # undersampled with a calibration block
gre(lines=reversed(range(ny))) # ordering, with no new argument
gre(lines=segment, dummies=20) # the same instance, with a run-inOne argument replaces acceleration, phase-encode partial Fourier, multi-shot and ordering, because each of those is a different list — and no generators ship, because which lines to acquire is a sequence-programming choice (ADR-003). Out-of-range or duplicate indices raise; a pattern omitting the centre of k-space warns.
dummies is a build argument for the same reason: it designs no waveform — build plays the first
acquired line's gradients with acquire=False — and it describes what the acquisition does, exactly
as lines does. That is also what lets time_to_center_line mirror build instead of reading one
of its two terms off self.
EPI2D is the same idea as CartesianLine at a different scale: not one line but the whole of
k-space in one shot, so the ordering lives inside the readout and the lobes alternate sign.
epi = sc.modules.EPI2D(opts=opts, fov_mm=220.0, matrix=(128, 128), dwell_s=2.5e-6)
shot = epi(lines=range(128), segment=0) # one shot, in acquisition order
assert abs(2 * epi.guard_s + epi.num_samples * epi.dwell_s - epi.echo_spacing_s) < 1e-12
assert epi.k_read_per_m[epi.echo_sample(0)] == 0.0 # k = 0 is a sample, not a moment
assert epi.polarity(1) == -1 # so echo 1 is k_read_per_m[::-1]Rule 1 — the sampling window is exactly centred in its lobe, T = 2*guard + N*dwell, with
equality. A trapezoid is symmetric about its own midpoint, so only a centred window makes sample
i of a forward lobe and sample N-1-i of the reverse lobe that follows it land on the same k.
Write the lobe the way a line is written — flat top rounded up onto the gradient raster, slack
left after the last sample — and the two polarities sample grids up to half a raster apart. That is
an N/2 ghost the sequence made itself, it is invisible in the block structure, and it is
indistinguishable from the artefact an EPI notebook exists to measure.
Rule 2 — the blip is centred on the seam, and sc.barrier() is forced there. The seam is where
the readout gradient passes through zero: the lowest simultaneous demand on the amplifier, and the
only placement needing half a blip of guard rather than a whole one. But a centred blip straddles
the boundary the compiler has to cut between two ADCs, and no instant in that gap cuts nothing —
left to choose, the compiler takes the midpoint and splits every readout lobe in the train into
arbitrary gradients. That compiles, passes every k-space check and simulates correctly; the only
report of it is a merge warning naming the readout axis. EPI2D is the first module to emit a
barrier, and §1.2 is what it emits.
The consequence to expect, not to fix: each block then carries the trailing half of one blip and
the leading half of the next, so the compiler sums them and says so — one merge warning on the
blip axis per compile.
Four properties are the reconstruction's whole interface, and none is derivable from the file's geometry alone:
k_read_per_m |
what to grid from — non-uniform under ramp_sampling, and the same for every echo up to the reversal |
pre_echo_samples, echo_sample(echo) |
where k = 0 sits in the window, forward and reverse |
polarity(echo), and the REV label |
which echoes to reverse. Read off the file rather than recomputed, which is why the label is emitted |
oversampling |
why the flat top is sampled densely enough to regrid at all. It costs no echo spacing: twice the samples at half the dwell is the same sampling duration, so the lobe does not move |
Parallel imaging adds no argument to the readout: blip_lines=R is the acceleration and
lines is the table. The one addition is reference=, which emits the REF/IMA pair, because a
reconstruction has to tell a calibration shot from an imaging one and counting shots is how it
comes to guess wrong.
The calibration data is not an EPI. A table of length one is a Cartesian gradient echo that
happens to use the EPI's own readout lobe: same gradient, same ADC, same ramp sampling, so one
regridding operator serves both — but no train, no blips, no alternating polarity, and no
ky-versus-time ramp for GRAPPA to mistake for receive sensitivity.
r = 3
accel = sc.modules.EPI2D(opts=opts, fov_mm=220.0, matrix=(128, 128), dwell_s=2.5e-6,
blip_lines=r)
imaging = accel(lines=range(accel.center_line % r, 128, r), segment=0, reference=False)
first = accel.center_line - 16 # a 32-line calibration band
calib = [accel(lines=[line], segment=n, reference=True, # one line per excitation
phase_deg=0.5 * 117.0 * n * (n + 1)) # ...and it is a spoiled scan
for n, line in enumerate(range(first, first + 32))]lines=range(center_line % r, ny, r) rather than range(0, ny, r): range(0, 128, 3) does not
contain 64, and a scan that never acquires the centre of k-space has no echo time —
time_to_center_line refuses it rather than returning one.
phase_deg is the receiver phase, and it is not optional in a spoiled sequence. Whatever
carrier phase the excitation was given, every ADC of the train it opens has to demodulate at — one
train is one excitation, so one number covers all of its echoes. Leaving it at zero while the
transmitter runs a spoiling schedule writes that schedule's quadratic phase into the shot, which
under segmentation is a different constant per shot: a period-shots modulation of ky, and a
replica at Ny/shots. CartesianLine.build has always taken this argument; EPI2D.build takes it
for the same reason.
examples/gre_epi_2d/02 §7 prices the separately acquired calibration band against a
self-calibration no real scan can have, and §8 decomposes a segmented EPI's replica at Ny/shots
over the TR, the run-in and the spoiling schedule.
ContinuousEPI2D is EPI2D's sibling with a different receiver: one ADC event spans every
lobe, so flat tops, ramps, turnarounds and blips are all sampled. The lobes, the blips centred on
the zero crossings, the line table, blip_lines, shots, segment and phase_deg mean what they
mean for EPI2D, and the two refuse the same tables with the same words.
window_opts = pp.Opts(max_grad=32, grad_unit='mT/m', max_slew=130, slew_unit='T/m/s',
rf_dead_time=100e-6, rf_ringdown_time=30e-6, adc_dead_time=10e-6,
adc_samples_limit=8192)
cepi = sc.modules.ContinuousEPI2D(opts=window_opts, fov_mm=220.0, matrix=(64, 64),
dwell_s=5e-6, min_samples_per_dk=1.5)
cepi_train = cepi(lines=range(64)) # one ADC event of 64 x 118 samples
assert cepi.samples_per_echo * cepi.dwell_s == cepi.echo_spacing_s
cepi_k = cepi.k_per_m(range(64)) # (2, 7552): where every sample lands
cepi_t = cepi.sample_times_s(range(64)) # and when, on the block's clock
cepi_te_end = cepi.time_to_center_line(range(64)) # the midpoint of the centre line's lobe| the lobe is the window | no guard: echo_spacing_s = samples_per_echo × dwell_s exactly, on the gradient raster. The echo spacing moves in steps of lcm(dwell_s, grad_raster_time), and the samples per echo are an output |
k = 0 is an instant |
the readout prephaser is half a lobe's area, so kx = 0 is each lobe's midpoint. That is on a sample only when samples_per_echo is odd, so there is no echo_sample |
min_samples_per_dk is a density bound |
the minimum number of samples per readout k-space step dk_read_per_m, dimensionless and at least 1: every kx step between consecutive samples is at most dk_read_per_m / min_samples_per_dk, met on the flat top, where it is readout_amplitude_hz_m × dwell_s. It sets no sample count, unlike EPI2D's integer oversampling, and it bounds the spacing along kx only — not the 2D sampling of ky lines and blip samples |
| each half-blip lies in a ramp | flat-top samples sit on their ky line, the samples within blip_duration_s / 2 of a seam lie between lines, and the centre line's midpoint has ky = 0 |
| one size limit | len(lines) × samples_per_echo has to fit opts.adc_samples_limit and be a multiple of opts.adc_samples_divisor. A limit of 0 is refused at construction, and a table above the limit is refused rather than split into several events |
With prephase=False the reported trajectory is nominal. k_per_m starts the train at
kx = -area_to_echo_per_m and ky = k_blip_per_m(lines[0]), which is what the module's own
prephasers deliver. A composition that dephases before a refocusing pulse has to deliver the same
state, and is checked on the assembled sequence; sc.kspace models the conjugation.
Out of scope: navigator echoes, readout partial echo, a readout field-of-view offset, REF and
IMA labels, segmentation of the window inside the interpreter, and reconstruction.
examples/gre_epi_2d/03 builds a complete
single-shot acquisition with it, writes it and reads it back.
RadialReadout is one spoke: a prephaser, a readout gradient and an ADC, oriented in the x-y
plane. A leaf, because it determines every event it emits from its own parameters.
import math
spoke = sc.modules.RadialReadout(opts=opts, fov_mm=260.0, matrix=64, dwell_s=20e-6)
tr_s, golden = 20e-3, 2 * math.pi / (1 + 5**0.5)
scan = sc.LogicBlock()
for n in range(64): # the schedule is the caller's
scan.add(n * tr_s, spoke(angle_rad=n * golden))It is built out of CartesianLine, because a spoke is a Cartesian line pointing somewhere
other than along an axis: the prephaser, the dwell arithmetic, the ADC and — the hard one —
which sample carries k = 0 are the same problem, already solved. What this module adds is the
rotation, the semantic trajectory geometry, and a contract stated in the vocabulary of a spoke.
partial_fourier spans the family, reusing the existing parameter rather than adding
readout_asymmetry beside it:
partial_fourier |
samples at matrix=64 |
centre sample | |
|---|---|---|---|
1.0 |
64 | 32 | full spoke, -32Δk … +31Δk |
0.75 |
48 | 16 | asymmetric |
0.5 |
32 | 0 | centre-out |
Δk = 1/FOV throughout. The range is closed at both ends and 0.5 is not degenerate: it is
centre-out, a sequence family rather than an edge case. The official UTE example spans the same
continuum with an argument running the other way and shrinks Δk instead of dropping samples;
both hold the resolution the protocol asked for.
The centre sample is not the ADC midpoint, and the difference is the point. A full spoke with
an even matrix has its centre one sample past the middle — the same matrix // 2 convention
PhaseEncode uses — and a centre-out spoke has it at sample zero. center_sample,
time_to_center(), dk_per_m, k_first_per_m, k_last_per_m and k_max_per_m are the module's
answers, and they exist because the alternative is what OpenMRF's radial readout has to do:
compile a probe sequence and read its trajectory back to find out where its own centre landed.
The block is already oriented. A caller does not rotate what build returns, because the
module's semantic properties describe the oriented spoke and a trajectory whose orientation lived
somewhere else would have two owners. Internally one canonical spoke is designed along x and
fresh rotated copies are derived per call — including the stored area, which
writeFastRadialGradientEcho.m and OpenMRF RAD, both of which spoil by extending the readout's flat
time, warn is otherwise left wrong.
What stays with the caller: how many spokes, which angles, in what order, golden-angle or
equal-increment or randomised, and the excitation, spoiling and TR around them.
tests/modules/test_radial_readout.py asserts the trajectory, and the rotation-equivariance test
there is the same one that passed against write_radial_gre.py before this module
existed.
RosetteReadout plays k(t) = k_max sin(ω1 t) e^{iω2 t} for a whole number of petals, as the
gradient raster can play it: the analytic gradient sampled on raster edges, one extended trapezoid
per in-plane axis. A zero-area lead-in brings the gradient up to g(0); after the core, a lead-out
along the last gradient and a perpendicular correction cancel the core's end point. So the block
starts and ends at rest with no net in-plane moment, and it holds one ADC event.
import math
scanner = pp.Opts(max_grad=32, grad_unit='mT/m', max_slew=120, slew_unit='T/m/s',
adc_dead_time=10e-6, adc_samples_limit=8192)
rosette = sc.modules.RosetteReadout(opts=scanner, fov_mm=256.0, matrix=128, petals=13,
omega_ratio=7 / 13, dwell_s=2e-6)
shots = sc.LogicBlock()
for n in range(8): # the shot schedule is the caller's
shots.add(n * 20e-3, rosette(angle_rad=2 * math.pi * n / 8))omega_ratio is ω2/ω1: 0 is a spike through the centre, below 1 narrow petals, 1 circles
through the origin, above 1 wide petals. A shot need not close on itself. petal_duration_s
defaults to the shortest whole-raster petal that the gradient and slew limits — applied to the
in-plane vector, so every rotation is legal on every axis — and the departure budget allow. The
dwell plays no part in that choice: a dwell that moves k more than Δk per sample is refused.
The departure budget. On the raster the core departs from the analytic curve by at most a
closed-form bound B, and this readout supports B ≤ 0.05 Δk. That is an engineering budget,
not an image-quality guarantee. The bound is conservative, so a refused petal may depart by less:
the refusal marks the supported domain, not a physical limit. A compiled sequence and a written
file each round the designed knots again; those roundings are bounded separately and are not part
of the budget.
The crossings are three facts each.
origin_crossing_ideal_s |
the formula's instants: the core start plus p petals |
origin_crossing_closest_s, origin_crossing_residual_per_m |
where the designed trajectory is nearest k = 0 around each, and how near |
origin_crossing_samples |
the sample nearest each ideal instant, in integer time; the earlier of two equally near |
All three are on the clock of the block build returns, and none of them is a TE: which crossing a
protocol calls its echo is the composing kernel's choice.
The window. One dwell of padding before the core and after it, the delay floored onto
rf_raster_time and the count rounded up to adc_samples_divisor. Then a check, not an
assumption: the samples must reach from the first crossing and its closest approach to the last,
and the window grows by a divisor of samples until they do. The samples outside core_samples
are real data on the lead-in, the lead-out, or the gradient at rest. opts.adc_samples_limit
must be positive; a readout above it is refused, because this one does not split its window. The
block lasts until both the gradient and the ADC's trailing dead time have ended, with or without
the ADC, so acquire=False gives a dummy shot of the same length.
What stays with the caller: the excitation, the shot angles, RF spoiling through phase_deg,
dummy shots, TR and contrast. There is no minimum-time traversal and no ADC segmentation.
WaveReadout contains a CartesianLine and adds a sine on sine_axis and a cosine on
cosine_axis.
- The prescription. Its continuous Wave is anchored to the ADC dwell window:
cycleswhole periods overnum_samples * dwell_s, phase zero at the ADC start. - The rasters. The ADC and the Wave keep their own rasters, and the emitted Wave's knots are the prescription at every gradient-raster edge.
- Off-raster boundaries. At a window boundary between two edges the emitted Wave need not take
the prescription's value. The ADC-sampled trajectory,
k_per_m()and the written file's, is what it plays.
The corkscrew's centring is a moment that must be in place before the readout, and the module
always states it. prephase=True plays it in the block, merging the cosine's share with its
entrance ramp. prephase=False leaves it to the composition, and the cosine's ramps stay in the
block either way:
wave_opts = pp.Opts(max_grad=80, grad_unit='mT/m', max_slew=200, slew_unit='T/m/s', B0=3.0,
rf_dead_time=100e-6, rf_ringdown_time=30e-6, adc_dead_time=20e-6)
wave = sc.modules.WaveReadout(opts=wave_opts, fov_mm=200.0, matrix=64, dwell_s=7.8e-6,
cycles=7, axis='z', sine_axis='y', cosine_axis='x',
centering='sinctr', prephase=False)
exc = sc.modules.Excitation(opts=wave_opts, flip_deg=15.0, thickness_mm=150.0, axis='x',
duration_s=1e-3)
dk = {'x': 1e3 / 150.0, 'y': 1e3 / 220.0, 'z': 0.0}
scope = sc.PhysicalDesignScope(
origin_s=exc.time_to_center(), before=exc(rephase=False), after=wave(),
echo_in_after_s=wave.time_to_echo(), axes=('x', 'y', 'z'), states=((3, -2), (0, 0)),
k_at_echo=lambda line, axis: ({'y': line[0], 'x': line[1]}.get(axis, 0) * dk[axis]
+ wave.echo_offset_per_m(axis)))
design = scope.design(opts=wave_opts, flow_comp=sc.FlowCompensation(axis=('x', 'y', 'z')))
k = sc.kspace(design.build((3, -2)), wave_opts)['k_adc']
assert abs(k[1].mean() - 3 * dk['y']) < 1e-6 # the sine corkscrew is centred on its lineGRE3DTR is a sibling of GRE2DTR, not a wrapper around it. A kernel that contained one
would have to reach back inside decisions that kernel has already made — its winder timing, its
TE, its rewinding — to change the z axis, which is the reverse nesting this library avoids. Nor
is a slice-selective 2D acquisition the centre partition of a 3D slab.
tr = sc.modules.GRE3DTR(opts=opts, fov_mm=(200.0, 200.0, 160.0), matrix=(64, 64, 64))
scan = sc.LogicBlock()
table = [(line, partition) for partition in range(0, 64, 16) for line in range(0, 64, 16)]
for n, (line, partition) in enumerate(table): # the ordering is the caller's
scan.add(n * tr.tr_s, tr(line=line, partition=partition))On x and y this is a 2D repetition. On z there are two cases, and slab_thickness_mm chooses
between them — a physical quantity rather than a slab_selective=True flag, mirroring
Excitation(thickness_mm=…):
slab_thickness_mm=None |
non-selective, as writeGradientEcho3D.m and write_3Dt1_mprage.py are. The z axis carries a partition encode and nothing else |
slab_thickness_mm=… |
slab-selective. The rephasing the slab implies and the partition encoding are two moments on one axis in one window, and the kernel solves A_z(p) = A_slab + A_partition(p) as a single gradient |
The mode chooses the pulse. With no slab the default is a short hard 'block' pulse, because
a non-selective excitation with a shaped one spends a soft pulse's duration and selects nothing —
the non-selective implementations in the GRE3D reference set use a block pulse, and writeGradientEcho3D.m's is 0.2 ms. A
slab gets a shaped 'sinc'. rf_pulse= overrides either, for a shaped but spatially
non-selective excitation.
slab_thickness_mm is independent of fov_mm[2] in both directions — the only requirement is
that it is positive. A slab smaller than the encoded FOV is a calibration or inner-volume
acquisition; a larger one buys transition band and alias protection without changing the
reconstructed geometry, and a conventional full-volume protocol usually wants at least the FOV.
Both z terms are signed, so the limiting partition is a result rather than an index.
A_slab = -120 partitions -200 | 0 | +200 -> A_z -320 | -120 | +80 low edge limits
A_slab = +120 -> A_z -80 | +120 | +320 high edge limits
Every partition is enumerated after the signed combination; limiting_partition reports which one
won. One winder duration then serves them all, because a per-partition window would make TE a
function of kz — a contrast gradient across the volume that no k-space check would show.
When the worst partition needs longer than x and y do, the window is lengthened. That is
design, not legalization: the kernel holds opts, so "this moment needs 420 µs rather than 300"
is its question. With te_s=None the result is the shortest legal design; an explicit request
below it raises, naming the partition responsible and its combined moment.
The slab rephaser is realised once. Excitation.rephaser_area_per_m states the requirement
and exc(rephase=False) declines to realise it, which is how the kernel takes it over — the same
split CartesianLine(prephase=False) and area_to_echo_per_m already draw for a readout.
rephase=False does not mean the pulse needs no rephasing.
Spoiling defaults to ('x',) here, where GRE2DTR uses ('x', 'z'): in 3D the z axis already
has the partition rewinder in the tail, and two gradients each designed at the full slew limit do
not sum to a legal one. writeGradientEcho3D.m spoils on x for the same reason.
TSEShot is one excitation and echoes refocused readouts; FSE2D is a list of shots and the
lines each one acquires. echoes=1 is a conventional spin echo and one shot with a long train
and partial_fourier below 1 is HASTE, so neither has a class.
shot = sc.modules.TSEShot(opts=opts, fov_mm=256.0, matrix=(128, 128), thickness_mm=5.0,
echoes=16)
fse = sc.modules.FSE2D(opts=opts, fov_mm=256.0, matrix=(128, 128), thickness_mm=5.0,
echoes=16, tr_s=2.0)
segments = [[s + n * 8 for n in range(16)] for s in range(8)] # interleaved: 8 shots of 16
scan = fse(segments=segments, dummy_shots=1)segments is data, and it carries the turbo factor, the ordering and the effective TE in one
argument. writeTSE.m's own reordering is commented "TSE echo time magic", which is a protocol
choice rather than arithmetic, so nothing here generates one.
The division of labour is the same one GRE2DTR/GRE2D draw, and the test for it is which
layer has enough information to determine the value:
| owns | |
|---|---|
CartesianLine |
how asymmetric it is about its own echo — area_to_echo_per_m, area_after_echo_per_m, echo_moment_imbalance_per_m |
Refocusing |
its crusher pair, balanced about its own effective centre, on the selection axis |
TSEShot |
the crusher window three axes share, the echo spacing it implies, the readout-axis lobes that compensate the readout's imbalance, and the shift that keeps every echo at the midpoint between its two pulses |
FSE2D |
how many shots, which lines each acquires, how many dummies, and therefore the effective TE |
The readout-axis lobe pair is the kernel's and not Refocusing's, and the reason is the rule
above rather than taste: its size depends on the readout's geometry as well as the pulse's, and a
refocusing pulse that knew about readouts would be wrong for SE-EPI, for a diffusion spin echo and
for spectroscopy. CartesianLine states the geometry; the kernel decides the compensation.
Three invariants a train has that a single echo does not, all measured in
tests/modules/test_tse_shot.py: the refocusing pulses are uniformly spaced, every echo sits at
the midpoint between its two pulses — primary and stimulated echoes coincide only there — and ky
returns to zero at every pulse, which is why the blip goes after the refocusing pulse and the
rewinder before the next one. A single-echo spin echo may legally put the blip first; a train
that does makes every later pulse flip the encode.
FSE2D warns rather than refuses when a table scatters one echo index across widely separated
ky: adjacent k-space rows then carry T2 weightings many echoes apart, and the symptom is
ghosting that reads as motion. It is also a legitimate experiment, so it is a warning.
The one picture pypulseq cannot draw: the tree, before the compiler chose boundaries.
fig = sc.plot_block(tr, opts, title='readout') # needs matplotlib
fig.savefig('readout.png')Gradients per axis, with RF and ADC windows shaded and barriers marked. Returns the figure and never
calls show(), so the caller decides — a notebook displays it, a script saves it, a test discards it.
This is the only module allowed to import matplotlib, and it does so lazily inside each function,
so import seqcraft stays cheap. Without matplotlib installed you get MissingExtraError naming the
extra: pip install "seqcraft[viz]". A test asserts that no other file in the package imports it.
For a compiled sequence, use pypulseq's own plotter — it is better maintained and it is the same picture everyone else in the ecosystem reads:
seq = sc.compile(tr, opts)
seq.plot() # block boundaries and allThe difference between the two pictures is exactly the block structure the compiler chose.
SeqCraftError # the base; catch this to catch everything
├── ConfigurationError # a call is wrong: bad type, unknown unit, unusable Opts
│ ├── RasterError # a time is off a raster (design/timing.py)
│ └── UnknownFieldError # an Opts override that is not a field (scanner/opts.py)
├── CompileError # this tree cannot become a legal sequence (compiler/errors.py)
├── HardwareLimitError # the machine cannot play it (compiler/errors.py)
├── DefinitionConflict # two sources claim one [DEFINITIONS] key (compiler/errors.py)
└── MissingExtraError # an optional dependency is needed; names the extra
CompilerContractError(RuntimeError) # a compiler bug (compiler/verification.py)
SeqCraftWarning(UserWarning) # the compiler changed something
Exceptions live with the code that raises them, and only those raised from more than one package
stay at the root. Every one is re-exported as sc.<Name>, so the spelling never depends on the
layout — and the layering test asserts the identity, not just the presence:
import seqcraft.compiler.errors, seqcraft.design.timing, seqcraft.scanner.opts
assert sc.CompileError is seqcraft.compiler.errors.CompileError
assert sc.RasterError is seqcraft.design.timing.RasterError
assert sc.UnknownFieldError is seqcraft.scanner.opts.UnknownFieldError
assert issubclass(sc.HardwareLimitError, sc.SeqCraftError)The shared formatter. Use it if you raise from your own component and want the same shape.
from seqcraft.errors import format_error
print(format_error('TE = 4.00 ms is too short.', {'minimum': '6.34 ms'}, ["te_s='min'"]))TE = 4.00 ms is too short.
minimum: 6.34 ms
fix
te_s='min'
sections adds extra named blocks after fields, for showing one ledger per constraint chain.
You do not need these to use seqcraft. They are documented because the package asserts a layering
over them, because a CompilerContractError points here, and because the error messages name them.
None of these is re-exported. seqcraft.compiler.__all__ is ['compile_sequence'] and nothing
else; reach a stage module by its full path.
| Stage | File | Responsibility |
|---|---|---|
| place | placement.py |
Walk the tree, resolve every event to absolute active and reservation intervals |
| bound | boundaries.py |
Choose block edges: exclusivity, indivisibility, label retiming, gap feasibility |
| legalize | legalization.py |
Schedule events, transform gradients, check limits, and return validated ready blocks |
| emit | emission.py |
Mechanically hand validated ready blocks to Sequence.add_block |
| verify | verification.py |
IR contracts, finished-sequence checks, and the against-the-tree self-check |
@dataclass(frozen=True)
class PlacedEvent:
node_t: float # the node's own time, before the event's delay
start: float; end: float # the active interval
res_start: float; res_end: float # the reservation, including dead times
event: Any # a *reference* to the pypulseq event, never a copy
path: tuple[str, ...] # provenanceProperties: kind (the event's type), where (the dotted path), source_path, duration,
reservation_duration, and summary(). It holds a reference rather than a copy: seqcraft treats
pypulseq events as read-only during a compile.
@dataclass(frozen=True)
class PulseqReadyBlock:
index: int
start: float; end: float; duration: float
events: tuple[Any, ...]
source_paths: tuple[tuple[str, ...], ...]
origin: tuple[str, ...]Properties: kinds, and summary().
@dataclass(frozen=True)
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 |
|---|---|
EXCLUSIVE_KINDS |
{'rf', 'adc'} — a block holds at most one, so a boundary is required between two |
INDIVISIBLE_KINDS |
{'rf', 'adc', 'trigger', 'output'} — no boundary may fall strictly inside |
in_block_delay(p, block_start, opts) |
the event's delay within its block, snapped to its own raster in integer ticks |
time_equal, time_before, time_at_or_before, time_strictly_between |
comparisons at EPS tolerance |
interval_duration(start, end) |
exact tick arithmetic, not end - start |
Comparisons use tolerance; interval arithmetic uses integer ticks. Keeping those apart is ADR-001.
place_events(root, opts) -> tuple[PlacedEvent, ...]— the tree to absolute-time IR.UNSUPPORTED_KINDS—{type: (description, hints)}for pypulseq events seqcraft rejects by name rather than dropping:rot3D,soft_delay,rf_shim. A tree carrying a rotation extension once compiled clean, reported nothing, and played unrotated.
| Function | Does |
|---|---|
check_exclusive(placed) -> None |
Raise if two RF or ADC reservations overlap — the one conflict no choice of boundaries can fix |
find_boundaries(placed, total, raster, max_block) -> list[float] |
The sorted block edges |
label_targets(placed) -> dict[int, float] |
Per label, the time it should be assigned at — its target ADC's reservation start |
label_order_conflict(placed, targets) -> CompileError | None |
Reject label groups pulseq cannot express, because it sorts a block's extensions by library id |
orphan_label_notes(placed, targets) -> list[str] |
One note per label with no ADC after it |
Labels are assigned by target, not by containment: a boundary pushed past an ADC's reservation end would otherwise put a label into the previous readout's block and silently overwrite its k-space 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, *, resampled=None, moved=None) |
The single gradient event for one axis over one interval, or None; a resample is appended to resampled as (block_index, axis) and to moved as (axis, sup |Δk|, Δm0, Δm1), and raises CompileError beyond the resample bound |
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 |
legalize_blocks(edges, placed, targets, opts, raster) -> LegalizationResult |
Produce and validate the complete immutable ready-block sequence and its notes |
The sum of PWL functions is PWL with knots at the union of theirs, so both operations — split at a
boundary, sum on an axis — are exact. axis_gradient picks whichever pulseq representation holds the
knots untouched (extended trapezoid for on-raster knots, arbitrary gradient for the raster-centre
pattern, delayed or zero-padded within the block). Only a waveform bending both on and off the
raster fits neither, and that one is resampled with a measured bound on how far it moved, and
refused when it would move k by more than r²·max_slew/4 per raster-centre piece (ADR-008).
| Function | Does |
|---|---|
emit_blocks(seq, blocks) -> None |
Add validated ready blocks without scheduling, transforming, or checking limits |
The ready-block origin is used to add source context when PyPulseq rejects a block. Emission has no access to placed events, boundaries, label targets, the scanner limits, or transformation notes.
| Function | Does |
|---|---|
verify_placed_events(events) -> tuple[ContractViolation, ...] |
Structural contract on the first IR |
verify_ready_blocks(blocks, *, expected_first_index=0, expected_start=None) |
Structural contract on the second |
require_valid_contract(name, violations) -> None |
Raise CompilerContractError if any |
check_event_sizes(seq, opts, origins=()) -> None |
Raise HardwareLimitError above the interpreter's per-event sample limit |
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 |
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:
- Total duration matches the tree's — guards a boundary merge that dropped time.
- 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.
- 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
Adisplaced bydtchanges it byA·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. - 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.
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 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.
require() probes the pinned pypulseq fork for the functions seqcraft needs and fails once with a
complete list, rather than letting the first caller that needs a missing one fail with an opaque
AttributeError halfway through a build. PYPULSEQ_VERSION is the expected version string. It runs
at import. Which pypulseq is pinned, and why, is in pypulseq_dependency.md.
| Removed | Replacement |
|---|---|
out = sc.compile(...) returning CompiledSequence |
seq = sc.compile(...) returning pypulseq.Sequence |
out.seq |
seq |
out.n_blocks |
len(seq.block_events) |
out.duration_s |
seq.duration()[0] |
out.definitions |
seq.definitions — set by the compiler |
out.check(), out.report, Issue, Report, ReportFailed |
the compile raised, or warned |
out.report.of_kind('grad_resample') |
pytest.warns(sc.SeqCraftWarning, match='resample') |
out.check().raise_if_failed() |
nothing — failures already raised |
out.write(path), WriteResult |
seq.write(str(path)) |
out.write(path, sidecar=True), sc.provenance |
nothing yet — see serialization.md |
out.origin(i) |
gone; provenance paths still name the source in every error message |
out.moments(1) |
sc.moments(tree, 1) |
out.kspace() |
sc.kspace(tree, opts) |
out.pns(hw) |
sc.pns(tree, opts, hw) — now returns the full curve |
sc.plot_sequence(out) |
seq.plot() |
sc.plot_trajectory(interleaves) |
sc.kspace(...) + three lines of matplotlib |
sc.testing.assert_* |
the compiler raises; for purity see writing_a_module.md |
sc.Geometry, compile(geometry=) |
salvage/geometry.py, passed via definitions= |
sc.validate.*, merge_definitions |
gone; two sources need a collision check, not a merge |
sc.UnitSanityError |
raised nowhere; salvage/geometry.py has its own |
seqcraft.design.sampling |
seqcraft.analysis |
seqcraft.result, seqcraft.report, seqcraft.testing |
deleted |
ADR-004 records why.
| Name | Where | Kind |
|---|---|---|
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 |
ConfigurationError |
errors |
exception |
ContinuousEPI2D |
modules |
class |
ContractViolation |
compiler.verification |
class |
DefinitionConflict |
compiler.errors |
exception |
DiffusionSEPrep |
modules |
class |
EPI2D |
modules |
class |
EPS |
design.timing |
constant |
EXCLUSIVE_KINDS |
compiler.model |
constant |
Event |
design.events |
type alias |
Excitation |
modules |
class |
FSE2D |
modules |
class |
GAMMA_1H |
design.units |
constant |
GRADIENT_KINDS |
design.events |
constant |
GRE2D |
modules |
class |
GRE2DTR |
modules |
class |
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 |
LABEL_KINDS |
design.events |
constant |
LegalizationResult |
compiler.model |
class |
LogicBlock |
design.logic |
class |
MissingExtraError |
errors |
exception |
Module |
design.module |
class |
Node |
design.logic |
class |
POINT_KINDS |
design.events |
constant |
PYPULSEQ_VERSION |
_compat |
constant |
PhaseEncode |
modules |
class |
VelocityEncode |
modules |
class |
FlowCompensation |
augmentation |
class |
VelocityEncoding |
augmentation |
class |
PhysicalDesign |
physical_design |
class |
PhysicalDesignScope |
physical_design |
class |
RadialReadout |
modules |
class |
RosetteReadout |
modules |
class |
PlacedEvent |
compiler.model |
class |
PulseqReadyBlock |
compiler.model |
class |
Raster |
design.timing |
class |
RasterError |
design.timing |
exception |
Refocusing |
modules |
class |
SaturationPrep |
modules |
class |
T2Prep |
modules |
class |
SpiralReadout |
modules |
class |
WaveReadout |
modules |
class |
TSEShot |
modules |
class |
SeqCraftError |
errors |
exception |
SeqCraftWarning |
errors |
warning |
TICKS_PER_SECOND |
design.timing |
constant |
UNSUPPORTED_KINDS |
compiler.placement |
constant |
UnknownFieldError |
scanner.opts |
exception |
axis_gradient |
compiler.legalization |
function |
b_value |
analysis |
function |
bSSFP2DTR |
modules |
class |
bSSFP3DTR |
modules |
class |
barrier |
design.logic |
function |
check_event_sizes |
compiler.verification |
function |
check_exclusive |
compiler.boundaries |
function |
check_label_addresses |
compiler.verification |
function |
check_rf_amplitude |
compiler.verification |
function |
check_limits |
design.events |
function |
check_limits |
compiler.legalization |
function |
common_path |
compiler.legalization |
function |
compile_sequence |
compiler |
function |
content_hash |
design.events |
function |
convert |
design.units |
function |
derate |
scanner.opts |
function |
derive |
design.events |
function |
dimension_of |
design.units |
function |
dimensions |
design.units |
function |
emit_blocks |
compiler.emission |
function |
exact_diff |
design.timing |
function |
exact_sum |
design.timing |
function |
expected_addresses |
compiler.verification |
function |
find_boundaries |
compiler.boundaries |
function |
flatten |
design.logic |
function |
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 |
known_units |
design.units |
function |
kspace |
analysis |
function |
label_order_conflict |
compiler.boundaries |
function |
label_targets |
compiler.boundaries |
function |
legalize_blocks |
compiler.legalization |
function |
load_hardware |
scanner.hardware |
function |
moments |
analysis |
function |
orphan_label_notes |
compiler.boundaries |
function |
place_events |
compiler.placement |
function |
plot_block |
display |
function |
pns |
analysis |
function |
pwl_moment |
design.events |
function |
require |
_compat |
function |
require_valid_contract |
compiler.verification |
function |
required_duration |
compiler.legalization |
function |
sample |
analysis |
function |
sequence_kspace |
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 |
time_before |
compiler.model |
function |
time_equal |
compiler.model |
function |
time_strictly_between |
compiler.model |
function |
to_ticks |
design.timing |
function |
verify_against_tree |
compiler.verification |
function |
verify_placed_events |
compiler.verification |
function |
verify_ready_blocks |
compiler.verification |
function |
waveform_of |
design.events |
function |