forked from klauer/dpc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dpc_gui.py
executable file
·2549 lines (2124 loc) · 91 KB
/
dpc_gui.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
#!/usr/bin/env python
"""
Created on May 23, 2013
@author: Cheng Chang ([email protected])
Computer Science Group, Computational Science Center
Brookhaven National Laboratory
This code is for Differential Phase Contrast (DPC) imaging based on
Fourier-shift fitting implementation.
Reference: Yan, H. et al. Quantitative x-ray phase imaging at the nanoscale by
multilayer Laue lenses. Sci. Rep. 3, 1307; DOI:10.1038/srep01307
(2013).
Test data is available at:
https://docs.google.com/file/d/0B3v6W1bQwN_AdjZwWmE3WTNqVnc/edit?usp=sharing
"""
from __future__ import print_function, division
import os
import sys
import csv
import time
import logging
from datetime import datetime
from functools import wraps
import multiprocessing as mp
import subprocess
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication,
QMainWindow,
QInputDialog,
QFileDialog,
QLabel,
QLineEdit,
QDoubleSpinBox,
QSpinBox,
QComboBox,
QPushButton,
QSizePolicy,
QGroupBox,
QGridLayout,
QListWidget,
QWidget,
QCheckBox,
QTextEdit,
QFrame,
QHBoxLayout,
QSlider,
QAction,
QStyleFactory,
QRubberBand,
QMessageBox,
QMenu,
)
from PyQt5.QtGui import QPalette, QPixmap, QIcon, QPen, QPainter, QTextCursor
import matplotlib.cm as cm
from PIL import Image
import PIL
from skimage import exposure
import numpy as np
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import psutil
try:
from tifffile import imsave
havetiff = True
except ImportError as ex:
print("[!] Import error - tifffile not available. Tif files will not be saved")
print("[!] (import error: {})".format(ex))
havetiff = False
import load_timepix
import h5py
import dpc_kernel as dpc
import pyspecfile
from db_config.db_config import db
try:
import hxntools
from hxntools.scan_info import ScanInfo
from hxntools.scan_monitor import HxnScanMonitor
# from databroker import DataBroker
except ImportError as ex:
print("[!] Unable to import hxntools-related packages some features will " "be unavailable")
print("[!] (import error: {})".format(ex))
hxntools = None
logger = logging.getLogger(__name__)
get_save_filename = QFileDialog.getSaveFileName
get_open_filename = QFileDialog.getOpenFileName
version = "1.1.0"
SOLVERS = [
"Nelder-Mead",
"Powell",
"CG",
"BFGS",
"Newton-CG",
"Anneal",
"L-BFGS-B",
"TNC",
"COBYLA",
"SLS-QP",
"dogleg",
"trust-ncg",
]
TYPES = [
"TIFF",
"Timepix TIFF",
"ASCII",
"HDF5",
"FileStore",
]
roi_x1 = 0
roi_x2 = 0
roi_y1 = 0
roi_y2 = 0
a = None
gx = None
gy = None
phi = None
rx = None
ry = None
CMAP_PREVIEW_PATH = os.path.join(os.path.dirname(__file__), ".cmap_previews")
def load_image_pil(path):
"""
Read images using the PIL lib
"""
f = Image.open(str(path)) # 'I;16B'
return np.array(f.getdata()).reshape(f.size[::-1])
def load_data_hdf5(file_path):
"""
Read images using the h5py lib
"""
f = h5py.File(str(file_path), "r")
entry = f["entry"]
instrument = entry["instrument"]
detector = instrument["detector"]
dsdata = detector["data"]
data = dsdata[...]
f.close()
return np.array(data)
def load_image_hdf5(file_path):
data = load_data_hdf5(file_path)
return data[0, :, :]
def load_image_ascii(path):
"""
Read ASCII images using the csv lib
"""
delimiter = "\t"
data = []
for row in csv.reader(open(path), delimiter=delimiter):
data.append(row[:-1])
img = np.array(data).astype(np.double)
return img
def brush_to_color_tuple(brush):
r, g, b, a = brush.color().getRgbF()
return (r, g, b)
class MyStream(QtCore.QObject):
message = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(MyStream, self).__init__(parent)
def write(self, message):
self.message.emit(str(message))
def flush(self):
pass
class DPCThread(QtCore.QThread):
def __init__(self, canvas, pool=None, parent=None):
QtCore.QThread.__init__(self, parent)
self.canvas = canvas
self.pool = pool
update_signal = QtCore.pyqtSignal(object, object, object, object, object, object)
def run(self):
print("DPC thread started")
main = DPCWindow.instance
try:
ret = dpc.main(
pool=self.pool,
display_fcn=self.update_signal.emit,
load_image=main.load_image,
**self.dpc_settings,
)
print("DPC finished")
global a
global gx
global gy
global phi
global rx
global ry
a, gx, gy, phi, rx, ry = ret
main.a, main.gx, main.gy, main.phi, main.rx, main.ry = a, gx, gy, phi, rx, ry
main.line_btn.setEnabled(True)
main.reverse_x.setEnabled(True)
main.reverse_y.setEnabled(True)
main.swap_xy.setEnabled(True)
main.save_result_tiff.setEnabled(True)
main.save_result_txt.setEnabled(True)
main.hanging_opt.setEnabled(True)
main.random_processing_opt.setEnabled(True)
main.pyramid_scan.setEnabled(True)
main.pad_recon.setEnabled(True)
# main.direction_btn.setEnabled(True)
# main.removal_btn.setEnabled(True)
# main.confirm_btn.setEnabled(True)
finally:
main.set_running(False)
class MplCanvas(FigureCanvas):
"""
Canvas which allows us to use matplotlib with pyqt4
"""
def __init__(self, fig=None, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
# We want the axes cleared every time plot() is called
self.axes = fig.add_subplot(1, 1, 1)
# self.axes.hold(False)
self.axes.cla()
FigureCanvas.__init__(self, fig)
# self.figure
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self._title = ""
self.title_font = {"family": "serif", "fontsize": 10}
self._title_size = 0
self.figure.subplots_adjust(top=0.95, bottom=0.15)
window_brush = self.window().palette().window()
fig.set_facecolor(brush_to_color_tuple(window_brush))
fig.set_edgecolor(brush_to_color_tuple(window_brush))
self._active = False
def _get_title(self):
return self._title
def _set_title(self, title):
self._title = title
if self.axes:
self.axes.set_title(title, fontdict=self.title_font)
# bbox = t.get_window_extent()
# bbox = bbox.inverse_transformed(self.figure.transFigure)
# self._title_size = bbox.height
# self.figure.subplots_adjust(top=1.0 - self._title_size)
title = property(_get_title, _set_title)
class Label(QLabel):
def __init__(self, parent=None):
super(Label, self).__init__(parent)
self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.origin = QtCore.QPoint()
def mousePressEvent(self, event):
global roi_x1
global roi_y1
self.rubberBand.hide()
if event.button() == Qt.LeftButton:
self.origin = QtCore.QPoint(event.pos())
self.rubberBand.setGeometry(QtCore.QRect(self.origin, QtCore.QSize()))
self.rubberBand.show()
roi_x1 = event.pos().x()
roi_y1 = event.pos().y()
def mouseMoveEvent(self, event):
# if event.buttons() == QtCore.Qt.NoButton:
# pos = event.pos()
if not self.origin.isNull():
self.rubberBand.setGeometry(QtCore.QRect(self.origin, event.pos()).normalized())
def mouseReleaseEvent(self, event):
global roi_x2
global roi_y2
roi_x2 = event.pos().x()
roi_y2 = event.pos().y()
main = DPCWindow.instance
if (roi_x1, roi_y1) != (roi_x2, roi_y2):
main.roi_x1_widget.setValue(roi_x1)
main.roi_y1_widget.setValue(roi_y1)
main.roi_x2_widget.setValue(roi_x2)
main.roi_y2_widget.setValue(roi_y2)
else:
if main.bad_flag != 0:
main.bad_pixels_widget.addItem("%d, %d" % (event.pos().x(), event.pos().y()))
for i in range(len(main.bad_pixels)):
main.roi_img_masked[main.bad_pixels[i][1], main.bad_pixels[i][0]] = 0
main.ax.imshow(
main.roi_img_masked, interpolation="nearest", origin="upper", cmap=main._ref_color_map
)
main.ref_canvas.draw()
self.rubberBand.show()
class paintLabel(QLabel):
def __init__(self, parent=None):
super(paintLabel, self).__init__(parent)
def paintEvent(self, event):
super(paintLabel, self).paintEvent(event)
qp = QPainter()
qp.begin(self)
self.drawLine(event, qp)
qp.end()
def drawLine(self, event, qp):
size = self.size()
pen = QPen(QtCore.Qt.red)
qp.setPen(pen)
qp.drawLine(size.width() / 2, 0, size.width() / 2, size.height() - 1)
qp.drawLine(size.width() / 2 - 1, 0, size.width() / 2 - 1, size.height() - 1)
qp.drawLine(0, size.height() / 2, size.width() - 1, size.height() / 2)
qp.drawLine(0, size.height() / 2 - 1, size.width() - 1, size.height() / 2 - 1)
pen.setStyle(QtCore.Qt.DashLine)
pen.setColor(QtCore.Qt.black)
qp.setPen(pen)
qp.drawLine(0, 0, size.width() - 1, 0)
qp.drawLine(0, size.height() - 1, size.width() - 1, size.height() - 1)
qp.drawLine(0, 0, 0, size.height() - 1)
qp.drawLine(size.width() - 1, 0, size.width() - 1, size.height() - 1)
class DPCWindow(QMainWindow):
CM_DEFAULT = "gray"
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
DPCWindow.instance = self
self.bin_num = 2 ** 16
self._thread = None
self.ion_data = None
self.bad_flag = 0
self.direction = -1 # 1 for horizontal and -1 for vertical
self.crop_x0 = None
self.crop_x1 = None
self.crop_y0 = None
self.crop_y1 = None
self.set_roi_enabled = False
self.his_enabled = False
self.scan = None
self.contrastval = 0
self.histequalization = False
self.showresiduals = False
self.running = False
self.gx, self.gy, self.phi, self.a, self.rx, self.ry = None, None, None, None, None, None
self.file_widget = QLineEdit("Chromosome_9_%05d.tif")
self.file_widget.setFixedWidth(350)
self.save_path_widget = QLineEdit("/home")
self.focus_widget = QDoubleSpinBox()
self.dx_widget = QDoubleSpinBox()
self.dy_widget = QDoubleSpinBox()
self.pixel_widget = QDoubleSpinBox()
self.energy_widget = QDoubleSpinBox()
self.rows_widget = QSpinBox()
self.cols_widget = QSpinBox()
self.mosaic_x_widget = QSpinBox()
self.mosaic_y_widget = QSpinBox()
self.roi_x1_widget = QSpinBox()
self.roi_x2_widget = QSpinBox()
self.roi_y1_widget = QSpinBox()
self.roi_y2_widget = QSpinBox()
self.strap_start = QSpinBox()
self.strap_end = QSpinBox()
self.first_widget = QSpinBox()
self.first_widget.valueChanged.connect(self._first_changed)
self.processes_widget = QSpinBox()
self.processes_widget.setMinimum(1)
self.processes_widget.setValue(psutil.cpu_count())
self.processes_widget.setMaximum(psutil.cpu_count())
self.solver_widget = QComboBox()
for solver in SOLVERS:
self.solver_widget.addItem(solver)
self.start_widget = QPushButton("Start")
self.stop_widget = QPushButton("Stop")
self.save_widget = QPushButton("Save")
self.scan_button = QPushButton("Load")
self.color_map = QComboBox()
self.update_color_maps()
self.color_map.currentIndexChanged.connect(self._set_color_map)
self._color_map = mpl.cm.get_cmap(self.CM_DEFAULT)
self.ref_color_map = QComboBox()
self.update_ref_color_maps()
self.ref_color_map.currentIndexChanged.connect(self._set_ref_color_map)
self._ref_color_map = mpl.cm.get_cmap(self.CM_DEFAULT)
self.start_widget.clicked.connect(self.start)
self.stop_widget.clicked.connect(self.stop)
self.save_widget.clicked.connect(self.save)
self.scan_button.clicked.connect(self.load_from_spec_scan)
self.load_image = load_timepix.load
def format_coord(x, y):
col = int(x + 0.5)
row = int(y + 0.5)
if row >= 0 and row < self.roi_img.shape[0] and col >= 0 and col < self.roi_img.shape[1]:
z = self.roi_img[row, col]
return "x=%1.4f y=%1.4f v=%1.4f" % (x, y, z)
else:
return "x=%1.4f y=%1.4f" % (x, y)
self.rect = Rectangle((0, 0), 0, 0, alpha=0.3, facecolor="gray", edgecolor="red", linewidth=2)
self.ref_fig = plt.figure()
# self.ref_canvas = MplCanvas(self.ref_fig, width=8, height=10, dpi=50)
self.ref_canvas = FigureCanvas(self.ref_fig)
self.ref_fig.subplots_adjust(top=0.99, left=0.01, right=0.99, bottom=0.04)
self.ref_fig.canvas.mpl_connect("button_press_event", self.on_press)
self.ref_fig.canvas.mpl_connect("button_release_event", self.on_release)
self.ref_fig.canvas.mpl_connect("motion_notify_event", self.on_motion)
self.ax = self.ref_fig.add_subplot(111)
self.ax.format_coord = format_coord
self.ax.add_patch(self.rect)
self.ax.figure.canvas.draw()
self.ref_toolbar = NavigationToolbar(self.ref_canvas, self)
self.his_btn = QPushButton("Equalize")
self.his_btn.setCheckable(True)
self.his_btn.clicked[bool].connect(self.histgramEqua)
self.roi_btn = QPushButton("Set ROI")
self.roi_btn.setCheckable(True)
self.roi_btn.clicked[bool].connect(self.set_roi_enable)
self.bri_btn = QPushButton("Brightest")
self.bri_btn.clicked.connect(self.select_bri_pixels)
self.bad_btn = QPushButton("Pick")
self.bad_btn.setCheckable(True)
self.bad_btn.clicked[bool].connect(self.bad_enable)
self.line_btn = QPushButton("Add")
self.line_btn.setEnabled(False)
self.line_btn.clicked.connect(self.add_strap)
direction_text = "\N{CLOCKWISE OPEN CIRCLE ARROW} 90\N{DEGREE SIGN}"
self.direction_btn = QPushButton(direction_text)
self.direction_btn.clicked.connect(self.change_direction)
self.direction_btn.setEnabled(False)
self.removal_btn = QPushButton("Remove")
self.removal_btn.clicked.connect(self.remove_background)
self.removal_btn.setEnabled(False)
self.confirm_btn = QPushButton("Apply")
self.confirm_btn.clicked.connect(self.confirm)
self.confirm_btn.setEnabled(False)
self.hide_btn = QPushButton("View && set")
self.hide_btn.setCheckable(True)
self.hide_btn.clicked.connect(self.hide_ref)
self.ok_btn = QPushButton("OK")
self.ok_btn.clicked.connect(self.crop_ok)
self.cancel_btn = QPushButton("Cancel")
self.cancel_btn.clicked.connect(self.crop_cancel)
# Setting widget (QGridLayout) in the bottom of reference image
self.min_lbl = QLabel("Min")
self.max_lbl = QLabel("Max")
self.min_box = QSpinBox()
self.max_box = QSpinBox()
self.min_box.setMaximum(self.bin_num)
self.min_box.setMinimum(0)
self.max_box.setMaximum(self.bin_num)
self.max_box.setMinimum(0)
self.rescale_intensity_btn = QPushButton("Apply")
self.rescale_intensity_btn.clicked.connect(self.rescale_intensity)
self.badPixelGbox = QGroupBox("Bad pixels")
self.badPixelGridLayout = QGridLayout()
self.badPixelGbox.setLayout(self.badPixelGridLayout)
bpw = self.bad_pixels_widget = QListWidget()
# Set the minimum height of the qlistwidget as 1 so that the
# qlistwidget is always as as high as its two side buttons
bpw.setMinimumHeight(1)
bpw.setContextMenuPolicy(Qt.CustomContextMenu)
bpw.customContextMenuRequested.connect(self._bad_pixels_menu)
self.badPixelGridLayout.addWidget(self.bri_btn, 0, 0)
self.badPixelGridLayout.addWidget(self.bad_btn, 1, 0)
self.badPixelGridLayout.addWidget(self.bad_pixels_widget, 0, 1, 2, 1)
def ref_close(event):
self.hide_btn.setChecked(False)
self.ref_grid = QGridLayout()
self.ref_widget = QWidget()
self.ref_widget.closeEvent = ref_close
self.ref_widget.setLayout(self.ref_grid)
self.ref_grid.addWidget(self.ref_canvas, 0, 0, 1, 6)
self.ref_grid.addWidget(self.ref_toolbar, 1, 0, 1, 6)
self.ref_grid.addWidget(self.badPixelGbox, 2, 0, 3, 1)
self.ref_grid.addWidget(self.ref_color_map, 2, 1, 1, 5)
self.ref_grid.addWidget(self.his_btn, 3, 1, 1, 2)
self.ref_grid.addWidget(self.roi_btn, 3, 3, 1, 2)
self.ref_grid.addWidget(self.min_lbl, 4, 1)
self.ref_grid.addWidget(self.min_box, 4, 2)
self.ref_grid.addWidget(self.max_lbl, 4, 3)
self.ref_grid.addWidget(self.max_box, 4, 4)
self.ref_grid.addWidget(self.rescale_intensity_btn, 4, 5)
self.file_format_btn = QPushButton("Select")
# self.file_format_btn.setStyle(WinLayout)
self.file_format_btn.clicked.connect(self.select_path)
"""
QGroupBox implementation for image settings
"""
self.imageSettingGbox = QGroupBox("Image settings")
self.imageSettingGridLayout = QGridLayout()
self.imageSettingGbox.setLayout(self.imageSettingGridLayout)
self.scan_number_lbl = QLabel("Scan number")
self.roi_x1_lbl = QLabel("ROI X1")
self.roi_x2_lbl = QLabel("ROI X2")
self.roi_y1_lbl = QLabel("ROI Y1")
self.roi_y2_lbl = QLabel("ROI Y2")
self.img_type_lbl = QLabel("Image type")
self.pixel_size_lbl = QLabel("Pixel size (um)")
self.file_name_lbl = QLabel("File name")
self.first_img_num_lbl = QLabel("First image number")
self.scan_info_lbl = QLabel("")
self.scan_info_lbl.setWordWrap(True)
self.select_ref_btn = QPushButton("Select the reference")
self.select_ref_btn.clicked.connect(self.select_ref_img)
self.img_type_combobox = itc = QComboBox()
for types in TYPES:
itc.addItem(types)
itc.currentIndexChanged.connect(self.load_img_method)
self.first_ref_cbox = QCheckBox("Use as the reference image")
self.first_ref_cbox.stateChanged.connect(self.first_equal_ref)
self.use_scan_number_cb = QCheckBox("Read from metadatastore")
self.use_scan_number_cb.toggled.connect(self._use_scan_number_clicked)
fs_key_cbox = self.fs_key_cbox = QComboBox()
fs_key_cbox.currentIndexChanged.connect(self._filestore_key_changed)
self.load_scan_btn = QPushButton("Load")
self.load_scan_btn.clicked.connect(self.load_scan_from_mds)
self.ref_image_path_QLineEdit = QLineEdit("reference image")
self.ref_image_path_QLineEdit.setFixedWidth(350)
self.scan_number_text = QLineEdit("3449")
row = 0
layout = self.imageSettingGridLayout
if hxntools is not None:
layout.addWidget(self.scan_number_lbl, row, 0)
layout.addWidget(self.scan_number_text, row, 1)
layout.addWidget(self.load_scan_btn, row, 2)
layout.addWidget(self.use_scan_number_cb, row, 3)
row += 1
layout.addWidget(self.fs_key_cbox, row, 0)
layout.addWidget(self.scan_info_lbl, row, 1, 1, 3)
row += 1
layout.addWidget(self.img_type_lbl, row, 0)
layout.addWidget(self.img_type_combobox, row, 1)
layout.addWidget(self.pixel_size_lbl, row, 2)
layout.addWidget(self.pixel_widget, row, 3)
row += 1
layout.addWidget(self.file_name_lbl, row, 0)
layout.addWidget(self.file_widget, row, 1, 1, 3)
layout.addWidget(self.file_format_btn, row, 4)
row += 1
layout.addWidget(self.first_img_num_lbl, row, 0)
layout.addWidget(self.first_widget, row, 1)
layout.addWidget(self.first_ref_cbox, row, 2, 1, 2)
row += 1
layout.addWidget(self.select_ref_btn, row, 0)
layout.addWidget(self.ref_image_path_QLineEdit, row, 1, 1, 3)
row += 1
layout.addWidget(self.roi_x1_lbl, row, 0)
layout.addWidget(self.roi_x1_widget, row, 1)
layout.addWidget(self.roi_x2_lbl, row, 2)
layout.addWidget(self.roi_x2_widget, row, 3)
layout.addWidget(self.hide_btn, row, 4)
row += 1
layout.addWidget(self.roi_y1_lbl, row, 0)
layout.addWidget(self.roi_y1_widget, row, 1)
layout.addWidget(self.roi_y2_lbl, row, 2)
layout.addWidget(self.roi_y2_widget, row, 3)
# QGroupBox implementation for experiment parameters
self.experimentParaGbox = QGroupBox("Experiment parameters")
self.experimentParaGridLayout = QGridLayout()
self.experimentParaGbox.setLayout(self.experimentParaGridLayout)
self.energy_lbl = QLabel("Energy (keV)")
self.detector_sample_lbl = QLabel("Detector-sample distance (m)")
self.x_step_size_lbl = QLabel("X step size (um)")
self.y_step_size_lbl = QLabel("Y step size (um)")
self.x_steps_number_lbl = QLabel("Columns (x)")
self.y_steps_number_lbl = QLabel("Rows (y)")
self.mosaic_x_size_lbl = QLabel("Mosaic column number")
self.mosaic_y_size_lbl = QLabel("Mosaic row number")
self.experimentParaGridLayout.addWidget(self.energy_lbl, 0, 0)
self.experimentParaGridLayout.addWidget(self.energy_widget, 0, 1)
self.experimentParaGridLayout.addWidget(self.detector_sample_lbl, 0, 2)
self.experimentParaGridLayout.addWidget(self.focus_widget, 0, 3)
self.experimentParaGridLayout.addWidget(self.x_step_size_lbl, 1, 0)
self.experimentParaGridLayout.addWidget(self.dx_widget, 1, 1)
self.experimentParaGridLayout.addWidget(self.y_step_size_lbl, 1, 2)
self.experimentParaGridLayout.addWidget(self.dy_widget, 1, 3)
self.experimentParaGridLayout.addWidget(self.x_steps_number_lbl, 2, 0)
self.experimentParaGridLayout.addWidget(self.cols_widget, 2, 1)
self.experimentParaGridLayout.addWidget(self.y_steps_number_lbl, 2, 2)
self.experimentParaGridLayout.addWidget(self.rows_widget, 2, 3)
self.experimentParaGridLayout.addWidget(self.mosaic_x_size_lbl, 3, 0)
self.experimentParaGridLayout.addWidget(self.mosaic_x_widget, 3, 1)
self.experimentParaGridLayout.addWidget(self.mosaic_y_size_lbl, 3, 2)
self.experimentParaGridLayout.addWidget(self.mosaic_y_widget, 3, 3)
"""
QGroupBox implementation for computation parameters
"""
self.computationParaGbox = QGroupBox("Computation parameters")
self.computationParaGridLayout = QGridLayout()
self.computationParaGbox.setLayout(self.computationParaGridLayout)
self.solver_method_lbl = QLabel("Solver method")
self.processes_lbl = QLabel("Processes")
self.random_processing_checkbox = QCheckBox("Random mode")
self.hanging_checkbox = QCheckBox("Hanging mode")
layout = self.computationParaGridLayout
layout.addWidget(self.solver_method_lbl, 0, 0)
layout.addWidget(self.solver_widget, 0, 1)
layout.addWidget(self.processes_lbl, 0, 2)
layout.addWidget(self.processes_widget, 0, 3)
# layout.addWidget(self.random_processing_checkbox, 1, 0)
# layout.addWidget(self.hanging_checkbox, 1, 1)
layout.addWidget(self.start_widget, 0, 4)
layout.addWidget(self.stop_widget, 0, 5)
"""
QGroupBox implementation for console information
"""
self.consoleInfoGbox = QGroupBox("Console information")
self.consoleInfoGridLayout = QGridLayout()
self.consoleInfoGbox.setLayout(self.consoleInfoGridLayout)
self.console_info = QTextEdit(self)
self.console_info.setReadOnly(True)
self.consoleInfoGridLayout.addWidget(self.console_info)
self.background_remove_qbox = QGroupBox("Remove background")
self.background_remove_layout = QGridLayout()
self.background_remove_qbox.setLayout(self.background_remove_layout)
self.strap_start_label = QLabel("Start")
self.strap_end_label = QLabel("End")
self.background_remove_layout.addWidget(self.strap_start_label, 0, 0)
self.background_remove_layout.addWidget(self.strap_start, 0, 1)
self.background_remove_layout.addWidget(self.strap_end_label, 0, 2)
self.background_remove_layout.addWidget(self.strap_end, 0, 3)
self.background_remove_layout.addWidget(self.line_btn, 0, 4)
self.background_remove_layout.addWidget(self.direction_btn, 0, 5)
self.background_remove_layout.addWidget(self.removal_btn, 0, 6)
self.background_remove_layout.addWidget(self.confirm_btn, 0, 7)
self.canvas = MplCanvas(width=10, height=12, dpi=50)
self.toolbar = NavigationToolbar(self.canvas, self)
self.image_vis_qbox = QGroupBox("Image visualization")
self.image_vis_layout = QGridLayout()
self.image_vis_qbox.setLayout(self.image_vis_layout)
self.image_vis_layout.addWidget(self.toolbar, 0, 0)
self.image_vis_layout.addWidget(self.color_map, 0, 1)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
self.image_vis_layout.addWidget(line, 1, 0)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
self.image_vis_layout.addWidget(line, 1, 1)
hboxcb = QHBoxLayout()
self.cb_histeq = QCheckBox("Histogram Equalization", self)
self.cb_histeq.setChecked(False)
self.cb_histeq.stateChanged.connect(self.OnCBHistEqualization)
hboxcb.addWidget(self.cb_histeq)
self.cb_resid = QCheckBox("Show Residuals", self)
self.cb_resid.setChecked(False)
self.cb_resid.stateChanged.connect(self.OnCBShowResiduals)
hboxcb.addWidget(self.cb_resid)
self.image_vis_layout.addLayout(hboxcb, 2, 1)
hboxslider = QHBoxLayout()
hboxslider.addWidget(QLabel("Contrast"))
self.slider_constrast = QSlider(QtCore.Qt.Horizontal)
self.slider_constrast.setFocusPolicy(QtCore.Qt.StrongFocus)
self.slider_constrast.setRange(0, 25)
self.slider_constrast.setValue(0)
self.slider_constrast.setTickPosition(QSlider.TicksBelow)
self.slider_constrast.setTickInterval(5)
hboxslider.addWidget(self.slider_constrast)
self.slider_constrast.valueChanged[int].connect(self.OnContrastSlider)
self.image_vis_layout.addLayout(hboxslider, 2, 0)
self.canvas_QGridLayout = QGridLayout()
self.canvas_widget = QWidget()
self.canvas_widget.setLayout(self.canvas_QGridLayout)
self.canvas_QGridLayout.addWidget(self.canvas, 0, 0, 1, 2)
self.canvas_QGridLayout.addWidget(self.image_vis_qbox, 1, 0)
self.canvas_QGridLayout.addWidget(self.background_remove_qbox, 1, 1)
self.crop_widget = QWidget()
self.crop_layout = QGridLayout()
self.crop_widget.setLayout(self.crop_layout)
self.crop_canvas = MplCanvas(width=8, height=8, dpi=50)
self.crop_fig = self.crop_canvas.figure
self.crop_fig.subplots_adjust(top=0.95, left=0.05, right=0.95, bottom=0.05)
self.crop_ax = self.crop_fig.add_subplot(111)
# self.crop_ax.hold(False)
self.crop_ax.cla()
self.crop_layout.addWidget(self.crop_canvas, 0, 0, 1, 2)
self.crop_layout.addWidget(self.ok_btn, 1, 0)
self.crop_layout.addWidget(self.cancel_btn, 1, 1)
self.last_path = ""
self.main_grid = QGridLayout()
self.main_widget = QWidget()
self.main_widget.setLayout(self.main_grid)
self.main_grid.addWidget(self.imageSettingGbox, 0, 0)
self.main_grid.addWidget(self.experimentParaGbox, 1, 0)
self.main_grid.addWidget(self.computationParaGbox, 2, 0)
self.main_grid.addWidget(self.consoleInfoGbox, 3, 0)
# Add menu
self.menu = self.menuBar()
self.save_result_tiff = QAction("Export to .tiff", self)
self.save_result_tiff.setEnabled(False)
self.save_result_tiff.triggered.connect(self.save_file_tiff)
self.save_result_txt = QAction("Export to .txt", self)
self.save_result_txt.setEnabled(False)
self.save_result_txt.triggered.connect(self.save_file_txt)
self.save_scan_params = QAction("Save scan parameters", self)
self.save_scan_params.triggered.connect(self.save_params_to_file)
self.load_scan_params = QAction("Load scan parameters", self)
self.load_scan_params.triggered.connect(self.load_params_from_file)
self.start_batch_gui = QAction("Launch DPC Batch GUI", self)
self.start_batch_gui.triggered.connect(self.launch_batch_gui)
self.reverse_x = QAction("Reverse gx", self, checkable=True)
self.reverse_x.triggered.connect(self.reverse_gx)
self.reverse_x.setEnabled(False)
self.reverse_y = QAction("Reverse gy", self, checkable=True)
self.reverse_y.triggered.connect(self.reverse_gy)
self.reverse_y.setEnabled(False)
self.swap_xy = QAction("Swap x/y", self, checkable=True)
self.swap_xy.triggered.connect(self.swap_x_y)
self.swap_xy.setEnabled(False)
self.random_processing_opt = QAction("Random mode", self, checkable=True)
self.hanging_opt = QAction("Hanging mode", self, checkable=True)
self.pyramid_scan = QAction("Pyramid scan", self, checkable=True)
self.pad_recon = QAction("Padding mode", self, checkable=True)
self.pad_recon.triggered.connect(self.padding_recon)
file_menu = self.menu.addMenu("File")
file_menu.addAction(self.save_result_tiff)
file_menu.addAction(self.save_result_txt)
file_menu.addAction(self.save_scan_params)
file_menu.addAction(self.load_scan_params)
file_menu.addAction(self.start_batch_gui)
option_menu = self.menu.addMenu("Option")
option_menu.addAction(self.reverse_x)
option_menu.addAction(self.reverse_y)
option_menu.addAction(self.swap_xy)
option_menu.addAction(self.random_processing_opt)
option_menu.addAction(self.hanging_opt)
option_menu.addAction(self.pyramid_scan)
option_menu.addAction(self.pad_recon)
if hxntools is not None:
self.monitor_scans = QAction("Monitor acquired scans", self, checkable=True)
self.monitor_scans.triggered.connect(self.monitor_toggled)
self.scan_monitor = HxnScanMonitor(uid_pv, db)
self.scan_monitor.connect("start", self.bs_scan_started)
self.scan_monitor.connect("stop", self.bs_scan_finished)
option_menu.addAction(self.monitor_scans)
self.setCentralWidget(self.main_widget)
self.setWindowTitle("DPC v.{0}".format(version))
# QApplication.setStyle(QStyleFactory.create('Cleanlooks'))
QApplication.setStyle(QStyleFactory.create("Plastique"))
# QApplication.setStyle(QStyleFactory.create('cde'))
self._init_settings()
for w in [
self.pixel_widget,
self.focus_widget,
self.energy_widget,
self.dx_widget,
self.dy_widget,
self.rows_widget,
self.cols_widget,
self.roi_x1_widget,
self.roi_x2_widget,
self.roi_y1_widget,
self.roi_y2_widget,
self.first_widget,
self.mosaic_x_widget,
self.mosaic_y_widget,
self.strap_start,
self.strap_end,
]:
w.setMinimum(0)
w.setMaximum(int(2 ** 31 - 1))
try:
w.setDecimals(3)
except Exception:
pass
for w in [self.strap_start, self.strap_end]:
w.setMinimum(0)
w.setMaximum(9999)
self.load_settings()
def monitor_toggled(self):
pass
def bs_scan_started(self, uid, hxn_info=None, **hdr):
if not self.monitoring:
return
print("Scan started")
self.set_scan_from_scaninfo(ScanInfo(hdr), load_config=True)
def bs_scan_finished(self, uid, hxn_info=None, **hdr):
if not self.monitoring:
return
print("Scan finished")
self.stop()
self.set_scan_from_scaninfo(ScanInfo(hdr), load_config=True)
def _init_settings(self):
def typed_setter(fcn, type_):
@wraps(fcn)
def wrapped(value):
return fcn(type_(value))
return wrapped
def checked_setter(widget, offset=1):
@wraps(widget.setChecked)
def wrapped(value):
widget.setChecked(int(value) + offset)
return wrapped
def getter(attr):
def wrapped():
return getattr(self, attr)
return wrapped
def setter(attr):
def wrapped(value):
return setattr(self, attr, value)
return wrapped
self._settings = {
"file_format": [getter("file_format"), self.file_widget.setText],
"save_path": [getter("save_path"), self.save_path_widget.setText],
"dx": [getter("dx"), setter("dx")],
"dy": [getter("dy"), setter("dy")],
"x1": [getter("roi_x1"), typed_setter(self.roi_x1_widget.setValue, int)],
"y1": [getter("roi_y1"), typed_setter(self.roi_y1_widget.setValue, int)],
"x2": [getter("roi_x2"), typed_setter(self.roi_x2_widget.setValue, int)],
"y2": [getter("roi_y2"), typed_setter(self.roi_y2_widget.setValue, int)],
"pixel_size": [getter("pixel_size"), typed_setter(self.pixel_widget.setValue, float)],
"focus_to_det": [getter("focus"), typed_setter(self.focus_widget.setValue, float)],
"energy": [getter("energy"), typed_setter(self.energy_widget.setValue, float)],
"rows": [getter("rows"), typed_setter(self.rows_widget.setValue, int)],
"cols": [getter("cols"), typed_setter(self.cols_widget.setValue, int)],
"mosaic_y": [getter("mosaic_y"), typed_setter(self.mosaic_y_widget.setValue, int)],
"mosaic_x": [getter("mosaic_x"), typed_setter(self.mosaic_x_widget.setValue, int)],
"swap": [getter("swap"), checked_setter(self.swap_xy, 1)],
"reverse_x": [getter("re_x"), checked_setter(self.reverse_x, -1)],
"reverse_y": [getter("re_y"), checked_setter(self.reverse_y, -1)],
"random": [getter("random"), checked_setter(self.random_processing_opt, 1)],
"pyramid": [getter("pyramid"), checked_setter(self.pyramid_scan, 1)],
"pad": [getter("pad"), checked_setter(self.pad_recon, True)],
"hang": [getter("hang"), checked_setter(self.hanging_opt, 1)],
"ref_image": [getter("ref_image"), self.ref_image_path_QLineEdit.setText],
"first_image": [getter("first_image"), typed_setter(self.first_widget.setValue, int)],
"processes": [getter("processes"), typed_setter(self.processes_widget.setValue, int)],
"bad_pixels": [getter("bad_pixels"), self.set_bad_pixels],
"solver": [getter("solver"), setter("solver")],
"last_path": [getter("last_path"), setter("last_path")],
"scan_number": [getter("scan_number"), setter("scan_number")],
"use_mds": [getter("use_mds"), setter("use_mds")],
"filestore_key": [getter("filestore_key"), setter("filestore_key")],
# 'color_map': [lambda: self._color_map,
# setter('last_path')],
}
def _use_scan_number_clicked(self, checked):
self.use_mds = checked
self.file_widget.setEnabled(not self.use_mds)
self.fs_key_cbox.setVisible(self.use_mds)
self.scan_info_lbl.setVisible(self.use_mds)
self.select_ref_btn.setEnabled(not self.use_mds)
self.ref_image_path_QLineEdit.setEnabled(not self.use_mds)
if self.use_mds:
self.img_type_combobox.setCurrentIndex(TYPES.index("FileStore"))
self.first_ref_cbox.setChecked(True)
self.img_type_combobox.setEnabled(not self.use_mds)
@property
def use_mds(self):
if hxntools is None:
return False
return bool(self.use_scan_number_cb.isChecked())
@use_mds.setter
def use_mds(self, checked):
self.use_scan_number_cb.setChecked(bool(checked))
@property
def filestore_key(self):
return str(self.fs_key_cbox.currentText())
@filestore_key.setter
def filestore_key(self, key):
keys = list(sorted(self.scan.filestore_keys))
self.fs_key_cbox.setCurrentIndex(keys.index(key))
def _load_scan_from_mds(self, scan_id, load_config=True):