forked from mikgroup/sigpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot.py
1174 lines (959 loc) · 37.2 KB
/
plot.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
# -*- coding: utf-8 -*-
"""This module contains plotting functions based on matplotlib
for image, line, and scatter plots.
A feature of these plotting functions is that
they can be controlled using only hotkeys
so the user does not need to move away from the keyboard.
Given an array ``x``, an example usage is:
>>> ImagePlot(x)
>>> LinePlot(x)
>>> ScatterPlot(x)
"""
import os
import uuid
import subprocess
import datetime
import numpy as np
import sigpy as sp
__all__ = ['ImagePlot', 'LinePlot', 'ScatterPlot']
image_plot_help_str = r"""
$\bf{Hotkeys:}$
$\bf{h:}$ show/hide hotkey menu.
$\bf{x/y/z:}$ set current axis as x/y/z.
$\bf{t:}$ swap between x and y.
$\bf{c:}$ select current axis as color.
$\bf{left/right:}$ change current axis.
$\bf{up/down:}$ change slice along current axis.
$\bf{a:}$ toggle hide all labels, titles and axes.
$\bf{m/p/r/i/l:}$ magnitude/phase/real/imaginary/log mode.
$\bf{[/]:}$ change brightness.
$\bf{\{/\}:}$ change contrast.
$\bf{s:}$ save as png.
$\bf{g/v:}$ save as gif/video by along current axis.
$\bf{q:}$ refresh.
$\bf{0-9:}$ enter slice number.
$\bf{enter:}$ set current axis as slice number.
"""
class ImagePlot(object):
"""Plot array as image.
Press 'h' for a menu for hotkeys.
Args:
im (array): image numpy/cupy array.
x (int): x axis.
y (int): y axis.
z (None or int): z axis.
c (None or int): color axis.
hide_axes (bool): toggle hiding axes, labels and title.
mode (str): specify magnitude, phase, real, imaginary,
and log mode. {'m', 'p', 'r', 'i', 'l'}.
title (str): title.
interpolation (str): plot interpolation.
save_basename (str): saved png, gif, and video base name.
fps (int): frame per seconds for gif and video.
"""
def __init__(
self,
im,
x=-1,
y=-2,
z=None,
c=None,
hide_axes=False,
mode=None,
colormap=None,
vmin=None,
vmax=None,
title='',
interpolation='nearest',
save_basename='Figure',
fps=10):
if im.ndim < 2:
raise TypeError(
'Image dimension must at least be two, got {im_ndim}'.format(
im_ndim=im.ndim))
import matplotlib.pyplot as plt
self.axim = None
self.im = im
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.shape = self.im.shape
self.ndim = self.im.ndim
self.slices = [s // 2 for s in self.shape]
self.flips = [1] * self.ndim
self.x = x % self.ndim
self.y = y % self.ndim
self.z = z % self.ndim if z is not None else None
self.c = c % self.ndim if c is not None else None
self.d = max(self.ndim - 3, 0)
self.hide_axes = hide_axes
self.show_help = False
self.title = title
self.interpolation = interpolation
self.mode = mode
self.colormap = colormap
self.entering_slice = False
self.vmin = vmin
self.vmax = vmax
self.save_basename = save_basename
self.fps = fps
self.help_text = None
self.fig.canvas.mpl_disconnect(
self.fig.canvas.manager.key_press_handler_id)
self.fig.canvas.mpl_connect('key_press_event', self.key_press)
self.update_axes()
self.update_image()
self.fig.canvas.draw()
plt.show()
def key_press(self, event):
if event.key == 'up':
if self.d not in [self.x, self.y, self.z, self.c]:
self.slices[self.d] = (
self.slices[self.d] + 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 'down':
if self.d not in [self.x, self.y, self.z, self.c]:
self.slices[self.d] = (
self.slices[self.d] - 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 'left':
self.d = (self.d - 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'right':
self.d = (self.d + 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'x' and self.d not in [self.x, self.z, self.c]:
if self.d == self.y:
self.x, self.y = self.y, self.x
else:
self.x = self.d
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 'y' and self.d not in [self.y, self.z, self.c]:
if self.d == self.x:
self.x, self.y = self.y, self.x
else:
self.y = self.d
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 'z' and self.d not in [self.x, self.y, self.c]:
if self.d == self.z:
self.z = None
else:
self.z = self.d
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif (event.key == 'c' and
self.d not in [self.x, self.y, self.z] and
self.shape[self.d] == 3):
if self.d == self.c:
self.c = None
else:
self.c = self.d
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 't':
self.x, self.y = self.y, self.x
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 'a':
self.hide_axes = not self.hide_axes
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'f':
self.fig.canvas.manager.full_screen_toggle()
elif event.key == 'q':
self.vmin = None
self.vmax = None
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == ']':
width = self.vmax - self.vmin
self.vmin -= width * 0.1
self.vmax -= width * 0.1
self.update_image()
self.fig.canvas.draw()
elif event.key == '[':
width = self.vmax - self.vmin
self.vmin += width * 0.1
self.vmax += width * 0.1
self.update_image()
self.fig.canvas.draw()
elif event.key == '}':
width = self.vmax - self.vmin
center = (self.vmax + self.vmin) / 2
self.vmin = center - width * 1.1 / 2
self.vmax = center + width * 1.1 / 2
self.update_image()
self.fig.canvas.draw()
elif event.key == '{':
width = self.vmax - self.vmin
center = (self.vmax + self.vmin) / 2
self.vmin = center - width * 0.9 / 2
self.vmax = center + width * 0.9 / 2
self.update_image()
self.fig.canvas.draw()
elif event.key in ['m', 'p', 'r', 'i', 'l']:
self.vmin = None
self.vmax = None
self.mode = event.key
self.update_axes()
self.update_image()
self.fig.canvas.draw()
elif event.key == 's':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.png')
self.fig.savefig(filename, transparent=True, format='png',
bbox_inches='tight', pad_inches=0)
elif event.key == 'g':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.gif')
temp_basename = uuid.uuid4()
bbox = self.fig.get_tightbbox(self.fig.canvas.get_renderer())
for i in range(self.shape[self.d]):
self.slices[self.d] = i
self.update_axes()
self.update_image()
self.fig.canvas.draw()
self.fig.savefig('{} {:05d}.png'.format(temp_basename, i),
format='png', bbox_inches=bbox, pad_inches=0)
subprocess.run(['ffmpeg',
'-f',
'image2',
'-s',
'{}x{}'.format(int(bbox.width * self.fig.dpi),
int(bbox.height * self.fig.dpi)),
'-framerate',
str(self.fps),
'-i',
'{} %05d.png'.format(temp_basename),
'-vf',
'palettegen',
'{} palette.png'.format(temp_basename)])
subprocess.run(['ffmpeg', '-f', 'image2',
'-s', '{}x{}'.format(
int(bbox.width * self.fig.dpi),
int(bbox.height * self.fig.dpi)),
'-framerate', str(self.fps),
'-i', '{} %05d.png'.format(temp_basename),
'-i', '{} palette.png'.format(temp_basename),
'-lavfi', 'paletteuse', filename])
os.remove('{} palette.png'.format(temp_basename))
for i in range(self.shape[self.d]):
os.remove('{} {:05d}.png'.format(temp_basename, i))
elif event.key == 'v':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.mp4')
temp_basename = uuid.uuid4()
for i in range(self.shape[self.d]):
self.slices[self.d] = i
self.update_axes()
self.update_image()
self.fig.canvas.draw()
self.fig.savefig('{} {:05d}.png'.format(temp_basename, i),
format='png', transparent=True,
bbox_inches='tight', pad_inches=0)
subprocess.run(['ffmpeg',
'-r', str(self.fps),
'-i', '{} %05d.png'.format(temp_basename),
'-vf', 'crop=floor(iw/2)*2-10:floor(ih/2)*2-10',
'-pix_fmt', 'yuv420p',
'-crf', '1',
'-vcodec', 'libx264',
'-preset', 'veryslow',
filename])
for i in range(self.shape[self.d]):
os.remove('{} {:05d}.png'.format(temp_basename, i))
elif (event.key in ['0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', 'backspace'] and
self.d not in [self.x, self.y, self.z, self.c]):
if self.entering_slice:
if event.key == 'backspace':
if self.entered_slice < 10:
self.entering_slice = False
else:
self.entered_slice //= 10
else:
self.entered_slice = self.entered_slice * \
10 + int(event.key)
elif event.key != 'backspace':
self.entering_slice = True
self.entered_slice = int(event.key)
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'enter' and self.entering_slice:
self.entering_slice = False
if self.entered_slice < self.shape[self.d]:
self.slices[self.d] = self.entered_slice
self.update_image()
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'h':
self.show_help = not self.show_help
self.update_image()
self.fig.canvas.draw()
else:
return
def update_image(self):
# Extract slice.
idx = []
for i in range(self.ndim):
if i in [self.x, self.y, self.z, self.c]:
idx.append(slice(None, None, self.flips[i]))
else:
idx.append(self.slices[i])
idx = tuple(idx)
imv = sp.to_device(self.im[idx])
# Transpose to have [z, y, x, c].
imv_dims = [self.y, self.x]
if self.z is not None:
imv_dims = [self.z] + imv_dims
if self.c is not None:
imv_dims = imv_dims + [self.c]
imv = np.transpose(imv, np.argsort(np.argsort(imv_dims)))
imv = array_to_image(imv, color=self.c is not None)
if self.mode is None:
if np.isrealobj(imv):
self.mode = 'r'
else:
self.mode = 'm'
if self.mode == 'm':
imv = np.abs(imv)
elif self.mode == 'p':
imv = np.angle(imv)
elif self.mode == 'r':
imv = np.real(imv)
elif self.mode == 'i':
imv = np.imag(imv)
elif self.mode == 'l':
imv = np.abs(imv)
imv = np.log(imv, out=np.ones_like(imv) * -31, where=imv != 0)
if self.vmin is None:
self.vmin = imv.min()
if self.vmax is None:
self.vmax = imv.max()
if self.axim is None:
if self.colormap is None:
colormap = 'gray'
else:
colormap = self.colormap
self.axim = self.ax.imshow(
imv,
vmin=self.vmin,
vmax=self.vmax,
cmap=colormap,
origin='lower',
interpolation=self.interpolation,
aspect=1.0,
extent=[
0,
imv.shape[1],
0,
imv.shape[0]])
if self.colormap is not None:
self.fig.colorbar(self.axim)
else:
self.axim.set_data(imv)
self.axim.set_extent([0, imv.shape[1], 0, imv.shape[0]])
self.axim.set_clim(self.vmin, self.vmax)
if self.help_text is None:
bbox_props = dict(boxstyle="round",
pad=1, fc="white", alpha=0.95, lw=0)
l, b, w, h = self.ax.get_position().bounds
self.help_text = self.ax.text(imv.shape[0] / 2, imv.shape[1] / 2,
image_plot_help_str,
ha='center', va='center',
linespacing=1.5,
ma='left', size=8, bbox=bbox_props)
self.help_text.set_visible(self.show_help)
def update_axes(self):
if not self.hide_axes:
caption = '['
for i in range(self.ndim):
if i == self.d:
caption += '['
else:
caption += ' '
if (self.flips[i] == -1 and (i == self.x or
i == self.y or
i == self.z or
i == self.c)):
caption += '-'
if i == self.x:
caption += 'x'
elif i == self.y:
caption += 'y'
elif i == self.z:
caption += 'z'
elif i == self.c:
caption += 'c'
elif i == self.d and self.entering_slice:
caption += str(self.entered_slice) + '_'
else:
caption += str(self.slices[i])
if i == self.d:
caption += ']'
else:
caption += ' '
caption += ']'
self.ax.set_title(caption)
self.fig.suptitle(self.title)
self.ax.xaxis.set_visible(True)
self.ax.yaxis.set_visible(True)
self.ax.title.set_visible(True)
else:
self.ax.set_title('')
self.fig.suptitle('')
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.ax.title.set_visible(False)
def mosaic_shape(batch):
mshape = [int(batch**0.5), batch // int(batch**0.5)]
while (sp.prod(mshape) < batch):
mshape[1] += 1
if (mshape[0] - 1) * (mshape[1] + 1) == batch:
mshape[0] -= 1
mshape[1] += 1
return tuple(mshape)
def array_to_image(arr, color=False):
"""
Flattens all dimensions except the last two
Args:
arr (array): shape [z, x, y, c] if color, else [z, x, y]
"""
if color and not (arr.max() == 0 and arr.min() == 0):
arr = arr / np.abs(arr).max()
if arr.ndim == 2:
return arr
elif color and arr.ndim == 3:
return arr
if color:
img_shape = arr.shape[-3:]
batch = sp.prod(arr.shape[:-3])
mshape = mosaic_shape(batch)
else:
img_shape = arr.shape[-2:]
batch = sp.prod(arr.shape[:-2])
mshape = mosaic_shape(batch)
if sp.prod(mshape) == batch:
img = arr.reshape((batch, ) + img_shape)
else:
img = np.zeros((sp.prod(mshape), ) + img_shape, dtype=arr.dtype)
img[:batch, ...] = arr.reshape((batch, ) + img_shape)
img = img.reshape(mshape + img_shape)
if color:
img = np.transpose(img, (0, 2, 1, 3, 4))
img = img.reshape((img_shape[0] * mshape[0],
img_shape[1] * mshape[1], 3))
else:
img = np.transpose(img, (0, 2, 1, 3))
img = img.reshape((img_shape[0] * mshape[0],
img_shape[1] * mshape[1]))
return img
class LinePlot(object):
"""Plot array as lines.
Keyword Args:
x: select current dimension as x
left/right: increment/decrement current dimension
up/down: flip axis when current dimension is x or y
otherwise increment/decrement slice at current dimension
h: toggle hide all labels, titles and axes
m: magnitude mode
p: phase mode
r: real mode
i: imaginary mode
l: log mode
s: save as png.
g: save as gif by traversing current dimension.
v: save as video by traversing current dimension.
"""
def __init__(self, arr, x=-1, hide_axes=False, mode='m', title='',
save_basename='Figure', fps=10):
import matplotlib.pyplot as plt
self.arr = arr
self.axarr = None
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.shape = self.arr.shape
self.ndim = self.arr.ndim
self.slices = [s // 2 for s in self.shape]
self.flips = [1] * self.ndim
self.x = x % self.ndim
self.d = max(self.ndim - 3, 0)
self.hide_axes = hide_axes
self.title = title
self.mode = mode
self.save_basename = save_basename
self.fps = fps
self.bottom = None
self.top = None
self.fig.canvas.mpl_disconnect(
self.fig.canvas.manager.key_press_handler_id)
self.fig.canvas.mpl_connect('key_press_event', self.key_press)
self.update_axes()
self.update_line()
self.fig.canvas.draw()
plt.show()
def key_press(self, event):
if event.key == 'up':
if self.d != self.x:
self.slices[self.d] = (
self.slices[self.d] + 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_line()
self.fig.canvas.draw()
elif event.key == 'down':
if self.d != self.x:
self.slices[self.d] = (
self.slices[self.d] - 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_line()
self.fig.canvas.draw()
elif event.key == 'left':
self.d = (self.d - 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'right':
self.d = (self.d + 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'x' and self.d != self.x:
self.x = self.d
self.update_axes()
self.update_line()
self.fig.canvas.draw()
elif event.key == 'a':
self.hide_axes = not self.hide_axes
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'f':
self.fig.canvas.manager.full_screen_toggle()
elif (event.key == 'm' or event.key == 'p' or
event.key == 'r' or event.key == 'i' or event.key == 'l'):
self.mode = event.key
self.bottom = None
self.top = None
self.update_axes()
self.update_line()
self.fig.canvas.draw()
elif event.key == 's':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.png')
self.fig.savefig(filename, transparent=True, format='png',
bbox_inches='tight', pad_inches=0)
elif event.key == 'g':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.gif')
temp_basename = uuid.uuid4()
bbox = self.fig.get_tightbbox(self.fig.canvas.get_renderer())
for i in range(self.shape[self.d]):
self.slices[self.d] = i
self.update_axes()
self.update_line()
self.fig.canvas.draw()
self.fig.savefig('{} {:05d}.png'.format(temp_basename, i),
format='png', bbox_inches=bbox, pad_inches=0)
subprocess.run(['ffmpeg',
'-f',
'image2',
'-s',
'{}x{}'.format(int(bbox.width * self.fig.dpi),
int(bbox.height * self.fig.dpi)),
'-framerate',
str(self.fps),
'-i',
'{} %05d.png'.format(temp_basename),
'-vf',
'palettegen',
'{} palette.png'.format(temp_basename)])
subprocess.run(['ffmpeg', '-f', 'image2',
'-s', '{}x{}'.format(
int(bbox.width * self.fig.dpi),
int(bbox.height * self.fig.dpi)),
'-framerate', str(self.fps),
'-i', '{} %05d.png'.format(temp_basename),
'-i', '{} palette.png'.format(temp_basename),
'-lavfi', 'paletteuse', filename])
os.remove('{} palette.png'.format(temp_basename))
for i in range(self.shape[self.d]):
os.remove('{} {:05d}.png'.format(temp_basename, i))
elif event.key == 'v':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %h.%M.%S %p.mov')
temp_basename = uuid.uuid4()
bbox = self.fig.get_tightbbox(self.fig.canvas.get_renderer())
for i in range(self.shape[self.d]):
self.slices[self.d] = i
self.update_axes()
self.update_line()
self.fig.canvas.draw()
self.fig.savefig('{} {:05d}.png'.format(temp_basename, i),
format='png', bbox_inches=bbox, pad_inches=0)
subprocess.run(['ffmpeg',
'-framerate', str(self.fps),
'-i', '{} %05d.png'.format(temp_basename),
'-vcodec', 'png',
filename])
for i in range(self.shape[self.d]):
os.remove('{} {:05d}.png'.format(temp_basename, i))
else:
return
return
def update_line(self):
order = ([i for i in range(self.ndim)
if i != self.x] + [self.x])
idx = tuple([self.slices[i] for i in order[:-1]] +
[slice(None, None, self.flips[self.x])])
arrv = self.arr.transpose(order)[idx]
if self.mode == 'm':
arrv = np.abs(arrv)
elif self.mode == 'p':
arrv = np.angle(arrv)
elif self.mode == 'r':
arrv = np.real(arrv)
elif self.mode == 'i':
arrv = np.imag(arrv)
elif self.mode == 'l':
eps = 1e-31
arrv = np.log(np.abs(arrv) + eps)
if self.bottom is None:
self.bottom = arrv.min()
if self.top is None:
self.top = arrv.max()
if self.axarr is None:
self.axarr = self.ax.plot(arrv)[0]
else:
self.axarr.set_xdata(np.arange(len(arrv)))
self.axarr.set_ydata(arrv)
self.ax.set_ylim(self.bottom, self.top)
def update_axes(self):
if not self.hide_axes:
caption = 'Slice: ['
for i in range(self.ndim):
if i == self.d:
caption += '['
else:
caption += ' '
if self.flips[i] == -1 and i == self.x:
caption += '-'
if i == self.x:
caption += 'x'
else:
caption += str(self.slices[i])
if i == self.d:
caption += ']'
else:
caption += ' '
caption += ']'
self.ax.set_title(caption)
self.ax.axis('on')
self.fig.suptitle(self.title)
self.ax.xaxis.set_visible(True)
self.ax.yaxis.set_visible(True)
self.ax.title.set_visible(True)
else:
self.ax.set_title('')
self.fig.suptitle('')
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.ax.title.set_visible(False)
class ScatterPlot(object):
"""Plot array as scatter.
Keyword Args:
z: toggle current dimension as z dimension
left/right: increment/decrement current dimension
up/down: flip axis when current dimension is x or y
otherwise increment/decrement slice at current dimension
h: toggle hide all labels, titles and axes
m: magnitude mode
p: phase mode
r: real mode
i: imaginary mode
l: log mode
"""
def __init__(
self,
coord,
data=None,
z=None,
hide_axes=False,
mode='m',
title='',
save_basename='Figure',
fps=10):
import matplotlib.pyplot as plt
self.coord = coord
assert coord.shape[-1] == 2
if data is None:
self.data = np.ones(coord.shape[:-1])
else:
self.data = data
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.ax.set_facecolor('k')
self.ax.axis('equal')
for c, d in zip(coord.shape[:-1], self.data.shape[-coord.ndim + 1:]):
assert c == d
self.ndim = self.data.ndim - self.coord.ndim + 1
self.shape = self.data.shape[:self.ndim]
self.slices = [s // 2 for s in self.shape]
self.flips = [1] * self.ndim
self.z = z % self.ndim if z is not None else None
self.d = 0
self.hide_axes = hide_axes
self.title = title
self.mode = mode
self.axsc = None
self.entering_slice = False
self.save_basename = save_basename
self.fps = fps
self.vmin = None
self.vmax = None
self.fig.canvas.mpl_disconnect(
self.fig.canvas.manager.key_press_handler_id)
self.fig.canvas.mpl_connect('key_press_event', self.key_press)
self.update_axes()
self.update_data()
self.fig.canvas.draw()
plt.show()
def key_press(self, event):
if event.key == 'up':
if self.d != self.z:
self.slices[self.d] = (
self.slices[self.d] + 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_data()
self.fig.canvas.draw()
elif event.key == 'down':
if self.d != self.z:
self.slices[self.d] = (
self.slices[self.d] - 1) % self.shape[self.d]
else:
self.flips[self.d] *= -1
self.update_axes()
self.update_data()
self.fig.canvas.draw()
elif event.key == 'left':
self.d = (self.d - 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'right':
self.d = (self.d + 1) % self.ndim
self.update_axes()
self.fig.canvas.draw()
# elif event.key == 'z':
# if self.d == self.z:
# self.z = None
# else:
# self.z = self.d
# self.update_axes()
# self.update_data()
# self.fig.canvas.draw()
elif event.key == 'a':
self.hide_axes = not self.hide_axes
self.update_axes()
self.fig.canvas.draw()
elif event.key == 'f':
self.fig.canvas.manager.full_screen_toggle()
elif (event.key == 'm' or event.key == 'p' or
event.key == 'r' or event.key == 'i' or event.key == 'l'):
self.mode = event.key
self.vmin = None
self.vmax = None
self.update_axes()
self.update_data()
self.fig.canvas.draw()
elif event.key == 's':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.png')
self.fig.savefig(filename, transparent=True, format='png',
bbox_inches='tight', pad_inches=0)
elif event.key == 'g':
filename = self.save_basename + \
datetime.datetime.now().strftime(
' %Y-%m-%d at %I.%M.%S %p.gif')
temp_basename = uuid.uuid4()
bbox = self.fig.get_tightbbox(self.fig.canvas.get_renderer())
for i in range(self.shape[self.d]):
self.slices[self.d] = i
self.update_axes()
self.update_data()
self.fig.canvas.draw()
self.fig.savefig('{} {:05d}.png'.format(temp_basename, i),
format='png', bbox_inches=bbox, pad_inches=0)
subprocess.run(['ffmpeg',
'-f',
'image2',