Reconstruction plugins#
A reconstruction plugin is a file, <name>.py in a --plugins directory of the
reconstruction proxy, holding a ReconPlugin subclass
and a module-level PLUGIN instance. This one is bart pics on ESPIRiT maps:
# recon/gre.py
import bartorch.tools as bt
import torch
from bartorch import apps, priors
from pulserver import recon
class Pics(recon.ReconPlugin):
def recon(self, context, branch, data):
kspace = torch.from_numpy(data.data.kspace) # (coils, y, x)
maps = bt.ecalib(kspace, maps=1)
image = apps.pics(kspace, maps, regularizers=priors.Wavelet((-1, -2), 0.005))
return recon.ReconResult(image.abs().numpy())
PLUGIN = Pics()
data is the ReconData of one reconstruction unit,
and data.data its k-space, (coils, ..., readout), with the axes
data.data.axes names. Readouts are placed by their echo along the readout and
by their encoding counters along the encoded axes (Readout placement); a
sequence sets the counters with pypulseqpp.sequences.Labels or
pp.make_label as in PyPulseq, and a readout placed over another raises a
warning.
The proxy runs the plugin in a worker process, one per series, over an MRD stream enriched from the sequence’s design (Reconstruction session). The client names the plugin of a series in its config (Reconstruction client), independently of the scanner-sequence plugin the series was played from.
Site dependencies#
A site library holds packages outside the environment managed by an installer.
PULSERVER_SITE_PACKAGES names this directory. A scanner installer may configure
it through a Python startup hook; pulserver site path prints the active path.
The library precedes the managed packages and is available to sequence plugins,
reconstruction workers, offline replay and Python subprocesses using that
interpreter. Restart design/reconstruction services after changing packages;
already imported modules retain their code.
Install local wheels with the interpreter that will run them:
pulserver site --root /path/to/site/lib install ./my_qsm-1.2-py3-none-any.whl
This uses pip with --target, --no-index, --no-deps and --upgrade.
Private wheels need no package index. Download or build dependencies as wheels
and install them explicitly; the command does not replace the managed
environment. A package can also be copied into the library, or installed with
python -m pip install --target /path/to/site/lib --no-deps package.whl.
Wheel hashes and the installation’s Python ABI are recorded by site install;
a direct pip install or source copy does not create that record.
A plugin declares requirements as a module-level literal tuple or list:
REQUIRES = ("my-qsm>=1.2",)
REQUIRES_IMPORTS = ("my_qsm._core", "my_qsm._cuda")
Both plugin loaders check REQUIRES before executing the plugin. Installed
versions, transitive requirements, extras and environment markers are checked;
direct URL requirements belong to the installation command, not this declaration.
A source-only package needs distribution metadata for a version requirement.
REQUIRES_IMPORTS is an explicit preflight list, not a request to import GPU
libraries in the design server. Run this on each computer that runs the plugin,
before scanning:
pulserver site check --plugin /path/to/recon50.py
The check resolves requirements and imports each REQUIRES_IMPORTS module.
--import MODULE adds an import probe. This can detect missing native libraries
and extension import failures; it does not exercise CUDA kernels. Run the
package’s GPU self-test on the reconstruction computer as well.
C++/CUDA wheels must match the running Python ABI, architecture, system-library
requirements and GPU runtime/device support. pip checks wheel platform tags;
those tags do not establish PyTorch/CUDA binary compatibility. The site installer
records the Torch build for native wheels and refuses a recorded library after
its Python ABI, architecture or Torch build changes. Use an empty library and
compatible wheels for an upgraded environment. Bundled shared libraries must be
loadable by the wheel’s own paths (for example an ELF $ORIGIN RPATH).
Declared dependencies enter the sequence design identity and manifest.
Reconstruction results carry PulserverReconstructionManifest and the JSON
PulserverReconstructionDependencies in MRD image attributes. The same JSON is
saved under manifests/ beside the site library, or PULSERVER_PROVENANCE_DIR
when set. It identifies the plugin source, resolved package versions, runtime,
measurement, installed site-package versions and recorded wheel hashes. Site
packages are recorded even when a plugin has no hard requirements, covering
optional backends. Optional backends that a plugin can skip
should not be hard requirements.
Reconstruction units#
A reconstruction unit is the set of readouts reconstructed together
(Reconstruction plugins and calibration context): those of one branch and one encoding
space that share their slice, contrast, cardiac phase, repetition, set and
average counters. The segment and user counters do not separate units. A
counter named in axes becomes an axis of the unit’s k-space instead, so that
the echoes or averages of an image are one unit.
A unit closes when the flag triggers names for its branch has arrived at every
position along its axes and merge counters, and recon is called with it
once. The unit is released when recon returns, so a series holds only the
units open at once, and a plugin that needs the data of an earlier unit keeps
the parts it needs. A unit still open at the last readout of the measurement
(LAST_IN_MEASUREMENT) or at the end of the stream is reconstructed then,
under its own branch, in the order the units opened.
Argument |
Sets |
|---|---|
|
|
|
|
|
The counters that are axes of a unit instead of separating units |
|
The counters that neither separate units nor are axes: a unit waits for its closing flag at each of their values, and their readouts fill one k-space, as the place in an echo train or an inversion shot ( |
|
The flags an acquisition must all carry, and those any one of which excludes it |
|
Whether readouts are placed in |
recon receives the unit as a ReconData:
Attribute |
Holds |
|---|---|
|
The k-space of the imaging readouts, a |
|
The k-space of the parallel-imaging calibration readouts, laid out as |
|
The unit’s image counters not in |
|
The waveforms received since the previous unit closed |
|
Every readout the unit received, in arrival order |
A readout flagged IS_PARALLEL_CALIBRATION is placed in ref only, one flagged
IS_PARALLEL_CALIBRATION_AND_IMAGING in both, and one flagged
IS_PHASECORR_DATA in neither unless it is also a calibration readout.
Plugin hooks#
The runtime calls three hooks over one stream:
Hook |
Called |
|---|---|
once, before any acquisition |
|
for each unit, as it closes |
|
once, after the last unit |
Only recon has to be written. The runtime passes every acquisition to
receive(), which is not overridden: it
applies require_flags and reject_flags, runs the gadgets over the
readout, adds it to the unit of the branch
branch_for() names, and calls recon for
each unit that closes. branch_for returns no branch for a noise measurement,
nor for a navigator readout unless triggers declares a "navigator" branch;
every other readout belongs to the first branch triggers declares.
>>> import numpy as np
>>> import pulserver.mrd as mrd
>>> import pulserver.recon as recon
>>> class DropNoise(recon.Gadget):
... def __call__(self, acquisition, data):
... noise = mrd.has_acquisition_flag(acquisition, "ACQ_IS_NOISE_MEASUREMENT")
... return None if noise else data
>>> class RootSumOfSquares(recon.ReconPlugin):
... def __init__(self):
... super().__init__(
... gadgets=[DropNoise()],
... triggers={"imaging": mrd.AcquisitionFlag.LAST_IN_SLICE},
... )
... def recon(self, context, branch, data):
... image = np.fft.fftshift(np.fft.ifft2(data.data.kspace))
... return recon.ReconResult(np.sqrt(np.sum(np.abs(image) ** 2, axis=0)))
>>> PLUGIN = RootSumOfSquares()
A ReconResult is packaged as an MRD image, so a
plugin builds no image header. The field of view is that of the unit’s encoding
space, the position, orientation and physiology time stamps are those of the
unit’s reference acquisition, data.data.reference, and the time stamp is the
earliest of the unit’s acquisitions. reference=<acquisition> takes the
geometry from another acquisition. The MRD image holds the array as returned,
float32 or complex64, with no scale applied. dicom=True sends the result
as DICOM instead (DICOM output).
Each series runs on its own copy of PLUGIN
(spawn()), and a hook reaches its gadgets
through self.gadget(kind). context.exam, an
ExamCache, is shared by the series of one exam, such
as for a coil calibration; under the proxy a stored value reaches the next
series pickled, as a copy without its cleanup. context.device is the GPU
the proxy gave the series, such as "cuda:0", or None. The shipped plugins
keep a unit’s k-space, maps and solver vectors on the host and build their
encoding on that device, which brings a coil at a time over as it applies. A
child process started with the spawn method runs functions from importable
modules, not from the plugin file.
Readout placement#
A readout of a Cartesian encoding space is placed so that its echo,
center_sample, lies at sample N // 2 of the readout axis, the samples from
discard_pre to number_of_samples - discard_post being the ones copied. The
counter of a line is placed at counter - center + extent // 2 along the
encoded axis, center being the counter of the k-space centre in the header’s
encoding limits, so the counters of a partial-Fourier or undersampled scan
need not start at 0. A readout or a line that falls outside the buffer raises a
ValueError. data.data.readout is the first and last sample placed.
Two gadgets bring the readouts to the reconstruction matrix, run in this order.
AsymmetricEcho zero-fills a partial echo to the full
echo that is symmetric about its center_sample, and declares the zeros
discarded so that they are not placed.
RemoveReadoutOversampling crops a full echo to the
readout field of view of the reconstruction, the ratio of the header’s encoded
to reconstructed field of view along the readout. A gadget states the echo of
the readout it returns by assigning center_sample, discard_pre and
discard_post of the acquisition it is given, which is a copy of the one the
stream delivered:
>>> import ismrmrd
>>> acquisition = ismrmrd.Acquisition()
>>> acquisition.resize(5, 2)
>>> acquisition.center_sample = 1
>>> full = recon.AsymmetricEcho()(acquisition, np.ones((2, 5), dtype=np.complex64))
>>> full.shape[-1], acquisition.discard_pre, acquisition.center_sample
(8, 3, 4)
The placement and the image headers are specified in Reconstruction proxy.
Non-Cartesian data#
A buffer holds the trajectory of its samples beside the k-space, as the
acquisitions carry it: k along the sequence’s x, y and z gradient axes, in 1/m.
grid_trajectory() returns it in the grid
units and layout bartorch.linop.NUFFT takes, with the coils of the buffer’s
kspace as a batch axis of the image:
import torch
from bartorch.linop import NUFFT
buffer = data.data
nufft = NUFFT(
torch.from_numpy(buffer.grid_trajectory()),
image_shape=(buffer.coils, *buffer.image_shape),
)
coil_images = nufft.adjoint(torch.from_numpy(buffer.kspace))
The partitions of a stack of spokes or spirals are placed by their
kspace_encode_step_2 counter and carry no kz: transform the partition axis
with an FFT before the in-plane NUFFT.
Coil sensitivities, noise and compression#
coil_maps() returns the coil sensitivities of a unit as
a complex torch tensor (coils, [z,] y, x) on the host. They are
estimated by the function the plugin passes, from the unit’s calibration
k-space data.ref, or taken from the maps the stream or the exam holds
(Calibration, noise and coil compression states the order and the
conditions for reuse). Prewhiten is a gadget and
CoilCompression a step called from recon; all three
compute with bartorch. The gadget CompressChannels
compresses each readout as it arrives instead, from the calibration readouts
that lead the scan, so the buffers never hold the full set of channels.
# recon/gre.py
import torch
from bartorch import apps, priors
from pulserver import mrd, recon
class Pics(recon.ReconPlugin):
def __init__(self):
super().__init__(
gadgets=[
recon.Prewhiten(),
recon.AsymmetricEcho(),
recon.RemoveReadoutOversampling(),
],
triggers={"imaging": mrd.AcquisitionFlag.LAST_IN_SLICE},
)
self.compression = recon.CoilCompression(6)
def recon(self, context, branch, data):
data = self.compression(context, data)
maps = recon.coil_maps(context, data, estimate=apps.nlinv_maps)
if data.data is None: # a unit of calibration readouts only
return None
kspace = torch.from_numpy(data.data.kspace)
image = apps.pics(kspace, maps, regularizers=priors.Wavelet((-1, -2), 0.005))
return recon.ReconResult(image.abs().numpy())
PLUGIN = Pics()
Prewhiten consumes the noise readouts of the stream and whitens every other
readout with them, or with the noise covariance a noise series left in the
exam. Without either it passes readouts unchanged and logs a warning once;
Prewhiten(required=True) raises instead. CoilCompression(n) keeps n
virtual channels, at most the channels of the first unit, with the basis of
that unit’s calibration k-space (its imaging k-space where it has none), and
projects every later unit onto it. Compress a unit before requesting its maps,
so that they are estimated in the basis of the data they are used with.
CompressChannels(n), placed after Prewhiten and before AsymmetricEcho,
holds the leading calibration readouts until the first imaging-only readout,
estimates the basis from those of the first contrast, and gives them on
projected; a scan whose first readout is not calibration passes it unchanged,
and a CoilCompression step in recon then compresses each unit.
apps.pics computes where the maps are, here the host. An encoding built with
device=context.device, such as bartorch.linop.CartesianSense(), computes
on the GPU and takes the k-space, the maps and the solver’s vectors from the
host a coil at a time, so the GPU never holds a whole multi-coil volume; the
pics plugin solves so. Off the grid, apps.pics builds its encoding where the
trajectory is, so a trajectory on context.device with the rest on the host
does the same; the nufft plugin solves so.
The pics and nufft handlers fit the maps with
apps.nlinv_maps(kspace, phase_pole=0), bart nlinv --phase-pole 0, on a grid
of the central 48 lines, or of the trajectory’s samples within 24 grid units of
the centre, and zero-fill them to the image grid: after every Gauss-Newton step
the phase poles the maps share are moved into the image. Without it, maps that
share a phase pole go to zero there in every coil, and the image has a dark
spot at it. BART refuses the detection on a grid with an axis no longer than a
twentieth of its longest, rounded up; a slab of 3 partitions or fewer, on a
matrix of 48 or more, is fitted without the correction. A grid of 24 lines
left a ghost at half the field of view of a scan undersampled by 2 along its
partitions.
A calibration unit, whose data.data is None, stores its maps for its slice,
and the imaging units of that slice take them from the stream. A series that is
only a calibration leaves its maps to the exam by assigning
context.coil_sensitivities, and a noise series leaves its whitening with
publish():
class Calibration(recon.ReconPlugin):
def recon(self, context, branch, data):
recon.coil_maps(context, data, estimate=apps.nlinv_maps)
context.coil_sensitivities = context.coil_maps[data.counters["slice"]]
class Noise(recon.ReconPlugin):
def __init__(self):
super().__init__(gadgets=[recon.Prewhiten()])
def recon(self, context, branch, data):
return None
def finish(self, context):
self.gadget(recon.Prewhiten).publish()
The exam holds one set of maps. A later series is given them only where the
coil labels, the whitening, the compression and the geometry equal its own;
otherwise MissingCalibration is raised, naming the
first field that differs with both values, and the failure text the client
receives carries the message. required=False returns None instead of
raising.
DICOM output#
A DICOM dataset stores integer pixels, made when a result with dicom=True is
converted from the image the plugin returned. The dataset’s rescale maps them
to the values of the image, value = stored × RescaleSlope + RescaleIntercept,
with one mapping per DICOM series, a series being the images that share
image_series_index.
An integer image is stored as it is. Its dataset carries a rescale only when the attributes of the result state one.
The first floating-point image of a series fixes the mapping of the series. The intercept is 0, so that zero is stored as zero, and the slope stores the peak magnitude of the image at half the stored range, which leaves headroom for later images of the series up to twice as large. The stored type is 16-bit, signed when that image has a negative value and unsigned otherwise. An image that states
ArrayMinimumandArrayMaximumis mapped as the array of images it belongs to, so the mapping of a series that begins with a volume does not depend on which partition arrives first. A complex image is stored as its magnitude. An image with no nonzero finite value fixes no mapping.Every later image of the series is stored under the mapping of the series, so the ratios between the values of its images are the ratios between their stored integers.
A mapping stated in the attributes of a result,
RescaleSlopeorRescaleIntercept, is the mapping of that image:stored = round((value - intercept) / slope), a slope left out being 1 and an intercept left out 0. The slope is nonzero and both are finite. When the image is the first floating-point image of its series, the stated mapping is also that of the series, and later images that state none are stored under it:return recon.ReconResult( image, dicom=True, attributes={"RescaleSlope": 1e-4, "RescaleIntercept": 0.0}, )
A value outside the range of the stored type is clipped to the nearest end of the range, never wrapped, and NaN is stored as 0. The clipped pixels are counted for each series, and the first clipping of a series is logged with its count. An image whose peak exceeds twice the peak its series was mapped from is clipped under the mapping of the series, unless the plugin states a mapping.
RescaleType is US, unspecified: the units are those of the reconstruction.
A DICOM image is written in the radiological display orientation of the plane it lies closest to: an axial image with the patient’s right on the left and anterior at the top, a coronal one with the right on the left and superior at the top, a sagittal one with anterior on the left and superior at the top. Its pixels are flipped and transposed to that orientation, never resampled; the MRD image keeps the orientation the reconstruction returned.
Each series_index is a DICOM series of its own. The first to arrive takes the
series identity the header states; each later one a series UID derived from it
and, on a GE system, the series number 100 × measurementID + k for the
k-th after the first.
A plot, a fit or a report reaches the scanner as an RGB result: a (y, x, 3)
array of values from 0 to 255, which figure_rgb() draws
from a matplotlib figure, stored as a DICOM secondary capture.
return recon.ReconResult(
recon.figure_rgb(figure),
image_type="rgb",
series_index=10,
dicom=True,
attributes={"SeriesDescription": "T1 fit"},
)
Recon parameters#
A sequence states values for its reconstruction with
pulserver.design.recon_parameters(), which writes each as a definition
and lists its name in the ReconParameters definition. The proxy copies every
listed definition into the MRD header as a user parameter string of the same
name, which the reconstruction reads:
from pulserver import mrd
anatomy = int(float(mrd.user_parameter(context.header, "QsmAnatomy", 0)))
The shipped reconstructions read QsmAnatomy (qsm) and KSpaceFilter,
GradientUnwarp, IntensityCorrection and IntensityCorrectionLevels (all
of them; Shipped reconstructions).
Diffusion tables#
The proxy states the diffusion table a design names in the header’s
diffusion_table user parameter string. pulserver.mrd.diffusion_table()
returns it as the b-value of each volume, in s/mm², and its unit direction
along the logical readout, phase and slice axes, zero where the b-value is
zero. Row i is the volume whose repetition counter is i:
from pulserver import mrd
b, g = mrd.diffusion_table(context.header)
A DICOM result of a series with a table states the image’s DiffusionBValue,
its DiffusionGradientOrientation, the direction turned into the patient frame
through the image’s read_dir, phase_dir and slice_dir, and its
DiffusionDirectionality. These are the DICOM standard’s own attributes, from
which dcm2niix writes the .bval and .bvec files FSL, DIPY and BIDS read, and
which MRtrix reads directly.
Logging#
A plugin logs with the standard logging module, under a logger of its own
(logging.getLogger(__name__)). Under the proxy, what a plugin logs, prints or
warns is appended to the proxy’s --logfile, each record stamped with its time,
process ID, level and logger name.
Offline reconstruction#
run() reconstructs an ISMRMRD HDF5 file in
the calling process, through the same hooks. A file the proxy’s --save-data
keeps is enriched already and plays as it stands. A file recorded as the
scanner sends it, such as pulserver scan --mrd raw.h5 writes, is enriched
first from the design it was played from, found in a design store or given as
its sequence file, with its manifest beside it; given a design, an enriched
file is still played as it stands, never enriched twice:
images = PLUGIN.run("raw.h5", store="designs")
images = PLUGIN.run("raw.h5", design="designs/scan/9c74a8aa28527cf231/sequence.seq")
pulserver replay does the same from the command line
(Series replay).
Calling the plugin on an AcquisitionBucket runs
startup, passes every acquisition to receive, reconstructs the units still
open, runs finish, and returns the last output. A header need only describe
the encoded space and the receiver channels:
>>> from types import SimpleNamespace
>>> matrix = SimpleNamespace(matrixSize=SimpleNamespace(x=8, y=4, z=1))
>>> header = SimpleNamespace(
... encoding=[SimpleNamespace(encodedSpace=matrix, reconSpace=matrix)],
... acquisitionSystemInformation=SimpleNamespace(receiverChannels=2),
... )
>>> bucket = mrd.AcquisitionBucket.from_arrays(
... np.ones((4, 2, 8), dtype=np.complex64),
... labels={"kspace_encode_step_1": np.arange(4)},
... )
>>> result = PLUGIN(bucket, recon.ReconContext.offline(header))
>>> result.data.shape
(4, 8)
Shipped reconstructions#
Seven shipped plugins are complete reconstructions, returning the values of their
transform or solve, unscaled but for the corrections below. They are searched after every reconstruction
plugin directory, so a client can name one, such as nufft, without a file of
its own, and a file of the same name in a --plugins directory replaces it.
Each whitens its readouts with Prewhiten, compresses
more than six receive channels to six virtual channels (pics as the readouts
arrive, CompressChannels; the others a unit at a
time, CoilCompression), and sends a volume as one
image per partition.
Every shipped plugin corrects each image in three steps, in this order
(Corrections):
Step |
Correction |
History |
Recon parameter |
Argument |
|---|---|---|---|---|
Fermi filter |
The k-space of the complex image the solve returns, over its encoded axes, is multiplied by a radial Fermi window, half height at the Nyquist edge and a transition of ten samples of the longest axis ( |
|
|
|
Gradient nonlinearity |
The image is resampled from where its voxels were acquired to where they belong, from the gradient coil’s table the header states as |
|
|
|
Receive field |
The magnitude images are divided by the field N4 estimates from the first magnitude image of each slice and set ( |
|
|
|
A recon parameter of 0, off, false or no turns its step off, and any other number, on, true or yes on; without
one, the plugin’s argument decides, and every argument defaults to on.
IntensityCorrectionLevels states the fitting levels of the receive field,
four where absent: a scan of a vial phantom whose intensity ratios are
measured states 2, or IntensityCorrection 0 to send the magnitude as
solved:
from pulserver.design import recon_parameters
recon_parameters(seq, IntensityCorrectionLevels=2)
When a series starts, the log states which steps are on and why any is off, such as a header that states no gradient coil table, and each step logs a line when it corrects the series’ first image. A step that cannot run, such as the receive field without SimpleITK, sends the image on as it was and logs why. A site turns a step off for a plugin with its argument:
from pulserver.recon.handlers.pics import PicsRecon
PLUGIN = PicsRecon(intensity_correction=False)
Plugin |
Reconstructs |
|---|---|
|
One image per slice, contrast, cardiac phase, set and repetition, averages summed, from readouts placed by their encoding counters, whitened, compressed to six virtual channels from the calibration readouts that lead the scan, completed to full echoes and cropped to the reconstruction field of view as they arrive ( |
|
Every frame of a 2D Cartesian slice solved together by ADMM over a wavelet and a temporal total-variation term, the frames sharing the coil maps: cardiac phases labelled |
|
|
|
|
|
|
|
The images of |
|
|
|
|
|
A multi-echo 3D gradient echo: the echoes themselves are not sent. |
|
|
A plugin file that re-exports one under another name,
from pulserver.recon.handlers.pics import PLUGIN, is the same reconstruction.
See also#
Reconstruction plugins and calibration context: units, images and the calibration context.
Reconstruction session: enrichment, workers and slots.
Reconstruction plugins: the plugin interface.
MRD data: acquisitions, flags, counters and images.