1. Your first scan#

Open in Colab

In this lesson you run a whole scan without writing any plugin. You use a sequence and a reconstruction that ship with pulserver (gre2d, a 2D gradient echo, and pics, a compressed-sensing reconstruction with BART), and the virtual scanner plays the sequence on a phantom. You will do what a scanner does: ask for the protocol, edit it, start the scan and get the image back.

Every step you run here is one step of the README’s How it works. The rest of the course opens them one at a time, and replaces the shipped plugins with your own.

Learning objectives

  • Run the six steps of a scan in one notebook.

  • See what the operator sees: the protocol, and what pulserver sends back after an edit.

  • Know which lesson of the course covers each step.

Next: 2. Your sequence in the scanner UI, where you write the sequence plugin yourself.

A scanner in your notebook#

A Console stands in for the scanner: it makes the same calls a scanner makes, plays the sequence on a phantom, and reconstructs in this process instead of in a separate reconstruction server.

It needs two things. The system is the scanner’s hardware: field strength, maximum gradient amplitude and slew rate. These are the arguments of Pulseq’s system object (pypulseqpp.Opts), written as the text block a scanner sends; raster times and dead times you leave out take their defaults. The store is the folder where finished sequences are kept.

import tempfile
from pathlib import Path

import numpy as np

from pulserver import virtual

system = """[Limits]
B0: 3.0
max_grad: 40
grad_unit: mT/m
max_slew: 150
slew_unit: T/m/s
[Limits End]
"""
store = Path(tempfile.mkdtemp())
console = virtual.Console(plugins=[], limits=system, store=store, recon_plugins=[])

Step 1: the protocol#

When the operator opens a sequence, the scanner asks pulserver which parameters to show. This is the reply for gre2d: one line per parameter, with its type, current value, range and unit. The scanner builds its UI from it.

from pulserver.protocol import UIParam, format_values, parse_listing, parse_validation

listing = console.design("list", "gre2d")["reply"]
block = listing[listing.index("[Protocol]") :]
print("\n".join(block.splitlines()[:12]) + "\n...")
[Protocol]
imaging_mode: stringlist|0|2d|3d
flip: float|typein|12.0|1.0|90.0|1.0|deg
TE: int|dropdown|8000|1000|80000|10|us|-2|5000|8000
TR: int|dropdown|250000|1000|5000000|1|us|-1
bandwidth: float|typein|250000.0|1000.0|1000000.0|1.0|Hz
fov: float|typein|220.0|50.0|500.0|1.0|mm
phase_fov: float|typein|220.0|50.0|500.0|1.0|mm
nx: int|typein|128|32|512|2|
ny: int|typein|128|32|512|2|
nslices: int|typein|1|1|64|1|
slice_spacing: float|typein|0.0|0.0|100.0|0.1|mm
...

Step 2: an edit#

The operator changes the matrix to 64 by 64. The scanner sends the new values back, and pulserver asks the sequence what it can achieve with them. The reply says whether the protocol is valid, the scan time, and any value the sequence had to change: here the receiver bandwidth.

entries = parse_listing(block)
values = {key: entry.value for key, entry in entries.items()}
values.update({UIParam.NX: 64, UIParam.NY: 64})
request = format_values(values, entries)

validation = parse_validation(
    console.design("validate", "gre2d", request)["reply"], entries
)
print(f"valid: {validation.valid}, scan time {validation.duration:.1f} s")
for key, value in validation.values.items():
    if value != values[key]:
        print(f"{key}: requested {values[key]}, achieved {value}")
valid: True, scan time 22.2 s
bandwidth: requested 250000.0, achieved 100000.0

Step 3: the sequence for the scanner#

The operator presses Scan. pulserver designs the whole sequence, checks it against the limits, converts it into the cache the scanner plays and keeps both in the store, under the scan that plays them.

generated = console.design("generate", "gre2d", request)
scan, design = generated["scan"], generated["design"]
print(generated["reply"])
print(sorted(path.name for path in (store / scan / design).iterdir()))
GENERATED 045871dc6c96204797

['manifest.json', 'resolved.protocol', 'sequence.pseg', 'sequence.seq']

Steps 4 to 6: scan and reconstruct#

An exam puts a subject in the scanner. Here it is a phantom of eight vials, seven of water with different T1 and T2 and one of fat, in the body coil. The exam returns a localizer, a quick image of the phantom, as the scanner would.

The scan then plays the stored sequence on the phantom, pulserver labels the raw data from the sequence, and pics reconstructs it. The images come back as DICOM, as they would on the console.

import base64
import io

import pydicom

localizer = [pydicom.dcmread(io.BytesIO(f)) for f in console.exam("vials", coil="body")]

received = []
status = console.scan(
    design,
    rotation=np.eye(3),
    centre_mm=(0.0, 0.0, 0.0),
    emit=received.append,
    recon="pics",
)
images = [
    pydicom.dcmread(io.BytesIO(base64.b64decode(item["dicom"])))
    for item in received
    if "dicom" in item
]
print(f"status {status}, {len(images)} image of {images[0].pixel_array.shape}")
the phantom (localizer), your scan: gre2d + pics
status 0, 1 image of (64, 64)

The localizer is drawn from the phantom’s geometry. Your image is reconstructed from raw data the virtual scanner simulated, at the 64 x 64 matrix you set. Both are drawn on the same millimetre scale: your image covers the protocol’s 220 mm field of view, the localizer a wider one.

What you just ran#

Each call above was one step of a scan. The rest of the course opens them in the same order:

01 protocol to image
  • Lesson 2 replaces the shipped gre2d plugin with your own: steps 1 and 2.

  • Lesson 3 looks inside what generate produced: step 3.

  • Lessons 4 and 5 follow the raw data into a reconstruction plugin you write: steps 5 and 6.

  • Lesson 6 puts your two plugins together on the virtual scanner: step 4.

As a spec#

What this lesson did, stated the way you would ask an agent for it:

On pulserver's virtual console at 3 T (40 mT/m, 150 T/m/s), list the
shipped gre2d protocol, set a 64 x 64 matrix, generate the design, and
scan it on the vials phantom in the body coil with the pics
reconstruction. Show the localizer next to the image.

Total running time of the script: (0 minutes 0.834 seconds)

Gallery generated by Sphinx-Gallery