Skip to content

Plotting

plotting

This module contains plotting functionality to illustrate sequence definitions in a commonly occuring format.

plot_moment

plot_moment(
    seq: Sequence,
    moment_order: int = 0,
    axes: Union[Tuple[Axes, ...], Axes, str] = None,
    start_time: Quantity = None,
) -> plt.Figure

Creates a figure with a 3x1 subplot grid and plots the gradient moment of specified order for all 3 gradient components over time. Also plots gradients superimposed into the corresponding subplot

Parameters:

Name Type Description Default
axes Union[Tuple[Axes, ...], Axes, str]

(plt.Axes, plt.Axes, plt.Axes) (gx, gy, gz) or a single instance of plt.Axes if everything shall be plotted in the same axis. If the value is set to string "single", a new figure is created plotting everything into a single axis. If none a new figure with 3 separate axes is created.

None
seq Sequence

Instance of cmrseq.Sequence

required
moment_order int

order of the moment to be plotted

0

Returns:

Type Description
plt.figure with 3x1 suplot grid
Source code in cmrseq/plotting.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def plot_moment(seq: Sequence, moment_order: int = 0,
                axes: Union[Tuple[plt.Axes, ...], plt.Axes, str] = None,
                start_time: Quantity = None) -> plt.Figure:
    r"""Creates a figure with a 3x1 subplot grid and plots the gradient moment
     of specified order for all 3 gradient components over time. Also plots gradients superimposed
     into the corresponding subplot

    Parameters
    ----------
    axes
        (plt.Axes, plt.Axes, plt.Axes) (gx, gy, gz) or a single instance of plt.Axes if everything shall be plotted in the same axis. If the value is set to string "single", a new figure is created plotting everything into a single axis. If none a new figure with 3 separate axes is created.
    seq
        Instance of cmrseq.Sequence
    moment_order
        order of the moment to be plotted

    Returns
    -------
    plt.figure with 3x1 suplot grid
    """
    single_plot = False
    if axes is None:
        axes = "perchannel"
    if isinstance(axes, str):
        if axes == "perchannel":
            f, axes = plt.subplots(3, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
        elif axes == "single":
            f, axes = plt.subplots(1, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
            single_plot = True
        else:
            raise NotImplementedError(f"Argument for axes is string valued [{axes}] but does not "
                             f"match the allowed cases (single, perchannel)")
    elif isinstance(axes, plt.Axes):
        f = None
        single_plot = True
    elif isinstance(axes, Tuple) or isinstance(axes, List):
        if len(axes) != 3:
            raise ValueError(f"Argument for axes is a list or tuple, but does not contain 3 axes "
                             f"({len(axes)} given)")
        elif axes[0] == axes[1] ==axes[2]:
            axes = axes[0]
            single_plot=True
        f = None
    else:
        f = None

    time, gradient_waveform = seq.gradients_to_grid()

    # Shift timing according to start time.
    # If not given, use the center time of the first RF pulse (if any)
    if start_time is not None:
        time -= start_time.m_as("ms")
    elif seq.rf_events: # RF event present, use the first center time as the start time
        time -= seq.rf_events[0][0].m_as("ms")

    # Shift sampling to window center
    gradient_centers = (gradient_waveform[:,1:] + gradient_waveform[:,:-1])/2
    t_centers = (time[1:] + time[:-1])/2
    dt = np.diff(time)

    moment_integrand = gradient_centers * (t_centers ** moment_order) * dt
    gradient_moment = np.cumsum(moment_integrand, axis=1)
    gradient_moment = np.insert(gradient_moment, 0, 0, axis=1) # first point is assume zero

    # Shift moments to 0 at t=0
    gradient_moment[0,:] -= np.interp(0, time, gradient_moment[0,:],)
    gradient_moment[1,:] -= np.interp(0, time, gradient_moment[1,:])
    gradient_moment[2,:] -= np.interp(0, time, gradient_moment[2,:])

    grad_range = np.array([-seq._system_specs.max_grad.m_as("mT/m"),
                           seq._system_specs.max_grad.m_as("mT/m")])

    moment_lim =np.max(np.abs(gradient_moment))

    twin = []
    # get short symbol of moment which is a pin feature:
    # https://stackoverflow.com/questions/65681490/format-pint-unit-as-short-form-symbol
    # moment_unit = format(Quantity(1, f"mT/m*ms**{moment_order}"), "~")
    moment_unit = f"mT/m*ms^{moment_order+1}"
    if moment_order == 0:
        moment_unit = f"mT/m*ms"
    moment_strings = ["th", "st", "nd", "rd"] + ["th"] * 100
    moment_label = f"{moment_order}" + "^{{" + moment_strings[moment_order] + "}}"

    if single_plot:
        axes.set_ylim(grad_range * 1.1)
        axes.set_yticks(np.linspace(grad_range[0], grad_range[1], 5))
        axes.set_ylabel("Gradient [$mT/m$]")
        axes.grid(True)
        axes.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))

        twinax = axes.twinx()
        twinax.tick_params("y", colors="darkorchid", direction="in")
        twinax.yaxis.set_label_position('left')
        twinax.yaxis.label.set_color("darkorchid")
        twinax.yaxis.set_ticks_position('left')
        twinax.set_ylim(-moment_lim * 1.1, moment_lim * 1.1)
        twinax.set_yticks(np.linspace(-moment_lim, moment_lim, 5))
        twinax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))
        twinax.set_ylabel(f"${moment_label}$ Moment " + f"[${moment_unit}$]", labelpad=20)

        for idx, grad_channel, moment_channel in zip(range(3), gradient_waveform, gradient_moment):
            axes.plot(time, grad_channel, color=f"C{idx}",linestyle="--")
            twinax.plot(time, moment_channel, color=f"C{idx}")

        axes.legend([lines.Line2D([0], [0], ls='--', c=f'C0'),
                     lines.Line2D([0], [0], ls='--', c=f'C1'),
                     lines.Line2D([0], [0], ls='--', c=f'C2'),
                     lines.Line2D([0], [0], ls='-', c=f'C0'),
                     lines.Line2D([0], [0], ls='-', c=f'C1'),
                     lines.Line2D([0], [0], ls='-', c=f'C2')],
                     ["Gx","Gy","Gz","$Mx$","My","Mz"], ncols=2,loc='lower left')

        axes.set_xlabel("Time [ms]")
        [tick.set_verticalalignment("bottom") for tick in axes.get_yticklabels()]
        [tick.set_verticalalignment("top") for tick in twinax.get_yticklabels()]

        axes = [axes]

    else:
        for idx, ax, grad_channel, moment_channel, label_m, label_g \
                in zip(range(3), axes, gradient_waveform, gradient_moment,
                    ["Mx[$" + moment_unit + "$]", "My[$" + moment_unit + "$]",
                        "Mz[$" + moment_unit + "$]"], ["Gx [mT/m]", "Gy [mT/m]", "Gz [mT/m]"]):
            ax.plot(time, grad_channel, color=f"C{idx}",linestyle="--")
            ax.set_ylim(grad_range * 1.1)
            ax.set_yticks(np.linspace(grad_range[0], grad_range[1], 5))
            ax.set_ylabel(label_g)
            ax.grid(True)
            ax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))

            twinax = ax.twinx()
            twinax.tick_params("y", colors=f"C{idx}", direction="in")
            twinax.yaxis.set_label_position('left')
            twinax.yaxis.label.set_color(f"C{idx}")
            twinax.yaxis.set_ticks_position('left')
            twinax.plot(time, moment_channel, color=f"C{idx}")
            ylim = np.max((np.max(abs(moment_channel)), 1))
            twinax.set_ylim(-ylim * 1.1, ylim * 1.1)
            twinax.set_yticks(np.linspace(-ylim, ylim, 5))
            twinax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))
            twinax.set_ylabel(label_m, labelpad=20)
            twinax.legend([lines.Line2D([0], [0], ls='--', c=f'C{idx}'),
                        lines.Line2D([0], [0], ls='-', c=f'C{idx}')],
                        ['Gradient', f"${moment_label}$ Moment"])
            twin.append(twinax)

        axes[-1].set_xlabel("Time [ms]")
        for ax, tax in zip(axes, twin):
            [tick.set_verticalalignment("bottom") for tick in ax.get_yticklabels()]
            [tick.set_verticalalignment("top") for tick in tax.get_yticklabels()]
    return axes[0].figure

plot_sequence

plot_sequence(
    seq: Sequence,
    axes: Union[Tuple[Axes, ...], Axes, str] = None,
    format_axes: bool = True,
    add_legend: bool = True,
    adc_yoffset: float = 0,
    n_yticks: int = 5,
    plot_center_lines: bool = True,
    legend_position: str = "upper left",
    gradient_style: str = "line",
    gradient_colors: List[str] = ("C0", "C1", "C2"),
    rf_color: str = "purple",
    add_flip_angles: bool = False,
) -> plt.Figure

Plot RF, gradients and adc events into a(4, 1) axes grid. If for axes are specified as argument, plots are inserted there.

Parameters:

Name Type Description Default
seq Sequence

Instance of cmrseq.Sequence

required
axes Union[Tuple[Axes, ...], Axes, str]

(plt.Axes, plt.Axes, plt.Axes, plt.Axes) (rf, gx, gy, gz) or a single instance of plt.Axes if everything shall be plotted in the same axis. If the value is set to string "single", a new figure is create plotting everyting into a single axis. If none a new figure with 4 separate axes is created.

None
format_axes bool

if true applies styling to the axes

True
add_legend bool

if true adds legend to the first axis. If no axes are provided, this is forced to be True

True
adc_yoffset float

determines the y-offset for adc-event markers

0
n_yticks int

determines the number of y ticks if format axes is True

5
plot_center_lines bool

If True, adds vertical lines for rf-centers and adc-centers

True
legend_position str

Position of legend if it is added

'upper left'
gradient_style str

if "line" only the line is plotted, if "filled" filled between the axes

'line'
gradient_colors List[str]

tuple of 3 colors, the channels are plotted in.

('C0', 'C1', 'C2')
rf_color str

determines the color, RF waveforms are plotted.

'purple'
add_flip_angles bool

If true, adds text_labels to the RF centers stating the flip angle

False
Source code in cmrseq/plotting.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def plot_sequence(seq: Sequence,
                  axes: Union[Tuple[plt.Axes, ...], plt.Axes, str] = None,
                  format_axes: bool = True,
                  add_legend: bool = True,
                  adc_yoffset: float = 0,
                  n_yticks: int = 5,
                  plot_center_lines: bool = True,
                  legend_position: str = "upper left",
                  gradient_style: str = "line",
                  gradient_colors: List[str] = ("C0", "C1", "C2"),
                  rf_color: str = "purple",
                  add_flip_angles: bool = False,
                  ) -> plt.Figure:
    r"""Plot RF, gradients and adc events into a(4, 1) axes grid. If for axes are specified
    as argument, plots are inserted there.

    Parameters
    ----------
    seq
        Instance of cmrseq.Sequence
    axes
        (plt.Axes, plt.Axes, plt.Axes, plt.Axes) (rf, gx, gy, gz) or a single instance of plt.Axes if everything shall be plotted in the same axis. If the value is set to string "single", a new figure is create plotting everyting into a single axis. If none a new figure with 4 separate axes is created.
    format_axes
        if true applies styling to the axes
    add_legend
        if true adds legend to the first axis. If no axes are provided, this is forced to be True
    adc_yoffset
        determines the y-offset for adc-event markers
    n_yticks
        determines the number of y ticks if format axes is True
    plot_center_lines
        If True, adds vertical lines for rf-centers and adc-centers
    legend_position
        Position of legend if it is added
    gradient_style
        if "line" only the line is plotted, if "filled" filled between the axes
    gradient_colors
        tuple of 3 colors, the channels are plotted in.
    rf_color
        determines the color, RF waveforms are plotted.
    add_flip_angles
        If true, adds text_labels to the RF centers stating the flip angle
    """
    if axes is None:
        axes = "perchannel"
    if isinstance(axes, str):
        if axes == "perchannel":
            f, axes = plt.subplots(4, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
        elif axes == "single":
            f, axes = plt.subplots(1, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
        else:
            raise NotImplementedError(f"Argument for axes is string valued [{axes}] but does not "
                             f"match the allowed cases (single, perchannel)")
    else:
        f = None

    if gradient_style.split("_")[0].lower() not in ("line", "filled", "hatched"):
        raise NotImplementedError(f"Argument for 'gradient_style' [{gradient_style}] does not"
                         f" match the allowed cases (line, filled, hatched_?)")

    single_axis = isinstance(axes, plt.Axes)
    if single_axis:
        rf_ax = axes.twinx()
        rf_ax.tick_params("y", colors=rf_color, direction="in")
        rf_ax.yaxis.set_label_position('left')
        rf_ax.yaxis.label.set_color(rf_color)
        rf_ax.yaxis.set_ticks_position('left')
        axes = [rf_ax, axes, axes, axes]

    # Plot RF
    t, rf_grid = seq.combined_rf()
    if rf_grid is not None:
        axes[0].plot(t, np.real(rf_grid), color=rf_color, label="Re(RF)")
        axes[0].plot(t, np.imag(rf_grid), color=rf_color, linestyle="--", label="Im(RF)")
        if add_flip_angles:
            for t_rf, fa in seq.rf_events:
                axes[0].text(t_rf.m, seq._system_specs.rf_peak_power.m,
                             f"{fa.m:1.0f}" + r"$^{\circ}$", ha='center',
                             va="bottom", color=rf_color)

    if plot_center_lines:
        rf_events = seq.rf_events
        if rf_events:  # [] == False
            [axes[0].axvline(t.m_as("ms"), linestyle='-', linewidth=1, color=rf_color, alpha=0.5)
             for (t, _) in rf_events]

    # Plot Gradients
    t, gradients = seq.combined_gradients()
    if gradients is not None:
        labels = ["Gx", "Gy", "Gz"]
        if gradient_style.lower() == "line":
            for idx, ax, gc, color in zip(range(3), axes[1:], gradients, gradient_colors):
                ax.plot(t, gc, color=color, label=labels[idx])
        elif gradient_style.lower() == "filled":
            edge_colors = [to_rgba(c, 1) for c in gradient_colors]
            face_colors = [to_rgba(c, 0.5) for c in gradient_colors]
            for idx, ax, gc in zip(range(3), axes[1:], gradients):
                ax.fill_between(t, gc, ec=edge_colors[idx], fc=face_colors[idx])
        elif gradient_style.split("_")[0].lower() == "hatched":
            hatch_pattern = gradient_style.split("_")[1]
            edge_colors = [to_rgba(c, 1) for c in gradient_colors]
            for idx, ax, gc in zip(range(3), axes[1:], gradients):
                ax.fill_between(t, gc, ec=edge_colors[idx], fc=(1., 1., 1., 0.),
                                hatch=hatch_pattern)

    # Plot ADC
    for block in seq:
        if isinstance(block, ADC):
            sampling_times = block.adc_timing
            rect = patches.Rectangle((block.tmin.m_as("ms"), adc_yoffset - 1),
                                     (block.tmax - block.tmin).m_as("ms"),
                                     2, linewidth=1.5, facecolor=(0, 0, 0, 0.1),
                                     edgecolor=(0., 0., 0., 0.2))
            if plot_center_lines:
                axes[0].axvline(block.anchor_time.m_as("ms"), linestyle="--",
                                color=(234 / 256, 211 / 256, 168 / 256, 1.))
            axes[0].add_patch(rect)
            normed_phase = block.adc_phase / np.pi
            axes[0].vlines(sampling_times.m_as("ms"), adc_yoffset - 0.75, adc_yoffset + 0.75,
                           color="crimson", linewidth=1.5)
            axes[0].plot(sampling_times.m_as("ms"), normed_phase + adc_yoffset,
                         linestyle="-", color=(234 / 256, 211 / 256, 168 / 256, 1.), linewidth=4)

    # Create custom legend
    if add_legend:
        legend_handles = [patches.Rectangle((0, 0), 1, 1, facecolor=rf_color),
                          plt.Line2D([0], [0], linestyle="-", color=rf_color),
                          plt.Line2D([0], [0], linestyle="--", color=rf_color),
                          plt.Line2D([0], [0], linestyle="-", color="C0"),
                          plt.Line2D([0], [0], linestyle="-", color="C1"),
                          plt.Line2D([0], [0], linestyle="-", color="C2"),
                          patches.Rectangle((0, 0), 1, 1, linewidth=1.5,
                                            facecolor=(0, 0, 0, 0.2), edgecolor=(0., 0., 0., 0.4)),
                          plt.Line2D([0], [0], color="crimson", marker="|", linewidth=0),
                          plt.Line2D([0], [0], linestyle="-",
                                     color=(234 / 256, 211 / 256, 168 / 256, 1.)),
                          plt.Line2D([0], [0], color=rf_color, marker="|", linewidth=0),
                          plt.Line2D([0], [0],
                                     color=(234 / 256, 211 / 256, 168 / 256, 1.),
                                     marker="|", linewidth=0),
                          plt.Line2D([0], [0], color="white", marker="|", linewidth=0, alpha=0)
                          ]
        legend_names = ["RF", r"$Re$", r"$Im$", "Gx", "Gy", "Gz", "ADC", "events",
                        "phase", "RF-centers", "ADC-centers", ""]
        legend = axes[0].legend(handles=legend_handles, labels=legend_names, ncol=4,
                                columnspacing=2, fontsize=10, handlelength=3, loc=legend_position)
        small_texts = [legend.get_texts()[i] for i in [1, 2, 7, 8]]
        [t.set_size(7) for t in small_texts]
        small_handles = [legend.legend_handles[i] for i in [1, 2, 7, 8]]
        [plt.setp(h, xdata=np.array([h.get_xdata()[-1] * 0.4, *h.get_xdata()[1:]]))
         for h in small_handles]

    if format_axes:
        [ax.set_ylabel(l) for ax, l in zip(axes, [r"RF [$\mu$T]", "G [mT/m]",
                                                  "G [mT/m]", "G [mT/m]"])]
        axes[-1].set_xlabel("Time [ms]")
        grad_range = np.array([-seq._system_specs.max_grad.m_as("mT/m"),
                               seq._system_specs.max_grad.m_as("mT/m")])
        rf_range = np.array([-seq._system_specs.rf_peak_power.m_as("uT"),
                             seq._system_specs.rf_peak_power.m_as("uT")])
        [ax.grid(True) for ax in axes]
        [ax.set_ylim(grad_range * 1.1) for ax in axes[1:]]
        [ax.set_yticks(np.linspace(*grad_range, n_yticks)) for ax in axes[1:]]
        [ax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f')) for ax in axes]
        axes[0].set_ylim(rf_range * 1.1), axes[0].set_yticks(np.linspace(*rf_range, n_yticks))
        if single_axis:
            [tick.set_verticalalignment("bottom") for tick in axes[0].get_yticklabels()]
            [tick.set_verticalalignment("top") for tick in axes[1].get_yticklabels()]
            axes[0].set_ylabel("RF" + r"[$\mu$T]", labelpad=20)
    return f

plot_kspace_2d

plot_kspace_2d(
    seq: Sequence,
    plot_raster_trajectory: bool = True,
    k_axes: Tuple[int, int] = (0, 1),
    ax: Axes = None,
    format_axes: bool = True,
    markersize: int = 15,
    map_sampling_times: str = None,
    add_colorbar: bool = None,
    colorbar_kwargs: dict = None,
) -> plt.Axes

2D-scatter plot the trajectory of the sequence and its adc events

Parameters:

Name Type Description Default
seq Sequence
required
plot_raster_trajectory bool

if true plots the k-space points for all gradient raster points

True
k_axes Tuple[int, int]

determines which combination of (kx, ky, kz) to scatter plot

(0, 1)
ax Axes

plt.Axis, if not None this is used to plot k-space

None
format_axes bool
True
markersize int
15
map_sampling_times str

str from [None, "global", "relative"]. For 'global', the reference point is 0 ms for 'relative' the temporal difference to the center k-space sample is used as reference.

None
add_colorbar bool

if true a color-bar for the sampling time mapping

None
colorbar_kwargs dict

keyword arguments for color bar. Only has an effect if 'add_colorbar==True'

None

Returns:

Type Description
axis used to plot
Source code in cmrseq/plotting.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def plot_kspace_2d(seq: Sequence, plot_raster_trajectory: bool = True,
                   k_axes: Tuple[int, int] = (0, 1), ax: plt.Axes = None,
                   format_axes: bool = True, markersize: int = 15,
                   map_sampling_times: str = None,
                   add_colorbar: bool = None, colorbar_kwargs: dict = None) -> plt.Axes:
    r"""2D-scatter plot the trajectory of the sequence and its adc events

    Parameters
    ----------
    seq
    plot_raster_trajectory
        if true plots the k-space points for all gradient raster points
    k_axes
        determines which combination of (kx, ky, kz) to scatter plot
    ax
        plt.Axis, if not None this is used to plot k-space
    format_axes
    markersize
    map_sampling_times
        str from [None, "global", "relative"]. For 'global', the reference point is 0 ms for 'relative' the temporal difference to the center k-space sample is used as reference.
    add_colorbar
        if true a color-bar for the sampling time mapping
    colorbar_kwargs
        keyword arguments for color bar. Only has an effect if 'add_colorbar==True'

    Returns
    -------
    axis used to plot
    """
    axes_labels = ["$k_x$", "$k_y$", "$k_z$"]
    ktot, kadc, t_adc = seq.calculate_kspace()
    if ax is None:
        _, ax = plt.subplots(1, 1)
        format_axes = True
    if plot_raster_trajectory:
        ax.plot(*ktot[k_axes, :], color=np.array([[41, 52, 98]]) / 255,
                label="Full Trajectory", alpha=0.4)

    colorbar_kwargs_base = dict(label="", orientation="vertical", shrink=0.8, pad=0.05,
                                location="right")
    if map_sampling_times is not None:
        if map_sampling_times.lower() == "global":
            colorbar_kwargs_base["label"] = "$t_{ADC}$  $(ms)$"
            sampling_times = t_adc
        elif map_sampling_times.lower() == "relative":
            colorbar_kwargs_base["label"] = "$|t_{ADC} - t_{center}|$  $(ms)$"
            sampling_times = np.abs(t_adc - np.median(t_adc))
        else:
            raise NotImplementedError(
                f"map_sampling_times must be from [global, relative] but"
                f" got {map_sampling_times.lower()}")
        if kadc is not None:
            scatter_artist = ax.scatter(*kadc[k_axes, :], s=markersize, marker="x",
                                        c=sampling_times, label="Sampling events",
                                        vmin=np.min(sampling_times),
                                        vmax=np.max(sampling_times),
                                        cmap=plt.cm.get_cmap('rainbow'))
    else:
        marker_color = np.array([[242, 76, 76]]) / 255
        if kadc is not None:
            scatter_artist = ax.scatter(*kadc[k_axes, :], s=markersize, marker="x",
                                        c=marker_color, label="Sampling events")
    if format_axes:
        ax.set_xlabel(axes_labels[k_axes[0]] + r" $[1/m]$")
        ax.set_ylabel(axes_labels[k_axes[1]] + r" $[1/m]$")
        ax.grid(True, alpha=0.5)

    if add_colorbar and map_sampling_times:
        if colorbar_kwargs is not None:
            colorbar_kwargs_base.update(colorbar_kwargs)
        ax.figure.colorbar(scatter_artist, ax=ax, **colorbar_kwargs_base)

    return ax

plot_kspace_3d

plot_kspace_3d(
    seq: Sequence,
    plot_raster_trajectory: bool = False,
    axis: Axes = None,
    format_axis: bool = True,
    marker_kw: dict = None,
    line_kw: dict = None,
) -> (plt.Figure, plt.Axes)

3D-scatter plot the trajectory of the sequence and its adc events

Parameters:

Name Type Description Default
seq Sequence
required
plot_raster_trajectory bool

if true plots the k-space points for all gradient raster points

False
axis Axes
None
format_axis bool
True
marker_kw dict

keyword arguments for sample-markers

None
line_kw dict

keyword arguments for gradient trajectory line

None
Source code in cmrseq/plotting.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def plot_kspace_3d(seq: Sequence, plot_raster_trajectory: bool = False,
                   axis: plt.Axes = None, format_axis: bool = True, marker_kw: dict = None,
                   line_kw: dict = None) -> (plt.Figure, plt.Axes):
    r"""3D-scatter plot the trajectory of the sequence and its adc events

    Parameters
    ----------
    seq
    plot_raster_trajectory
        if true plots the k-space points for all gradient raster points
    axis
    format_axis
    marker_kw
        keyword arguments for sample-markers
    line_kw
        keyword arguments for gradient trajectory line
    """
    if axis is None:
        fig, axis = plt.subplots(1, 1, subplot_kw={'projection': '3d'})

    if format_axis:
        axis.grid(True)
        axis.set_xlabel("$k_x$"), axis.set_ylabel("$k_y$"), axis.set_ylabel("$k_z$")

    if marker_kw is None:
        marker_kw = {'s':2., 'marker':"x", 'c':"red"}
    if line_kw is None:
        line_kw = {'c':"blue", 'linewidth':2}

    ktot, kadc, _ = seq.calculate_kspace()
    if plot_raster_trajectory and ktot is not None:
        axis.plot(*ktot, **line_kw)
    if kadc is not None:
        axis.scatter(*kadc, **marker_kw)
    return axis

plot_block_names

plot_block_names(
    seq: Sequence, axis: Axes, fontsize: float = 9
)

Plots a time for the given sequence, on which the names of all contained blocks are added at their corresponding start time

Parameters:

Name Type Description Default
seq Sequence
required
axis Axes
required
fontsize float
9

Returns:

Type Description
object
Source code in cmrseq/plotting.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def plot_block_names(seq: Sequence, axis: plt.Axes, fontsize: float = 9):
    r"""Plots a time for the given sequence, on which the names of all contained blocks are
    added at their corresponding start time

    Parameters
    ----------
    seq
    axis
    fontsize

    Returns
    -------
    object
    """

    def plot_glyph(start, end, ypos, color, text, fontsize):
        axis.vlines([start, end], ypos - 0.75, ypos + 0.75, color=color, linewidth=2)
        axis.plot([start, end], [ypos, ypos], color=color, linewidth=2)
        axis.text(start + 0.05, ypos + 0.25, text, rotation=90, ha="left", fontsize=fontsize)

    block_types = [cmrseq.bausteine.RFPulse, cmrseq.bausteine.ADC, cmrseq.bausteine.Gradient]
    style_per_type = (dict(color="purple", ypos=4), dict(color="crimson", ypos=4),
                      dict(color="C0", ypos=0), dict(color="C1", ypos=-3),
                      dict(color="C2", ypos=-6))

    for _, bn in enumerate(seq.blocks):
        block = seq.get_block(bn)
        type_idx = [isinstance(block, t) for t in block_types].index(True)
        if type_idx == 2:  # if gradient determine the major gradient axis
            max_axis = np.argmax(np.max(np.abs(block.gradients[1]), axis=1).m)
            type_idx += max_axis
        plot_glyph(block.tmin.m_as("ms"), block.tmax.m_as("ms"),
                   **style_per_type[type_idx], text=bn, fontsize=fontsize)
    axis.set_yticks(range(-8, 7))
    axis.set_yticklabels(
        ["", "", "$G_z$", "", "", "$G_y$", "", "", "$G_x$", "", "", "", "RF/ADC", "", ""])
    axis.grid(True)

plot_slew

plot_slew(
    seq: Sequence,
    axes: Union[Tuple[Axes, ...], Axes, str] = None,
)

Plots the gradient and slew over time.

Parameters:

Name Type Description Default
seq Sequence

Instance of cmrseq.Sequence.

required
axes Union[Tuple[Axes, ...], Axes, str]

Three axes, a single axis, "single", "perchannel", or None.

None

Returns:

Type Description
figure
Source code in cmrseq/plotting.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def plot_slew(seq: Sequence, axes: Union[Tuple[plt.Axes, ...], plt.Axes, str] = None):
    r"""Plots the gradient and slew over time.

    Parameters
    ----------
    seq
        Instance of cmrseq.Sequence.
    axes
        Three axes, a single axis, `"single"`, `"perchannel"`, or `None`.

    Returns
    -------
    plt.figure
    """
    single_plot = False
    if axes is None:
        axes = "perchannel"
    if isinstance(axes, str):
        if axes == "perchannel":
            f, axes = plt.subplots(3, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
        elif axes == "single":
            f, axes = plt.subplots(1, 1, sharex='col', constrained_layout=True, figsize=(10, 6))
            single_plot = True
        else:
            raise NotImplementedError(f"Argument for axes is string valued [{axes}] but does not "
                             f"match the allowed cases (single, perchannel)")
    elif isinstance(axes, plt.Axes):
        f = None
        single_plot = True
    elif isinstance(axes, Tuple) or isinstance(axes, List):
        if len(axes) != 3:
            raise ValueError(f"Argument for axes is a list or tuple, but does not contain 3 axes "
                             f"({len(axes)} given)")
        elif axes[0] == axes[1] ==axes[2]:
            axes = axes[0]
            single_plot=True
        f = None
    else:
        f = None

    time, gradient_waveform = seq.gradients_to_grid()

    # Shift sampling to window center
    t_centers = (time[1:] + time[:-1])/2
    dt = np.diff(time)
    slew = np.diff(gradient_waveform,axis=1)/dt

    grad_range = np.array([-seq._system_specs.max_grad.m_as("mT/m"),
                           seq._system_specs.max_grad.m_as("mT/m")])

    slew_range = np.array([-seq._system_specs.max_slew.m_as("mT/m/ms"),
                           seq._system_specs.max_slew.m_as("mT/m/ms")])


    twin = []

    if single_plot:
        axes.set_ylim(grad_range * 1.1)
        axes.set_yticks(np.linspace(grad_range[0], grad_range[1], 5))
        axes.set_ylabel("Gradient [$mT/m$]")
        axes.grid(True)
        axes.yaxis.set_major_formatter(FormatStrFormatter('%3.1f'))

        twinax = axes.twinx()
        twinax.tick_params("y", colors="darkorchid", direction="in")
        twinax.yaxis.set_label_position('left')
        twinax.yaxis.label.set_color("darkorchid")
        twinax.yaxis.set_ticks_position('left')
        twinax.set_ylim(slew_range * 1.1)
        twinax.set_yticks(np.linspace(slew_range[0], slew_range[1], 5))
        twinax.yaxis.set_major_formatter(FormatStrFormatter('%3.1f'))
        twinax.set_ylabel("Slew [$mT/m/ms$]",labelpad=20)

        for idx, grad_channel, slew_channel in zip(range(3), gradient_waveform, slew):
            axes.plot(time, grad_channel, color=f"C{idx}",linestyle="--")
            twinax.plot(t_centers, slew_channel, color=f"C{idx}")

        axes.legend([lines.Line2D([0], [0], ls='--', c=f'C0'),
                     lines.Line2D([0], [0], ls='--', c=f'C1'),
                     lines.Line2D([0], [0], ls='--', c=f'C2'),
                     lines.Line2D([0], [0], ls='-', c=f'C0'),
                     lines.Line2D([0], [0], ls='-', c=f'C1'),
                     lines.Line2D([0], [0], ls='-', c=f'C2')],
                     ["Gx","Gy","Gz",r"$\Delta Gx$",r"$\Delta Gy$",r"$\Delta Gz$"], ncols=2,loc='lower left')

        axes.set_xlabel("Time [ms]")
        [tick.set_verticalalignment("bottom") for tick in axes.get_yticklabels()]
        [tick.set_verticalalignment("top") for tick in twinax.get_yticklabels()]

        axes = [axes]

    else:
        for idx, ax, grad_channel, slew_channel, label_m, label_g \
                in zip(range(3), axes, gradient_waveform, slew,
                    [r"$\Delta$Gx [mT/m/ms]",r"$\Delta$Gy [mT/m/ms]",r"$\Delta$Gz [mT/m/ms]"], ["Gx [mT/m]", "Gy [mT/m]", "Gz [mT/m]"]):
            ax.plot(time, grad_channel, color=f"C{idx}",linestyle="--")
            ax.set_ylim(grad_range * 1.1)
            ax.set_yticks(np.linspace(grad_range[0], grad_range[1], 5))
            ax.set_ylabel(label_g)
            ax.grid(True)
            ax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))

            twinax = ax.twinx()
            twinax.tick_params("y", colors=f"C{idx}", direction="in")
            twinax.yaxis.set_label_position('left')
            twinax.yaxis.label.set_color(f"C{idx}")
            twinax.yaxis.set_ticks_position('left')
            twinax.plot(t_centers, slew_channel, color=f"C{idx}")
            twinax.set_ylim(slew_range * 1.1)
            twinax.set_yticks(np.linspace(slew_range[0], slew_range[1], 5))
            twinax.yaxis.set_major_formatter(FormatStrFormatter('%3.2f'))
            twinax.set_ylabel(label_m, labelpad=20)
            twinax.legend([lines.Line2D([0], [0], ls='--', c=f'C{idx}'),
                        lines.Line2D([0], [0], ls='-', c=f'C{idx}')],
                        ['Gradient', 'Slew'])
            twin.append(twinax)

        axes[-1].set_xlabel("Time [ms]")
        for ax, tax in zip(axes, twin):
            [tick.set_verticalalignment("bottom") for tick in ax.get_yticklabels()]
            [tick.set_verticalalignment("top") for tick in tax.get_yticklabels()]

    return f

plot_gradient_spectra

plot_gradient_spectra(
    seq: Sequence,
    directions: List[ndarray] = None,
    start_time: Quantity = None,
    end_time: Quantity = None,
    ax: Axes = None,
) -> plt.Figure

Plots gradient sampling spectra for a given sequence along a list of directions. If no directions are given, plots along MPS.

Parameters:

Name Type Description Default
seq Sequence

Instance of cmrseq.Sequence to plot spectra

required
directions List[ndarray]

List[np.ndarray of shape (3, )] directions to plot spectra along, default will plot MPS

None
start_time Quantity

Quantity[Time] Start time of spectra calculation window

None
end_time Quantity

Quantity[Time] End time of spectra calculation window

None
ax Axes

plt.Axes axis to place plots into, if not given creates and returns new figure

None
Source code in cmrseq/plotting.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def plot_gradient_spectra(seq: Sequence, directions: List[np.ndarray] = None,
                          start_time: Quantity = None,
                          end_time: Quantity = None, ax: plt.Axes = None) -> plt.Figure:
    r"""Plots gradient sampling spectra for a given sequence along a list of directions.
    If no directions are given, plots along MPS.

    Parameters
    ----------
    seq
        Instance of cmrseq.Sequence to plot spectra
    directions
        List[np.ndarray of shape (3, )] directions to plot spectra along, default will plot MPS
    start_time
        Quantity[Time] Start time of spectra calculation window
    end_time
        Quantity[Time] End time of spectra calculation window
    ax
        plt.Axes axis to place plots into, if not given creates and returns new figure
    """
    if ax is None:
        f, ax = plt.subplots(1, 1, )
        f.set_size_inches(6, 3)
    else:
        f = ax.figure

    if directions is not None:
        spectra, freq = cmrseq.utils.calculate_gradient_spectra(seq, directions=directions,
                                                                start_time=start_time,
                                                                end_time=end_time)
        for s in spectra:
            ax.plot(freq.m_as('Hz'), s.m_as('mT^2/m^2*ms^4'))
    else:
        dirs = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1])]
        spectra, freq = cmrseq.utils.calculate_gradient_spectra(seq, directions=dirs,
                                                                start_time=start_time,
                                                                end_time=end_time)
        ax.plot(freq.m_as('Hz'), spectra[0].m_as('mT^2/m^2*ms^4'))
        ax.plot(freq.m_as('Hz'), spectra[1].m_as('mT^2/m^2*ms^4'))
        ax.plot(freq.m_as('Hz'), spectra[2].m_as('mT^2/m^2*ms^4'))
        ax.legend(['M', 'P', 'S'])

    ax.set_xlim([0, 3000])
    ax.set_xlabel('Frequency, Hz')
    ax.set_ylabel(r'$S(\omega,t)$, $(mT/m*ms^2)^2$')

    return f

anotate_timing

anotate_timing(
    start: Quantity,
    end: Quantity,
    ypos: float,
    text: str,
    axis: Axes,
    color: str = None,
    fontsize: float = 12,
    height: float = 2,
    rot: float = 0,
    vertical_alignment: str = None,
    linewidth: float = 2,
) -> None

Adds a line with two vertical ticks and a descriptive text into the given axes.

Parameters:

Name Type Description Default
start Quantity

Start of annotation interval

required
end Quantity

End of annotation interval

required
ypos float

position on y-axes in units of the axis

required
text str

string containing the label

required
axis Axes

axes object to insert the text into

required
color str

Color of text and glyph

None
fontsize float

Fontsize of annotation

12
height float

Height of the annotations vertical ticks in units of the axis

2
rot float

Angle in degrees, that the text is rotated

0
vertical_alignment str

defaults to top if ypos > 0 otherwise bottom

None
linewidth float

Linewidth of the annotion glyph

2
Source code in cmrseq/plotting.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
def anotate_timing(start: Quantity, end: Quantity, ypos: float, text: str, axis: plt.Axes,
                   color: str = None, fontsize: float = 12, height: float = 2,
                   rot: float = 0, vertical_alignment: str = None, linewidth: float = 2) -> None:
    r"""Adds a line with two vertical ticks and a descriptive text into the given axes.

    Parameters
    ----------
    start
        Start of annotation interval
    end
        End of annotation interval
    ypos
        position on y-axes in units of the axis
    text
        string containing the label
    axis
        axes object to insert the text into
    color
        Color of text and glyph
    fontsize
        Fontsize of annotation
    height
        Height of the annotations vertical ticks in units of the axis
    rot
        Angle in degrees, that the text is rotated
    vertical_alignment
        defaults to top if ypos > 0 otherwise bottom
    linewidth
        Linewidth of the annotion glyph
    """
    # Set vertical alignment of text (below for glyph for negativ positions and above for positive)
    va = vertical_alignment
    if va is None:
        if ypos > 0:
            va = "top"
        else:
            va = "bottom"

    start, end = start.m_as("ms"), end.m_as("ms")
    axis.vlines([start, end], ypos - height, ypos + height, color=color, linewidth=linewidth)
    axis.plot([start, end], [ypos, ypos], color=color, linewidth=linewidth)
    mid_pos = (end + start) / 2
    axis.text(mid_pos, ypos * 1.05, text, rotation=rot, fontsize=fontsize,
              horizontalalignment='center', verticalalignment=va, color=color)

center_axes

center_axes(
    axis: Axes,
    linewidth: float = 2,
    color=(0, 0, 0, 1),
    xy: str = "xy",
    ticksoff: str = "",
) -> None

Formats the given axes object, such that the spine of desired axes (xy) is rendered as arrow in the of the plot, rather than the outer box.

Parameters:

Name Type Description Default
axis Axes

Axes object to format

required
linewidth float

Linewidth of the axis spine

2
color

Color of the new axis spine

(0, 0, 0, 1)
xy str

String specifying which axes to modify (x, y, xy)

'xy'
ticksoff str

String specifying where to switch of ticks

''
Source code in cmrseq/plotting.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def center_axes(axis: plt.Axes, linewidth: float = 2, color=(0, 0, 0, 1), xy: str = "xy",
                ticksoff: str = "") -> None:
    r"""Formats the given axes object, such that the spine of desired axes (xy) is rendered as
    arrow in the of the plot, rather than the outer box.

    Parameters
    ----------
    axis
        Axes object to format
    linewidth
        Linewidth of the axis spine
    color
        Color of the new axis spine
    xy
        String specifying which axes to modify (x, y, xy)
    ticksoff
        String specifying where to switch of ticks
    """
    if 'x' in xy.lower():
        axis.spines['bottom'].set_position('zero')
        axis.spines['bottom'].set_linewidth(linewidth)
        axis.spines['bottom'].set_color(color)
        axis.spines['top'].set_visible(False)
        axis.plot((1), (0), ls="", marker=">", ms=6, color=color,
                  transform=axis.get_yaxis_transform(), clip_on=False)

    if 'y' in xy.lower():
        axis.spines['left'].set_position('zero')
        axis.spines['left'].set_linewidth(linewidth)
        axis.spines['left'].set_color(color)
        axis.spines['right'].set_visible(False)
        axis.plot((0), (1), ls="", marker="^", ms=6, color=color,
                  transform=axis.get_xaxis_transform(), clip_on=False)

    if 'x' in ticksoff.lower():
        axis.set_xticks([])
    if 'y' in ticksoff.lower():
        axis.set_yticks([])
    axis.xaxis.set_ticks_position('bottom')
    axis.yaxis.set_ticks_position('left')