diff --git a/marge/console/__init__.py b/marge/console/__init__.py new file mode 100644 index 0000000..44c5d1f --- /dev/null +++ b/marge/console/__init__.py @@ -0,0 +1 @@ +"""The console of pulserver's virtual scanner: the exam's series, their viewer and the graphical prescription.""" diff --git a/marge/console/geometry.py b/marge/console/geometry.py new file mode 100644 index 0000000..da653cb --- /dev/null +++ b/marge/console/geometry.py @@ -0,0 +1,368 @@ +"""Geometry of a prescription and of the images it is planned on, in the patient's LPS frame, in mm. + +The physical axes of pulserver's virtual scanner are the patient's LPS axes for +a subject lying head first and supine, and a prescription's rotation takes the +logical readout, phase and slice axes to them: its columns are the readout, +phase and slice directions. A DICOM image's ``ImageOrientationPatient`` holds +the directions of increasing column and row, so an image of a prescription +carries its readout and phase directions. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass, replace + +import numpy as np + +#: The starting planes of a prescription, as the localizer shows them: the +#: readout, phase and slice directions as columns. +BASES = { + "axial": np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), + "coronal": np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]]), + "sagittal": np.array([[0.0, 0.0, -1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]), +} + +#: How far from facing the slices, in degrees, a view may be and still show +#: the field of view as a box projected onto it, rather than the slices as +#: the lines they cut it along. +FACING_DEG = 45.0 + + +def turn(axis: Sequence[float], degrees: float) -> np.ndarray: + """Return the right-handed rotation by ``degrees`` about ``axis``.""" + k = np.asarray(axis, dtype=float) + k = k / np.linalg.norm(k) + cross = np.array([[0.0, -k[2], k[1]], [k[2], 0.0, -k[0]], [-k[1], k[0], 0.0]]) + theta = math.radians(degrees) + return np.eye(3) + math.sin(theta) * cross + (1.0 - math.cos(theta)) * cross @ cross + + +def rotation(base: str, inplane: float, tilt_read: float, tilt_phase: float) -> np.ndarray: + """Return the rotation of a prescription turned from a starting plane, in degrees. + + The plane is tilted about its readout direction, then about its phase + direction, then turned in-plane about its slice direction: ``B Rx Ry Rz``, + each factor about the logical axis it names. + """ + logical = turn((1, 0, 0), tilt_read) @ turn((0, 1, 0), tilt_phase) @ turn((0, 0, 1), inplane) + return BASES[base] @ logical + + +def angles(matrix: np.ndarray, base: str) -> tuple[float, float, float]: + """Return the in-plane turn and the tilts about the readout and phase directions, in degrees, of a rotation from a starting plane. + + The inverse of :func:`rotation`; a tilt about the phase direction of a + right angle leaves the other two apart only by their sum, which is taken + as the in-plane turn. + """ + m = BASES[base].T @ np.asarray(matrix, dtype=float) + tilt_phase = math.degrees(math.asin(max(-1.0, min(1.0, m[0, 2])))) + if abs(m[0, 2]) > 1.0 - 1e-12: + return math.degrees(math.atan2(m[1, 0], m[1, 1])), 0.0, tilt_phase + tilt_read = math.degrees(math.atan2(-m[1, 2], m[2, 2])) + inplane = math.degrees(math.atan2(-m[0, 1], m[0, 0])) + return inplane, tilt_read, tilt_phase + + +@dataclass(frozen=True) +class ImagePlane: + """Where an image's pixels are: the plane of a DICOM image. + + Attributes + ---------- + origin + Centre of the first pixel, ``ImagePositionPatient``. + across, down + Directions of increasing column and row, ``ImageOrientationPatient``. + spacing + Distance between columns and between rows. + shape + Rows and columns. + """ + + origin: np.ndarray + across: np.ndarray + down: np.ndarray + spacing: tuple[float, float] + shape: tuple[int, int] + + @classmethod + def of(cls, dataset) -> ImagePlane: + """Return the plane of a DICOM image.""" + orientation = np.asarray(dataset.ImageOrientationPatient, dtype=float) + rows, columns = (float(s) for s in dataset.PixelSpacing) + return cls( + np.asarray(dataset.ImagePositionPatient, dtype=float), + orientation[:3], + orientation[3:], + (columns, rows), + (int(dataset.Rows), int(dataset.Columns)), + ) + + @property + def normal(self) -> np.ndarray: + return np.cross(self.across, self.down) + + @property + def centre(self) -> np.ndarray: + rows, columns = self.shape + return self.point(0.5 * (columns - 1), 0.5 * (rows - 1)) + + def point(self, column: float, row: float) -> np.ndarray: + """Return the point at a fractional column and row.""" + return self.origin + column * self.spacing[0] * self.across + row * self.spacing[1] * self.down + + def pixel(self, points: np.ndarray) -> np.ndarray: + """Return the fractional ``(column, row)`` of points, projected onto the plane along its normal.""" + offset = np.asarray(points, dtype=float) - self.origin + return np.stack( + [offset @ self.across / self.spacing[0], offset @ self.down / self.spacing[1]], axis=-1 + ) + + def corners(self) -> np.ndarray: + """Return the corners of the area the pixels cover, in order around it.""" + rows, columns = self.shape + return np.array( + [self.point(c, r) for c, r in ((-0.5, -0.5), (columns - 0.5, -0.5), (columns - 0.5, rows - 0.5), (-0.5, rows - 0.5))] + ) + + +@dataclass(frozen=True) +class Prescription: + """Where a scan acquires: a stack of slices, or a slab of locations, and its field of view. + + Attributes + ---------- + centre + Centre of the stack. + rotation + Readout, phase and slice directions as columns. + fov + Field of view along the readout and phase directions. + thickness + Thickness of a slice, or of a location of a slab; None where the + sequence does not state it. + gap + Gap between adjacent slices; a slab's locations have none. + slices + Slices of the stack, or locations of the slab. + slab + Whether the locations form one slab, as a 3D acquisition's do. + limits + Fewest and most slices. + """ + + centre: np.ndarray + rotation: np.ndarray + fov: tuple[float, float] + thickness: float | None + gap: float = 0.0 + slices: int = 1 + slab: bool = False + limits: tuple[int, int] = (1, 1024) + + @property + def normal(self) -> np.ndarray: + return self.rotation[:, 2] + + @property + def pitch(self) -> float: + """Distance between the centres of adjacent slices or locations; zero without a thickness.""" + if self.thickness is None: + return 0.0 + return self.thickness + (0.0 if self.slab else self.gap) + + @property + def extent(self) -> float: + """Half the stack's thickness along its normal, from the first slice's far face to the last's.""" + if self.thickness is None: + return 0.0 + return 0.5 * ((self.slices - 1) * self.pitch + self.thickness) + + def slice_centres(self) -> np.ndarray: + offsets = (np.arange(self.slices) - 0.5 * (self.slices - 1)) * self.pitch + return self.centre + offsets[:, None] * self.normal + + def end(self, side: int) -> np.ndarray: + """Return the centre of the first slice, ``side`` -1, or of the last, ``side`` +1.""" + return self.centre + side * 0.5 * (self.slices - 1) * self.pitch * self.normal + + def moved(self, delta: Sequence[float]) -> Prescription: + return replace(self, centre=self.centre + np.asarray(delta, dtype=float)) + + def turned(self, axis: Sequence[float], degrees: float) -> Prescription: + """Return the prescription turned about ``axis`` through its centre.""" + return replace(self, rotation=turn(axis, degrees) @ self.rotation) + + def resized(self, read: float, phase: float) -> Prescription: + return replace(self, fov=(float(read), float(phase))) + + def stretched(self, side: int, distance: float) -> Prescription: + """Return the stack with slices added past its ``side`` end, or removed from it, the other end in place. + + ``distance`` is how far the end is dragged outward, in mm; a slice is + added for every pitch, to the nearest, within the stack's limits. + """ + if self.pitch <= 0.0: + return self + lo, hi = self.limits + slices = int(min(hi, max(lo, self.slices + round(distance / self.pitch)))) + added = slices - self.slices + return replace( + self, slices=slices, centre=self.centre + side * 0.5 * added * self.pitch * self.normal + ) + + +@dataclass(frozen=True) +class Band: + """A saturation band: a slab of any orientation. + + Attributes + ---------- + normal + Its unit normal along the physical axes. + position + Its centre's distance from the isocentre along the normal. + thickness + Its thickness along the normal. + """ + + normal: np.ndarray + position: float + thickness: float + + def moved(self, distance: float) -> Band: + return replace(self, position=self.position + distance) + + def turned(self, axis: Sequence[float], degrees: float, about: Sequence[float]) -> Band: + """Return the band turned about ``axis`` through the point ``about``, which stays on its centre plane.""" + normal = turn(axis, degrees) @ self.normal + return replace(self, normal=normal, position=float(np.asarray(about, dtype=float) @ normal)) + + +@dataclass(frozen=True) +class Section: + """A prescription as a view shows it, in the view's fractional pixels. + + Attributes + ---------- + facing + Whether the view faces the slices, within :data:`FACING_DEG`. + box + The field of view of the slice nearest the view, projected onto it, + its corners in order, on a view that faces the slices; else None. + lines + Each slice's trace on the view, its two ends, on a view across the + slices; empty for a slab. + outline + The trace of the stack or slab as a box across the view, its corners + in order; empty where the view misses it. + ends + Where the first and the last slice's handles go, or None where the + view misses that end. + centre + The centre projected onto the view. + """ + + facing: bool + box: np.ndarray | None + lines: list[np.ndarray] + outline: np.ndarray + ends: tuple[np.ndarray | None, np.ndarray | None] + centre: np.ndarray + + +def section(prescription: Prescription, plane: ImagePlane) -> Section: + """Return how a view shows a prescription.""" + p = prescription + read, phase, normal = p.rotation.T + half = (0.5 * p.fov[0] * read, 0.5 * p.fov[1] * phase) + facing = abs(float(normal @ plane.normal)) > math.cos(math.radians(FACING_DEG)) + centre = plane.pixel(p.centre) + if facing: + nearest = p.slice_centres()[np.argmin(np.abs((p.slice_centres() - plane.centre) @ plane.normal))] + box = plane.pixel(_rectangle(nearest, *half)) + return Section(True, box, [], np.empty((0, 2)), (None, None), centre) + lines = [] + if not p.slab: + for middle in p.slice_centres(): + cut = _cut_polygon(_rectangle(middle, *half), plane) + if len(cut) == 2: + lines.append(plane.pixel(cut)) + depth = p.extent * normal + outline = _cut_box(p.centre, (*half, depth), plane) + ends = [] + for side in (-1, 1): + face = p.end(side) + (side * 0.5 * p.thickness * normal if p.slab and p.thickness else 0.0) + cut = _cut_polygon(_rectangle(face, *half), plane) + ends.append(plane.pixel(cut.mean(axis=0)) if len(cut) == 2 else None) + return Section(False, None, lines, plane.pixel(outline) if len(outline) else np.empty((0, 2)), tuple(ends), centre) + + +def band_area(band: Band, plane: ImagePlane) -> np.ndarray: + """Return the part of a view a band covers, its corners in fractional pixels; empty where it covers none.""" + polygon = plane.corners() + for sign in (-1.0, 1.0): + # Keep the side of each face that holds the band. + bound = band.position + sign * 0.5 * band.thickness + polygon = _clip(polygon, -sign * band.normal, -sign * bound) + return plane.pixel(polygon) if len(polygon) else np.empty((0, 2)) + + +def _rectangle(centre: np.ndarray, u: np.ndarray, v: np.ndarray) -> np.ndarray: + return np.array([centre - u - v, centre + u - v, centre + u + v, centre - u + v]) + + +def _cut_polygon(corners: np.ndarray, plane: ImagePlane) -> np.ndarray: + """Return where a planar polygon's edges cross a view's plane.""" + side = (corners - plane.origin) @ plane.normal + points = [] + for k in range(len(corners)): + a, b = side[k], side[(k + 1) % len(corners)] + if (a < 0.0) != (b < 0.0): + t = a / (a - b) + points.append(corners[k] + t * (corners[(k + 1) % len(corners)] - corners[k])) + return np.array(points) if points else np.empty((0, 3)) + + +def _cut_box(centre: np.ndarray, halves: tuple[np.ndarray, ...], plane: ImagePlane) -> np.ndarray: + """Return where a box's edges cross a view's plane, in order around the section.""" + u, v, w = halves + signs = [(a, b, c) for a in (-1, 1) for b in (-1, 1) for c in (-1, 1)] + vertices = {s: centre + s[0] * u + s[1] * v + s[2] * w for s in signs} + side = {s: float((x - plane.origin) @ plane.normal) for s, x in vertices.items()} + points = [] + for s in signs: + for k in range(3): + if s[k] < 0: + t_ = list(s) + t_[k] = 1 + t = tuple(t_) + a, b = side[s], side[t] + if (a < 0.0) != (b < 0.0): + f = a / (a - b) + points.append(vertices[s] + f * (vertices[t] - vertices[s])) + if len(points) < 3: + return np.empty((0, 3)) + points = np.array(points) + middle = points.mean(axis=0) + angle = np.arctan2((points - middle) @ plane.down, (points - middle) @ plane.across) + return points[np.argsort(angle)] + + +def _clip(polygon: np.ndarray, normal: np.ndarray, offset: float) -> np.ndarray: + """Return the part of a polygon where ``x . normal >= offset``.""" + if len(polygon) == 0: + return polygon + kept = [] + side = polygon @ normal - offset + for k in range(len(polygon)): + a, b = side[k], side[(k + 1) % len(polygon)] + if a >= 0.0: + kept.append(polygon[k]) + if (a >= 0.0) != (b >= 0.0): + t = a / (a - b) + kept.append(polygon[k] + t * (polygon[(k + 1) % len(polygon)] - polygon[k])) + return np.array(kept) if kept else np.empty((0, 3)) diff --git a/marge/console/prescribe.py b/marge/console/prescribe.py new file mode 100644 index 0000000..19c7acf --- /dev/null +++ b/marge/console/prescribe.py @@ -0,0 +1,156 @@ +"""A plugin's protocol entries as a prescription and saturation bands, and back. + +The prescription's orientation is a starting plane, an in-plane turn and two +tilts, and its centre a point in the patient's LPS frame, in mm; its field of +view, slices and thickness are the plugin's own entries, in the units its +listing states. Values written back are held within each entry's range and on +its step, as the interpreter holds them. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any + +import numpy as np + +from . import geometry + +#: Millimetres per unit of a length entry. +MM_PER_UNIT = {"mm": 1.0, "cm": 10.0, "m": 1000.0} + +#: The entries that place and size what a scan acquires, and those of its +#: saturation bands, by their meaning. +READ_FOV, PHASE_FOV, THICKNESS, SLICES, GAP, MODE = ( + "fov", "phase_fov", "slice_thickness", "nslices", "slice_spacing", "imaging_mode" +) +GEOMETRY = (READ_FOV, PHASE_FOV, SLICES, THICKNESS, GAP) +#: The explicit saturation bands' mask: bit n - 1 turns band n on. +BAND_MASK = "exsat_mask" + +#: The console's own values of the prescription, beside the plugin's entries. +ORIENTATION, CENTRE, INPLANE, TILT_READ, TILT_PHASE = ( + "orientation", "centre", "inplane", "tilt_read", "tilt_phase" +) +PRESCRIPTION = (ORIENTATION, CENTRE, INPLANE, TILT_READ, TILT_PHASE) + +Key = Callable[[str], str] + + +def slab(entries: Mapping[str, Mapping[str, Any]]) -> bool: + """Whether a plugin's locations form one slab, as its ``imaging_mode`` states; a plugin that states none acquires slices.""" + mode = entries.get(MODE) + return mode is not None and str(mode["value"]).strip().lower() == "3d" + + +def unstated(entries: Mapping[str, Mapping[str, Any]]) -> list[str]: + """Return the geometry entries a plugin does not state, without which its prescription cannot be drawn whole.""" + return [name for name in (MODE, READ_FOV, SLICES, THICKNESS) if name not in entries] + + +def prescription( + values: Mapping[str, Any], + entries: Mapping[str, Mapping[str, Any]], + key: Key = str, +) -> geometry.Prescription: + """Return the prescription a sequence's values state; ``key`` names the value of each entry.""" + matrix = geometry.rotation( + str(values[ORIENTATION]).strip().lower(), + float(values[INPLANE]), + float(values[TILT_READ]), + float(values[TILT_PHASE]), + ) + + def length(name: str) -> float | None: + return _mm(entries, name, values[key(name)]) if name in entries else None + + read = length(READ_FOV) or 0.0 + slices = entries.get(SLICES) + return geometry.Prescription( + centre=np.asarray(values[CENTRE], dtype=float), + rotation=matrix, + fov=(read, length(PHASE_FOV) or read), + thickness=length(THICKNESS), + gap=length(GAP) or 0.0, + slices=int(values[key(SLICES)]) if slices else 1, + slab=slab(entries), + limits=(int(slices["min"]), int(slices["max"])) if slices else (1, 1), + ) + + +def written( + planned: geometry.Prescription, + values: Mapping[str, Any], + entries: Mapping[str, Mapping[str, Any]], + key: Key = str, +) -> dict[str, Any]: + """Return the values that state ``planned``, by their keys, those that change only.""" + base = str(values[ORIENTATION]).strip().lower() + inplane, tilt_read, tilt_phase = geometry.angles(planned.rotation, base) + found = { + INPLANE: round(inplane, 2), + TILT_READ: round(tilt_read, 2), + TILT_PHASE: round(tilt_phase, 2), + CENTRE: [round(float(c), 1) for c in planned.centre], + } + lengths = {READ_FOV: planned.fov[0], PHASE_FOV: planned.fov[1], THICKNESS: planned.thickness} + for name, mm in lengths.items(): + if name in entries and mm is not None: + found[key(name)] = _held(entries[name], mm / MM_PER_UNIT.get(entries[name].get("unit", ""), 1.0)) + if SLICES in entries: + found[key(SLICES)] = int(_held(entries[SLICES], planned.slices)) + return {name: value for name, value in found.items() if values.get(name) != value} + + +def bands( + values: Mapping[str, Any], entries: Mapping[str, Mapping[str, Any]], key: Key = str +) -> list[tuple[int, geometry.Band]]: + """Return each explicit saturation band a sequence's values turn on, by its number, 1 to 6.""" + if BAND_MASK not in entries: + return [] + mask = int(values[key(BAND_MASK)]) + found = [] + for n in range(1, 7): + if not mask & (1 << (n - 1)) or f"exsat{n}_loc" not in entries: + continue + normal = np.array([float(values[key(f"exsat{n}_normal_{a}")]) for a in "xyz"]) + length = float(np.linalg.norm(normal)) + if length == 0.0: + continue + position = _mm(entries, f"exsat{n}_loc", values[key(f"exsat{n}_loc")]) + thickness = _mm(entries, f"exsat{n}_thickness", values[key(f"exsat{n}_thickness")]) + found.append((n, geometry.Band(normal / length, position, thickness))) + return found + + +def band_written( + n: int, + band: geometry.Band, + values: Mapping[str, Any], + entries: Mapping[str, Mapping[str, Any]], + key: Key = str, +) -> dict[str, Any]: + """Return the values that place band ``n``, those that change only.""" + found = {} + for axis, component in zip("xyz", band.normal, strict=True): + name = f"exsat{n}_normal_{axis}" + found[key(name)] = _held(entries[name], float(component)) + for name, mm in ((f"exsat{n}_loc", band.position), (f"exsat{n}_thickness", band.thickness)): + entry = entries[name] + found[key(name)] = _held(entry, mm / MM_PER_UNIT.get(entry.get("unit", ""), 1.0)) + return {name: value for name, value in found.items() if values.get(name) != value} + + +def _mm(entries: Mapping[str, Mapping[str, Any]], name: str, value: Any) -> float: + return float(value) * MM_PER_UNIT.get(entries[name].get("unit", ""), 1.0) + + +def _held(entry: Mapping[str, Any], value: float) -> float | int: + """Return ``value`` within the entry's range, on its step from its minimum.""" + low, high, step = float(entry["min"]), float(entry["max"]), float(entry.get("step") or 0.0) + value = min(high, max(low, float(value))) + if step > 0.0: + value = min(high, low + round((value - low) / step) * step) + if entry["kind"] == "int": + return int(round(value)) + return round(value, 6) diff --git a/marge/console/series.py b/marge/console/series.py new file mode 100644 index 0000000..e1b7fdb --- /dev/null +++ b/marge/console/series.py @@ -0,0 +1,63 @@ +"""The exam's series: the images of each run, with where each lies.""" + +from __future__ import annotations + +import io +from collections.abc import Sequence +from dataclasses import dataclass + +import numpy as np + +from .geometry import ImagePlane + + +@dataclass(frozen=True) +class Series: + """The images of one run of the exam. + + Attributes + ---------- + number + The run's place in the exam, from 1. + description + What acquired it: the plugin's name, or ``Localizer``. + name + The name MaRGE gives the run, by which its history entry knows it. + images + Each image, ``(rows, columns)``, its pixel values rescaled. + planes + Where each image lies. + """ + + number: int + description: str + name: str + images: tuple[np.ndarray, ...] + planes: tuple[ImagePlane, ...] + + @classmethod + def of(cls, number: int, description: str, name: str, files: Sequence[bytes]) -> Series: + """Return the series of a run's DICOM files. + + The images of a stack, all parallel, are ordered along its normal; + others keep their instance order. + """ + import pydicom + + datasets = [pydicom.dcmread(io.BytesIO(data)) for data in files] + datasets.sort(key=lambda d: int(getattr(d, "InstanceNumber", 0) or 0)) + planes = [ImagePlane.of(d) for d in datasets] + if len(planes) > 1 and all(abs(p.normal @ planes[0].normal) > 1.0 - 1e-6 for p in planes): + depth = [p.origin @ planes[0].normal for p in planes] + order = np.argsort(depth, kind="stable") + datasets, planes = [datasets[k] for k in order], [planes[k] for k in order] + images = tuple( + d.pixel_array.astype(float) * float(getattr(d, "RescaleSlope", 1.0)) + + float(getattr(d, "RescaleIntercept", 0.0)) + for d in datasets + ) + return cls(number, description, name, images, tuple(planes)) + + @property + def label(self) -> str: + return f"S{self.number} {self.description}" diff --git a/marge/console/workspace.py b/marge/console/workspace.py new file mode 100644 index 0000000..a496afc --- /dev/null +++ b/marge/console/workspace.py @@ -0,0 +1,406 @@ +"""The console's workspace: three views to prescribe on, above a viewer of the exam's series. + +Each view shows an image of a series it chooses, a slice at a time. The +prescribing views draw the selected sequence's prescription where it lies on +their image, with handles that move, turn, resize and stretch it and move its +saturation bands; every drag writes the sequence's values, and every value +typed redraws the views. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from typing import Any + +import numpy as np +import pyqtgraph as pg +from PyQt5 import QtCore, QtWidgets + +from . import geometry +from .series import Series + +#: Colours of what a view draws. +STACK, SLAB, HANDLE, TURN, END, BAND = "#ffd23f", "#ffd23f", "#3ddc97", "#ff6ad5", "#4cc9f0", "#ff595e" + +#: How far past the field of view the turning handle sits, as a fraction of it. +LEVER = 0.15 + +#: How far along its trace a band's turning handle sits from its centre, in mm. +BAND_LEVER = 60.0 + + +class Handle(pg.TargetItem): + """A handle a view's prescription is dragged by, which tells its view when a drag starts and ends.""" + + def __init__(self, view: PlanView, role: Any, symbol: str, colour: str, size: int = 12) -> None: + super().__init__( + size=size, + symbol=symbol, + pen=pg.mkPen(colour, width=2), + brush=pg.mkBrush(colour), + hoverPen=pg.mkPen("w", width=2), + hoverBrush=pg.mkBrush("w"), + movable=True, + ) + self.view, self.role = view, role + self.sigPositionChanged.connect(lambda handle: handle.moving and view.dragged(handle)) + + def mouseDragEvent(self, ev) -> None: # noqa: N802 -- Qt's API + if ev.isStart() and ev.button() == QtCore.Qt.MouseButton.LeftButton: + self.view.began(self) + super().mouseDragEvent(ev) + if ev.isFinish(): + self.view.ended(self) + + def place(self, xy: np.ndarray | None) -> None: + """Put the handle at a view's ``(x, y)``, or hide it; a handle being dragged stays where it is dragged.""" + if xy is None: + self.hide() + return + self.show() + if not self.moving: + self.setPos(float(xy[0]), float(xy[1])) + + +class SeriesView(QtWidgets.QWidget): + """An image of one of the exam's series, a slice at a time.""" + + def __init__(self, workspace: Workspace, title: str) -> None: + super().__init__() + self.workspace = workspace + self.series: Series | None = None + self.index = 0 + layout = QtWidgets.QVBoxLayout(self) + layout.setContentsMargins(2, 2, 2, 2) + header = QtWidgets.QHBoxLayout() + self.title = QtWidgets.QLabel(title) + self.choice = QtWidgets.QComboBox() + self.choice.currentIndexChanged.connect(self._chosen) + header.addWidget(self.title) + header.addWidget(self.choice, 1) + layout.addLayout(header) + self.graphics = pg.GraphicsLayoutWidget() + self.plot = self.graphics.addPlot() + self.plot.setAspectLocked(True) + self.plot.invertY(True) + self.plot.hideAxis("left") + self.plot.hideAxis("bottom") + self.plot.setMenuEnabled(False) + self.image = pg.ImageItem(axisOrder="row-major") + self.plot.addItem(self.image) + layout.addWidget(self.graphics, 1) + self.slider = QtWidgets.QSlider(QtCore.Qt.Orientation.Horizontal) + self.slider.valueChanged.connect(self._slid) + self.where = QtWidgets.QLabel("") + footer = QtWidgets.QHBoxLayout() + footer.addWidget(self.slider, 1) + footer.addWidget(self.where) + layout.addLayout(footer) + + @property + def plane(self) -> geometry.ImagePlane | None: + return None if self.series is None else self.series.planes[self.index] + + def offer(self, series: list[Series]) -> None: + """List the exam's series to choose from, keeping the one shown.""" + self.choice.blockSignals(True) + self.choice.clear() + self.choice.addItems([s.label for s in series]) + if self.series is not None: + self.choice.setCurrentIndex([s.name for s in series].index(self.series.name)) + self.choice.blockSignals(False) + + def show_series(self, series: Series, index: int | None = None) -> None: + """Show an image of ``series``, the middle one unless ``index`` names another.""" + fresh = self.series is None or series.name != self.series.name + self.series = series + self.index = len(series.images) // 2 if index is None else index + names = [s.name for s in self.workspace.series] + if series.name in names: + self.choice.blockSignals(True) + self.choice.setCurrentIndex(names.index(series.name)) + self.choice.blockSignals(False) + self.slider.blockSignals(True) + self.slider.setRange(0, len(series.images) - 1) + self.slider.setValue(self.index) + self.slider.blockSignals(False) + self._draw(fresh) + + def _chosen(self, index: int) -> None: + if 0 <= index < len(self.workspace.series): + self.show_series(self.workspace.series[index]) + + def _slid(self, index: int) -> None: + if self.series is not None: + self.index = index + self._draw(False) + + def _draw(self, fresh: bool) -> None: + image = self.series.images[self.index] + self.image.setImage(image, autoLevels=True) + self.where.setText(f"{self.index + 1}/{len(self.series.images)}") + if fresh: + self.plot.autoRange() + self.drawn() + + def drawn(self) -> None: + """Called once a new image is drawn.""" + + +class PlanView(SeriesView): + """A view the selected sequence is prescribed on. + + A view that faces the slices shows the field of view as a box, with a + handle at each corner that resizes it; one across them shows each slice + as a line, or a slab as a box, with a diamond on the first and on the + last slice that drags slices onto that end or off it. Every view has a + handle at the centre that moves the prescription in the view's plane, and + one that turns it about the view's normal. Saturation bands show as + shaded areas, each with a handle that moves it along its normal, one + that sets its thickness and one that turns it about the view's normal. + """ + + def __init__(self, workspace: Workspace, title: str) -> None: + super().__init__(workspace, title) + self.traces = pg.PlotDataItem(pen=pg.mkPen(STACK, width=1.5), connect="pairs") + self.box = pg.PlotDataItem(pen=pg.mkPen(STACK, width=2)) + self.outline = pg.PlotDataItem(pen=pg.mkPen(SLAB, width=1.5, style=QtCore.Qt.PenStyle.DashLine)) + self.areas: list[QtWidgets.QGraphicsPolygonItem] = [] + for item in (self.traces, self.box, self.outline): + self.plot.addItem(item) + self.handles: dict[Any, Handle] = {} + for role, symbol, colour in (("centre", "o", HANDLE), ("turn", "o", TURN), (-1, "d", END), (1, "d", END)): + self._handle(role, symbol, colour) + for corner in range(4): + self._handle(("corner", corner), "s", STACK, 9) + self._start: tuple[Any, ...] | None = None + + def _handle(self, role: Any, symbol: str, colour: str, size: int = 12) -> Handle: + handle = Handle(self, role, symbol, colour, size) + handle.setZValue(10) + self.plot.addItem(handle) + handle.hide() + self.handles[role] = handle + return handle + + def drawn(self) -> None: + self.redraw() + + # Drawing --------------------------------------------------------------- + + def redraw(self) -> None: + """Draw the selected sequence's prescription on the image shown, or nothing without one.""" + plane, planned = self.plane, self.workspace.planned() + for area in self.areas: + self.plot.removeItem(area) + self.areas = [] + if plane is None or planned is None: + for item in (self.traces, self.box, self.outline): + item.setData([], []) + for handle in self.handles.values(): + handle.hide() + return + cut = geometry.section(planned, plane) + self.box.setData(*_closed(cut.box) if cut.box is not None else ([], [])) + lines = np.concatenate(cut.lines) if cut.lines else np.empty((0, 2)) + self.traces.setData(lines[:, 0] + 0.5, lines[:, 1] + 0.5) + self.outline.setData(*_closed(cut.outline) if len(cut.outline) else ([], [])) + self.handles["centre"].place(cut.centre + 0.5) + self.handles["turn"].place(plane.pixel(self._lever(planned, plane)) + 0.5) + for side, end in zip((-1, 1), cut.ends, strict=True): + self.handles[side].place(None if end is None else end + 0.5) + for corner in range(4): + self.handles[("corner", corner)].place(None if cut.box is None else cut.box[corner] + 0.5) + self._draw_bands(plane) + + def _draw_bands(self, plane: geometry.ImagePlane) -> None: + shown = set() + for n, band in self.workspace.bands(): + area = geometry.band_area(band, plane) + if not len(area): + continue + polygon = QtWidgets.QGraphicsPolygonItem(_polygon(area + 0.5)) + colour = pg.mkColor(BAND) + colour.setAlpha(70) + polygon.setBrush(pg.mkBrush(colour)) + polygon.setPen(pg.mkPen(BAND, width=1)) + self.plot.addItem(polygon) + self.areas.append(polygon) + middle = _on_view(plane, band, 0.0) + places = ( + ("band", middle, "t"), + ("width", _on_view(plane, band, 0.5 * band.thickness), "s"), + ("tilt", middle + BAND_LEVER * _along(plane, band), "o"), + ) + for role, at, symbol in places: + key = (role, n) + handle = self.handles.get(key) or self._handle(key, symbol, BAND, 10) + handle.place(plane.pixel(at) + 0.5) + shown.add(key) + for key, handle in self.handles.items(): + if isinstance(key, tuple) and key[0] in ("band", "width", "tilt") and key not in shown: + handle.hide() + + @staticmethod + def _lever(planned: geometry.Prescription, plane: geometry.ImagePlane) -> np.ndarray: + """Return where the turning handle goes: past the field of view, along the view, from the centre.""" + read, phase, normal = planned.rotation.T + along = np.cross(normal, plane.normal) + if np.linalg.norm(along) < 1e-6: + along = -phase + along = along / np.linalg.norm(along) + reach = 0.5 * (abs(along @ read) * planned.fov[0] + abs(along @ phase) * planned.fov[1]) + centre = plane.point(*plane.pixel(planned.centre)) + return centre - (1.0 + LEVER) * reach * (along if along @ plane.down < 0 else -along) + + # Dragging -------------------------------------------------------------- + + def _point(self, handle: Handle) -> np.ndarray: + position = handle.pos() + return self.plane.point(position.x() - 0.5, position.y() - 0.5) + + def began(self, handle: Handle) -> None: + self._start = (self.workspace.planned(), dict(self._bands()), self._point(handle)) + + def ended(self, handle: Handle) -> None: + self._start = None + self.workspace.redraw() + + def dragged(self, handle: Handle) -> None: + if self._start is None or self.plane is None: + return + planned, bands, start = self._start + point, plane = self._point(handle), self.plane + role = handle.role + if isinstance(role, tuple) and role[0] in ("band", "width", "tilt"): + kind, n = role + band = bands[n] + if kind == "band": + band = band.moved((point - start) @ band.normal) + elif kind == "width": + band = geometry.Band(band.normal, band.position, 2.0 * abs(point @ band.normal - band.position)) + else: + pivot = _on_view(plane, band, 0.0) + a, b = start - pivot, point - pivot + degrees = math.degrees(math.atan2(plane.normal @ np.cross(a, b), a @ b)) + band = band.turned(plane.normal, degrees, pivot) + self.workspace.place_band(n, band) + return + if planned is None: + return + if role == "centre": + planned = planned.moved(point - start) + elif role == "turn": + pivot = plane.point(*plane.pixel(planned.centre)) + a, b = start - pivot, point - pivot + degrees = math.degrees(math.atan2(plane.normal @ np.cross(a, b), a @ b)) + planned = planned.turned(plane.normal, degrees) + elif role in (-1, 1): + planned = planned.stretched(role, role * (point - start) @ planned.normal) + elif isinstance(role, tuple) and role[0] == "corner": + offset = point - planned.centre + read, phase, _ = planned.rotation.T + planned = planned.resized(2.0 * abs(offset @ read), 2.0 * abs(offset @ phase)) + self.workspace.prescribe(planned) + + def _bands(self) -> list[tuple[int, geometry.Band]]: + return self.workspace.bands() + + +class Workspace(QtWidgets.QWidget): + """Three views to prescribe on and a viewer, over the exam's series. + + Parameters + ---------- + sequence + Returns the sequence selected in MaRGE, or None where it is not one + that is prescribed: one with ``planned``, ``plan``, ``planned_bands`` + and ``plan_band``. + shown + Shows a sequence's values that the views have changed, by their keys. + """ + + def __init__(self, sequence: Callable[[], Any], shown: Callable[[Any, list[str]], None]) -> None: + super().__init__() + self._sequence, self._shown = sequence, shown + self.series: list[Series] = [] + layout = QtWidgets.QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + row = QtWidgets.QHBoxLayout() + self.views = [PlanView(self, f"Rx {k + 1}") for k in range(3)] + for view in self.views: + row.addWidget(view, 1) + layout.addLayout(row, 1) + self.viewer = SeriesView(self, "Viewer") + layout.addWidget(self.viewer, 1) + + def add(self, series: Series) -> None: + """Add a run's series to the exam and show it in the viewer; a localizer's planes also go to the views that show nothing yet.""" + self.series.append(series) + for view in (*self.views, self.viewer): + view.offer(self.series) + if series.description == "Localizer": + for index, view in enumerate(self.views[: len(series.images)]): + view.show_series(series, index) + self.viewer.show_series(series) + + def show_run(self, name: str) -> None: + """Show the series of the run MaRGE names ``name`` in the viewer.""" + for series in self.series: + if series.name == name: + self.viewer.show_series(series) + return + + def planned(self) -> geometry.Prescription | None: + sequence = self._sequence() + return None if sequence is None else sequence.planned() + + def bands(self) -> list[tuple[int, geometry.Band]]: + sequence = self._sequence() + return [] if sequence is None else sequence.planned_bands() + + def prescribe(self, planned: geometry.Prescription) -> None: + sequence = self._sequence() + if sequence is not None: + self._shown(sequence, list(sequence.plan(planned))) + self.redraw() + + def place_band(self, n: int, band: geometry.Band) -> None: + sequence = self._sequence() + if sequence is not None: + self._shown(sequence, list(sequence.plan_band(n, band))) + self.redraw() + + def redraw(self) -> None: + for view in self.views: + view.redraw() + + +def _closed(points: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + ring = np.vstack([points, points[:1]]) + 0.5 + return ring[:, 0], ring[:, 1] + + +def _polygon(points: np.ndarray): + from PyQt5 import QtGui + + return QtGui.QPolygonF([QtCore.QPointF(float(x), float(y)) for x, y in points]) + + +def _along(plane: geometry.ImagePlane, band: geometry.Band) -> np.ndarray: + """Return the direction a band's centre plane crosses a view along; the view's across where they are parallel.""" + along = np.cross(band.normal, plane.normal) + length = np.linalg.norm(along) + return plane.across if length < 1e-9 else along / length + + +def _on_view(plane: geometry.ImagePlane, band: geometry.Band, offset: float) -> np.ndarray: + """Return the point of a view on a band's centre plane shifted by ``offset`` along its normal, nearest the view's centre.""" + centre = plane.centre + target = band.position + offset + # Move from the view's centre within the view's plane until on the target plane. + along = band.normal - (band.normal @ plane.normal) * plane.normal + if np.linalg.norm(along) < 1e-9: + return centre + return centre + (target - centre @ band.normal) / (along @ band.normal) * along diff --git a/marge/controller/controller_sequence_inputs.py b/marge/controller/controller_sequence_inputs.py index 245e1eb..5b31af7 100644 --- a/marge/controller/controller_sequence_inputs.py +++ b/marge/controller/controller_sequence_inputs.py @@ -4,7 +4,7 @@ :affiliation: MRILab, i3M, CSIC, Valencia, Spain """ -from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit +from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QScrollArea, QFrame from marge.widgets.widget_sequence_inputs import SequenceInputsWidget from marge.seq.sequences import defaultsequences import numpy as np @@ -31,8 +31,24 @@ def __init__(self, *args, **kwargs): """ super(SequenceInputsController, self).__init__(*args, **kwargs) self.seq_name = self.main.sequence_list.seq_name + self.fields = {} self.displayInputParameters() + def showValues(self, sequence, keys): + """ + Show values of the sequence that changed elsewhere, such as in the console's prescribing views. + + Args: + sequence: The sequence whose values changed. + keys (list): The keys of the values that changed. + """ + for key in keys: + field = self.fields.get(sequence.mapNmspc.get(key)) + if field is not None: + field.blockSignals(True) + field.setText(str(sequence.mapVals[key])) + field.blockSignals(False) + def displayInputParameters(self): """ Displays the input parameters for the selected sequence. @@ -40,28 +56,33 @@ def displayInputParameters(self): self.seq_name = self.main.sequence_list.seq_name if hasattr(defaultsequences[self.seq_name], 'IMproperties'): props, tips = defaultsequences[self.seq_name].IMproperties - input_widgets_1 = self.createTab(props, tips) - self.addTab(input_widgets_1, "Image") + if props: + input_widgets_1 = self.createTab(props, tips) + self.addTab(input_widgets_1, "Image") if hasattr(defaultsequences[self.seq_name], 'RFproperties'): props, tips = defaultsequences[self.seq_name].RFproperties - input_widgets_2 = self.createTab(props, tips) - self.addTab(input_widgets_2, "RF") + if props: + input_widgets_2 = self.createTab(props, tips) + self.addTab(input_widgets_2, "RF") if hasattr(defaultsequences[self.seq_name], 'SEQproperties'): props, tips = defaultsequences[self.seq_name].SEQproperties - input_widgets_3 = self.createTab(props, tips) - self.addTab(input_widgets_3, "Sequence") + if props: + input_widgets_3 = self.createTab(props, tips) + self.addTab(input_widgets_3, "Sequence") if hasattr(defaultsequences[self.seq_name], 'OTHproperties'): props, tips = defaultsequences[self.seq_name].OTHproperties - input_widgets_4 = self.createTab(props, tips) - self.addTab(input_widgets_4, "Others") + if props: + input_widgets_4 = self.createTab(props, tips) + self.addTab(input_widgets_4, "Others") if hasattr(defaultsequences[self.seq_name], 'PROproperties'): props, tips = defaultsequences[self.seq_name].PROproperties - input_widgets_5 = self.createTab(props, tips) - self.addTab(input_widgets_5, "Tyger") + if props: + input_widgets_5 = self.createTab(props, tips) + self.addTab(input_widgets_5, "Tyger") def removeTabs(self): """ @@ -72,6 +93,7 @@ def removeTabs(self): self.removeTab(0) self.removeTab(0) self.removeTab(0) + self.fields = {} def createTab(self, inputs, tips): """ @@ -95,11 +117,18 @@ def createTab(self, inputs, tips): for key in inputs.keys(): input_layout = SequenceParameter([key, str(inputs[key][0])], tips[key][0], self.seq_name) layout.addLayout(input_layout) + self.fields[key] = input_layout.input_value # Add spacer to place all the items on the top layout.addStretch() - return widget + # Scroll the inputs that do not fit + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.NoFrame) + scroll.setWidget(widget) + + return scroll class SequenceParameter(QHBoxLayout): @@ -192,6 +221,10 @@ def getValue(self): else: sequence.mapVals[key] = inputNum + # Let the sequence follow the value, as the console's prescription does + if hasattr(sequence, 'parameterChanged'): + sequence.parameterChanged(key) + # Print value into the console seqTime = sequence.sequenceTime() if hasattr(self, 'oldSeqTime'): diff --git a/marge/seq/pulserver_console.py b/marge/seq/pulserver_console.py index 4f255fa..74d6cd6 100644 --- a/marge/seq/pulserver_console.py +++ b/marge/seq/pulserver_console.py @@ -22,6 +22,7 @@ import json import math import os +import re import sys import traceback from collections.abc import Callable, Mapping, Sequence @@ -40,27 +41,16 @@ FOV_ROTATION = tuple(f"fov_rotation_{i}{j}" for i in (1, 2, 3) for j in (1, 2, 3)) PRESCRIPTION = FOV_OFFSET + FOV_ROTATION -#: Rotations from the logical readout, phase and slice axes to the physical ones. -ORIENTATIONS = { - "axial": np.eye(3), - "coronal": np.array([[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), - "sagittal": np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), -} +#: MaRGE's names of the localizer's axial, coronal and sagittal planes. +PLANE_TITLES = ("Transversal", "Coronal", "Sagittal") -#: The protocol's field-of-view entries along the logical readout, phase and -#: slice axes, which MaRGE plans as its ``fov``, in cm. -FOV_SIZE = ("fov", "phase_fov", "slice_thickness") +#: The keys MaRGE gives every sequence; a protocol entry of the same name is +#: held under its name with this suffix. +MARGE_KEYS = frozenset(("seqName", "toMaRGE", "pulserverConsole", "fov", "dfov", "angle", "rotationAxis")) +RENAMED = "_protocol" -#: MaRGE's names of the localizer's axial, coronal and sagittal planes, on -#: which it plans the field of view. -PLANE_TITLES = ("Transversal", "Coronal", "Sagittal") -#: The physical directions of MaRGE's planning axes 0, 1 and 2, as columns. -#: MaRGE takes the across and down directions of its Transversal, Coronal and -#: Sagittal images as its axes 2 and 1, 2 and 0, and 1 and 0; on the -#: localizer's planes these are +x and +y, +x and -z, and +y and -z. -MARGE_AXES = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]) -#: Centimetres per unit of a field-of-view entry. -CM_PER_UNIT = {"mm": 0.1, "cm": 1.0, "m": 100.0} +#: A user entry, ``user_value``, named by its ``user_name`` description. +USER_ENTRY = re.compile(r"user(\d+)_value") _EDITABLE = ("float", "int", "bool", "stringlist") @@ -122,14 +112,20 @@ def parse_listing(reply: str) -> dict[str, dict[str, Any]]: return entries +#: Entries a sequence states once, as the interpreter reads them at its start, +#: and a console does not edit. +STATED = ("imaging_mode",) + + def shown(entries: Mapping[str, Mapping[str, Any]]) -> list[str]: - """Return the entries a console shows for editing: the editable ones outside the prescription.""" + """Return the entries a console shows for editing: the editable ones outside the prescription and those the sequence states.""" return [ name for name, entry in entries.items() if entry["kind"] in _EDITABLE and entry.get("mode") != "off" and name not in PRESCRIPTION + and name not in STATED ] @@ -167,33 +163,6 @@ def format_values( return "\n".join([PROTOCOL_BEGIN, *lines, PROTOCOL_END]) + "\n" -def prescription( - orientation: str, - angle_deg: float, - axis: Sequence[float], - dfov_mm: Sequence[float], -) -> tuple[np.ndarray, np.ndarray]: - """Return the rotation from logical to physical axes and the offset along the logical axes, in mm. - - The orientation's rotation is turned by ``angle_deg`` about the physical - ``axis``, right-handed, as MaRGE's FOV planning turns a box; ``dfov_mm`` - is the field-of-view centre along the physical axes. - """ - axis = np.asarray(axis, dtype=float) - norm = np.linalg.norm(axis) - turn = np.eye(3) - if norm > 0.0 and angle_deg != 0.0: - k = axis / norm - cross = np.array([[0.0, -k[2], k[1]], [k[2], 0.0, -k[0]], [-k[1], k[0], 0.0]]) - theta = math.radians(angle_deg) - turn = np.eye(3) + math.sin(theta) * cross + (1 - math.cos(theta)) * cross @ cross - name = orientation.strip().lower() - if name not in ORIENTATIONS: - raise ValueError(f"orientation is one of {', '.join(ORIENTATIONS)}, not {orientation!r}") - rotation = turn @ ORIENTATIONS[name] - return rotation, rotation.T @ np.asarray(dfov_mm, dtype=float) - - def subject_phantom(session: Mapping[str, Any]) -> str: """Return the phantom a session's subject names: its name, else its id.""" for key in ("subject_name", "subject_id"): @@ -421,6 +390,17 @@ async def listings_async(gateway: Any) -> dict[str, dict[str, dict[str, Any]]]: SPEAKER: Callable[[np.ndarray, float], None] | None = None +#: The console's workspace, where each run's series is shown and the selected +#: sequence prescribed; MaRGE shows a run's images itself without it. +WORKSPACE: Any = None + + +def register_workspace(workspace: Any) -> None: + """Record the console's workspace.""" + global WORKSPACE + WORKSPACE = workspace + + def register_console(toolbar: Any) -> None: """Record MaRGE's sequence toolbar, through which background scans show their images.""" global TOOLBAR @@ -513,9 +493,21 @@ class ConsoleSequence(base): titles: Sequence[str] | None = None def sequenceAnalysis(self, mode=None) -> list: # noqa: N802 -- MaRGE's API + """Save the run; show its images in the workspace as a series of the exam, else as MaRGE's output.""" self.mode = mode - self.output = _image_output(dicom_images(self.files), self.titles) + self.output = [] if WORKSPACE is not None else _image_output(dicom_images(self.files), self.titles) self.saveRawData() + if WORKSPACE is not None and self.files: + from marge.console.series import Series + + WORKSPACE.add( + Series.of( + len(WORKSPACE.series) + 1, + str(self.mapVals["seqName"]), + str(self.mapVals.get("fileName", "")), + self.files, + ) + ) return self.output def saveRawData(self) -> None: # noqa: N802 -- MaRGE's API @@ -563,19 +555,37 @@ async def work() -> bool: return Localizer -def _marge_axes(rotation: np.ndarray) -> list[int]: - """Return the MaRGE axis closest to each of the logical readout, phase and slice axes.""" - return [int(np.argmax(np.abs(MARGE_AXES.T @ column))) for column in np.asarray(rotation).T] +def _key(name: str) -> str: + """Return the key of a protocol entry among a sequence's values.""" + return f"{name}{RENAMED}" if name in MARGE_KEYS else name + + +def _field(name: str) -> str: + """Return MaRGE's tab of a protocol entry: the image tab for what places and samples the image, the other tab for the user entries, the sequence tab for the rest.""" + from marge.console import prescribe + + if USER_ENTRY.fullmatch(name): + return "OTH" + if name in (*prescribe.GEOMETRY, prescribe.MODE, "nx", "ny"): + return "IM" + return "SEQ" + + +def _label(name: str, entries: Mapping[str, Mapping[str, Any]]) -> str: + """Return the label of an entry: a user entry's name where the plugin gives one, with the entry's unit.""" + user = USER_ENTRY.fullmatch(name) + named = entries.get(f"user{user.group(1)}_name") if user else None + label = str(named["value"]) if named and str(named["value"]).strip() else name + unit = entries[name].get("unit", "") + return f"{label} ({unit})" if unit else label def _plugin_class( base: type, gateway: Any, plugin: str, entries: Mapping[str, Mapping[str, Any]] ) -> type: - sizes = [name for name in FOV_SIZE if name in shown(entries)] - names = [name for name in shown(entries) if name not in sizes] + from marge.console import prescribe - def cm_per_unit(name: str) -> float: - return CM_PER_UNIT.get(entries[name].get("unit", ""), CM_PER_UNIT["mm"]) + names = shown(entries) class PluginSequence(_console_class(base)): def __init__(self) -> None: @@ -583,26 +593,26 @@ def __init__(self) -> None: self.addParameter(key="seqName", string=plugin, val=plugin) self.addParameter(key="toMaRGE", val=True) self.addParameter(key="pulserverConsole", val=True) + # MaRGE's own field of view and centre, in cm and mm, which it keeps + # with each run; the prescription is the values below. + self.addParameter(key="fov", val=[0.0, 0.0, 0.0], units=1e-2) + self.addParameter(key="dfov", val=[0.0, 0.0, 0.0], units=1e-3) + for key, label, value, tip in ( + (prescribe.ORIENTATION, "Orientation", "axial", "axial, coronal or sagittal: the plane the prescription is turned from"), + (prescribe.CENTRE, "Centre (mm)", [0.0, 0.0, 0.0], "Centre of the stack along the patient's L, P and S axes"), + (prescribe.INPLANE, "In-plane (deg)", 0.0, "Turn about the slice direction"), + (prescribe.TILT_READ, "Tilt about read (deg)", 0.0, "Tilt of the starting plane about its readout direction"), + (prescribe.TILT_PHASE, "Tilt about phase (deg)", 0.0, "Tilt of the starting plane about its phase direction"), + ): + self.addParameter(key=key, string=label, val=value, units=1, field="IM", tip=tip) for name in names: - entry = entries[name] - unit = entry.get("unit", "") - label = f"{name} ({unit})" if unit else name - self.addParameter(key=name, string=label, val=entry["value"], units=1, field="SEQ") - fov = [0.0, 0.0, 0.0] - for name, axis in zip(FOV_SIZE, _marge_axes(ORIENTATIONS["axial"]), strict=True): - if name in sizes: - fov[axis] = entries[name]["value"] * cm_per_unit(name) - self.addParameter(key="fov", string="FOV (cm)", val=fov, units=1e-2, field="IM") - self.addParameter( - key="orientation", string="Orientation", val="axial", units=1, field="IM" - ) - self.addParameter( - key="dfov", string="FOV centre (mm)", val=[0.0, 0.0, 0.0], units=1e-3, field="IM" - ) - self.addParameter(key="angle", string="Angle (deg)", val=0.0, units=1, field="IM") - self.addParameter( - key="rotationAxis", string="Rotation axis", val=[1.0, 0.0, 0.0], units=1, field="IM" - ) + self.addParameter( + key=_key(name), + string=_label(name, entries), + val=entries[name]["value"], + units=1, + field=_field(name), + ) self.files: list[bytes] = [] self.clock = (0.0, 0.0) self.prepared = 0 @@ -610,19 +620,37 @@ def __init__(self) -> None: def sequenceRun(self, plotSeq=0, demo=False) -> bool: # noqa: N802 -- MaRGE's API return _run(self, gateway, self._scan) + def planned(self): + """Return the prescription the values state.""" + return prescribe.prescription(self.mapVals, entries, _key) + + def plan(self, planned) -> dict: + """Set the values that state ``planned``; return those that changed, by their keys.""" + changed = prescribe.written(planned, self.mapVals, entries, _key) + self.mapVals.update(changed) + return changed + + def planned_bands(self) -> list: + return prescribe.bands(self.mapVals, entries, _key) + + def plan_band(self, n: int, band) -> dict: + """Set the values that place saturation band ``n``; return those that changed, by their keys.""" + changed = prescribe.band_written(n, band, self.mapVals, entries, _key) + self.mapVals.update(changed) + return changed + + def parameterChanged(self, key: str) -> None: # noqa: N802 -- MaRGE's naming + """Redraw the prescription once a value is typed.""" + if WORKSPACE is not None: + WORKSPACE.redraw() + async def _scan(self) -> bool: - centre = MARGE_AXES @ np.asarray(self.mapVals["dfov"], dtype=float) - rotation, offset = prescription( - str(self.mapVals["orientation"]), - float(self.mapVals["angle"]), - MARGE_AXES @ np.asarray(self.mapVals["rotationAxis"], dtype=float), - centre, - ) - values = {name: self.mapVals[name] for name in names} - for name, axis in zip(FOV_SIZE, _marge_axes(rotation), strict=True): - if name in sizes: - values[name] = float(self.mapVals["fov"][axis]) / cm_per_unit(name) - block = format_values(values, entries, rotation, offset) + planned = self.planned() + rotation, centre = planned.rotation, planned.centre + self.mapVals["fov"] = [0.1 * planned.fov[0], 0.1 * planned.fov[1], 0.2 * planned.extent] + self.mapVals["dfov"] = [float(c) for c in centre] + values = {name: self.mapVals[_key(name)] for name in names} + block = format_values(values, entries, rotation, rotation.T @ centre) generated = await _answer(gateway.request("generate", plugin=plugin, block=block)) if generated["status"] != 0: raise RuntimeError(generated["reply"].strip()) diff --git a/marge/ui/window_main.py b/marge/ui/window_main.py index 44e4aa4..9163efb 100644 --- a/marge/ui/window_main.py +++ b/marge/ui/window_main.py @@ -28,6 +28,9 @@ from marge.controller.controller_sequence_inputs import SequenceInputsController from marge.widgets.widget_custom_and_protocol import CustomAndProtocolWidget from marge.controller.controller_postprocessing import ProcessingWindowController +from marge.console.workspace import Workspace +from marge.seq.pulserver_console import console_mode, register_workspace +from marge.seq.sequences import defaultsequences class MainWindow(QMainWindow): @@ -137,6 +140,16 @@ def __init__(self, session, demo=False, parent=None): self.figures_layout.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.layout_right.addWidget(self.figures_layout) + # As the console of pulserver's virtual scanner, the workspace takes the + # figures' place: the views to prescribe on and the viewer of the series + self.workspace = None + if console_mode(): + self.workspace = Workspace(self.prescribedSequence, self.sequence_inputs.showValues) + self.workspace.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.figures_layout.hide() + self.layout_right.insertWidget(0, self.workspace, 1) + register_workspace(self.workspace) + # Layout for output history self.layout_right_h = QHBoxLayout() self.layout_right.addLayout(self.layout_right_h) @@ -153,6 +166,12 @@ def __init__(self, session, demo=False, parent=None): self.input_table.setMinimumHeight(200) self.layout_right_h.addWidget(self.input_table, 1) + if self.workspace is not None: + self.sequence_list.currentTextChanged.connect(self.workspace.redraw) + self.history_list.itemClicked.connect( + lambda item: self.workspace.show_run(item.text().split(" | ", 1)[-1]) + ) + # Create the post-processing toolbox self.post_gui = ProcessingWindowController(session=self.session, main=self) @@ -160,6 +179,11 @@ def __init__(self, session, demo=False, parent=None): self.printer = Printer(main=self) + def prescribedSequence(self): + """Return the selected sequence where the workspace prescribes it, else None.""" + sequence = defaultsequences.get(self.sequence_list.getCurrentSequence()) + return sequence if hasattr(sequence, "planned") else None + def show(self): """Show the window; in a browser tab, filling the tab, so that the history below the figures is in view.""" if sys.platform == "emscripten": diff --git a/tests/test_browser.py b/tests/test_browser.py index ccbdf58..6ce884a 100644 --- a/tests/test_browser.py +++ b/tests/test_browser.py @@ -217,6 +217,8 @@ def test_an_exam_opens_on_the_localizer_of_the_subjects_phantom_among_pulservers assert history[0].split(" | ")[1].startswith("Localizer.") assert localizer == 3 assert names == sorted(["Localizer", *_console_plugins()]) + views = _python(page, PRELUDE + "json.dumps([[v.series.label, v.index] for v in main.workspace.views])") + assert views == [["S1 Localizer", 0], ["S1 Localizer", 1], ["S1 Localizer", 2]] def test_the_console_offers_acquire_and_the_localizer_and_not_what_needs_marcos(page): @@ -261,11 +263,30 @@ def test_a_scan_of_marges_protocol_plays_its_sound_and_returns_its_reconstructio assert history[1].split(" | ")[1].startswith("gre2d.") assert files >= 1 + shown = _python(page, PRELUDE + "json.dumps(main.workspace.viewer.series.description)") + assert shown == "gre2d" assert prepared >= 1 assert clock[0] == pytest.approx(clock[1]) and clock[1] > 0.0 assert played == pytest.approx(clock[1], rel=0.01) +def test_a_slice_count_typed_in_the_image_tab_redraws_the_stack_across_the_localizer(page): + lines = _python( + page, + PRELUDE + + """ +main.sequence_list.setCurrentText("gre2d") +field = main.sequence_inputs.fields["nslices"] +field.setText("7") +coronal = main.workspace.views[1] +x, _ = coronal.traces.getData() +json.dumps(0 if x is None else len(x) // 2) +""", + ) + + assert lines == 7 + + def test_another_subject_in_the_session_window_opens_another_exam_on_its_localizer(page): _python( page, diff --git a/tests/test_console_geometry.py b/tests/test_console_geometry.py new file mode 100644 index 0000000..3c99703 --- /dev/null +++ b/tests/test_console_geometry.py @@ -0,0 +1,187 @@ +"""The geometry of the console's graphical prescription, in the patient's LPS frame.""" + +import types + +import numpy as np +import pytest + +from marge.console import geometry as g + + +def _plane(across, down, centre=(0.0, 0.0, 0.0), size=128, spacing=2.0): + across, down = np.asarray(across, float), np.asarray(down, float) + origin = np.asarray(centre, float) - 0.5 * (size - 1) * spacing * (across + down) + return g.ImagePlane(origin, across, down, (spacing, spacing), (size, size)) + + +AXIAL = _plane((1, 0, 0), (0, 1, 0)) +CORONAL = _plane((1, 0, 0), (0, 0, -1)) +SAGITTAL = _plane((0, 1, 0), (0, 0, -1)) + + +@pytest.mark.parametrize("base", list(g.BASES)) +def test_each_starting_plane_is_a_rotation_whose_image_reads_as_the_localizers_plane(base): + planes = {"axial": AXIAL, "coronal": CORONAL, "sagittal": SAGITTAL} + matrix = g.BASES[base] + + assert np.allclose(matrix.T @ matrix, np.eye(3)) and np.linalg.det(matrix) == pytest.approx(1.0) + assert np.allclose(matrix[:, 0], planes[base].across) + assert np.allclose(matrix[:, 1], planes[base].down) + + +@pytest.mark.parametrize("base", list(g.BASES)) +@pytest.mark.parametrize("turns", [(0, 0, 0), (30, 0, 0), (0, 20, 0), (0, 0, -15), (25, -10, 40)]) +def test_the_angles_of_a_rotation_rebuild_it(base, turns): + matrix = g.rotation(base, *turns) + + assert np.allclose(g.angles(matrix, base), turns, atol=1e-9) + + +def test_a_tilt_about_the_readout_turns_the_slices_about_the_readout_direction(): + matrix = g.rotation("axial", 0.0, 10.0, 0.0) + + assert np.allclose(matrix[:, 0], (1, 0, 0)) + assert matrix[:, 2] @ (0, 0, 1) == pytest.approx(np.cos(np.radians(10.0))) + + +def test_an_image_planes_pixels_map_to_points_and_back(): + plane = _plane((0.6, 0.8, 0.0), (0.0, 0.0, -1.0), centre=(5, -3, 12)) + pixels = np.array([[0.0, 0.0], [10.5, 3.25], [127.0, 127.0]]) + points = np.array([plane.point(*p) for p in pixels]) + + assert np.allclose(plane.pixel(points), pixels) + assert np.allclose(plane.centre, (5, -3, 12)) + + +def test_a_planes_dicom_geometry_reads_with_its_row_and_column_spacings_apart(): + dataset = types.SimpleNamespace( + ImageOrientationPatient=[1, 0, 0, 0, 1, 0], + ImagePositionPatient=[-127, -100, 4], + PixelSpacing=[3.0, 2.0], # between rows, between columns + Rows=64, + Columns=128, + ) + plane = g.ImagePlane.of(dataset) + + assert plane.spacing == (2.0, 3.0) + assert np.allclose(plane.point(1, 1), (-125, -97, 4)) + + +def _stack(**changes): + values = dict( + centre=np.zeros(3), rotation=g.BASES["axial"], fov=(200.0, 160.0), thickness=4.0, gap=1.0, slices=5 + ) + return g.Prescription(**{**values, **changes}) + + +def test_an_axial_stack_shows_as_a_box_on_the_axial_view_and_as_lines_across_the_others(): + stack = _stack() + + on_axial = g.section(stack, AXIAL) + on_coronal = g.section(stack, CORONAL) + + assert on_axial.facing and on_axial.lines == [] + assert np.ptp(on_axial.box[:, 0]) == pytest.approx(200.0 / 2.0) + assert np.ptp(on_axial.box[:, 1]) == pytest.approx(160.0 / 2.0) + assert not on_coronal.facing and len(on_coronal.lines) == 5 + rows = sorted(line[0, 1] for line in on_coronal.lines) + assert np.allclose(np.diff(rows), 5.0 / 2.0) # a pitch of 5 mm, 2 mm pixels + assert all(np.ptp(line[:, 0]) == pytest.approx(100.0) for line in on_coronal.lines) + + +def test_the_end_handles_sit_on_the_first_and_last_slice_across_the_stack(): + stack = _stack(centre=np.array([0.0, 0.0, 10.0])) + + first, last = g.section(stack, CORONAL).ends + + assert np.allclose(CORONAL.point(*first), (0, 0, 0)) + assert np.allclose(CORONAL.point(*last), (0, 0, 20)) + + +def test_a_stack_tilted_out_of_a_view_shows_as_lines_that_tilt_on_it(): + stack = _stack(rotation=g.rotation("axial", 0.0, 0.0, 20.0)) + + lines = g.section(stack, CORONAL).lines + slope = [np.diff(line[:, 1]) / np.diff(line[:, 0]) for line in lines] + + assert np.allclose(np.abs(slope), np.tan(np.radians(20.0))) + + +@pytest.mark.parametrize("side", [-1, 1]) +def test_dragging_an_end_outward_adds_slices_past_it_and_keeps_the_other_end(side): + stack = _stack() + + grown = stack.stretched(side, 2.2 * stack.pitch) + + assert grown.slices == 7 + assert np.allclose(grown.end(-side), stack.end(-side)) + assert np.allclose(grown.end(side), stack.end(side) + side * 2 * stack.pitch * stack.normal) + + +def test_dragging_an_end_inward_removes_slices_down_to_the_fewest(): + stack = _stack(limits=(2, 64)) + + assert stack.stretched(1, -1.0 * stack.pitch).slices == 4 + assert stack.stretched(1, -10.0 * stack.pitch).slices == 2 + + +def test_a_slab_spans_its_locations_without_gaps_and_shows_as_one_box(): + slab = _stack(slab=True, slices=32, thickness=1.0, gap=3.0) + + on_coronal = g.section(slab, CORONAL) + + assert slab.pitch == 1.0 and slab.extent == 16.0 + assert on_coronal.lines == [] + assert np.ptp(on_coronal.outline[:, 1]) == pytest.approx(32.0 / 2.0) + assert np.allclose([CORONAL.point(*e)[2] for e in on_coronal.ends], (-16.0, 16.0)) + + +def test_turning_a_prescription_turns_it_about_its_centre(): + stack = _stack(centre=np.array([5.0, 0.0, 0.0])) + + turned = stack.turned((0, 0, 1), 90.0) + + assert np.allclose(turned.centre, stack.centre) + assert np.allclose(turned.rotation[:, 0], (0, 1, 0)) + + +@pytest.mark.parametrize(("position", "covered"), [(0.0, 40.0), (120.0, 28.0), (400.0, 0.0)]) +def test_a_band_covers_the_part_of_a_view_within_its_slab(position, covered): + band = g.Band(normal=np.array([1.0, 0.0, 0.0]), position=position, thickness=40.0) + + area = g.band_area(band, AXIAL) + width = np.ptp(area[:, 0]) * 2.0 if len(area) else 0.0 + + assert width == pytest.approx(covered) + + +def test_an_oblique_band_covers_the_part_of_a_view_between_its_faces(): + normal = np.array([1.0, 1.0, 0.0]) / np.sqrt(2.0) + band = g.Band(normal=normal, position=0.0, thickness=20.0) + + area = g.band_area(band, AXIAL) + points = np.array([AXIAL.point(*p) for p in area]) + + assert len(area) >= 4 + assert np.all(np.abs(points @ normal) <= 10.0 + 1e-9) + + +def test_the_box_cut_of_a_stack_lies_on_the_view(): + stack = _stack(rotation=g.rotation("axial", 30.0, 15.0, -20.0), centre=np.array([3.0, -4.0, 2.0])) + + outline = g.section(stack, SAGITTAL).outline + points = np.array([SAGITTAL.point(*p) for p in outline]) + + assert len(outline) >= 4 + assert np.allclose((points - SAGITTAL.origin) @ SAGITTAL.normal, 0.0) + assert all(abs((p - stack.centre) @ stack.normal) <= stack.extent + 1e-9 for p in points) + + +def test_a_stack_tilted_less_than_half_a_right_angle_still_faces_its_starting_view_as_a_projected_box(): + stack = _stack(rotation=g.rotation("axial", 0.0, 0.0, 30.0)) + + on_axial = g.section(stack, AXIAL) + + assert on_axial.facing and on_axial.lines == [] + assert np.ptp(on_axial.box[:, 0]) == pytest.approx(200.0 * np.cos(np.radians(30.0)) / 2.0) + assert not g.section(_stack(rotation=g.rotation("axial", 0.0, 0.0, 50.0)), AXIAL).facing diff --git a/tests/test_console_prescribe.py b/tests/test_console_prescribe.py new file mode 100644 index 0000000..4e68acb --- /dev/null +++ b/tests/test_console_prescribe.py @@ -0,0 +1,130 @@ +"""A plugin's protocol entries as the console's prescription and saturation bands, and back.""" + +import numpy as np +import pytest + +from marge.console import geometry, prescribe +from marge.seq.pulserver_console import parse_listing + +LISTING = """PROTOCOL +[Protocol] +imaging_mode: stringlist|0|2d|3d +fov: float|typein|220.0|50.0|500.0|1.0|mm +phase_fov: float|typein|200.0|50.0|500.0|1.0|mm +nslices: int|typein|5|1|64|1| +slice_thickness: float|typein|4.0|1.0|20.0|0.5|mm +slice_spacing: float|typein|1.0|0.0|20.0|0.5|mm +exsat_mask: int|typein|0|0|3|1| +exsat1_normal_x: float|typein|1.0|-1.0|1.0|0.001| +exsat1_normal_y: float|typein|0.0|-1.0|1.0|0.001| +exsat1_normal_z: float|typein|0.0|-1.0|1.0|0.001| +exsat1_loc: float|typein|-60.0|-500.0|500.0|1.0|mm +exsat1_thickness: float|typein|40.0|5.0|200.0|1.0|mm +exsat2_normal_x: float|typein|0.0|-1.0|1.0|0.001| +exsat2_normal_y: float|typein|1.0|-1.0|1.0|0.001| +exsat2_normal_z: float|typein|0.0|-1.0|1.0|0.001| +exsat2_loc: float|typein|60.0|-500.0|500.0|1.0|mm +exsat2_thickness: float|typein|40.0|5.0|200.0|1.0|mm +[Protocol End] +""" + + +@pytest.fixture +def entries(): + return parse_listing(LISTING) + + +@pytest.fixture +def values(entries): + stated = {name: entry["value"] for name, entry in entries.items()} + return {**stated, "orientation": "axial", "centre": [0.0, 0.0, 0.0], "inplane": 0.0, "tilt_read": 0.0, "tilt_phase": 0.0} + + +def test_a_two_dimensional_plugin_prescribes_a_stack_of_its_slices_spaced_by_their_gap(entries, values): + planned = prescribe.prescription(values, entries) + + assert not planned.slab + assert planned.fov == (220.0, 200.0) + assert (planned.slices, planned.thickness, planned.gap, planned.pitch) == (5, 4.0, 1.0, 5.0) + assert planned.limits == (1, 64) + + +def test_a_three_dimensional_plugin_prescribes_one_slab_of_its_locations(entries, values): + values["imaging_mode"] = "3d" + entries["imaging_mode"]["value"] = "3d" + + planned = prescribe.prescription(values, entries) + + assert planned.slab and planned.pitch == 4.0 and planned.extent == 10.0 + + +def test_a_plugin_that_states_no_imaging_mode_or_thickness_is_told_apart(entries): + del entries["imaging_mode"], entries["slice_thickness"] + + assert prescribe.unstated(entries) == ["imaging_mode", "slice_thickness"] + assert not prescribe.slab(entries) + + +def test_an_orientation_is_read_whatever_its_case(entries, values): + values["orientation"] = " Coronal" + + assert np.allclose(prescribe.prescription(values, entries).rotation, geometry.BASES["coronal"]) + + +def test_written_values_are_held_within_each_entrys_range_and_on_its_step(entries, values): + planned = prescribe.prescription(values, entries).resized(600.0, 123.4) + + changed = prescribe.written(planned, values, entries) + + assert changed == {"fov": 500.0, "phase_fov": 123.0} + + +def test_a_stack_dragged_longer_writes_its_slices_and_its_new_centre(entries, values): + planned = prescribe.prescription(values, entries) + + changed = prescribe.written(planned.stretched(1, 2 * planned.pitch), values, entries) + + assert changed == {"nslices": 7, "centre": [0.0, 0.0, 5.0]} + + +def test_a_turned_prescription_is_written_as_its_angles_from_the_starting_plane(entries, values): + planned = prescribe.prescription(values, entries).turned((1, 0, 0), 12.0) + + changed = prescribe.written(planned, values, entries) + + assert changed == {"tilt_read": 12.0} + + +def test_a_band_turned_on_is_read_with_its_normal_and_written_back_held(entries, values): + values["exsat_mask"] = 2 + + ((n, band),) = prescribe.bands(values, entries) + turned = geometry.Band(np.array([0.0, 0.6, 0.8]), 72.6, 35.2) + + assert n == 2 and np.allclose(band.normal, (0, 1, 0)) and (band.position, band.thickness) == (60.0, 40.0) + assert prescribe.band_written(n, turned, values, entries) == { + "exsat2_normal_y": 0.6, + "exsat2_normal_z": 0.8, + "exsat2_loc": 73.0, + "exsat2_thickness": 35.0, + } + + +def test_a_band_turned_about_a_point_on_it_keeps_that_point_on_its_centre_plane(): + band = geometry.Band(np.array([0.0, 1.0, 0.0]), 20.0, 10.0) + point = np.array([5.0, 20.0, -3.0]) + + turned = band.turned((0, 0, 1), 30.0, point) + + assert turned.position == pytest.approx(point @ turned.normal) + assert np.allclose(turned.normal, (-0.5, np.cos(np.radians(30.0)), 0.0)) + + +def test_values_are_read_and_written_under_the_keys_a_sequence_holds_them_by(entries, values): + renamed = {f"{k}_p" if k in entries else k: v for k, v in values.items()} + + planned = prescribe.prescription(renamed, entries, key=lambda name: f"{name}_p") + changed = prescribe.written(planned.resized(210.0, 200.0), renamed, entries, key=lambda name: f"{name}_p") + + assert planned.fov == (220.0, 200.0) + assert changed == {"fov_p": 210.0} diff --git a/tests/test_console_workspace.py b/tests/test_console_workspace.py new file mode 100644 index 0000000..2dbc5a2 --- /dev/null +++ b/tests/test_console_workspace.py @@ -0,0 +1,207 @@ +"""The console's workspace: the exam's series in the views, and the prescription dragged on them.""" + +import io +import os + +import numpy as np +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +QtWidgets = pytest.importorskip("PyQt5.QtWidgets") + +from marge.console import geometry, prescribe # noqa: E402 +from marge.console.series import Series # noqa: E402 +from marge.console.workspace import Workspace # noqa: E402 +from marge.seq.pulserver_console import parse_listing # noqa: E402 + +LISTING = """PROTOCOL +[Protocol] +imaging_mode: stringlist|0|2d|3d +fov: float|typein|200.0|50.0|500.0|1.0|mm +phase_fov: float|typein|200.0|50.0|500.0|1.0|mm +nslices: int|typein|5|1|64|1| +slice_thickness: float|typein|4.0|1.0|20.0|0.5|mm +slice_spacing: float|typein|1.0|0.0|20.0|0.5|mm +exsat_mask: int|typein|2|0|3|1| +exsat1_normal_x: float|typein|1.0|-1.0|1.0|0.001| +exsat1_normal_y: float|typein|0.0|-1.0|1.0|0.001| +exsat1_normal_z: float|typein|0.0|-1.0|1.0|0.001| +exsat1_loc: float|typein|-60.0|-500.0|500.0|1.0|mm +exsat1_thickness: float|typein|40.0|5.0|200.0|1.0|mm +exsat2_normal_x: float|typein|0.0|-1.0|1.0|0.001| +exsat2_normal_y: float|typein|1.0|-1.0|1.0|0.001| +exsat2_normal_z: float|typein|0.0|-1.0|1.0|0.001| +exsat2_loc: float|typein|60.0|-500.0|500.0|1.0|mm +exsat2_thickness: float|typein|40.0|5.0|200.0|1.0|mm +[Protocol End] +""" + +#: The localizer's planes: their directions across and down. +PLANES = {"axial": ((1, 0, 0), (0, 1, 0)), "coronal": ((1, 0, 0), (0, 0, -1)), "sagittal": ((0, 1, 0), (0, 0, -1))} + + +@pytest.fixture(scope="module") +def application(): + return QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + + +def _dicom(across, down, number, size=64, spacing=4.0): + import pydicom + + across, down = np.asarray(across, float), np.asarray(down, float) + dataset = pydicom.Dataset() + dataset.file_meta = pydicom.dataset.FileMetaDataset() + dataset.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian + dataset.file_meta.MediaStorageSOPClassUID = pydicom.uid.MRImageStorage + dataset.file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid() + dataset.SOPClassUID = pydicom.uid.MRImageStorage + dataset.SOPInstanceUID = dataset.file_meta.MediaStorageSOPInstanceUID + dataset.Rows = dataset.Columns = size + dataset.SamplesPerPixel, dataset.PhotometricInterpretation = 1, "MONOCHROME2" + dataset.BitsAllocated, dataset.BitsStored, dataset.HighBit, dataset.PixelRepresentation = 16, 16, 15, 0 + dataset.PixelData = (np.arange(size * size) % 4096).astype("