-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfigure_plotting.py
1767 lines (1443 loc) · 65.4 KB
/
figure_plotting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
175
176
177
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
348
349
350
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
424
425
426
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
462
463
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
501
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
625
626
627
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
674
675
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
720
721
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from matplotlib.ticker import FuncFormatter
import matplotlib
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d.art3d import Line3DCollection
import matplotlib.cm as cm
import sigpy as sp
import csv
import sys
import cfl # For data i/o
from scipy import signal
import data_processing as proc
import run_bpt as run
def load_motion_signals(inpdir, fname, tr=4.4e-3):
''' Load motion signals for concept figure '''
data = np.real(cfl.readcfl(os.path.join(inpdir,fname)))
t = np.arange(data.shape[0])*tr
return data, t
def plot_motion_signals(inpdir="./concept", shift=-5):
''' Plot respiratory, cardiac, and head signals '''
trs = [4.4e-3, 8.7e-3, 4.4e-3]
plt.figure(figsize=(5,10))
for i, fname in enumerate(["bpt_resp", "bpt_cardiac", "bpt_head"]):
bpt, t = load_motion_signals(inpdir, fname, tr=trs[i])
plt.plot(t, proc.normalize(bpt) + i*shift, lw=3)
plt.axis("off")
def load_kspace(inpdir):
''' Load kspace from cfl file '''
ksp = cfl.readcfl(os.path.join(inpdir, "ksp"))
return ksp
def calculate_rss(ksp):
''' Calculate rss across coils '''
ksp_f = sp.ifft(ksp, axes=(0,))
ksp_f_rss = sp.rss(sp.ifft(ksp, axes=(0,)), axes=(-1,))
return ksp_f_rss
def prepare_data(ksp_f_rss):
''' Stack data into a 3D stack '''
# Collapse into a single time dimension
tmp = np.transpose(ksp_f_rss[10:240, ...], (1, -1, 0)) # Show only one tone
ksp_f_r = np.vstack(tmp) # [N*nph, N, ncoils] - first dim is time dim
# Number of kspace lines to plot
Nt, N = ksp_f_r.shape
Nlines = 50
inds = np.linspace(0, ksp_f_r.shape[0] - 1, Nlines).astype(int)
ksp_data = np.abs(ksp_f_r[inds, :].T)
# Add extra stuff to ksp
buffer = 26
ksp_stack = np.empty((ksp_data.shape[0] + buffer, ksp_data.shape[1]))
# Extra noise
ksp_stack[:buffer // 2, :] = ksp_data[-buffer // 2:, :]
ksp_stack[buffer // 2:buffer, :] = ksp_data[-buffer // 2:, :]
ksp_stack[buffer:, :] = ksp_data
N_f = N + buffer
freq_data = 250 / N_f * np.linspace(-N_f / 2, N_f / 2, N_f)[:, None] * np.ones(Nlines)[None, :] # 256 x Npts
# time
t = np.arange(Nlines)
return ksp_stack, freq_data, t
def plot_kspace(ksp_stack, freq_data, t):
''' Create plot as a PolyCollection '''
# Make vertices
verts = []
Nlines = t.shape[0]
for irad in range(Nlines):
# Add a zero amplitude at the beginning and the end to get a nice flat bottom on the polygons
xs = np.concatenate([[freq_data[0, irad]], freq_data[:, irad], [freq_data[-1, irad]]])
ys = np.concatenate([[0], ksp_stack[:, irad], [0]])
verts.append(list(zip(xs, ys)))
# Make PolyCollection
poly = PolyCollection(verts, facecolors='gray', edgecolors='k')
poly.set_alpha(0.9) # Transparency
# Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.add_collection3d(poly, zs=t, zdir='y')
# Set labels
ax.set_xlim3d(freq_data.min(), freq_data.max())
ax.set_ylim3d(t.min(), t.max())
ax.set_zlim3d(ksp_stack.min(), ksp_stack.max())
ax.set_xticks(np.linspace(-125, 125, 3).astype(int))
ax.tick_params(pad=-7, rotation=-10) # Make numbers closer to ticks
ax.set_zticks([]) # No amplitude numbers
ax.set_yticks([]) # No time axis
ax.view_init(elev=29, azim=-66)
def plot_ksp_f(inpdir):
''' Plot 3D ksp vs f figure '''
# Load kspace
ksp = load_kspace(inpdir)
# Calculate rss
ksp_f_rss = calculate_rss(ksp)
# Prepare data
ksp_stack, freq_data, t = prepare_data(ksp_f_rss)
# Plot kspace
plot_kspace(ksp_stack, freq_data, t)
def plot_cardiac_signals(inpdir):
''' Plot cardiac signals with overlaid purple points for two coils '''
# Define BPT and time data
bpt_cardiac = np.real(cfl.readcfl(os.path.join(inpdir, "bpt_cardiac")))
tr_card = 8.7e-3 # Seconds
t_card = np.arange(bpt_cardiac.shape[0]) * tr_card
# Colors and shift for plot
colors = ["tab:green", "tab:orange"]
shift = -8.5
# Define scattered points to overlay on the plot
points = (np.arange(0.1, 0.25, 0.05) / (tr_card/2)).astype(int)
# Plot cardiac signals with points
plt.figure(figsize=(10, 5.5))
for i in range(bpt_cardiac.shape[1]):
plt.plot(t_card, bpt_cardiac[:, i] + i * shift, color=colors[i])
plt.scatter(t_card[points], bpt_cardiac[points, i] + i * shift, c='darkmagenta', zorder=10, s=70)
plt.xlim([0, 8])
plt.yticks([])
plt.xlabel("Time (s)")
def get_H(inpdir, fname):
''' Load fields from text file '''
data = np.loadtxt(os.path.join(inpdir,fname), skiprows=2)
x,y,z,H = data.T
return H,x,y,z
def get_H_mult(inpdir, fld_list_sort):
''' Load multiplied fields '''
H_list = []
for i in range(len(fld_list_sort)):
H,x,y,z = get_H(inpdir, fld_list_sort[i])
H_list.append(H)
H_list = np.array(H_list)
# Multiply mags
H_mult = np.array([(H_list[i] * H_list[i+1]) for i in range(1,H_list.shape[0],2)])
H_mult = np.insert(H_mult, 0, H_list[0,...], axis=0)
return H_mult, x, y, z
def get_sorted_list(fld_list):
''' Sort list of fields by frequency, increasing order '''
freqs = np.array([float(fld_list[i].split("_")[1]) for i in range(len(fld_list))])
fld_inds = np.argsort(freqs)
# Sorted list of folders and freqs
fld_list_sort = fld_list[fld_inds]
freqs = freqs[fld_inds]
return fld_list_sort, freqs
def plot_rect(axs, width=14, height=10, overlap=[6,3], n_rect=3, lw=7):
''' Plot rectangular coils on axes '''
# Rectangular coil overlay
start_points = [[-3/2*width + overlap[0], -3/2*height + overlap[1]],
[-3/2*width + overlap[0], 1/2*height - overlap[1]],
[-width/2, -height/2]]
colors = ["tab:green", "tab:blue", "tab:orange"] # For correct overlapping
# Plot rectangles
for j in range(2): # Loop over subplots
# Vertical lines
axs[j].axvline(0, c='w', ls='--')
axs[j].axvline(10, c='w', ls='--')
for i in range(n_rect): # Loop over ciol
rgb_color = mcolors.to_rgba(colors[i])
rect = matplotlib.patches.Rectangle(start_points[i], width, height, color=colors[i])
# Set transparent face color with colored edges and linewidth
rect.set_facecolor(list(rgb_color[:-1]) + [0]) # Make transparent
rect.set_edgecolor(list(rgb_color[:-1]) + [1]) # Make opaque
rect.set_linewidth(lw)
# Add the patch to the axes
axs[j].add_patch(rect)
def plot_fields(H,x,y,z,plane="xy", cmap="jet", marker=".", fig=None, ax=None, figsize=(10,10), title="", xlim=[-0.3,0.3], ylim=[-0.3,0.3], clim=90):
''' 2D scatterplot of fields '''
# Plot
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
if plane == "xy":
x_axis = x
y_axis = y
elif plane == "yz":
x_axis = y
y_axis = z
else:
x_axis = x
y_axis = z
clim = [np.percentile(H,0), np.percentile(H,clim)]
sc = ax.scatter(x_axis*100, y_axis*100, c=H, cmap=cmap, marker=marker, vmin=clim[0], vmax=clim[1])
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.set_title(title)
def plot_field_w_coils(inpdir, figsize=(16.7,5), xlim=[-45,35], ylim=[-35,35], lw=7):
''' Plot fields at 127.8MHz and 2.4GHz with rectangular coils overlaid '''
fig, ax = plt.subplots(figsize=figsize, nrows=1, ncols=2)
axs = ax.flatten()
# Load fields
fld_list = np.array([f for f in os.listdir(inpdir) if f.endswith("_xy.fld")])
fld_list_sort, freqs = get_sorted_list(fld_list)
# Get multiplied H fields
H_mult, x, y, z = get_H_mult(inpdir, fld_list_sort)
H_set = H_mult[[0,-1],...]
# Plot subplot
for j in range(H_set.shape[0]):
plot_fields(H_set[j,...],x,y,z,
cmap="jet",
marker=".",
ax=axs[j],
fig=fig,
figsize=figsize,
title = "",
plane ="xy",
xlim=xlim,
ylim=ylim,
clim=95)
# Plot rectangle overlay
plot_rect(axs, width=14, height=10, overlap=[6,3], n_rect=3, lw=lw)
def load_csv(inpdir, fname):
''' Load csv as np array. Will return as strings if there are any strings '''
data = []
with open(os.path.join(inpdir,fname)) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
data.append(row)
data = np.array(data)
return data
def mirror_signal(signal):
''' Return a signal concatenated with its mirrored version '''
sig_flip = np.flip(signal)
sig_cat = np.concatenate((signal, sig_flip))
return sig_cat
def plot_flux_all(pos_all, flux_all, f_combined):
''' Plot flux over all frequencies and coils '''
# Plot simulated data
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(12,5))
axs = ax.flatten()
# Loop over freqs
data_mod = np.empty((flux_all.shape))
for i in range(len(axs)):
for c in range(flux_all.shape[0]):
# Get percent mod
plot_data = flux_all[c,i,...]
plot_data_mod = (plot_data/np.mean(plot_data) - 1)*100
data_mod[c,i,...] = plot_data_mod
# Plot
xpos = np.linspace(0,20,plot_data_mod.shape[0]*2)
axs[i].plot(xpos, mirror_signal(plot_data_mod))
# Reset labels
axs[i].set_yticks(np.linspace(np.amin(data_mod[:,i,:]), np.amax(data_mod[:,i,:]), 4).astype(int))
axs[i].set_xticks([0,10,20], labels=[0,10,0])
axs[i].set_title(str(f_combined[i]) + " MHz")
if i < 3:
axs[i].set_xticks([])
def plot_flux(flux_plot, pos, xlims, f_combined, mirror=True, fig=None, ax=None, figsize=(10,10), fname="sim"):
x_start, x_end = xlims
# Mag and phase
if fig is None:
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=figsize)
axs = ax.flatten()
# Loop over freqs
for i in range(len(axs)):
# Define range
n_start = np.where(np.logical_and((pos >= x_start), pos <= x_start + 1))[0][0]
n_end = np.where(np.logical_and((pos >= x_end), pos <= x_end + 1))[0][0]
# Get percent mod
plot_data = flux_plot[i,...]
plot_data_mod = (plot_data[n_start:n_end]/np.mean(plot_data[n_start:n_end]) - 1)*100
# Plot
if mirror is True:
xpos = np.linspace(0,20,plot_data_mod.shape[0]*2)
axs[i].plot(xpos, mirror_signal(plot_data_mod), label=fname)
else:
axs[i].plot(pos[n_start:n_end], plot_data_mod, label=fname)
# # Reset labels
axs[i].yaxis.set_major_locator(plt.MaxNLocator(5))
# axs[i].set_xticks([0,10,20], labels=[0,10,0])
axs[i].set_title(str(f_combined[i]) + " MHz")
if i < 3:
axs[i].set_xticks([])
def plot_sim(flux_mult_mag, freqs, xlims=[0,10], mirror=True, figsize=(12,5)):
# Get combined frequency
f_combined = proc.get_f_combined(freqs)
ncoils = 3
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=figsize)
for i in range(ncoils):
fname = "log_periodic_pa_{}.csv".format(i)
flux, freqs, pos = proc.get_phantom_flux(inpdir, fname, Npoints=81*4)
flux_mult_mag, flux_mult_ph = proc.get_phantom_flux_mult(flux, freqs)
# Plot only magnitude
plot_flux(flux_mult_mag, pos, xlims, f_combined, mirror=mirror, fig=fig, ax=ax, figsize=(20,10))
# Adjust spacing
plt.subplots_adjust(bottom=0.15, wspace=0.3, hspace=0.2)
def plot_overlaid_data(data_all, f_combined, error_samp=400):
''' Plot data overlaid from multiple periods '''
# Plot experimental data
xpos = np.linspace(0, 10, data_all.shape[-2])
mask = np.arange(len(xpos)) % error_samp == 0
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(12,5))
axs = ax.flatten()
for i in range(data_all.shape[1]):
for c in range(data_all.shape[-1]):
err = np.var(data_all[:,i,:,c], axis=0)
mean = np.mean(data_all[:,i,:,c], axis=0)
# Plot mean
axs[i].plot(xpos,mean)
axs[i].errorbar(x=xpos[mask], y=mean[mask], yerr=err[mask], fmt='', linestyle='', capsize=1, c='k',lw=1)
# Plot stdev as a transparent spread
# axs[i].fill_between(xpos, mean - err, mean + err, alpha=0.8)
# Set formatting
axs[i].set_title(str(f_combined[i]) + " MHz")
axs[i].set_yticks(np.linspace(np.amin(data_all[:,i,:,:]), np.amax(data_all[:,i,:,:]), 4).astype(int))
# Reset label
axs[i].set_xticks([0,5,10], labels=[0,10,0])
if i < 3:
axs[i].set_xticks([])
# Adjust spacing
# plt.subplots_adjust(bottom=0.15, wspace=0.3, hspace=0.2)
def plot_vibration(pt_mag_mat, t_starts, f_combined, period=12, tr=4.3e-3,
shifts=[-30, -50, -500, -100, -100, -100],
c_inds=np.arange(16,20),
figsize=(10,10), lw=2,
cutoffs=[1,1,1,5,5,5]):
# Plot
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=figsize)
axs = ax.flatten()
# Plot all signals
for i in np.arange(pt_mag_mat.shape[0]):
t_start = t_starts[i]
pt_mag = pt_mag_mat[i,...]
t = np.arange(pt_mag.shape[0])*tr - t_start
# Loop over coils
for idx, c in enumerate(c_inds):
pt = proc.filter_sig(pt_mag[...,c], cutoff=cutoffs[i], # Cutoff and fs in Hz
fs=1/(tr), order=6, btype='low')
shift = shifts[i]
line = axs[i].plot(t, (pt - np.mean(pt)) + shift*idx, label = "Coil {}".format(c-16), lw=lw)
axs[i].set_xlim([0, period])
axs[i].set_yticks([])
axs[i].set_title(str(f_combined[i]) + "MHz")
if i > 2:
axs[i].set_xlabel("Time (s)")
plt.show()
# Make legend
lines = []
labels = []
for ax in fig.axes:
Line, Label = ax.get_legend_handles_labels()
lines.extend(Line)
labels.extend(Label)
legendfig = plt.figure()
legendfig.legend(lines[:len(c_inds)], labels[:len(c_inds)], loc='center')
def plot_accel_comparison(pt_mag, accel_d, coil_inds=np.arange(16,20), start_times=[3, 5.3], time_len=8, tr=8.7e-3):
# Titles of each subplot
f_combined = proc.get_f_combined()
titles = f_combined[-2:]
# Plot
fig, ax = plt.subplots(figsize=(10,5), nrows=1, ncols=pt_mag.shape[0])
axs = ax.flatten()
for i in range(accel_d.shape[0]):
accel_d_tmp = accel_d[i,...]
bpt_tmp = pt_mag[i,...]
shift = -5
ncoils = bpt_tmp.shape[-1]
t = np.arange(bpt_tmp.shape[0])*tr - start_times[i]
for c in range(len(coil_inds)):
axs[i].plot(t, proc.normalize_c(bpt_tmp, var=True)[:,coil_inds[c]] + c*shift, label="Coil {}".format(c), lw=2);
axs[i].set_title(str(titles[i]) + " MHz")
axs[i].set_xlim([0,time_len])
axs[i].set_xlabel("Time (s)")
# z accel only
axs[i].plot(t, proc.normalize(accel_d_tmp[:,-1]) + (len(coil_inds))*shift, label= r'$\Delta$d', lw=2)
axs[i].set_yticks([])
plt.subplots_adjust(bottom=0.15, wspace=0.1, hspace=0.4)
# Make legend
lines = []
labels = []
for ax in fig.axes:
Line, Label = ax.get_legend_handles_labels()
print(Line)
lines.extend(Line)
labels.extend(Label)
legendfig = plt.figure()
legendfig.legend(lines[:len(coil_inds)+1], labels[:len(coil_inds)+1], loc='center')
plt.show()
def plot_pca_3d(pt_pca, ax=None, fig=None, elev=55, azim=-72, figsize=(10,5), title="", show_idx=False, label_interval=5, s=10, colorbar=True, label=True, rotations=[80,10,90], integer=True):
if ax is None:
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=figsize, subplot_kw={'projection': '3d'})
colors = cm.coolwarm(np.linspace(0, 1, pt_pca.shape[0]))
# Define data points
x, y, z = pt_pca.T
# Have to do this so that the xlims are correct
ax.scatter(x, y, z, c=colors, s=s, edgecolor='black', alpha=0)
# Add lines between points
# Define colormap
cmap = plt.get_cmap('coolwarm')
# Define segments for lines
segments = [(np.array([x[i], y[i], z[i]]), np.array([x[(i+1)%len(x)], y[(i+1)%len(y)], z[(i+1)%len(z)]])) for i in range(len(x))]
# Create Line3DCollection
lc = Line3DCollection(segments, cmap=cmap, alpha=0.4)
# Set array to color lines based on colormap
lc.set_array(np.arange(len(x)))
# Add Line3DCollection to the plot
ax.add_collection(lc)
# Actual scatterplot
ax.scatter(x, y, z, c=colors, s=s, alpha=1)
# Angles, labels, and params
ax.view_init(elev=elev, azim=azim)
if label is True:
lpad = 5 # Spacing for labels
ax.set_xlabel("PC 1", labelpad=lpad, rotation=rotations[0])
ax.set_ylabel("PC 2", labelpad=lpad, rotation=rotations[1])
ax.set_zlabel("PC 3", labelpad=lpad, rotation=rotations[2])
ax.set_title(title)
for axis in [ax.xaxis, ax.yaxis, ax.zaxis]:
if integer is True:
axis.set_major_locator(plt.MaxNLocator(nbins=3, integer=True))
axis.set_major_formatter(FuncFormatter(lambda x, _: '{:.0f}'.format(x)))
else:
axis.set_major_locator(plt.MaxNLocator(nbins=3))
axis.set_major_formatter(FuncFormatter(lambda x, _: '{:.1f}'.format(x)))
for axis in ['x', 'y', 'z']:
ax.tick_params(axis=str(axis), which='both', pad=0)
# Make background transparent?
# fig.patch.set_alpha(0.5) # Set alpha value for the background grid
# ax.patch.set_alpha(0.5) # Set alpha value for the background grid
# ax.set_facecolor('lightgrey')
# Change the color of the axes lines
ax.xaxis._axinfo['grid'].update(color='lightgray') # x-axis
ax.yaxis._axinfo['grid'].update(color='lightgray') # y-axis
ax.zaxis._axinfo['grid'].update(color='lightgray') # z-axis
# Get rid of colored axes planes
# First remove fill
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
# Now set color to white (or whatever is "invisible")
ax.xaxis.pane.set_edgecolor('w')
ax.yaxis.pane.set_edgecolor('w')
ax.zaxis.pane.set_edgecolor('w')
# Label all data points
if show_idx is True:
for label_idx in range(0, pt_pca.shape[0], label_interval):
label_text = '{}'.format(label_idx)
ax.text(x[label_idx], y[label_idx], z[label_idx], s=label_text, color='black')
# Set colorbar
if colorbar is True:
cbar = fig.colorbar(cm.ScalarMappable(cmap='RdBu'), ax=ax, ticks=[], location="right", pad=0.2, shrink=0.5)
def plot_pca_combined(pt_pcas, tr=4.4e-3, figsize=(10,10), colorbar=False):
''' Plot 3D PCA traces '''
titles = ["PT", "BPT"]
delta_tick = [100,100]
title_colors = ["tab:green", "tab:purple"]
fig = plt.figure(figsize=figsize)
axs = []
for i in range(2):
# Same colormap
pt_pca = pt_pcas[i]
colors = cm.RdBu(np.linspace(0, 1, pt_pca.shape[0]))
ax = fig.add_subplot(1,2, i+1, projection='3d')
# Change aspect ratio
ax.grid(True)
ax.set_box_aspect([3,4,2]) # [x-axis, y-axis, z-axis]
scatter = ax.scatter(pt_pca[...,0], pt_pca[...,1], pt_pca[...,2], c=colors)
ax.view_init(elev=37, azim=-27)
lpad = -10 # Spacing for labels
# Labels
rot = 45
ax.set_xlabel("PC 1", labelpad=lpad, rotation=-65)
ax.set_ylabel("PC 2", labelpad=lpad, rotation=23)
ax.set_zlabel("PC 3", labelpad=lpad, rotation=90)
# Remove axis ticks - note that if using xticks instead of xticklabels, the grid disappears!
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
axs.append(ax)
if i == 1 and colorbar is True:
cbar = fig.colorbar(cm.ScalarMappable(cmap='RdBu'), ax=ax, ticks=[], location="right", pad=0.2)
cbar.outline.set_edgecolor('None')
return fig, axs
def plot_mod(fb_2400, cutoff, num_max, color_dict, figsize=(20,10), t_lims=[0,78], titles=[], title_colors=[], coil_mat=None, sharey=False, shift=-10, c_inds=None):
''' Plot filtered percent modulation given pt object '''
# Subplot order:
# Row 0
# 0 - BPT mag
# 1 - BPT phase
# Row 1
# 2 - PT mag
# 3- PT phase
npts, N, ncoils = fb_2400.pt_mag_mod.shape
fig, ax = plt.subplots(nrows=4, ncols=1, figsize=figsize, sharey=sharey)
axs = ax.flatten()
tr = fb_2400.tr
t = proc.get_t_axis(N, tr)
t_start, t_end = t_lims
line_list = []
pt_ranges = []
# Plot loop
for i, subplot in enumerate(axs):
pt = fb_2400.pt
# if i <= 1:
if i%2 == 0:
# First row is BPT
pt_plot = pt[0,...]
else:
# Second row is PT
pt_plot = pt[1,...]
if i == 3:
subplot.set_xlabel("Time (s)")
# Even indices are magnitude
if i < 2:
# if i%2 == 0:
pt_plot = np.abs(pt_plot)
else:
# Phase
pt_plot, _ = proc.get_phase_pinv(pt_plot, k=4, pca=False, c_inds=c_inds)
# Filter
pt_plot = proc.filter_c(pt_plot, tr=tr, cutoff=cutoff)
# Set plot limits
n_start, n_end = [int(t_start/tr), int(t_end/tr)]
# Compute percent mod
pt_mod = (pt_plot[n_start:n_end,...] / np.mean(pt_plot[n_start:n_end,...], axis=0) - 1)*100
# Calculate range via percentiles
# pt_range = np.percentile(pt_mod, 99.9, axis=0) - np.percentile(pt_mod, 0, axis=0)
# pt_range = np.amax(pt_mod, axis=0) - np.amin(pt_mod, axis=0)
# pt_ranges.append(pt_range)
# Choose indices based on modulation if not specified
if coil_mat is None:
coil_inds = np.flip(np.argsort(np.var(np.abs(pt_mod), axis=0)))
else:
coil_inds = coil_mat[i]
# Remove bad means
means = np.mean(pt_plot[n_start:n_end,...], axis=0)
thres = 0.1
bad_means = np.where(np.abs(means) < thres)[0]
coil_inds_filt = coil_inds.copy()
for mean in bad_means:
coil_inds_filt = np.delete(coil_inds_filt, np.where(coil_inds_filt == mean)[0])
# Plot loop
for c in range(num_max):
coil_ind = coil_inds_filt[c]
line, = subplot.plot(t[n_start:n_end], pt_mod[:, coil_ind] + shift*c,
label = "Coil " + str(coil_ind), color=color_dict[coil_ind])
line_list.append(line)
# Set range
min_val = np.amin(pt_mod[:, coil_inds_filt[:num_max]])
max_val = np.amax(pt_mod[:, coil_inds_filt[:num_max]])
pt_range = max_val - min_val
pt_ranges.append(pt_range)
# subplot.set_yticks(np.linspace(min_val, max_val, 3))
subplot.set_yticks(np.linspace(min_val, max_val, 3, dtype=int))
# Set labels
title = subplot.set_title(titles[i], c='k')
title.set_position([0.5, 0.0])
# FOR DEBUGGING - set legend
# subplot.legend()
return axs, line_list, np.array(pt_ranges)
def plot_resp(fb_2400, cutoff=2, t_lims=[0,78], figsize=(10,10), num_max=2):
# Plot filtered modulation for breathing portion
bad_inds = np.array([10])
c_inds = np.delete(np.arange(16),bad_inds)
color_dict = make_color_dict(N=16)
titles = ["BPT Magnitude", "PT Magnitude", "BPT Phase", "PT Phase"]
title_colors = ["tab:purple", "tab:purple", "tab:green", "tab:green"]
coil_mat = None
axs_resp, line_list, pt_range = plot_mod(fb_2400, cutoff, num_max, color_dict,
coil_mat=coil_mat,
figsize=figsize,
t_lims=t_lims, titles=titles,
title_colors=title_colors,
sharey=False, shift=0,
c_inds=c_inds)
# Adjust spacing
plt.subplots_adjust(bottom=0.15, top=0.9, wspace=0.3, hspace=0.6)
return axs_resp, pt_range
def get_labels(axs):
''' Return list of labels from axis '''
all_labels = []
all_handles = []
for i in range(len(axs)):
handles, labels = axs[i].get_legend_handles_labels()
all_labels = all_labels + labels
all_handles = all_handles + handles
return all_labels, all_handles
def sort_labels(labels):
''' Sort labels by number at end '''
coil_no = np.array([labels[i].split(" ")[-1] for i in range(len(labels))]).astype(int)
coil_no_sorted, inds = np.unique(coil_no, return_index=True)
return coil_no_sorted, inds
def make_color_dict(N=16, color_inds=None):
# Make a color dictionary
colors = np.array(list(mcolors.TABLEAU_COLORS.keys()))
css4_colors = ['hotpink', 'navy', 'lime', 'black', 'darkgoldenrod','lightgray']
colors = list(colors) + list(css4_colors)
# Predefine dictionary of size N
if color_inds is None:
color_inds = np.arange(N)
color_dict = dict(zip(color_inds,np.array(colors)))
return color_dict
def plot_bpt_pt_overlay(img_crop_rss, fb_2400, pad=True, use_dict=True, start=[80,40], p_size=[10,1], scales=[-0.02,0.02], shifts=[7.8,4], c=[9,3], figsize=(10,7), t_end=30, show_text=True):
''' Plot BPT and PT overlaid on patch of image '''
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=figsize)
# Color dictionary
if use_dict is True:
color_dict = make_color_dict(N=16)
colors = [color_dict[c[0]], color_dict[c[1]]]
else:
colors = ["tab:blue", "tab:orange"]
# Stack parts of image
im_seg = img_crop_rss[start[0]:start[0]+p_size[0], start[1]:start[1]+p_size[1],:]
imstack = np.vstack(im_seg.T).T # This gives the correct shape
imstack_all = np.vstack((imstack, imstack)) # 2 imstacks for BPT and PT
im = ax.imshow(imstack_all,"gray", interpolation='lanczos')
# Plot overlay
if pad is True:
bpt_interp = proc.pad_bpt(fb_2400.pt_mag_filtered[0,...], npe=256, nph=100, dda=4)
pt_interp = proc.pad_bpt(fb_2400.pt_mag_filtered[1,...], npe=256, nph=100, dda=4)
else:
bpt_interp = proc.normalize_c(fb_2400.pt_mag_filtered[1,...])
pt_interp = proc.normalize_c(fb_2400.pt_mag_filtered[0,...])
# BPT
x_axis = np.linspace(-0.5,imstack.shape[-1]-0.5,bpt_interp.shape[0], endpoint=True)
ax.plot(x_axis, scales[0]*bpt_interp[...,c[0]] + shifts[0], lw=4, c=colors[0], alpha=0.8)
# PT
ax.plot(x_axis, scales[1]*pt_interp[...,c[1]] + shifts[1], lw=4, c=colors[1], alpha=0.8)
if show_text is True:
# Text
ax.text(0.5,0.9, 'BPT', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, c=colors[0], fontsize=24)
ax.text(0.5,0.4, 'PT', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, c=colors[1], fontsize=24)
ax.set_xlim([0,t_end*p_size[1]])
ax.axis("off")
def plot_img_patch(inpdir, img_plot=None, crop_win=40, start=[80,40], p_size=[10,1], c="orange", ylim=None, cmax=1500):
''' Plot image with overlaid patch '''
if img_plot is None:
ksp = np.squeeze(cfl.readcfl(os.path.join(inpdir,"ksp")))
# Get image and crop
img = sp.ifft(ksp, axes=(0,1))
img_crop = img[crop_win:-crop_win,...]
img_crop_rss = np.rot90(sp.rss(img_crop, axes=(-1,)),3) # Rotate so chest is facing up
img_plot = img_crop_rss[...,0]
else:
img_crop_rss = None
# Show image with rectangle overlay
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10,5))
im = ax.imshow(img_plot,"gray")
rect = matplotlib.patches.Rectangle([start[1], start[0]],
p_size[1],p_size[0],
linewidth=1, edgecolor=c,
facecolor=c, alpha=0.8)
ax.add_patch(rect)
if ylim is not None:
ax.set_ylim([200,60])
ax.axis("off")
im.set_clim(0,cmax)
return img_crop_rss
def plot_cardiac_bpt_pt(inpdir, outdir_list = np.array([127, 300, 800, 1200, 1800, 2400]).astype(str),
trs = np.array([4.312, 4.342, 4.321, 4.32, 4.326, 4.33])*1e-3,
titles = ["127.8MHz", "300MHz", "800MHz", "1.2GHz","1.8GHz","2.4GHz"],
t_start=0, t_end=2, shift=-5):
''' Plot cardiac BPT and PT '''
freqs = outdir_list
# Actual plot
fig, ax = plt.subplots(figsize=(10,3), nrows=1, ncols=5)
for i in range(len(outdir_list)):
tr = trs[i]
pt_mag_full = np.abs(np.squeeze(cfl.readcfl(os.path.join(inpdir, outdir_list[i],"pt_ravel"))))
# Plot BPT and PT
pt_mag, bpt_mag = pt_mag_full
# Sort indices by max energy in cardiac frequency band
pt_idxs = proc.get_max_energy(pt_mag, tr, f_range=[0.9,3])
bpt_idxs = proc.get_max_energy(bpt_mag, tr, f_range=[0.9,3])
# Filter
pt_filt = proc.filter_c(pt_mag, cutoff=2, tr=tr)
bpt_filt = proc.filter_c(bpt_mag, cutoff=25, tr=tr)
# Compare to physio data
bpt_len = bpt_filt.shape[0]*tr
ppg = proc.get_physio_waveforms(os.path.join(inpdir, outdir_list[i]), bpt_len,
load_ppg=True, load_ecg=False,
from_front=True)[0]
t_ppg = np.arange(ppg.shape[0])*10e-3
# Plot BPT, PT and PPG
C = 4 # Number of bpt coils to plot
t = np.arange(pt_mag.shape[0])*tr
ax[i].plot(t, proc.normalize_c(bpt_filt[:,bpt_idxs[:C]]) + np.arange(C)*shift)
ax[i].plot(t, -1*proc.normalize(pt_filt[:,21]) + shift*(C)) # Invert PT
ax[i].plot(t_ppg, proc.normalize(ppg) + shift*(C+1))
# Labels
ax[i].set_xlim([t_start,t_end])
ax[0].set_ylabel("Amplitude (a.u.)", labelpad=20)
ax[i].yaxis.set_major_locator(plt.MaxNLocator(4))
def plot_raw_cardiac_v2(inpdir, outdir_list = np.array([127, 300, 800, 1200, 1800, 2400]).astype(str),
trs = np.array([4.312, 4.342, 4.321, 4.32, 4.326, 4.33])*1e-3,
titles = ["127.8MHz", "300MHz", "800MHz", "1.2GHz","1.8GHz","2.4GHz"],
t_start=0, t_end=2, shift=-8, num_max=2):
''' Plot coils with most energy for each frequency '''
freqs = outdir_list
shifts = [-5, -5, -5, -9, -9, -9]
ylims = [[-7,7], [-7,7], [-5,5], [-12,7], [-15,7], [-15,7]]
fig, ax = plt.subplots(figsize=(10,3), nrows=1, ncols=6)
for i in range(len(outdir_list)):
tr = trs[i]
pt_mag_full = np.abs(np.squeeze(cfl.readcfl(os.path.join(inpdir, outdir_list[i],"pt_ravel"))))
# Select PT instead of BPT and filter
if i == 0:
pt_mag = proc.filter_c(pt_mag_full[0,...], cutoff=25, tr=tr)
else:
pt_mag = proc.filter_c(pt_mag_full[1,...], cutoff=25, tr=tr)
# Sort indices by max energy in cardiac frequency band
idxs = proc.get_max_energy(pt_mag, tr, f_range=[0.9,3])
# Plot loop
t = np.arange(pt_mag.shape[0])*tr
for k in range(num_max):
ax[i].plot(t, proc.normalize(pt_mag[:,idxs[k]]) + shifts[i]*k, lw=1)
ax[i].set_xlim([t_start,t_end])
ax[0].set_ylabel("Amplitude (a.u.)")
ax[i].yaxis.set_major_locator(plt.MaxNLocator(4))
def plot_bpt_physio(bpt, accel, ppg, ecg, tr=8.7e-3, tr_ecg=1e-3, tr_ppg=10e-3,
c=[16], norm_var=True,
shift=-5, t_end=10, title='', figsize=(10,10),
colors=None, labels=None,
xlim = np.array([0,7]),
v_shift=0.15, start_loc=0.96):
''' Compare BPT to accel and physio signals'''
# Time axes
t = np.arange(bpt.shape[0])*tr
t_ecg = proc.get_t_axis(ecg.shape[0], delta_t=tr_ecg)
t_ppg = proc.get_t_axis(ppg.shape[0], delta_t=tr_ppg)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
# Calculate time indices
xlim_n = (xlim*1/tr).astype(int)
# Plot BPT
for i in range(bpt.shape[1]):
line, = ax.plot(t[xlim_n[0]:xlim_n[1]], bpt[xlim_n[0]:xlim_n[1],i] + shift*i, color=colors[i])
# Accelerometer
accel_l, = ax.plot(t[xlim_n[0]:xlim_n[1]], proc.normalize(accel[xlim_n[0]:xlim_n[1]], var=norm_var) + shift*(i+1),color=colors[i+1])
# PPG
xlim_n = (xlim*1/tr_ppg).astype(int)
ppg_l, = ax.plot(t_ppg[xlim_n[0]:xlim_n[1]], proc.normalize(ppg[xlim_n[0]:xlim_n[1]], var=norm_var) + shift*(i+2),color=colors[i+2])
# ECG
xlim_n = (xlim*1/tr_ecg).astype(int)
ecg_l, = ax.plot(t_ecg[xlim_n[0]:xlim_n[1]], proc.normalize(ecg[xlim_n[0]:xlim_n[1]], var=norm_var) + shift*(i+3), color=colors[i+3])
ax.set_xlabel("Time (s)")
ax.set_yticks([])
ax.set_title(title)
# Set text
label_locs_v = np.array([start_loc - v_shift*i for i in range(len(colors))])
for i in range(len(colors)):
# Label the PT/BPT and coil
ax.text(-0.05, label_locs_v[i], labels[i], ha='center',va='center',
transform=ax.transAxes, c=colors[i], fontsize=20, rotation=0)
return fig, ax
def plot_8c(inpdir, tr=8.7e-3, cutoff=4, c=[30,24], figsize=(10,10), shift=-6):
# Load bpt
bpt = np.squeeze(cfl.readcfl(os.path.join(inpdir,"pt_ravel")))
# Get ECG and PPG
[ecg, ppg] = proc.get_physio_waveforms(inpdir, bpt_len=bpt.shape[1]*tr,
tr_ppg=10e-3, tr_ecg=1e-3,
from_front=True)
# Get accel data
accel, t_accel = proc.get_accel_data(inpdir)
# Integrate accel -> displacement
accel_d = proc.get_accel_d(accel, tr=tr, cutoff=cutoff)
# Filter PT
pt_filt = proc.filter_c(np.abs(bpt[0,...]), tr=tr, cutoff=3)
# Plot BPT
# bpt_stack = proc.normalize(np.abs(bpt[1,:,c[1]]), var=True)
# bpt_stack = bpt_stack[:,None]
# Plot BPT
bpt_stack = np.vstack((proc.normalize(pt_filt[...,c[0]], var=True),
proc.normalize(np.abs(bpt[1,:,c[1]]), var=True))).T
labels = ["PT coil {}".format(c[0] - 16),
"BPT coil {}".format(c[1] - 16),
"dBCG", "PPG", "ECG"]
# colors = ["tab:red","tab:gray", "tab:green", "tab:blue"]
colors = ["tab:brown", "tab:red","tab:orange", "tab:green", "tab:blue"]
fig, ax = plot_bpt_physio(bpt_stack, accel_d[:,1],
ppg, -1*ecg, tr=tr, c=c, norm_var=True,
shift=shift, t_end=7, figsize=figsize,
labels=labels, colors=colors, v_shift=0.2,
title="")
def plot_accel_bpt(bpt, accel_d, xlim=[0,5], tr=8.7e-3, cutoff=15, v_shift=0.15, start_loc=0.96, figsize=(10,5), label=True):
''' Plot displacement from accel vs BPT-dBCG '''
bpt_inp = proc.normalize_c(np.abs(bpt[1,...]))
accel_inp = proc.normalize_c(accel_d)
bpt_d = proc.get_bpt_d(accel_inp, bpt_inp)
bpt_filt = proc.filter_c(bpt_d, cutoff=cutoff, tr=tr)
# Labels and colors
labels = ["BPT-dBCG", "dBCG"]
colors = ["purple", "tab:orange"]
# Plot
t = proc.get_t_axis(bpt.shape[1], delta_t=tr)
fig, ax = plt.subplots(figsize=figsize)
shift = -5
for i, sig in enumerate([bpt_filt, accel_d]):
ax.plot(t, proc.normalize(sig[:,1]) + shift*i, label=labels[i], color=colors[i])
ax.set_xlim(xlim)
if label is True:
# Set text
label_locs_v = np.array([start_loc - v_shift*i for i in range(len(colors))])
for i in range(len(colors)):
# Label the PT/BPT and coil
ax.text(-0.05, label_locs_v[i], labels[i], ha='center',va='center',
transform=ax.transAxes, c=colors[i], fontsize=20, rotation=0)
ax.set_xlabel("Time (s)")
ax.set_yticks([])
def plot_head_pca_combined(pt_pcas, tr=4.4e-3, figsizes=None):
''' Plot 3D head motion PCA traces '''
titles = ["PT", "BPT"]
delta_tick = [40, 120]
ylim = [-200, 200] # Time-domain plot y-limits
# First plot
fig, ax1 = plt.subplots(nrows=1, ncols=2, figsize=figsizes[0])
for i in range(len(pt_pcas)):
pt_pca = pt_pcas[i]
# Set colormap
if i == 0: #
colors = cm.RdBu(np.linspace(0, 1, pt_pca.shape[0]))
else:
colors = cm.PRGn(np.linspace(0, 1, pt_pca.shape[0]))
t = np.arange(pt_pca.shape[0]) * tr
for j in range(pt_pca.shape[-1]):
ax1[i].scatter(t, pt_pca[..., j], c=colors, marker=".")
ax1[i].set_xlabel("Time (s)")
ax1[i].set_ylabel("Amplitude (a.u.)")
ax1[i].set_title(titles[i], pad=10)
ax1[i].set_ylim(ylim)
ax1[i].yaxis.set_major_locator(plt.MaxNLocator(4))