edview 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- edview/__init__.py +6 -0
- edview/assets/__init__.py +0 -0
- edview/assets/algodif_logo.png +0 -0
- edview/lib/__init__.py +0 -0
- edview/lib/interactions.py +2984 -0
- edview/lib/rendering.py +2365 -0
- edview/lib/utilities.py +2103 -0
- edview/main.py +65 -0
- edview-1.0.0.dist-info/METADATA +158 -0
- edview-1.0.0.dist-info/RECORD +14 -0
- edview-1.0.0.dist-info/WHEEL +5 -0
- edview-1.0.0.dist-info/entry_points.txt +2 -0
- edview-1.0.0.dist-info/licenses/LICENSE +201 -0
- edview-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,2984 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Interactions module for EDView.
|
|
3
|
+
Contains the user actions and calculations of the tabs, and the application
|
|
4
|
+
controller.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import json
|
|
10
|
+
import shutil
|
|
11
|
+
import threading
|
|
12
|
+
import traceback
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from PySide6.QtCore import Qt, QTimer, QObject, QEvent
|
|
18
|
+
from PySide6.QtGui import QIcon, QCursor
|
|
19
|
+
from PySide6.QtWidgets import (QApplication, QMessageBox, QFileDialog,
|
|
20
|
+
QTreeWidgetItem, QMenu, QListView, QTreeView,
|
|
21
|
+
QAbstractItemView, QListWidgetItem)
|
|
22
|
+
|
|
23
|
+
import algodif.io.loadersaver as losa
|
|
24
|
+
import edview.lib.rendering as ren
|
|
25
|
+
import edview.lib.utilities as util
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BaseLogic:
|
|
29
|
+
"""Worker threads and remembered folders, shared by the tabs."""
|
|
30
|
+
|
|
31
|
+
def folder_key(self, purpose):
|
|
32
|
+
return f"{type(self).__name__}.{purpose}"
|
|
33
|
+
|
|
34
|
+
def last_folder(self, purpose):
|
|
35
|
+
return util.get_last_folder(self.folder_key(purpose))
|
|
36
|
+
|
|
37
|
+
def remember_folder(self, purpose, path):
|
|
38
|
+
util.set_last_folder(self.folder_key(purpose), path)
|
|
39
|
+
|
|
40
|
+
def is_busy(self):
|
|
41
|
+
return self.worker is not None and self.worker.is_alive()
|
|
42
|
+
|
|
43
|
+
def run_worker(self, task, on_done, title, message):
|
|
44
|
+
"""Run task(cancel_event) in a thread behind a modal dialog."""
|
|
45
|
+
if self.is_busy():
|
|
46
|
+
raise ValueError("A calculation is running!")
|
|
47
|
+
self.worker_result = None
|
|
48
|
+
self.worker_error = None
|
|
49
|
+
self.progress = message
|
|
50
|
+
self.cancel_event = threading.Event()
|
|
51
|
+
self.dialog = ren.WorkerDialog(self, title, message,
|
|
52
|
+
self.cancel_worker)
|
|
53
|
+
self.dialog.show()
|
|
54
|
+
|
|
55
|
+
def target():
|
|
56
|
+
try:
|
|
57
|
+
self.worker_result = task(self.cancel_event)
|
|
58
|
+
except Exception as error:
|
|
59
|
+
traceback.print_exc()
|
|
60
|
+
self.worker_error = error
|
|
61
|
+
|
|
62
|
+
self.worker = threading.Thread(target=target, daemon=True)
|
|
63
|
+
self.worker.start()
|
|
64
|
+
QTimer.singleShot(util.WORKER_POLL_MS,
|
|
65
|
+
lambda: self.poll_worker(on_done))
|
|
66
|
+
|
|
67
|
+
def set_progress(self, text):
|
|
68
|
+
self.progress = text
|
|
69
|
+
|
|
70
|
+
def cancel_worker(self):
|
|
71
|
+
if not self.is_busy():
|
|
72
|
+
return
|
|
73
|
+
self.cancel_event.set()
|
|
74
|
+
if self.dialog is not None:
|
|
75
|
+
self.dialog.btn_cancel.setEnabled(False)
|
|
76
|
+
self.progress = "Cancelling... The current step must finish first."
|
|
77
|
+
|
|
78
|
+
def poll_worker(self, on_done):
|
|
79
|
+
if self.worker.is_alive():
|
|
80
|
+
if self.dialog is not None:
|
|
81
|
+
self.dialog.set_message(self.progress)
|
|
82
|
+
self.set_status(self.progress)
|
|
83
|
+
QTimer.singleShot(util.WORKER_POLL_MS,
|
|
84
|
+
lambda: self.poll_worker(on_done))
|
|
85
|
+
return
|
|
86
|
+
if self.dialog is not None:
|
|
87
|
+
self.dialog.finished_task = True
|
|
88
|
+
self.dialog.accept()
|
|
89
|
+
self.dialog.deleteLater()
|
|
90
|
+
self.dialog = None
|
|
91
|
+
if self.closing:
|
|
92
|
+
return
|
|
93
|
+
if self.worker_error is not None:
|
|
94
|
+
self.set_status(f"Error: {self.worker_error}")
|
|
95
|
+
QMessageBox.critical(self, "Error", str(self.worker_error))
|
|
96
|
+
return
|
|
97
|
+
try:
|
|
98
|
+
on_done(self.worker_result)
|
|
99
|
+
except Exception as error:
|
|
100
|
+
traceback.print_exc()
|
|
101
|
+
self.set_status(f"Error: {error}")
|
|
102
|
+
QMessageBox.critical(self, "Error", str(error))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ---------------------------------------------------------------------------
|
|
106
|
+
# Data browser
|
|
107
|
+
# ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
class BrowserTab(BaseLogic, ren.BrowserTabUI):
|
|
110
|
+
"""Browse folders, preview files and send them to the other tabs."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, base_folder=None):
|
|
113
|
+
super().__init__()
|
|
114
|
+
self.selected_folder = ""
|
|
115
|
+
self.preview_file = ""
|
|
116
|
+
# "images": slider over the images of the folder; "hdf": over the
|
|
117
|
+
# slices of a dataset
|
|
118
|
+
self.preview_mode = None
|
|
119
|
+
self.folder_images = []
|
|
120
|
+
self.hdf_shapes = {}
|
|
121
|
+
# Set by the controller: callback(paths) adding inputs to the
|
|
122
|
+
# correction tab
|
|
123
|
+
self.add_to_correction = None
|
|
124
|
+
# Set by the controller: min HDF ndim of each viewer by name;
|
|
125
|
+
# view_in(name, path) and metadata_to(name, path) switch to it
|
|
126
|
+
self.viewer_ndims = {}
|
|
127
|
+
self.view_in = None
|
|
128
|
+
self.metadata_to = None
|
|
129
|
+
# Set by the controller: name of the viewer of several scans, and
|
|
130
|
+
# view_scans(paths) showing them in it
|
|
131
|
+
self.scans_viewer = ""
|
|
132
|
+
self.view_scans = None
|
|
133
|
+
config = util.load_config() or {}
|
|
134
|
+
base_folder = base_folder or config.get("base_folder") or \
|
|
135
|
+
os.path.expanduser("~")
|
|
136
|
+
if not os.path.isdir(base_folder):
|
|
137
|
+
base_folder = os.path.expanduser("~")
|
|
138
|
+
self.set_base_folder(base_folder)
|
|
139
|
+
|
|
140
|
+
def set_base_folder(self, folder):
|
|
141
|
+
self.base_folder = os.path.abspath(folder)
|
|
142
|
+
self.lbl_base_folder.setText(self.base_folder)
|
|
143
|
+
self.selected_folder = self.base_folder
|
|
144
|
+
self.refresh_tree()
|
|
145
|
+
|
|
146
|
+
def select_base_folder(self):
|
|
147
|
+
folder = QFileDialog.getExistingDirectory(self, "Select base folder",
|
|
148
|
+
self.base_folder)
|
|
149
|
+
if folder:
|
|
150
|
+
self.set_base_folder(folder)
|
|
151
|
+
util.update_config(base_folder=self.base_folder)
|
|
152
|
+
|
|
153
|
+
def refresh_tree(self):
|
|
154
|
+
self.tree.clear()
|
|
155
|
+
item = QTreeWidgetItem(self.tree)
|
|
156
|
+
item.setText(0, self.base_folder)
|
|
157
|
+
item.setData(0, Qt.UserRole, self.base_folder)
|
|
158
|
+
QTreeWidgetItem(item).setText(0, "")
|
|
159
|
+
item.setExpanded(True)
|
|
160
|
+
self.list_files.clear()
|
|
161
|
+
self.show_preview_page("info")
|
|
162
|
+
|
|
163
|
+
def on_tree_expand(self, item):
|
|
164
|
+
path = item.data(0, Qt.UserRole)
|
|
165
|
+
if not path or not os.path.isdir(path):
|
|
166
|
+
return
|
|
167
|
+
item.takeChildren()
|
|
168
|
+
try:
|
|
169
|
+
subfolders = sorted((d for d in os.listdir(path)
|
|
170
|
+
if os.path.isdir(os.path.join(path, d))),
|
|
171
|
+
key=util.natural_key)
|
|
172
|
+
except OSError as error:
|
|
173
|
+
self.set_status(f"Error reading folder: {error}")
|
|
174
|
+
return
|
|
175
|
+
for sub in subfolders:
|
|
176
|
+
child = QTreeWidgetItem(item)
|
|
177
|
+
child.setText(0, sub)
|
|
178
|
+
child_path = os.path.join(path, sub)
|
|
179
|
+
child.setData(0, Qt.UserRole, child_path)
|
|
180
|
+
try:
|
|
181
|
+
has_kids = any(e.is_dir() for e in os.scandir(child_path))
|
|
182
|
+
except OSError:
|
|
183
|
+
has_kids = False
|
|
184
|
+
if has_kids:
|
|
185
|
+
QTreeWidgetItem(child).setText(0, "")
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def current_selected(view):
|
|
189
|
+
"""The current (last clicked) item if selected, else the first
|
|
190
|
+
selected item, or None."""
|
|
191
|
+
item = view.currentItem()
|
|
192
|
+
if item is not None and item.isSelected():
|
|
193
|
+
return item
|
|
194
|
+
items = view.selectedItems()
|
|
195
|
+
return items[0] if items else None
|
|
196
|
+
|
|
197
|
+
def on_folder_select(self):
|
|
198
|
+
item = self.current_selected(self.tree)
|
|
199
|
+
if item is None:
|
|
200
|
+
return
|
|
201
|
+
path = item.data(0, Qt.UserRole)
|
|
202
|
+
if not path or not os.path.isdir(path) or \
|
|
203
|
+
path == self.selected_folder and self.list_files.count():
|
|
204
|
+
return
|
|
205
|
+
self.selected_folder = path
|
|
206
|
+
self.preview_file = ""
|
|
207
|
+
self.preview_mode = None
|
|
208
|
+
self.set_status(path)
|
|
209
|
+
self.list_files.clear()
|
|
210
|
+
try:
|
|
211
|
+
files = sorted((f.name for f in os.scandir(path) if f.is_file()),
|
|
212
|
+
key=util.natural_key)
|
|
213
|
+
except OSError as error:
|
|
214
|
+
self.set_status(f"Error reading folder: {error}")
|
|
215
|
+
return
|
|
216
|
+
self.list_files.addItems(files)
|
|
217
|
+
self.show_preview_page("info")
|
|
218
|
+
self.lbl_preview_info.setText(f"{len(files)} file(s) in\n{path}")
|
|
219
|
+
|
|
220
|
+
def selected_file(self):
|
|
221
|
+
item = self.current_selected(self.list_files)
|
|
222
|
+
if item is None:
|
|
223
|
+
return ""
|
|
224
|
+
return os.path.join(self.selected_folder, item.text())
|
|
225
|
+
|
|
226
|
+
def on_file_select_change(self):
|
|
227
|
+
QTimer.singleShot(util.FILE_SELECT_DEBOUNCE_MS, self.preview_selected)
|
|
228
|
+
|
|
229
|
+
def preview_selected(self):
|
|
230
|
+
path = self.selected_file()
|
|
231
|
+
if not path or path == self.preview_file:
|
|
232
|
+
return
|
|
233
|
+
self.preview_file = path
|
|
234
|
+
self.set_status(path)
|
|
235
|
+
ext = Path(path).suffix.lower()
|
|
236
|
+
try:
|
|
237
|
+
if ext in util.IMAGE_EXT:
|
|
238
|
+
self.preview_image(path)
|
|
239
|
+
elif ext in util.HDF_EXT:
|
|
240
|
+
self.preview_hdf(path)
|
|
241
|
+
elif ext in util.TEXT_EXT or util.is_text_file(path):
|
|
242
|
+
self.preview_text(path)
|
|
243
|
+
else:
|
|
244
|
+
self.show_preview_page("info")
|
|
245
|
+
size = util.format_bytes(os.path.getsize(path))
|
|
246
|
+
self.lbl_preview_info.setText(f"No preview for this file "
|
|
247
|
+
f"type.\n{path}\n{size}")
|
|
248
|
+
except Exception as error:
|
|
249
|
+
self.preview_mode = None
|
|
250
|
+
self.show_preview_page("info")
|
|
251
|
+
self.lbl_preview_info.setText(f"Can't preview the file:\n"
|
|
252
|
+
f"{error}")
|
|
253
|
+
|
|
254
|
+
def show_preview(self, mat, title):
|
|
255
|
+
"""Show a 2D image (zoom out only if its shape changed) or a 1D
|
|
256
|
+
line."""
|
|
257
|
+
if mat.ndim == 1:
|
|
258
|
+
self.show_plot_page(True)
|
|
259
|
+
plot = self.p_preview_line
|
|
260
|
+
plot.clear()
|
|
261
|
+
plot.plot(np.arange(len(mat)), mat,
|
|
262
|
+
pen=ren.pg.mkPen(util.COLORS["blue"], width=1.2))
|
|
263
|
+
plot.enableAutoRange()
|
|
264
|
+
self.set_title(plot, title)
|
|
265
|
+
return
|
|
266
|
+
self.show_plot_page(False)
|
|
267
|
+
old = getattr(self.p_preview.image_item, "raw_data", None)
|
|
268
|
+
auto_range = old is None or np.shape(old) != mat.shape
|
|
269
|
+
self.show_image(self.p_preview, mat, auto_range=auto_range)
|
|
270
|
+
self.set_title(self.p_preview, title)
|
|
271
|
+
|
|
272
|
+
def preview_image(self, path):
|
|
273
|
+
"""Show an image file, with a slider over the images of its
|
|
274
|
+
folder."""
|
|
275
|
+
self.folder_images = [
|
|
276
|
+
(row, os.path.join(self.selected_folder,
|
|
277
|
+
self.list_files.item(row).text()))
|
|
278
|
+
for row in range(self.list_files.count())
|
|
279
|
+
if self.list_files.item(row).text().lower().endswith(
|
|
280
|
+
util.IMAGE_EXT)]
|
|
281
|
+
paths = [p for _, p in self.folder_images]
|
|
282
|
+
index = paths.index(path) if path in paths else 0
|
|
283
|
+
self.preview_mode = "images"
|
|
284
|
+
self.set_hdf_controls_visible(False)
|
|
285
|
+
self.show_preview_page("image")
|
|
286
|
+
self.setup_slice_row(0, "Image in folder", len(paths), index)
|
|
287
|
+
self.hide_slice_rows(1)
|
|
288
|
+
self.show_folder_image(index)
|
|
289
|
+
|
|
290
|
+
def show_folder_image(self, index):
|
|
291
|
+
path = self.folder_images[index][1]
|
|
292
|
+
mat = util.load_preview_image(path)
|
|
293
|
+
self.show_preview(mat, f"{Path(path).name} | Image {index + 1}/"
|
|
294
|
+
f"{len(self.folder_images)} | (height, "
|
|
295
|
+
f"width) = {mat.shape}")
|
|
296
|
+
|
|
297
|
+
def update_preview_slice(self):
|
|
298
|
+
try:
|
|
299
|
+
if self.preview_mode == "images":
|
|
300
|
+
index = self.slice_rows[0][3].value()
|
|
301
|
+
row, path = self.folder_images[index]
|
|
302
|
+
# Select the file in the list without previewing it again
|
|
303
|
+
self.preview_file = path
|
|
304
|
+
self.list_files.blockSignals(True)
|
|
305
|
+
self.list_files.setCurrentRow(row)
|
|
306
|
+
self.list_files.blockSignals(False)
|
|
307
|
+
self.list_files.scrollToItem(self.list_files.item(row))
|
|
308
|
+
self.set_status(path)
|
|
309
|
+
self.show_folder_image(index)
|
|
310
|
+
elif self.preview_mode == "hdf":
|
|
311
|
+
self.show_hdf_slice()
|
|
312
|
+
except Exception as error:
|
|
313
|
+
traceback.print_exc()
|
|
314
|
+
self.set_status(f"Can't preview: {error}")
|
|
315
|
+
|
|
316
|
+
def preview_text(self, path):
|
|
317
|
+
max_bytes = 5 * 1024 * 1024
|
|
318
|
+
if os.path.getsize(path) > max_bytes:
|
|
319
|
+
raise ValueError("The file is larger than 5 MB.")
|
|
320
|
+
with open(path, "r", encoding="utf-8", errors="replace") as file:
|
|
321
|
+
text = file.read()
|
|
322
|
+
if path.lower().endswith(".json"):
|
|
323
|
+
try:
|
|
324
|
+
text = json.dumps(json.loads(text), indent=4)
|
|
325
|
+
except ValueError:
|
|
326
|
+
pass
|
|
327
|
+
self.text_preview.setPlainText(text)
|
|
328
|
+
self.show_preview_page("text")
|
|
329
|
+
|
|
330
|
+
def preview_hdf(self, path):
|
|
331
|
+
self.hdf_shapes = dict(util.hdf_array_keys(path, 1))
|
|
332
|
+
self.preview_mode = "hdf"
|
|
333
|
+
self.combo_preview_key.blockSignals(True)
|
|
334
|
+
self.combo_preview_key.clear()
|
|
335
|
+
for key, shape in self.hdf_shapes.items():
|
|
336
|
+
self.combo_preview_key.addItem(f"{key} {shape}", key)
|
|
337
|
+
self.combo_preview_key.blockSignals(False)
|
|
338
|
+
self.set_hdf_controls_visible(True)
|
|
339
|
+
self.show_preview_page("image")
|
|
340
|
+
if not self.hdf_shapes:
|
|
341
|
+
self.hide_slice_rows()
|
|
342
|
+
self.show_preview_page("info")
|
|
343
|
+
self.lbl_preview_info.setText(
|
|
344
|
+
f"No numeric array in\n{path}\nDouble-click the file to "
|
|
345
|
+
f"show its content.")
|
|
346
|
+
return
|
|
347
|
+
self.on_preview_key_changed()
|
|
348
|
+
|
|
349
|
+
def preview_key(self):
|
|
350
|
+
return self.combo_preview_key.currentData() or ""
|
|
351
|
+
|
|
352
|
+
def num_slice_axes(self):
|
|
353
|
+
"""Number of sliced axes: 1 for 3D datasets, 2 for 4D or more."""
|
|
354
|
+
shape = self.hdf_shapes.get(self.preview_key(), ())
|
|
355
|
+
return min(max(len(shape) - 2, 0), len(self.slice_rows))
|
|
356
|
+
|
|
357
|
+
def on_preview_key_changed(self):
|
|
358
|
+
shape = self.hdf_shapes.get(self.preview_key())
|
|
359
|
+
if self.preview_mode != "hdf" or shape is None:
|
|
360
|
+
return
|
|
361
|
+
num_axes = self.num_slice_axes()
|
|
362
|
+
for num, (_, _, combo, _) in enumerate(self.slice_rows):
|
|
363
|
+
combo.blockSignals(True)
|
|
364
|
+
combo.clear()
|
|
365
|
+
if num < num_axes:
|
|
366
|
+
combo.addItems([str(i) for i in range(len(shape))])
|
|
367
|
+
combo.setCurrentIndex(num)
|
|
368
|
+
combo.blockSignals(False)
|
|
369
|
+
for num in range(num_axes):
|
|
370
|
+
self.setup_axis_slider(num)
|
|
371
|
+
self.hide_slice_rows(num_axes)
|
|
372
|
+
self.try_show_hdf_slice()
|
|
373
|
+
|
|
374
|
+
def on_preview_axis_changed(self, num):
|
|
375
|
+
if self.preview_mode != "hdf" or num >= self.num_slice_axes():
|
|
376
|
+
return
|
|
377
|
+
combos = [row[2] for row in self.slice_rows]
|
|
378
|
+
axis = combos[num].currentIndex()
|
|
379
|
+
if self.num_slice_axes() == 2:
|
|
380
|
+
other = combos[1 - num]
|
|
381
|
+
if other.currentIndex() == axis:
|
|
382
|
+
# The two sliced axes must differ
|
|
383
|
+
free = next(i for i in range(other.count()) if i != axis)
|
|
384
|
+
other.blockSignals(True)
|
|
385
|
+
other.setCurrentIndex(free)
|
|
386
|
+
other.blockSignals(False)
|
|
387
|
+
self.setup_axis_slider(1 - num)
|
|
388
|
+
self.setup_axis_slider(num)
|
|
389
|
+
self.try_show_hdf_slice()
|
|
390
|
+
|
|
391
|
+
def setup_axis_slider(self, num):
|
|
392
|
+
shape = self.hdf_shapes[self.preview_key()]
|
|
393
|
+
axis = self.slice_rows[num][2].currentIndex()
|
|
394
|
+
self.setup_slice_row(num, "Index", shape[axis], show_axis=True)
|
|
395
|
+
|
|
396
|
+
def try_show_hdf_slice(self):
|
|
397
|
+
try:
|
|
398
|
+
self.show_hdf_slice()
|
|
399
|
+
except Exception as error:
|
|
400
|
+
traceback.print_exc()
|
|
401
|
+
self.set_status(f"Can't preview '{self.preview_key()}': "
|
|
402
|
+
f"{error}")
|
|
403
|
+
|
|
404
|
+
def show_hdf_slice(self):
|
|
405
|
+
key = self.preview_key()
|
|
406
|
+
shape = self.hdf_shapes[key]
|
|
407
|
+
rows = self.slice_rows[:self.num_slice_axes()]
|
|
408
|
+
axes = [combo.currentIndex() for _, _, combo, _ in rows]
|
|
409
|
+
indices = [slider.value() for _, _, _, slider in rows]
|
|
410
|
+
mat = util.load_hdf_slice(self.preview_file, key, axes, indices)
|
|
411
|
+
title = f"{key}: {shape}"
|
|
412
|
+
for axis, index in zip(axes, indices):
|
|
413
|
+
title += f" | Axis {axis}: {index}/{shape[axis] - 1}"
|
|
414
|
+
if len(shape) > 4:
|
|
415
|
+
title += " (other leading axes at 0)"
|
|
416
|
+
self.show_preview(mat, title)
|
|
417
|
+
|
|
418
|
+
def on_file_double_click(self, item):
|
|
419
|
+
path = os.path.join(self.selected_folder, item.text())
|
|
420
|
+
if path.lower().endswith(util.HDF_EXT):
|
|
421
|
+
self.show_hdf_content(path)
|
|
422
|
+
|
|
423
|
+
@ren.safe_call
|
|
424
|
+
def show_hdf_content(self, path=None):
|
|
425
|
+
"""Window with the groups, datasets and attributes of an HDF
|
|
426
|
+
file."""
|
|
427
|
+
path = path or self.preview_file
|
|
428
|
+
if not path.lower().endswith(util.HDF_EXT):
|
|
429
|
+
return
|
|
430
|
+
window = ren.HdfContentWindow(self, path, util.hdf_nodes(path))
|
|
431
|
+
window.datasetActivated.connect(self.preview_hdf_dataset)
|
|
432
|
+
window.show()
|
|
433
|
+
|
|
434
|
+
def preview_hdf_dataset(self, path, key):
|
|
435
|
+
"""Preview a dataset double-clicked in an HDF content window."""
|
|
436
|
+
try:
|
|
437
|
+
if path != self.preview_file or self.preview_mode != "hdf":
|
|
438
|
+
self.preview_file = path
|
|
439
|
+
self.preview_hdf(path)
|
|
440
|
+
index = self.combo_preview_key.findData(key)
|
|
441
|
+
if index < 0:
|
|
442
|
+
self.set_status(f"'{key}' is not a numeric array: no "
|
|
443
|
+
f"preview.")
|
|
444
|
+
return
|
|
445
|
+
self.combo_preview_key.setCurrentIndex(index)
|
|
446
|
+
self.set_status(f"{path} :: {key}")
|
|
447
|
+
except Exception as error:
|
|
448
|
+
traceback.print_exc()
|
|
449
|
+
self.set_status(f"Can't preview '{key}': {error}")
|
|
450
|
+
|
|
451
|
+
@staticmethod
|
|
452
|
+
def is_correction_folder(path):
|
|
453
|
+
"""True if a folder (or its 'tifs' sub-folder) has several tif or
|
|
454
|
+
dat files to correct."""
|
|
455
|
+
tifs = os.path.join(path, "tifs")
|
|
456
|
+
folder = tifs if os.path.isdir(tifs) else path
|
|
457
|
+
return len(util.find_files(folder, util.TIF_EXT + (".dat",))) >= 2
|
|
458
|
+
|
|
459
|
+
def send_to_correction(self, path):
|
|
460
|
+
if os.path.isdir(path) and not self.is_correction_folder(path):
|
|
461
|
+
QMessageBox.information(
|
|
462
|
+
self, "Can't add the folder",
|
|
463
|
+
f"The folder must contain multiple tif or dat files:"
|
|
464
|
+
f"\n{path}")
|
|
465
|
+
return
|
|
466
|
+
self.add_to_correction([path])
|
|
467
|
+
self.set_status(f"Added to the Data correction input: {path}")
|
|
468
|
+
|
|
469
|
+
def multi_selection_menu(self, paths, kind):
|
|
470
|
+
"""Menu for several selected folders or files (kind): add them to
|
|
471
|
+
the Data correction input, or view them in the Multiple-scans
|
|
472
|
+
viewer. Unsuitable ones are skipped."""
|
|
473
|
+
if kind == "folder":
|
|
474
|
+
to_correct = [p for p in paths if self.is_correction_folder(p)]
|
|
475
|
+
scans = [p for p in paths if util.find_files(p)]
|
|
476
|
+
else:
|
|
477
|
+
to_correct = [p for p in paths if p.lower().endswith(
|
|
478
|
+
util.TIF_EXT + util.HDF_EXT + (".dat",))]
|
|
479
|
+
scans = [p for p in paths if p.lower().endswith(util.HDF_EXT)
|
|
480
|
+
and self.scans_viewer in self.viewers_for(p)]
|
|
481
|
+
menu = QMenu(self)
|
|
482
|
+
act_add = act_view = None
|
|
483
|
+
if self.add_to_correction is not None and to_correct:
|
|
484
|
+
act_add = menu.addAction(f"Add {len(to_correct)} {kind}(s) to "
|
|
485
|
+
f"Data correction input")
|
|
486
|
+
if self.view_scans is not None and scans:
|
|
487
|
+
act_view = menu.addAction(f"View {len(scans)} scan(s) in "
|
|
488
|
+
f"{self.scans_viewer}")
|
|
489
|
+
if menu.isEmpty():
|
|
490
|
+
self.set_status(f"The selected {kind}s can't be added to the "
|
|
491
|
+
f"Data correction input or viewed as scans.")
|
|
492
|
+
return
|
|
493
|
+
chosen = menu.exec(QCursor.pos())
|
|
494
|
+
if chosen is None:
|
|
495
|
+
return
|
|
496
|
+
if chosen == act_add:
|
|
497
|
+
kept, what = to_correct, "the Data correction input"
|
|
498
|
+
if kind == "folder":
|
|
499
|
+
what += " (needs multiple tif or dat files)"
|
|
500
|
+
self.add_to_correction(to_correct)
|
|
501
|
+
self.set_status(f"Added {len(to_correct)} {kind}(s) to the Data "
|
|
502
|
+
f"correction input.")
|
|
503
|
+
elif chosen == act_view:
|
|
504
|
+
kept, what = scans, f"the {self.scans_viewer}"
|
|
505
|
+
self.view_scans(scans)
|
|
506
|
+
else:
|
|
507
|
+
return
|
|
508
|
+
skipped = [os.path.basename(p) for p in paths if p not in kept]
|
|
509
|
+
if skipped:
|
|
510
|
+
QMessageBox.information(
|
|
511
|
+
self, "Skipped", f"Not suitable for {what}:\n"
|
|
512
|
+
+ "\n".join(skipped[:20])
|
|
513
|
+
+ ("\n..." if len(skipped) > 20 else ""))
|
|
514
|
+
|
|
515
|
+
def viewers_for(self, path, folder_only=False):
|
|
516
|
+
"""Names of the viewers able to show a folder of tif files, a tif
|
|
517
|
+
file (its folder) or an HDF file (by its dataset dimensions)."""
|
|
518
|
+
if self.view_in is None:
|
|
519
|
+
return []
|
|
520
|
+
if os.path.isdir(path):
|
|
521
|
+
return self.tif_viewers(path) if util.find_files(path) else []
|
|
522
|
+
if folder_only:
|
|
523
|
+
return []
|
|
524
|
+
lower = path.lower()
|
|
525
|
+
if lower.endswith(util.TIF_EXT):
|
|
526
|
+
return self.tif_viewers(os.path.dirname(path))
|
|
527
|
+
if lower.endswith(util.HDF_EXT):
|
|
528
|
+
try:
|
|
529
|
+
return util.viewers_for_hdf(path, self.viewer_ndims)
|
|
530
|
+
except OSError:
|
|
531
|
+
return []
|
|
532
|
+
return []
|
|
533
|
+
|
|
534
|
+
@staticmethod
|
|
535
|
+
def tif_viewers(folder):
|
|
536
|
+
"""Viewers of a folder of tif files; the 2D-scan viewer only for
|
|
537
|
+
files named '..._<row>_<col>.tif'."""
|
|
538
|
+
is_2d = util.is_2d_scan_folder(folder)
|
|
539
|
+
return [name for name in util.TIF_VIEWERS
|
|
540
|
+
if is_2d or name not in util.TIF_2D_VIEWERS]
|
|
541
|
+
|
|
542
|
+
def metadata_viewers(self, path):
|
|
543
|
+
if self.metadata_to is None or not os.path.isfile(path) or \
|
|
544
|
+
not path.lower().endswith((".json",) + util.HDF_EXT):
|
|
545
|
+
return []
|
|
546
|
+
return list(self.viewer_ndims)
|
|
547
|
+
|
|
548
|
+
@staticmethod
|
|
549
|
+
def add_viewer_menu(menu, title, names):
|
|
550
|
+
"""Submenu of viewer names; {action: name}."""
|
|
551
|
+
if not names:
|
|
552
|
+
return {}
|
|
553
|
+
sub = menu.addMenu(title)
|
|
554
|
+
return {sub.addAction(name): name for name in names}
|
|
555
|
+
|
|
556
|
+
def on_tree_context_menu(self, pos):
|
|
557
|
+
item = self.tree.itemAt(pos)
|
|
558
|
+
selected = self.tree.selectedItems()
|
|
559
|
+
if item is not None and item.isSelected() and len(selected) > 1:
|
|
560
|
+
paths = [i.data(0, Qt.UserRole) for i in selected]
|
|
561
|
+
paths = sorted((p for p in paths if p and os.path.isdir(p)),
|
|
562
|
+
key=util.natural_key)
|
|
563
|
+
self.multi_selection_menu(paths, "folder")
|
|
564
|
+
return
|
|
565
|
+
path = item.data(0, Qt.UserRole) if item else None
|
|
566
|
+
if not path or not os.path.isdir(path):
|
|
567
|
+
return
|
|
568
|
+
try:
|
|
569
|
+
with os.scandir(path) as entries:
|
|
570
|
+
empty = not any(True for _ in entries)
|
|
571
|
+
except OSError:
|
|
572
|
+
empty = True
|
|
573
|
+
menu = QMenu(self)
|
|
574
|
+
act_add = act_delete = None
|
|
575
|
+
if self.add_to_correction is not None and not empty:
|
|
576
|
+
act_add = menu.addAction("Add folder to Data correction input")
|
|
577
|
+
views = self.add_viewer_menu(menu, "View in",
|
|
578
|
+
self.viewers_for(path, True))
|
|
579
|
+
if os.path.abspath(path) != self.base_folder:
|
|
580
|
+
if not menu.isEmpty():
|
|
581
|
+
menu.addSeparator()
|
|
582
|
+
act_delete = menu.addAction("Delete folder")
|
|
583
|
+
if menu.isEmpty():
|
|
584
|
+
return
|
|
585
|
+
chosen = menu.exec(QCursor.pos())
|
|
586
|
+
if chosen is None:
|
|
587
|
+
return
|
|
588
|
+
if chosen == act_add:
|
|
589
|
+
self.send_to_correction(path)
|
|
590
|
+
elif chosen in views:
|
|
591
|
+
self.view_in(views[chosen], path)
|
|
592
|
+
elif chosen == act_delete:
|
|
593
|
+
self.delete_folder(item, path)
|
|
594
|
+
|
|
595
|
+
def delete_folder(self, item, path):
|
|
596
|
+
try:
|
|
597
|
+
num = sum(len(files) for _, _, files in os.walk(path))
|
|
598
|
+
except OSError:
|
|
599
|
+
num = 0
|
|
600
|
+
answer = QMessageBox.warning(
|
|
601
|
+
self, "Delete folder",
|
|
602
|
+
f"Permanently delete this folder and its content ({num} "
|
|
603
|
+
f"file(s))?\n{path}\n\nThis can't be undone.",
|
|
604
|
+
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
|
605
|
+
if answer != QMessageBox.Yes:
|
|
606
|
+
return
|
|
607
|
+
try:
|
|
608
|
+
shutil.rmtree(path)
|
|
609
|
+
except OSError as error:
|
|
610
|
+
QMessageBox.critical(self, "Error", f"Can't delete the folder:"
|
|
611
|
+
f"\n{error}")
|
|
612
|
+
return
|
|
613
|
+
deleted = os.path.abspath(path)
|
|
614
|
+
parent = item.parent()
|
|
615
|
+
if parent is not None:
|
|
616
|
+
parent.removeChild(item)
|
|
617
|
+
selected = os.path.abspath(self.selected_folder)
|
|
618
|
+
if selected == deleted or selected.startswith(deleted + os.sep):
|
|
619
|
+
self.list_files.clear()
|
|
620
|
+
self.preview_file = ""
|
|
621
|
+
self.preview_mode = None
|
|
622
|
+
self.show_preview_page("info")
|
|
623
|
+
self.lbl_preview_info.setText("Folder deleted.")
|
|
624
|
+
if parent is not None:
|
|
625
|
+
self.tree.setCurrentItem(parent)
|
|
626
|
+
self.set_status(f"Deleted: {path}")
|
|
627
|
+
|
|
628
|
+
def delete_file(self, item, path):
|
|
629
|
+
answer = QMessageBox.warning(
|
|
630
|
+
self, "Delete file",
|
|
631
|
+
f"Permanently delete this file?\n{path}\n\nThis can't be "
|
|
632
|
+
f"undone.", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
|
633
|
+
if answer != QMessageBox.Yes:
|
|
634
|
+
return
|
|
635
|
+
try:
|
|
636
|
+
os.remove(path)
|
|
637
|
+
except OSError as error:
|
|
638
|
+
QMessageBox.critical(self, "Error", f"Can't delete the file:"
|
|
639
|
+
f"\n{error}")
|
|
640
|
+
return
|
|
641
|
+
self.list_files.takeItem(self.list_files.row(item))
|
|
642
|
+
if path == self.preview_file:
|
|
643
|
+
self.preview_file = ""
|
|
644
|
+
self.preview_mode = None
|
|
645
|
+
self.show_preview_page("info")
|
|
646
|
+
self.lbl_preview_info.setText("File deleted.")
|
|
647
|
+
self.set_status(f"Deleted: {path}")
|
|
648
|
+
|
|
649
|
+
def on_file_context_menu(self, pos):
|
|
650
|
+
item = self.list_files.itemAt(pos)
|
|
651
|
+
selected = self.list_files.selectedItems()
|
|
652
|
+
if item is not None and item.isSelected() and len(selected) > 1:
|
|
653
|
+
paths = sorted((os.path.join(self.selected_folder, i.text())
|
|
654
|
+
for i in selected), key=util.natural_key)
|
|
655
|
+
self.multi_selection_menu(paths, "file")
|
|
656
|
+
return
|
|
657
|
+
menu = QMenu(self)
|
|
658
|
+
path = os.path.join(self.selected_folder, item.text()) if item \
|
|
659
|
+
else self.selected_folder
|
|
660
|
+
if item:
|
|
661
|
+
try:
|
|
662
|
+
stat = os.stat(path)
|
|
663
|
+
# Creation time when the OS records it, else modification
|
|
664
|
+
created = getattr(stat, "st_birthtime", None)
|
|
665
|
+
label = "Created" if created else "Modified"
|
|
666
|
+
date = datetime.fromtimestamp(created or stat.st_mtime)
|
|
667
|
+
info = [f"Size: {util.format_bytes(stat.st_size)}",
|
|
668
|
+
f"{label}: {date:%Y-%m-%d %H:%M:%S}"]
|
|
669
|
+
except OSError as error:
|
|
670
|
+
info = [f"Can't read file info: {error}"]
|
|
671
|
+
for text in info:
|
|
672
|
+
menu.addAction(text).setEnabled(False)
|
|
673
|
+
menu.addSeparator()
|
|
674
|
+
act_add = None
|
|
675
|
+
if self.add_to_correction is not None:
|
|
676
|
+
if item and path.lower().endswith(util.TIF_EXT + util.HDF_EXT
|
|
677
|
+
+ (".dat",)):
|
|
678
|
+
act_add = menu.addAction("Add file to Data correction "
|
|
679
|
+
"input")
|
|
680
|
+
elif not item and self.list_files.count():
|
|
681
|
+
act_add = menu.addAction("Add folder to Data correction "
|
|
682
|
+
"input")
|
|
683
|
+
views = self.add_viewer_menu(menu, "View in",
|
|
684
|
+
self.viewers_for(path))
|
|
685
|
+
metas = self.add_viewer_menu(menu, "Use as metadata in",
|
|
686
|
+
self.metadata_viewers(path)
|
|
687
|
+
if item else [])
|
|
688
|
+
if act_add is not None or views or metas:
|
|
689
|
+
menu.addSeparator()
|
|
690
|
+
act_copy = menu.addAction("Copy full path")
|
|
691
|
+
act_folder = menu.addAction("Copy folder path")
|
|
692
|
+
act_delete = None
|
|
693
|
+
if item:
|
|
694
|
+
menu.addSeparator()
|
|
695
|
+
act_delete = menu.addAction("Delete file")
|
|
696
|
+
chosen = menu.exec(QCursor.pos())
|
|
697
|
+
if chosen is None:
|
|
698
|
+
return
|
|
699
|
+
if chosen == act_add:
|
|
700
|
+
self.send_to_correction(path)
|
|
701
|
+
elif chosen in views:
|
|
702
|
+
self.view_in(views[chosen], path)
|
|
703
|
+
elif chosen in metas:
|
|
704
|
+
self.metadata_to(metas[chosen], path)
|
|
705
|
+
elif chosen == act_delete:
|
|
706
|
+
self.delete_file(item, path)
|
|
707
|
+
elif chosen == act_copy:
|
|
708
|
+
QApplication.clipboard().setText(os.path.normpath(path))
|
|
709
|
+
elif chosen == act_folder:
|
|
710
|
+
QApplication.clipboard().setText(
|
|
711
|
+
os.path.normpath(self.selected_folder))
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
# ---------------------------------------------------------------------------
|
|
715
|
+
# Data correction and conversion
|
|
716
|
+
# ---------------------------------------------------------------------------
|
|
717
|
+
|
|
718
|
+
def select_folders(parent, title, start):
|
|
719
|
+
"""Folder dialog allowing several folders (Ctrl/Shift-click)."""
|
|
720
|
+
dialog = QFileDialog(parent, title, start)
|
|
721
|
+
dialog.setFileMode(QFileDialog.Directory)
|
|
722
|
+
dialog.setOption(QFileDialog.ShowDirsOnly, True)
|
|
723
|
+
# Native dialogs can't select several folders
|
|
724
|
+
dialog.setOption(QFileDialog.DontUseNativeDialog, True)
|
|
725
|
+
for view in (dialog.findChild(QListView, "listView"),
|
|
726
|
+
dialog.findChild(QTreeView, "treeView")):
|
|
727
|
+
if view is not None:
|
|
728
|
+
view.setSelectionMode(QAbstractItemView.ExtendedSelection)
|
|
729
|
+
if not dialog.exec():
|
|
730
|
+
return []
|
|
731
|
+
return [f for f in dialog.selectedFiles() if os.path.isdir(f)]
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def scan_name_of(path):
|
|
735
|
+
"""Name of a scan from a folder or file path ('tifs' folders skipped)."""
|
|
736
|
+
path = Path(path)
|
|
737
|
+
folder = path if path.is_dir() else path.parent
|
|
738
|
+
if path.is_file() and path.suffix.lower() in util.HDF_EXT:
|
|
739
|
+
return path.stem
|
|
740
|
+
if folder.name.lower() == "tifs":
|
|
741
|
+
folder = folder.parent
|
|
742
|
+
return folder.name
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
class CorrectionTab(BaseLogic, ren.CorrectionTabUI):
|
|
746
|
+
"""Correct raw scans with calibration coefficients; convert data."""
|
|
747
|
+
|
|
748
|
+
def __init__(self):
|
|
749
|
+
super().__init__()
|
|
750
|
+
self.scans = []
|
|
751
|
+
self.plot_correction()
|
|
752
|
+
|
|
753
|
+
# Input
|
|
754
|
+
def update_hdf_keys(self, combo, path, min_ndim=2):
|
|
755
|
+
try:
|
|
756
|
+
keys = [k for k, _ in util.hdf_array_keys(path, min_ndim)]
|
|
757
|
+
except OSError:
|
|
758
|
+
return
|
|
759
|
+
current = combo.currentText()
|
|
760
|
+
combo.clear()
|
|
761
|
+
combo.addItems(keys)
|
|
762
|
+
if current in keys:
|
|
763
|
+
combo.setCurrentText(current)
|
|
764
|
+
|
|
765
|
+
@ren.safe_call
|
|
766
|
+
def browse_files(self):
|
|
767
|
+
paths, _ = QFileDialog.getOpenFileNames(
|
|
768
|
+
self, "Select raw data file(s)", self.last_folder("input"),
|
|
769
|
+
"Data (*.tif *.tiff *.hdf *.h5 *.hdf5 *.nxs *.dat);;"
|
|
770
|
+
"All files (*.*)")
|
|
771
|
+
if not paths:
|
|
772
|
+
return
|
|
773
|
+
self.remember_folder("input", paths[0])
|
|
774
|
+
self.add_inputs(paths)
|
|
775
|
+
|
|
776
|
+
@ren.safe_call
|
|
777
|
+
def browse_folders(self):
|
|
778
|
+
folders = select_folders(self, "Select scan folder(s)",
|
|
779
|
+
self.last_folder("input"))
|
|
780
|
+
if folders:
|
|
781
|
+
# Remember the parent, to select sibling scans next time
|
|
782
|
+
self.remember_folder("input", os.path.dirname(folders[0]))
|
|
783
|
+
self.add_inputs(folders)
|
|
784
|
+
|
|
785
|
+
def input_entries(self):
|
|
786
|
+
return [self.list_input.item(i).data(Qt.UserRole)
|
|
787
|
+
for i in range(self.list_input.count())]
|
|
788
|
+
|
|
789
|
+
@ren.safe_call
|
|
790
|
+
def add_inputs(self, paths):
|
|
791
|
+
"""Add rows: each folder or HDF file is a scan; other files are
|
|
792
|
+
grouped by folder into one scan."""
|
|
793
|
+
entries, groups = [], {}
|
|
794
|
+
for path in paths:
|
|
795
|
+
path = os.path.normpath(path)
|
|
796
|
+
if os.path.isdir(path) or path.lower().endswith(util.HDF_EXT):
|
|
797
|
+
entries.append(path)
|
|
798
|
+
elif os.path.isfile(path):
|
|
799
|
+
groups.setdefault(os.path.dirname(path), []).append(path)
|
|
800
|
+
for files in groups.values():
|
|
801
|
+
entries.append(";".join(sorted(files, key=util.natural_key)))
|
|
802
|
+
existing = set(self.input_entries())
|
|
803
|
+
for entry in entries:
|
|
804
|
+
if entry in existing:
|
|
805
|
+
continue
|
|
806
|
+
existing.add(entry)
|
|
807
|
+
files = entry.split(";")
|
|
808
|
+
if len(files) > 1:
|
|
809
|
+
label = f"{Path(files[0]).parent.name}: {len(files)} files"
|
|
810
|
+
else:
|
|
811
|
+
label = Path(entry).name
|
|
812
|
+
item = QListWidgetItem(label)
|
|
813
|
+
item.setData(Qt.UserRole, entry)
|
|
814
|
+
item.setToolTip("\n".join(files[:20]) +
|
|
815
|
+
("\n..." if len(files) > 20 else ""))
|
|
816
|
+
self.list_input.addItem(item)
|
|
817
|
+
hdf = next((e for e in self.input_entries()
|
|
818
|
+
if e.lower().endswith(util.HDF_EXT)), None)
|
|
819
|
+
if hdf and self.combo_hdf_key.count() == 0:
|
|
820
|
+
self.update_hdf_keys(self.combo_hdf_key, hdf)
|
|
821
|
+
self.on_inputs_changed()
|
|
822
|
+
|
|
823
|
+
def remove_inputs(self):
|
|
824
|
+
for item in self.list_input.selectedItems():
|
|
825
|
+
self.list_input.takeItem(self.list_input.row(item))
|
|
826
|
+
self.on_inputs_changed()
|
|
827
|
+
|
|
828
|
+
def clear_inputs(self):
|
|
829
|
+
self.list_input.clear()
|
|
830
|
+
self.on_inputs_changed()
|
|
831
|
+
|
|
832
|
+
def on_inputs_changed(self):
|
|
833
|
+
self.scans = []
|
|
834
|
+
num = self.list_input.count()
|
|
835
|
+
self.lbl_input_info.setText(
|
|
836
|
+
f"{num} scan(s) in the list. Click 'Load'." if num
|
|
837
|
+
else "No input loaded.")
|
|
838
|
+
|
|
839
|
+
def get_scans(self):
|
|
840
|
+
"""[(name, items, metadata path, input entry), ...] of the input
|
|
841
|
+
scans."""
|
|
842
|
+
entries = self.input_entries()
|
|
843
|
+
if not entries:
|
|
844
|
+
raise ValueError("Please add input folders or files!")
|
|
845
|
+
hdf_key = self.combo_hdf_key.currentText().strip()
|
|
846
|
+
axis = self.get_value(self.edit_axis, "Axis", int)
|
|
847
|
+
scans = []
|
|
848
|
+
for entry in entries:
|
|
849
|
+
items = util.raw_scan_items(entry, hdf_key, axis)
|
|
850
|
+
first = entry.split(";")[0]
|
|
851
|
+
scans.append((scan_name_of(first), items,
|
|
852
|
+
util.find_metadata_file(first), entry))
|
|
853
|
+
return scans
|
|
854
|
+
|
|
855
|
+
@ren.safe_call
|
|
856
|
+
def load_input(self):
|
|
857
|
+
self.scans = self.get_scans()
|
|
858
|
+
name, items = self.scans[0][:2]
|
|
859
|
+
hdf_key = self.combo_hdf_key.currentText().strip()
|
|
860
|
+
axis = self.get_value(self.edit_axis, "Axis", int)
|
|
861
|
+
self.raw_image = util.load_raw_image(items[0][0], hdf_key,
|
|
862
|
+
items[0][1], axis)
|
|
863
|
+
self.strip = min(self.strip, self.raw_image.shape[0] - 1)
|
|
864
|
+
num = sum(len(scan[1]) for scan in self.scans)
|
|
865
|
+
self.lbl_input_info.setText(
|
|
866
|
+
f"{len(self.scans)} scan(s), {num} image(s). First: {name}, "
|
|
867
|
+
f"{len(items)} image(s) of shape {self.raw_image.shape}.")
|
|
868
|
+
self.edit_start.setText("0")
|
|
869
|
+
self.edit_stop.setText("")
|
|
870
|
+
self.update_preview()
|
|
871
|
+
|
|
872
|
+
@ren.safe_call
|
|
873
|
+
def load_coefficients(self):
|
|
874
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
875
|
+
self, "Select coefficients file",
|
|
876
|
+
self.last_folder("coefficients"),
|
|
877
|
+
"CSV (*.csv);;All files (*.*)")
|
|
878
|
+
if not path:
|
|
879
|
+
return
|
|
880
|
+
self.remember_folder("coefficients", path)
|
|
881
|
+
coefs = np.asarray(losa.load_csv(path), dtype=np.float64)
|
|
882
|
+
if coefs.ndim == 1:
|
|
883
|
+
coefs = coefs[np.newaxis, :]
|
|
884
|
+
if coefs.ndim != 2 or np.any(np.isnan(coefs)):
|
|
885
|
+
raise ValueError("The file must contain a numeric matrix: one "
|
|
886
|
+
"row of coefficients (a0, a1, ...) per strip.")
|
|
887
|
+
self.coefs = coefs
|
|
888
|
+
self.edit_coef.setText(path)
|
|
889
|
+
self.set_status(f"Loaded coefficients of shape {coefs.shape}.")
|
|
890
|
+
self.update_preview()
|
|
891
|
+
|
|
892
|
+
def get_step(self, width):
|
|
893
|
+
if self.coefs is None:
|
|
894
|
+
raise ValueError("Please load the calibration coefficients!")
|
|
895
|
+
method = self.combo_step.currentText()
|
|
896
|
+
value = self.get_value(self.edit_step, "Value", allow_none=True)
|
|
897
|
+
return util.get_output_step(self.coefs, width, method, value)
|
|
898
|
+
|
|
899
|
+
@ren.safe_call
|
|
900
|
+
def update_preview(self):
|
|
901
|
+
self.corrected = self.corrected_raw = self.step = None
|
|
902
|
+
if self.raw_image is not None and self.coefs is not None:
|
|
903
|
+
width = self.raw_image.shape[1]
|
|
904
|
+
step, source = self.get_step(width)
|
|
905
|
+
self.corrected = util.correct_image(self.raw_image, self.coefs,
|
|
906
|
+
step)
|
|
907
|
+
self.corrected_raw = self.corrected
|
|
908
|
+
self.step = step
|
|
909
|
+
self.set_status(f"Preview updated. Output q-step: {step:.6g} "
|
|
910
|
+
f"({source}); q-max: {step * (width - 1):.4f}.")
|
|
911
|
+
self.plot_correction()
|
|
912
|
+
|
|
913
|
+
def get_background_para(self):
|
|
914
|
+
if not self.check_bck.isChecked():
|
|
915
|
+
return None
|
|
916
|
+
method = self.combo_bck.currentText()
|
|
917
|
+
specs = util.BCK_METHODS[method][1]
|
|
918
|
+
edits = self.bck_edits[method]
|
|
919
|
+
kwargs = {key: self.get_value(edits[key], label, dtype)
|
|
920
|
+
for key, label, _, dtype, _ in specs}
|
|
921
|
+
return method, kwargs
|
|
922
|
+
|
|
923
|
+
@ren.safe_call
|
|
924
|
+
def apply_background(self):
|
|
925
|
+
if self.corrected_raw is None:
|
|
926
|
+
raise ValueError("No corrected preview. Load the input and the "
|
|
927
|
+
"coefficients first!")
|
|
928
|
+
method, kwargs = self.get_background_para()
|
|
929
|
+
image = self.corrected_raw
|
|
930
|
+
|
|
931
|
+
def task(cancel_event):
|
|
932
|
+
return util.remove_background(image, method, kwargs,
|
|
933
|
+
cancel_event, self.set_progress)
|
|
934
|
+
|
|
935
|
+
def done(result):
|
|
936
|
+
if result is None:
|
|
937
|
+
self.set_status("Background removal cancelled.")
|
|
938
|
+
return
|
|
939
|
+
if image is self.corrected_raw:
|
|
940
|
+
self.corrected = result
|
|
941
|
+
self.plot_correction()
|
|
942
|
+
self.set_status(f"Background removed ({method}).")
|
|
943
|
+
|
|
944
|
+
self.run_worker(task, done, "Background removal",
|
|
945
|
+
f"Removing background ({method})...")
|
|
946
|
+
|
|
947
|
+
def on_click(self, plot, point):
|
|
948
|
+
if self.raw_image is None:
|
|
949
|
+
return
|
|
950
|
+
self.strip = int(np.clip(round(point.y()), 0,
|
|
951
|
+
self.raw_image.shape[0] - 1))
|
|
952
|
+
self.plot_correction()
|
|
953
|
+
|
|
954
|
+
def plot_correction(self):
|
|
955
|
+
if self.raw_image is None:
|
|
956
|
+
for plot in (self.p_raw, self.p_corr):
|
|
957
|
+
plot.image_item.clear()
|
|
958
|
+
plot.image_item.raw_data = None
|
|
959
|
+
self.p_strip.clear()
|
|
960
|
+
self.raw_line.hide()
|
|
961
|
+
self.corr_line.hide()
|
|
962
|
+
return
|
|
963
|
+
self.show_image(self.p_raw, self.raw_image)
|
|
964
|
+
self.raw_line.setValue(self.strip)
|
|
965
|
+
self.raw_line.show()
|
|
966
|
+
self.p_strip.clear()
|
|
967
|
+
label = util.Q_LABEL
|
|
968
|
+
if self.corrected is not None:
|
|
969
|
+
height, width = self.corrected.shape
|
|
970
|
+
self.show_image(self.p_corr, self.corrected,
|
|
971
|
+
(-0.5 * self.step, -0.5, width * self.step,
|
|
972
|
+
height))
|
|
973
|
+
self.set_label(self.p_corr, "bottom", label)
|
|
974
|
+
self.corr_line.setValue(self.strip)
|
|
975
|
+
self.corr_line.show()
|
|
976
|
+
self.p_strip.plot(np.arange(width) * self.step,
|
|
977
|
+
self.corrected[self.strip],
|
|
978
|
+
pen=ren.pg.mkPen(util.COLORS["blue"]))
|
|
979
|
+
self.set_label(self.p_strip, "bottom", label)
|
|
980
|
+
self.set_title(self.p_strip, f"Corrected strip {self.strip}")
|
|
981
|
+
else:
|
|
982
|
+
self.p_corr.image_item.clear()
|
|
983
|
+
self.p_corr.image_item.raw_data = None
|
|
984
|
+
self.corr_line.hide()
|
|
985
|
+
self.p_strip.plot(self.raw_image[self.strip],
|
|
986
|
+
pen=ren.pg.mkPen(util.COLORS["blue"]))
|
|
987
|
+
self.set_label(self.p_strip, "bottom", "Pixel index")
|
|
988
|
+
self.set_title(self.p_strip, f"Raw strip {self.strip} (load the "
|
|
989
|
+
f"coefficients to correct)")
|
|
990
|
+
|
|
991
|
+
# Output
|
|
992
|
+
@ren.safe_call
|
|
993
|
+
def browse_output(self):
|
|
994
|
+
folder = QFileDialog.getExistingDirectory(
|
|
995
|
+
self, "Select output folder", self.last_folder("output"))
|
|
996
|
+
if folder:
|
|
997
|
+
self.remember_folder("output", folder)
|
|
998
|
+
self.edit_output.setText(folder)
|
|
999
|
+
|
|
1000
|
+
@ren.safe_call
|
|
1001
|
+
def make_output_folder(self):
|
|
1002
|
+
folder = self.edit_output.text().strip()
|
|
1003
|
+
if not folder:
|
|
1004
|
+
raise ValueError("Please type the path of the folder to create!")
|
|
1005
|
+
Path(folder).mkdir(parents=True, exist_ok=True)
|
|
1006
|
+
self.set_status(f"Folder ready: {folder}")
|
|
1007
|
+
|
|
1008
|
+
def get_output_para(self, width):
|
|
1009
|
+
fmt = self.combo_format.currentText()
|
|
1010
|
+
step, source = self.get_step(width)
|
|
1011
|
+
para = {"step": step, "step_source": source,
|
|
1012
|
+
"coef_file": self.edit_coef.text().strip(),
|
|
1013
|
+
"hdf_key": self.combo_hdf_key.currentText().strip(),
|
|
1014
|
+
"axis": self.get_value(self.edit_axis, "Axis", int),
|
|
1015
|
+
"format": fmt, "bck": self.get_background_para(),
|
|
1016
|
+
"xy_type": self.combo_xy_type.currentText(),
|
|
1017
|
+
"zip": self.combo_zip.currentText() == "zip",
|
|
1018
|
+
"raw": self.combo_xy_data.currentText() == "raw",
|
|
1019
|
+
"xy_folder": self.edit_xy_folder.text().strip() or "xy",
|
|
1020
|
+
"xy_x": self.combo_xy_x.currentText(),
|
|
1021
|
+
"max_two_theta": self.get_max_two_theta(
|
|
1022
|
+
self.combo_xy_x, self.edit_max_tth),
|
|
1023
|
+
"out_key": util.check_output_key(self.edit_out_key.text())}
|
|
1024
|
+
return para
|
|
1025
|
+
|
|
1026
|
+
def get_max_two_theta(self, combo, edit):
|
|
1027
|
+
if combo.currentText() != "two-theta":
|
|
1028
|
+
return util.DEFAULT_MAX_TWO_THETA
|
|
1029
|
+
value = self.get_value(edit, "Max 2theta")
|
|
1030
|
+
if not 0 < value < 180:
|
|
1031
|
+
raise ValueError("Max 2theta must be between 0 and 180 "
|
|
1032
|
+
"degrees!")
|
|
1033
|
+
return value
|
|
1034
|
+
|
|
1035
|
+
@ren.safe_call
|
|
1036
|
+
def run_correction(self):
|
|
1037
|
+
if not self.scans:
|
|
1038
|
+
self.load_input()
|
|
1039
|
+
if not self.scans:
|
|
1040
|
+
return
|
|
1041
|
+
folder = self.edit_output.text().strip()
|
|
1042
|
+
if not folder:
|
|
1043
|
+
raise ValueError("Please select the output folder!")
|
|
1044
|
+
if not os.path.isdir(folder):
|
|
1045
|
+
raise ValueError(f"Output folder does not exist: {folder}. "
|
|
1046
|
+
f"Click 'Make folder' to create it.")
|
|
1047
|
+
out_base = Path(folder).resolve()
|
|
1048
|
+
for name, _, _, entry in self.scans:
|
|
1049
|
+
in_base = util.input_base_folder(entry).resolve()
|
|
1050
|
+
if out_base == in_base:
|
|
1051
|
+
raise ValueError(
|
|
1052
|
+
f"The output base folder must be different from the "
|
|
1053
|
+
f"input base folder:\n{in_base}\nOtherwise '{name}' "
|
|
1054
|
+
f"would be overwritten.")
|
|
1055
|
+
para = self.get_output_para(self.raw_image.shape[1])
|
|
1056
|
+
start = self.get_value(self.edit_start, "Start index", int)
|
|
1057
|
+
stop = self.get_value(self.edit_stop, "Stop index", int,
|
|
1058
|
+
allow_none=True)
|
|
1059
|
+
jobs = []
|
|
1060
|
+
for name, items, meta_path, entry in self.scans:
|
|
1061
|
+
last = len(items) - 1 if stop is None else min(stop,
|
|
1062
|
+
len(items) - 1)
|
|
1063
|
+
if not 0 <= start <= last:
|
|
1064
|
+
raise ValueError(f"Invalid image range [{start}, {stop}] "
|
|
1065
|
+
f"for {name} ({len(items)} images).")
|
|
1066
|
+
jobs.append((name, items[start:last + 1], meta_path, entry))
|
|
1067
|
+
existing = [name for name, *_ in jobs
|
|
1068
|
+
if (Path(folder) / name).is_dir()
|
|
1069
|
+
and any((Path(folder) / name).iterdir())]
|
|
1070
|
+
if existing:
|
|
1071
|
+
shown = ", ".join(existing[:10]) + \
|
|
1072
|
+
(", ..." if len(existing) > 10 else "")
|
|
1073
|
+
bck_note = ("Background removal is ON: use another output base "
|
|
1074
|
+
"folder to keep the data with background.\n\n"
|
|
1075
|
+
if para["bck"] is not None else "")
|
|
1076
|
+
answer = QMessageBox.warning(
|
|
1077
|
+
self, "Data may be overwritten",
|
|
1078
|
+
f"{len(existing)} scan folder(s) already exist in\n{folder}"
|
|
1079
|
+
f"\n{shown}\n\nTheir data may be overwritten.\n\n"
|
|
1080
|
+
f"{bck_note}Continue?",
|
|
1081
|
+
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
|
1082
|
+
if answer != QMessageBox.Yes:
|
|
1083
|
+
self.set_status("Correction cancelled: choose another "
|
|
1084
|
+
"output base folder.")
|
|
1085
|
+
return
|
|
1086
|
+
coefs = self.coefs
|
|
1087
|
+
num_images = sum(len(job[1]) for job in jobs)
|
|
1088
|
+
|
|
1089
|
+
def task(cancel_event):
|
|
1090
|
+
done_images = 0
|
|
1091
|
+
for name, items, meta_path, entry in jobs:
|
|
1092
|
+
metadata = losa.load_json(meta_path) if meta_path else {}
|
|
1093
|
+
num, cancelled = util.correct_scan(
|
|
1094
|
+
items, Path(folder) / name, coefs, para, cancel_event,
|
|
1095
|
+
self.set_progress, metadata, entry)
|
|
1096
|
+
done_images += num
|
|
1097
|
+
if cancelled:
|
|
1098
|
+
return done_images, True
|
|
1099
|
+
return done_images, False
|
|
1100
|
+
|
|
1101
|
+
def done(result):
|
|
1102
|
+
num, cancelled = result
|
|
1103
|
+
prefix = "Cancelled. " if cancelled else ""
|
|
1104
|
+
self.set_status(f"{prefix}Saved {num}/{num_images} image(s) of "
|
|
1105
|
+
f"{len(jobs)} scan(s) ({para['format']}) to "
|
|
1106
|
+
f"{folder}. Output step: {para['step']:.6g}.")
|
|
1107
|
+
|
|
1108
|
+
self.run_worker(task, done, "Correction in progress",
|
|
1109
|
+
f"Correcting {num_images} image(s) of {len(jobs)} "
|
|
1110
|
+
f"scan(s)...")
|
|
1111
|
+
|
|
1112
|
+
# Conversion
|
|
1113
|
+
@ren.safe_call
|
|
1114
|
+
def browse_conv_file(self):
|
|
1115
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1116
|
+
self, "Select source file", self.last_folder("conversion"),
|
|
1117
|
+
"HDF (*.hdf *.h5 *.hdf5 *.nxs);;All files (*.*)")
|
|
1118
|
+
if path:
|
|
1119
|
+
self.remember_folder("conversion", path)
|
|
1120
|
+
self.set_conversion_source(path)
|
|
1121
|
+
|
|
1122
|
+
@ren.safe_call
|
|
1123
|
+
def browse_conv_folder(self):
|
|
1124
|
+
folder = QFileDialog.getExistingDirectory(
|
|
1125
|
+
self, "Select source folder", self.last_folder("conversion"))
|
|
1126
|
+
if folder:
|
|
1127
|
+
self.remember_folder("conversion", folder)
|
|
1128
|
+
self.set_conversion_source(folder)
|
|
1129
|
+
|
|
1130
|
+
def set_conversion_source(self, path):
|
|
1131
|
+
if os.path.isfile(path) and not path.lower().endswith(util.HDF_EXT):
|
|
1132
|
+
path = os.path.dirname(path)
|
|
1133
|
+
self.edit_conv_source.setText(path)
|
|
1134
|
+
if path.lower().endswith(util.HDF_EXT):
|
|
1135
|
+
self.update_hdf_keys(self.combo_conv_key, path)
|
|
1136
|
+
|
|
1137
|
+
@ren.safe_call
|
|
1138
|
+
def browse_conv_output(self):
|
|
1139
|
+
path = QFileDialog.getExistingDirectory(
|
|
1140
|
+
self, "Output folder", self.last_folder("conv_output"))
|
|
1141
|
+
if path:
|
|
1142
|
+
self.remember_folder("conv_output", path)
|
|
1143
|
+
self.edit_conv_output.setText(path)
|
|
1144
|
+
|
|
1145
|
+
@ren.safe_call
|
|
1146
|
+
def make_conv_output_folder(self):
|
|
1147
|
+
folder = self.edit_conv_output.text().strip()
|
|
1148
|
+
if not folder:
|
|
1149
|
+
raise ValueError("Please type the path of the folder to create!")
|
|
1150
|
+
Path(folder).mkdir(parents=True, exist_ok=True)
|
|
1151
|
+
self.set_status(f"Folder ready: {folder}")
|
|
1152
|
+
|
|
1153
|
+
def conversion_output(self, mode, source):
|
|
1154
|
+
"""Output folder, or the HDF file in it for conversions to HDF."""
|
|
1155
|
+
folder = self.edit_conv_output.text().strip()
|
|
1156
|
+
if not folder:
|
|
1157
|
+
raise ValueError("Please select the output folder!")
|
|
1158
|
+
if mode not in ("tif_to_hdf", "tif2d_to_hdf4d"):
|
|
1159
|
+
return folder
|
|
1160
|
+
if not os.path.isdir(folder):
|
|
1161
|
+
raise ValueError(f"Output folder does not exist: {folder}. "
|
|
1162
|
+
f"Click 'Make folder' to create it.")
|
|
1163
|
+
name = self.edit_conv_out_name.text().strip() or \
|
|
1164
|
+
Path(source.rstrip("/\\")).name
|
|
1165
|
+
if not name:
|
|
1166
|
+
raise ValueError("Please input the output file name!")
|
|
1167
|
+
if not name.lower().endswith(util.HDF_EXT):
|
|
1168
|
+
name += ".hdf"
|
|
1169
|
+
return os.path.join(folder, name)
|
|
1170
|
+
|
|
1171
|
+
@ren.safe_call
|
|
1172
|
+
def run_conversion(self):
|
|
1173
|
+
mode = util.CONVERSIONS[self.combo_conversion.currentText()]
|
|
1174
|
+
source = self.edit_conv_source.text().strip()
|
|
1175
|
+
output = self.conversion_output(mode, source)
|
|
1176
|
+
hdf_key = self.combo_conv_key.currentText().strip()
|
|
1177
|
+
x_step = self.get_value(self.edit_conv_step, "Q step",
|
|
1178
|
+
allow_none=True)
|
|
1179
|
+
xy_type = self.combo_conv_xy_type.currentText()
|
|
1180
|
+
zipped = self.combo_conv_zip.currentText() == "zip"
|
|
1181
|
+
x_axis = self.combo_conv_xy_x.currentText()
|
|
1182
|
+
max_tth = self.get_max_two_theta(self.combo_conv_xy_x,
|
|
1183
|
+
self.edit_conv_max_tth)
|
|
1184
|
+
out_key = util.check_output_key(self.edit_conv_out_key.text())
|
|
1185
|
+
nrow = ncol = chunks = None
|
|
1186
|
+
scan_order = self.combo_conv_order.currentText()
|
|
1187
|
+
if mode == "tif2d_to_hdf4d":
|
|
1188
|
+
nrow = self.get_value(self.edit_conv_nrow, "Rows", int,
|
|
1189
|
+
allow_none=True)
|
|
1190
|
+
ncol = self.get_value(self.edit_conv_ncol, "Columns", int,
|
|
1191
|
+
allow_none=True)
|
|
1192
|
+
if (nrow is None) != (ncol is None) or \
|
|
1193
|
+
(nrow is not None and min(nrow, ncol) < 1):
|
|
1194
|
+
raise ValueError("Please input both rows and columns "
|
|
1195
|
+
"(positive), or leave both empty!")
|
|
1196
|
+
chunks = util.parse_chunks(self.edit_conv_chunks.text())
|
|
1197
|
+
|
|
1198
|
+
def task(cancel_event):
|
|
1199
|
+
return util.convert_data(mode, source, output, hdf_key, x_step,
|
|
1200
|
+
xy_type, zipped, cancel_event,
|
|
1201
|
+
self.set_progress, x_axis, max_tth,
|
|
1202
|
+
out_key, nrow, ncol, scan_order, chunks)
|
|
1203
|
+
|
|
1204
|
+
def done(result):
|
|
1205
|
+
message, _ = result
|
|
1206
|
+
self.lbl_conv_info.setText(message)
|
|
1207
|
+
self.set_status(message)
|
|
1208
|
+
|
|
1209
|
+
self.run_worker(task, done, "Conversion in progress",
|
|
1210
|
+
f"Converting {source}...")
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
# ---------------------------------------------------------------------------
|
|
1214
|
+
# Viewers
|
|
1215
|
+
# ---------------------------------------------------------------------------
|
|
1216
|
+
|
|
1217
|
+
def lazy_note(datasets):
|
|
1218
|
+
"""Status note for scans read on demand (too big for memory)."""
|
|
1219
|
+
lazy = [d for d in datasets if d.lazy]
|
|
1220
|
+
if not lazy:
|
|
1221
|
+
return ""
|
|
1222
|
+
size = util.format_bytes(sum(d.nbytes for d in lazy))
|
|
1223
|
+
return (f" Big data ({size}): read on demand from the file, slower "
|
|
1224
|
+
f"q-slices and patterns.")
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
class ViewerLogic(BaseLogic):
|
|
1228
|
+
"""Input and saving actions shared by the viewers."""
|
|
1229
|
+
|
|
1230
|
+
# (min, max) number of dimensions of the HDF datasets the viewer shows
|
|
1231
|
+
hdf_ndims = (3, 3)
|
|
1232
|
+
# Set by the controller: name of the viewer, ranges of all viewers,
|
|
1233
|
+
# and open_in(name, path) to show a file in another viewer
|
|
1234
|
+
viewer_name = ""
|
|
1235
|
+
viewer_ndims = {}
|
|
1236
|
+
open_in = None
|
|
1237
|
+
|
|
1238
|
+
def update_hdf_keys(self, path):
|
|
1239
|
+
try:
|
|
1240
|
+
keys = [k for k, _ in util.hdf_array_keys(path,
|
|
1241
|
+
*self.hdf_ndims)]
|
|
1242
|
+
except OSError as error:
|
|
1243
|
+
self.set_status(f"Can't read {path}: {error}")
|
|
1244
|
+
return
|
|
1245
|
+
current = self.combo_hdf_key.currentText()
|
|
1246
|
+
self.combo_hdf_key.clear()
|
|
1247
|
+
self.combo_hdf_key.addItems(keys)
|
|
1248
|
+
if current in keys:
|
|
1249
|
+
self.combo_hdf_key.setCurrentText(current)
|
|
1250
|
+
|
|
1251
|
+
def offer_other_viewers(self, error):
|
|
1252
|
+
"""For HDF data this viewer can't show (util.WrongDimensionError):
|
|
1253
|
+
ask to open the file in a viewer able to show it."""
|
|
1254
|
+
names = []
|
|
1255
|
+
if self.open_in is not None:
|
|
1256
|
+
try:
|
|
1257
|
+
names = [name for name in util.viewers_for_hdf(
|
|
1258
|
+
error.path, self.viewer_ndims)
|
|
1259
|
+
if name != self.viewer_name]
|
|
1260
|
+
except OSError:
|
|
1261
|
+
pass
|
|
1262
|
+
if not names:
|
|
1263
|
+
raise error
|
|
1264
|
+
box = QMessageBox(QMessageBox.Question, "Open in another viewer",
|
|
1265
|
+
f"{error}\n\nOpen the file in another viewer?",
|
|
1266
|
+
parent=self)
|
|
1267
|
+
buttons = {box.addButton(f"Open in {name}", QMessageBox.AcceptRole):
|
|
1268
|
+
name for name in names}
|
|
1269
|
+
box.addButton(QMessageBox.Cancel)
|
|
1270
|
+
QApplication.changeOverrideCursor(Qt.ArrowCursor)
|
|
1271
|
+
box.exec()
|
|
1272
|
+
name = buttons.get(box.clickedButton())
|
|
1273
|
+
if name is None:
|
|
1274
|
+
self.set_status(f"Not loaded: {error}")
|
|
1275
|
+
return
|
|
1276
|
+
self.open_in(name, error.path)
|
|
1277
|
+
|
|
1278
|
+
def check_scan_input(self, path, hdf_key):
|
|
1279
|
+
"""Check the dimensions of the HDF data of a 1D scan before
|
|
1280
|
+
reading them. False (after offering the other viewers) if this
|
|
1281
|
+
viewer can't show them."""
|
|
1282
|
+
try:
|
|
1283
|
+
util.check_scan_input(path, hdf_key)
|
|
1284
|
+
except util.WrongDimensionError as error:
|
|
1285
|
+
self.offer_other_viewers(error)
|
|
1286
|
+
return False
|
|
1287
|
+
return True
|
|
1288
|
+
|
|
1289
|
+
def set_path(self, path, append=False):
|
|
1290
|
+
if os.path.isfile(path) and not path.lower().endswith(util.HDF_EXT):
|
|
1291
|
+
path = os.path.dirname(path)
|
|
1292
|
+
if append and self.edit_path.text().strip():
|
|
1293
|
+
paths = [p.strip() for p in self.edit_path.text().split(";")
|
|
1294
|
+
if p.strip()]
|
|
1295
|
+
if path not in paths:
|
|
1296
|
+
paths.append(path)
|
|
1297
|
+
self.edit_path.setText("; ".join(paths))
|
|
1298
|
+
else:
|
|
1299
|
+
self.edit_path.setText(path)
|
|
1300
|
+
if path.lower().endswith(util.HDF_EXT):
|
|
1301
|
+
self.update_hdf_keys(path)
|
|
1302
|
+
|
|
1303
|
+
@ren.safe_call
|
|
1304
|
+
def browse_folder(self):
|
|
1305
|
+
folder = QFileDialog.getExistingDirectory(
|
|
1306
|
+
self, "Select a folder of processed tif files",
|
|
1307
|
+
self.last_folder("data"))
|
|
1308
|
+
if folder:
|
|
1309
|
+
self.remember_folder("data", folder)
|
|
1310
|
+
self.reset_metadata()
|
|
1311
|
+
self.set_path(folder, append=self.multi_input)
|
|
1312
|
+
self.load_data()
|
|
1313
|
+
|
|
1314
|
+
def reset_metadata(self):
|
|
1315
|
+
"""Clear the metadata, q-step and positions of the previous data."""
|
|
1316
|
+
for combo in self.position_combos:
|
|
1317
|
+
combo.clear()
|
|
1318
|
+
self.edit_metadata.clear()
|
|
1319
|
+
self.edit_step.clear()
|
|
1320
|
+
|
|
1321
|
+
@ren.safe_call
|
|
1322
|
+
def show_input(self, path):
|
|
1323
|
+
"""Fill the inputs for a folder of tif files or an HDF file, with
|
|
1324
|
+
the metadata, HDF key and q-step found."""
|
|
1325
|
+
is_hdf = path.lower().endswith(util.HDF_EXT)
|
|
1326
|
+
if os.path.isfile(path) and not is_hdf:
|
|
1327
|
+
path = os.path.dirname(path)
|
|
1328
|
+
for combo in self.position_combos:
|
|
1329
|
+
combo.clear()
|
|
1330
|
+
self.edit_step.setText("")
|
|
1331
|
+
self.edit_metadata.blockSignals(True)
|
|
1332
|
+
self.edit_metadata.setText("" if is_hdf
|
|
1333
|
+
else util.find_metadata_file(path))
|
|
1334
|
+
self.edit_metadata.blockSignals(False)
|
|
1335
|
+
self.set_path(path)
|
|
1336
|
+
key = ""
|
|
1337
|
+
if is_hdf:
|
|
1338
|
+
keys = [self.combo_hdf_key.itemText(i)
|
|
1339
|
+
for i in range(self.combo_hdf_key.count())]
|
|
1340
|
+
if util.HDF_DATA_KEY in keys:
|
|
1341
|
+
self.combo_hdf_key.setCurrentText(util.HDF_DATA_KEY)
|
|
1342
|
+
key = self.combo_hdf_key.currentText().strip()
|
|
1343
|
+
meta = self.edit_metadata.text().strip()
|
|
1344
|
+
metadata = losa.load_json(meta) \
|
|
1345
|
+
if meta.lower().endswith(".json") else {}
|
|
1346
|
+
step = util.get_x_step(metadata, path if is_hdf else None, key,
|
|
1347
|
+
path)
|
|
1348
|
+
if step:
|
|
1349
|
+
self.edit_step.setText(f"{step:.10g}")
|
|
1350
|
+
self.set_status(f"Input: {path}")
|
|
1351
|
+
|
|
1352
|
+
@ren.safe_call
|
|
1353
|
+
def browse_file(self):
|
|
1354
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1355
|
+
self, "Select a data file", self.last_folder("data"),
|
|
1356
|
+
"Data (*.hdf *.h5 *.hdf5 *.nxs *.tif *.tiff);;All files (*.*)")
|
|
1357
|
+
if path:
|
|
1358
|
+
self.remember_folder("data", path)
|
|
1359
|
+
self.reset_metadata()
|
|
1360
|
+
self.set_path(path, append=self.multi_input)
|
|
1361
|
+
self.load_data()
|
|
1362
|
+
|
|
1363
|
+
@ren.safe_call
|
|
1364
|
+
def browse_metadata(self):
|
|
1365
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1366
|
+
self, "Select metadata", self.last_folder("metadata"),
|
|
1367
|
+
"JSON (*.json);;All files (*.*)")
|
|
1368
|
+
if path:
|
|
1369
|
+
self.remember_folder("metadata", path)
|
|
1370
|
+
self.edit_metadata.setText(path)
|
|
1371
|
+
|
|
1372
|
+
def input_options(self):
|
|
1373
|
+
return {"hdf_key": self.combo_hdf_key.currentText().strip(),
|
|
1374
|
+
"metadata_path": self.edit_metadata.text().strip(),
|
|
1375
|
+
"x_step": self.get_value(self.edit_step, "Q step",
|
|
1376
|
+
allow_none=True)}
|
|
1377
|
+
|
|
1378
|
+
def radius(self):
|
|
1379
|
+
return int(self.combo_radius.currentText())
|
|
1380
|
+
|
|
1381
|
+
def loaded_datasets(self):
|
|
1382
|
+
if getattr(self, "datasets", None):
|
|
1383
|
+
return list(self.datasets)
|
|
1384
|
+
data = getattr(self, "dataset", None)
|
|
1385
|
+
return [] if data is None else [data]
|
|
1386
|
+
|
|
1387
|
+
def x_calibrated(self):
|
|
1388
|
+
return all(d.calibrated for d in self.loaded_datasets())
|
|
1389
|
+
|
|
1390
|
+
def x_label(self):
|
|
1391
|
+
return util.Q_LABEL if self.x_calibrated() else "Pixel index"
|
|
1392
|
+
|
|
1393
|
+
def x_name(self):
|
|
1394
|
+
return "Q" if self.x_calibrated() else "Pixel"
|
|
1395
|
+
|
|
1396
|
+
def check_x_step(self):
|
|
1397
|
+
"""Show the q-step found for the loaded data, or ask for it."""
|
|
1398
|
+
datasets = self.loaded_datasets()
|
|
1399
|
+
if datasets and self.x_calibrated():
|
|
1400
|
+
if not self.edit_step.text().strip():
|
|
1401
|
+
self.edit_step.setText(f"{datasets[0].x_step:.10g}")
|
|
1402
|
+
return
|
|
1403
|
+
if datasets:
|
|
1404
|
+
QMessageBox.information(
|
|
1405
|
+
self, "Q-step not found",
|
|
1406
|
+
"The q-step wasn't found in the map_info, the metadata or "
|
|
1407
|
+
"the HDF file. The x-axis is shown in pixels.\n\nType the "
|
|
1408
|
+
"q-step in 'Q step' and press Enter to show q.")
|
|
1409
|
+
|
|
1410
|
+
@ren.safe_call
|
|
1411
|
+
def on_step_entered(self):
|
|
1412
|
+
"""Apply the typed q-step to the loaded data (empty: pixels)."""
|
|
1413
|
+
datasets = self.loaded_datasets()
|
|
1414
|
+
if not datasets:
|
|
1415
|
+
return
|
|
1416
|
+
step = self.get_value(self.edit_step, "Q step", allow_none=True)
|
|
1417
|
+
if step is not None and step <= 0:
|
|
1418
|
+
raise ValueError("The q-step must be positive!")
|
|
1419
|
+
for data in datasets:
|
|
1420
|
+
data.set_x_step(step)
|
|
1421
|
+
self.refresh_all()
|
|
1422
|
+
for plot in self.plots:
|
|
1423
|
+
plot.enableAutoRange()
|
|
1424
|
+
self.set_status(f"X-axis: {self.x_label()}.")
|
|
1425
|
+
|
|
1426
|
+
def show_scan_image(self, plot, mat, x_step):
|
|
1427
|
+
height, width = mat.shape
|
|
1428
|
+
self.show_image(plot, mat, (-0.5 * x_step, -0.5, width * x_step,
|
|
1429
|
+
height))
|
|
1430
|
+
self.set_label(plot, "bottom", self.x_label())
|
|
1431
|
+
|
|
1432
|
+
def show_qslice(self, mat, y_label):
|
|
1433
|
+
self.show_image(self.p_slice, mat)
|
|
1434
|
+
self.set_label(self.p_slice, "left", f"{y_label} (index)")
|
|
1435
|
+
|
|
1436
|
+
def set_span(self, x_index, x_step):
|
|
1437
|
+
radius = self.radius()
|
|
1438
|
+
self.img_span.setRegion(((x_index - radius - 0.5) * x_step,
|
|
1439
|
+
(x_index + radius + 0.5) * x_step))
|
|
1440
|
+
self.img_span.show()
|
|
1441
|
+
self.prof_line.setValue(x_index * x_step)
|
|
1442
|
+
self.prof_line.show()
|
|
1443
|
+
|
|
1444
|
+
def set_crosshairs(self, scan_index):
|
|
1445
|
+
if self.row is None:
|
|
1446
|
+
for line in (self.img_row_line, self.slice_hline,
|
|
1447
|
+
self.slice_vline):
|
|
1448
|
+
line.hide()
|
|
1449
|
+
return
|
|
1450
|
+
self.img_row_line.setValue(self.row)
|
|
1451
|
+
self.slice_hline.setValue(scan_index)
|
|
1452
|
+
self.slice_vline.setValue(self.row)
|
|
1453
|
+
for line in (self.img_row_line, self.slice_hline, self.slice_vline):
|
|
1454
|
+
line.show()
|
|
1455
|
+
|
|
1456
|
+
def plot_waterfall(self, curves, current, ylabel):
|
|
1457
|
+
"""Curves (x, y, label) offset vertically; current one in red."""
|
|
1458
|
+
self.p_prof.clear()
|
|
1459
|
+
self.p_prof.addItem(self.prof_line)
|
|
1460
|
+
peak = max((float(np.max(y)) for _, y, _ in curves if len(y)),
|
|
1461
|
+
default=1.0)
|
|
1462
|
+
spacing = peak * 0.3 if peak > 0 else 1.0
|
|
1463
|
+
for i, (x, y, _) in enumerate(curves):
|
|
1464
|
+
color = util.COLORS["red"] if i == current \
|
|
1465
|
+
else util.COLORS["blue"]
|
|
1466
|
+
width = 1.5 if i == current else 0.8
|
|
1467
|
+
self.p_prof.plot(x, np.asarray(y) + i * spacing,
|
|
1468
|
+
pen=ren.pg.mkPen(color, width=width))
|
|
1469
|
+
self.set_label(self.p_prof, "left", ylabel)
|
|
1470
|
+
self.set_label(self.p_prof, "bottom", self.x_label())
|
|
1471
|
+
self.pattern_curves = curves
|
|
1472
|
+
|
|
1473
|
+
def plot_single(self, x, y, title):
|
|
1474
|
+
self.p_prof.clear()
|
|
1475
|
+
self.p_prof.addItem(self.prof_line)
|
|
1476
|
+
self.p_prof.plot(x, y, pen=ren.pg.mkPen(util.COLORS["blue"],
|
|
1477
|
+
width=1.0))
|
|
1478
|
+
self.set_title(self.p_prof, title)
|
|
1479
|
+
self.set_label(self.p_prof, "left", "Intensity")
|
|
1480
|
+
self.set_label(self.p_prof, "bottom", self.x_label())
|
|
1481
|
+
self.pattern_curves = [(x, y, "intensity")]
|
|
1482
|
+
|
|
1483
|
+
def refresh_all(self):
|
|
1484
|
+
self.update_image()
|
|
1485
|
+
self.update_qslice()
|
|
1486
|
+
|
|
1487
|
+
def clear_profile(self):
|
|
1488
|
+
self.p_prof.clear()
|
|
1489
|
+
self.p_prof.addItem(self.prof_line)
|
|
1490
|
+
self.prof_line.hide()
|
|
1491
|
+
self.pattern_curves = None
|
|
1492
|
+
|
|
1493
|
+
@ren.safe_call
|
|
1494
|
+
def save_pattern(self):
|
|
1495
|
+
curves = getattr(self, "pattern_curves", None)
|
|
1496
|
+
if not curves:
|
|
1497
|
+
raise ValueError("Click on the image to select a row first!")
|
|
1498
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
1499
|
+
self, "Save pattern(s)", os.path.join(self.last_folder("save"),
|
|
1500
|
+
"pattern.csv"),
|
|
1501
|
+
"CSV (*.csv)")
|
|
1502
|
+
if not path:
|
|
1503
|
+
return
|
|
1504
|
+
self.remember_folder("save", path)
|
|
1505
|
+
lengths = {len(x) for x, _, _ in curves}
|
|
1506
|
+
if len(lengths) == 1:
|
|
1507
|
+
columns = [curves[0][0]] + [y for _, y, _ in curves]
|
|
1508
|
+
header = "x," + ",".join(label for _, _, label in curves)
|
|
1509
|
+
else:
|
|
1510
|
+
columns, labels = [], []
|
|
1511
|
+
for x, y, label in curves:
|
|
1512
|
+
columns += [x, y]
|
|
1513
|
+
labels += [f"x_{label}", label]
|
|
1514
|
+
width = max(lengths)
|
|
1515
|
+
columns = [np.pad(np.asarray(c, float), (0, width - len(c)),
|
|
1516
|
+
constant_values=np.nan) for c in columns]
|
|
1517
|
+
header = ",".join(labels)
|
|
1518
|
+
np.savetxt(path, np.column_stack(columns), delimiter=",",
|
|
1519
|
+
header=header, comments="")
|
|
1520
|
+
self.set_status(f"Saved: {path}")
|
|
1521
|
+
|
|
1522
|
+
@ren.safe_call
|
|
1523
|
+
def save_qslice(self):
|
|
1524
|
+
mat = getattr(self, "qslice_raw", None)
|
|
1525
|
+
if mat is None:
|
|
1526
|
+
raise ValueError("No q-slice image! Load data first.")
|
|
1527
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
1528
|
+
self, "Save q-slice", os.path.join(self.last_folder("save"),
|
|
1529
|
+
"q_slice.tif"),
|
|
1530
|
+
"TIFF (*.tif)")
|
|
1531
|
+
if not path:
|
|
1532
|
+
return
|
|
1533
|
+
self.remember_folder("save", path)
|
|
1534
|
+
path = losa.save_image(path, np.float32(mat))
|
|
1535
|
+
self.set_status(f"Saved: {path}")
|
|
1536
|
+
|
|
1537
|
+
|
|
1538
|
+
class PositionsMixin:
|
|
1539
|
+
"""Metadata (JSON or nxs/HDF) and choice of the positions of the
|
|
1540
|
+
images by their key, shared by the 1D-scan viewers. With several scans,
|
|
1541
|
+
the keys are listed from the first scan and each scan reads its own
|
|
1542
|
+
metadata."""
|
|
1543
|
+
|
|
1544
|
+
def __init__(self):
|
|
1545
|
+
super().__init__()
|
|
1546
|
+
self.edit_path.editingFinished.connect(self.update_positions)
|
|
1547
|
+
self.combo_hdf_key.currentTextChanged.connect(
|
|
1548
|
+
lambda _t: self.update_positions())
|
|
1549
|
+
self.edit_metadata.textChanged.connect(
|
|
1550
|
+
lambda _t: self.update_positions())
|
|
1551
|
+
|
|
1552
|
+
def first_path(self):
|
|
1553
|
+
return self.edit_path.text().split(";")[0].strip()
|
|
1554
|
+
|
|
1555
|
+
def set_path(self, path, append=False):
|
|
1556
|
+
super().set_path(path, append)
|
|
1557
|
+
self.update_positions()
|
|
1558
|
+
|
|
1559
|
+
@ren.safe_call
|
|
1560
|
+
def browse_metadata(self):
|
|
1561
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1562
|
+
self, "Select metadata", self.last_folder("metadata"),
|
|
1563
|
+
"Metadata (*.json *.nxs *.hdf *.h5 *.hdf5);;All files (*.*)")
|
|
1564
|
+
if path:
|
|
1565
|
+
self.remember_folder("metadata", path)
|
|
1566
|
+
self.edit_metadata.setText(path)
|
|
1567
|
+
|
|
1568
|
+
def update_positions(self):
|
|
1569
|
+
"""List the 1D arrays of the metadata (JSON lists, or 1D datasets
|
|
1570
|
+
of a nxs/HDF file) with one value per image."""
|
|
1571
|
+
items, num = [], None
|
|
1572
|
+
try:
|
|
1573
|
+
items, num = util.list_positions(
|
|
1574
|
+
self.first_path(), self.combo_hdf_key.currentText().strip(),
|
|
1575
|
+
self.edit_metadata.text())
|
|
1576
|
+
except (OSError, ValueError) as error:
|
|
1577
|
+
self.set_status(f"Can't list the positions: {error}")
|
|
1578
|
+
current = self.combo_motor.currentData()
|
|
1579
|
+
self.combo_motor.clear()
|
|
1580
|
+
for key, size in items:
|
|
1581
|
+
self.combo_motor.addItem(f"{key} ({size})", key)
|
|
1582
|
+
index = self.combo_motor.findData(current)
|
|
1583
|
+
if index >= 0:
|
|
1584
|
+
self.combo_motor.setCurrentIndex(index)
|
|
1585
|
+
self.combo_motor.setEnabled(bool(items))
|
|
1586
|
+
if num is not None:
|
|
1587
|
+
self.combo_motor.setToolTip(
|
|
1588
|
+
f"Positions of the {num} images: a 1D array with {num} "
|
|
1589
|
+
f"values. Its name labels the axes.")
|
|
1590
|
+
|
|
1591
|
+
def input_options(self):
|
|
1592
|
+
options = super().input_options()
|
|
1593
|
+
options["motor_key"] = self.combo_motor.currentData() or ""
|
|
1594
|
+
return options
|
|
1595
|
+
|
|
1596
|
+
def metadata_for_all(self):
|
|
1597
|
+
"""Metadata file of the positions of all scans: the one given, or
|
|
1598
|
+
the one of the first scan."""
|
|
1599
|
+
return self.edit_metadata.text().strip() or \
|
|
1600
|
+
util.positions_source(self.first_path())[1]
|
|
1601
|
+
|
|
1602
|
+
def warn_positions(self, notes):
|
|
1603
|
+
if notes:
|
|
1604
|
+
QMessageBox.warning(self, "Positions not used",
|
|
1605
|
+
"\n".join(notes))
|
|
1606
|
+
|
|
1607
|
+
@ren.safe_call
|
|
1608
|
+
def load_metadata(self):
|
|
1609
|
+
"""Use the selected positions for the loaded data, without loading
|
|
1610
|
+
the images again."""
|
|
1611
|
+
self.update_positions()
|
|
1612
|
+
datasets = self.loaded_datasets()
|
|
1613
|
+
if not datasets:
|
|
1614
|
+
self.set_status("Metadata listed. Load the data to use the "
|
|
1615
|
+
"positions.")
|
|
1616
|
+
return
|
|
1617
|
+
metadata = self.metadata_for_all()
|
|
1618
|
+
key = self.combo_motor.currentData() or ""
|
|
1619
|
+
notes = []
|
|
1620
|
+
for data in datasets:
|
|
1621
|
+
name, positions, note = util.resolve_positions(
|
|
1622
|
+
data.source, metadata, key, data.depth)
|
|
1623
|
+
data.set_positions(name, positions)
|
|
1624
|
+
data.position_note = note
|
|
1625
|
+
if note:
|
|
1626
|
+
notes.append(f"{data.name}: {note}")
|
|
1627
|
+
self.refresh_all()
|
|
1628
|
+
data = datasets[0]
|
|
1629
|
+
self.set_status(" ".join(notes) or (
|
|
1630
|
+
"Positions: image index." if data.motor_name == "Image"
|
|
1631
|
+
else f"Positions: {data.motor_name}."))
|
|
1632
|
+
self.warn_positions(notes)
|
|
1633
|
+
|
|
1634
|
+
@staticmethod
|
|
1635
|
+
def position_text(data, idx):
|
|
1636
|
+
"""Motor name and position of an image, for plot titles."""
|
|
1637
|
+
if data.motor_name == "Image":
|
|
1638
|
+
return f"Image {idx}"
|
|
1639
|
+
return f"{data.motor_name} = {data.positions[idx]:.6g} | Image " \
|
|
1640
|
+
f"{idx}"
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
class Positions2DMixin(PositionsMixin):
|
|
1644
|
+
"""Metadata and positions of the two axes of a 2D scan: a key (1D
|
|
1645
|
+
array) for the rows and one for the columns."""
|
|
1646
|
+
|
|
1647
|
+
def position_keys(self):
|
|
1648
|
+
return tuple(combo.currentData() or ""
|
|
1649
|
+
for combo in self.position_combos)
|
|
1650
|
+
|
|
1651
|
+
def scan_grid(self):
|
|
1652
|
+
"""(nrow, ncol, scan_order) of a 3D HDF dataset; None if not
|
|
1653
|
+
used."""
|
|
1654
|
+
return None
|
|
1655
|
+
|
|
1656
|
+
def update_positions(self):
|
|
1657
|
+
"""List the 1D arrays of the metadata with one value per row (axis
|
|
1658
|
+
0) or per column (axis 1)."""
|
|
1659
|
+
shape, arrays = None, []
|
|
1660
|
+
try:
|
|
1661
|
+
shape = util.scan2d_shape(
|
|
1662
|
+
self.first_path(), self.combo_hdf_key.currentText().strip(),
|
|
1663
|
+
self.scan_grid())
|
|
1664
|
+
arrays = util.list_position_arrays(self.first_path(),
|
|
1665
|
+
self.edit_metadata.text())
|
|
1666
|
+
except (OSError, ValueError) as error:
|
|
1667
|
+
self.set_status(f"Can't list the positions: {error}")
|
|
1668
|
+
units = ("row", "column")
|
|
1669
|
+
for axis, combo in enumerate(self.position_combos):
|
|
1670
|
+
num = shape[axis] if shape else None
|
|
1671
|
+
current = combo.currentData()
|
|
1672
|
+
items = [(key, size) for key, size in arrays if size == num]
|
|
1673
|
+
combo.clear()
|
|
1674
|
+
for key, size in items:
|
|
1675
|
+
combo.addItem(f"{key} ({size})", key)
|
|
1676
|
+
index = combo.findData(current)
|
|
1677
|
+
if index < 0 and axis == 0 and shape and shape[0] == shape[1] \
|
|
1678
|
+
and len(items) > 1:
|
|
1679
|
+
# Same number of rows and columns: the columns are listed
|
|
1680
|
+
# first, the rows second
|
|
1681
|
+
index = 1
|
|
1682
|
+
if index >= 0:
|
|
1683
|
+
combo.setCurrentIndex(index)
|
|
1684
|
+
combo.setEnabled(bool(items))
|
|
1685
|
+
if num is not None:
|
|
1686
|
+
combo.setToolTip(f"Positions of the {num} {units[axis]}s: "
|
|
1687
|
+
f"a 1D array with {num} values. Its name "
|
|
1688
|
+
f"labels the plots.")
|
|
1689
|
+
|
|
1690
|
+
def input_options(self):
|
|
1691
|
+
# The 2D scan takes one key per axis, not the key of PositionsMixin
|
|
1692
|
+
options = super(PositionsMixin, self).input_options()
|
|
1693
|
+
options["motor_keys"] = self.position_keys()
|
|
1694
|
+
return options
|
|
1695
|
+
|
|
1696
|
+
def positions_status(self):
|
|
1697
|
+
names = [name for name, _ in self.dataset.motors]
|
|
1698
|
+
return f"Positions: {names[0]} (rows), {names[1]} (columns)."
|
|
1699
|
+
|
|
1700
|
+
@ren.safe_call
|
|
1701
|
+
def load_metadata(self):
|
|
1702
|
+
"""Use the selected positions for the loaded data, without loading
|
|
1703
|
+
the images again."""
|
|
1704
|
+
self.update_positions()
|
|
1705
|
+
data = self.dataset
|
|
1706
|
+
if data is None:
|
|
1707
|
+
self.set_status("Metadata listed. Load the data to use the "
|
|
1708
|
+
"positions.")
|
|
1709
|
+
return
|
|
1710
|
+
data.apply_positions(self.position_keys(), self.metadata_for_all())
|
|
1711
|
+
self.apply_motor_labels()
|
|
1712
|
+
self.refresh_all()
|
|
1713
|
+
self.set_status(" ".join(data.position_notes)
|
|
1714
|
+
or self.positions_status())
|
|
1715
|
+
self.warn_positions(data.position_notes)
|
|
1716
|
+
|
|
1717
|
+
|
|
1718
|
+
class EddtViewer(PositionsMixin, ViewerLogic, ren.EddtViewerUI):
|
|
1719
|
+
"""Viewer of a 1D scan; MultiLinesViewer shows a waterfall of all
|
|
1720
|
+
images."""
|
|
1721
|
+
|
|
1722
|
+
hdf_ndims = (2, 3)
|
|
1723
|
+
|
|
1724
|
+
@ren.safe_call
|
|
1725
|
+
def load_data(self):
|
|
1726
|
+
path = self.edit_path.text()
|
|
1727
|
+
options = self.input_options()
|
|
1728
|
+
if not self.check_scan_input(path, options["hdf_key"]):
|
|
1729
|
+
return
|
|
1730
|
+
|
|
1731
|
+
def task(cancel_event):
|
|
1732
|
+
return util.load_scan(path, cancel_event=cancel_event,
|
|
1733
|
+
progress=self.set_progress, **options)
|
|
1734
|
+
|
|
1735
|
+
self.run_worker(task, self.on_data_loaded, "Loading data",
|
|
1736
|
+
f"Loading {path}...")
|
|
1737
|
+
|
|
1738
|
+
def on_data_loaded(self, dataset):
|
|
1739
|
+
if dataset is None:
|
|
1740
|
+
self.set_status("Loading cancelled.")
|
|
1741
|
+
return
|
|
1742
|
+
if self.dataset is not None:
|
|
1743
|
+
self.dataset.close()
|
|
1744
|
+
self.dataset = dataset
|
|
1745
|
+
data = self.dataset
|
|
1746
|
+
self.row = None
|
|
1747
|
+
self.clear_profile()
|
|
1748
|
+
self.slider_img.set_range(data.depth - 1)
|
|
1749
|
+
self.slider_x.set_range(data.width - 1)
|
|
1750
|
+
self.slider_img.set_value(0, notify=False)
|
|
1751
|
+
self.slider_x.set_value(data.width // 2, notify=False)
|
|
1752
|
+
self.refresh_all()
|
|
1753
|
+
for plot in (self.p_img, self.p_slice):
|
|
1754
|
+
plot.enableAutoRange()
|
|
1755
|
+
positions = data.position_note or (
|
|
1756
|
+
"Positions: image index." if data.motor_name == "Image"
|
|
1757
|
+
else f"Positions: {data.motor_name}.")
|
|
1758
|
+
step = f"Q-step: {data.x_step:.6g}." if data.calibrated \
|
|
1759
|
+
else "Q-step not found: x-axis in pixels."
|
|
1760
|
+
self.set_status(f"Loaded {data.name}: {data.depth} image(s) of "
|
|
1761
|
+
f"shape ({data.height}, {data.width}). {step} "
|
|
1762
|
+
f"{positions}{lazy_note([data])} Click on the "
|
|
1763
|
+
f"image to select a row.")
|
|
1764
|
+
self.check_x_step()
|
|
1765
|
+
self.warn_positions([data.position_note] if data.position_note
|
|
1766
|
+
else [])
|
|
1767
|
+
|
|
1768
|
+
def update_image(self):
|
|
1769
|
+
data = self.dataset
|
|
1770
|
+
if data is None:
|
|
1771
|
+
return
|
|
1772
|
+
idx = self.slider_img.value()
|
|
1773
|
+
self.show_scan_image(self.p_img, data.image(idx), data.x_step)
|
|
1774
|
+
self.set_title(self.p_img, self.position_text(data, idx))
|
|
1775
|
+
self.set_crosshairs(idx)
|
|
1776
|
+
self.update_profile()
|
|
1777
|
+
|
|
1778
|
+
def update_qslice(self):
|
|
1779
|
+
data = self.dataset
|
|
1780
|
+
if data is None:
|
|
1781
|
+
return
|
|
1782
|
+
x_idx = self.slider_x.value()
|
|
1783
|
+
self.qslice_raw = data.q_slice(x_idx, self.radius())
|
|
1784
|
+
self.show_qslice(self.qslice_raw, data.motor_name)
|
|
1785
|
+
self.set_title(self.p_slice, f"Mean of slices around "
|
|
1786
|
+
f"{self.x_name()}="
|
|
1787
|
+
f"{x_idx * data.x_step:.4g}")
|
|
1788
|
+
self.set_span(x_idx, data.x_step)
|
|
1789
|
+
self.set_crosshairs(self.slider_img.value())
|
|
1790
|
+
|
|
1791
|
+
def update_profile(self):
|
|
1792
|
+
data = self.dataset
|
|
1793
|
+
if data is None or self.row is None:
|
|
1794
|
+
return
|
|
1795
|
+
idx = self.slider_img.value()
|
|
1796
|
+
if self.stack_mode:
|
|
1797
|
+
patterns = data.row_patterns(self.row)
|
|
1798
|
+
curves = [(data.x_list, patterns[i], f"image_{i}")
|
|
1799
|
+
for i in range(data.depth)]
|
|
1800
|
+
self.plot_waterfall(curves, idx, f"{data.motor_name} "
|
|
1801
|
+
f"(image index, offset)")
|
|
1802
|
+
self.set_title(self.p_prof, f"Patterns of all images at row "
|
|
1803
|
+
f"{self.row} | Red: "
|
|
1804
|
+
f"{self.position_text(data, idx)}")
|
|
1805
|
+
else:
|
|
1806
|
+
self.plot_single(data.x_list, data.pattern(idx, self.row),
|
|
1807
|
+
f"Pattern at row {self.row} | "
|
|
1808
|
+
f"{self.position_text(data, idx)}")
|
|
1809
|
+
|
|
1810
|
+
def on_click(self, plot, point):
|
|
1811
|
+
data = self.dataset
|
|
1812
|
+
if data is None:
|
|
1813
|
+
return
|
|
1814
|
+
if plot is self.p_img:
|
|
1815
|
+
self.row = int(np.clip(round(point.y()), 0, data.height - 1))
|
|
1816
|
+
self.slider_x.set_value(data.x_index(point.x()), notify=False)
|
|
1817
|
+
self.update_qslice()
|
|
1818
|
+
self.update_profile()
|
|
1819
|
+
elif plot is self.p_slice:
|
|
1820
|
+
self.row = int(np.clip(round(point.x()), 0, data.height - 1))
|
|
1821
|
+
self.slider_img.set_value(int(np.clip(round(point.y()), 0,
|
|
1822
|
+
data.depth - 1)))
|
|
1823
|
+
elif plot is self.p_prof:
|
|
1824
|
+
self.slider_x.set_value(data.x_index(point.x()))
|
|
1825
|
+
|
|
1826
|
+
|
|
1827
|
+
class GLWaterfallMixin:
|
|
1828
|
+
"""Patterns drawn as lines in a 3D view (OpenGL): x = q, y = image or
|
|
1829
|
+
scan, z = intensity, with a hover readout. Viewers without the 3D view
|
|
1830
|
+
(no PyOpenGL) keep their 2D waterfall."""
|
|
1831
|
+
|
|
1832
|
+
def __init__(self):
|
|
1833
|
+
super().__init__()
|
|
1834
|
+
self.gl_points = None
|
|
1835
|
+
self.gl_marker = None
|
|
1836
|
+
if self.gl_view is not None:
|
|
1837
|
+
self.gl_view.installEventFilter(self)
|
|
1838
|
+
|
|
1839
|
+
def eventFilter(self, obj, event):
|
|
1840
|
+
if obj is self.gl_view:
|
|
1841
|
+
if event.type() == QEvent.MouseMove and not event.buttons():
|
|
1842
|
+
self.on_gl_hover(event.position())
|
|
1843
|
+
elif event.type() == QEvent.Leave and self.cursor_func:
|
|
1844
|
+
self.cursor_func("")
|
|
1845
|
+
return super().eventFilter(obj, event)
|
|
1846
|
+
|
|
1847
|
+
def on_gl_hover(self, pos):
|
|
1848
|
+
"""Show x, y, z of the line point nearest to the mouse."""
|
|
1849
|
+
if self.gl_points is None or self.cursor_func is None:
|
|
1850
|
+
return
|
|
1851
|
+
view = self.gl_view
|
|
1852
|
+
viewport = view.getViewport()
|
|
1853
|
+
matrix = view.projectionMatrix(viewport, viewport) * \
|
|
1854
|
+
view.viewMatrix()
|
|
1855
|
+
mat = np.array(matrix.copyDataTo(), dtype=float).reshape(4, 4)
|
|
1856
|
+
pts = np.column_stack([self.gl_points,
|
|
1857
|
+
np.ones(len(self.gl_points))])
|
|
1858
|
+
clip = pts @ mat.T
|
|
1859
|
+
w_clip = clip[:, 3]
|
|
1860
|
+
valid = w_clip > 1e-9
|
|
1861
|
+
if not np.any(valid):
|
|
1862
|
+
return
|
|
1863
|
+
ndc = clip[valid, :2] / w_clip[valid, None]
|
|
1864
|
+
px = (ndc[:, 0] + 1) / 2 * view.width()
|
|
1865
|
+
py = (1 - ndc[:, 1]) / 2 * view.height()
|
|
1866
|
+
dist2 = (px - pos.x()) ** 2 + (py - pos.y()) ** 2
|
|
1867
|
+
i = int(np.argmin(dist2))
|
|
1868
|
+
if dist2[i] > util.GL_HOVER_PX ** 2:
|
|
1869
|
+
self.cursor_func("")
|
|
1870
|
+
return
|
|
1871
|
+
x_val, line, z_val = self.gl_values[np.flatnonzero(valid)[i]]
|
|
1872
|
+
self.cursor_func(f"x: {self.x_name()} = {x_val:.5g} y: "
|
|
1873
|
+
f"{self.gl_y_name} = {self.gl_y_texts[int(line)]}"
|
|
1874
|
+
f" z: intensity = {z_val:.5g}")
|
|
1875
|
+
|
|
1876
|
+
def clear_profile(self):
|
|
1877
|
+
if self.gl_view is None:
|
|
1878
|
+
return super().clear_profile()
|
|
1879
|
+
self.gl_view.clear()
|
|
1880
|
+
self.gl_marker = None
|
|
1881
|
+
self.gl_points = None
|
|
1882
|
+
self.pattern_curves = None
|
|
1883
|
+
|
|
1884
|
+
def set_span(self, x_index, x_step):
|
|
1885
|
+
if self.gl_view is None:
|
|
1886
|
+
return super().set_span(x_index, x_step)
|
|
1887
|
+
radius = self.radius()
|
|
1888
|
+
self.img_span.setRegion(((x_index - radius - 0.5) * x_step,
|
|
1889
|
+
(x_index + radius + 0.5) * x_step))
|
|
1890
|
+
self.img_span.show()
|
|
1891
|
+
self.update_gl_marker()
|
|
1892
|
+
|
|
1893
|
+
@staticmethod
|
|
1894
|
+
def gl_color(color, alpha=1.0):
|
|
1895
|
+
rgba = ren.pg.mkColor(color).getRgbF()
|
|
1896
|
+
return rgba[0], rgba[1], rgba[2], alpha
|
|
1897
|
+
|
|
1898
|
+
def draw_gl_curves(self, curves, current, y_name, y_texts):
|
|
1899
|
+
"""Draw curves [(x, intensity), ...] scaled into util.GL_BOX, one
|
|
1900
|
+
per y step, the current one in red, with a grid, the axis names and
|
|
1901
|
+
their ranges. y_texts: label of each curve on the y axis."""
|
|
1902
|
+
view = self.gl_view
|
|
1903
|
+
view.clear()
|
|
1904
|
+
size_x, size_y, size_z = util.GL_BOX
|
|
1905
|
+
width = max(len(x) for x, _ in curves)
|
|
1906
|
+
step = max(1, int(np.ceil(width / util.GL_MAX_POINTS)))
|
|
1907
|
+
curves = [(np.asarray(x[::step], dtype=float),
|
|
1908
|
+
np.asarray(y[::step], dtype=float)) for x, y in curves]
|
|
1909
|
+
x_min = min(float(x[0]) for x, _ in curves)
|
|
1910
|
+
x_max = max(float(x[-1]) for x, _ in curves)
|
|
1911
|
+
z_min = min(min(float(np.min(y)) for _, y in curves), 0.0)
|
|
1912
|
+
z_max = max(float(np.max(y)) for _, y in curves)
|
|
1913
|
+
x_range = max(x_max - x_min, 1e-12)
|
|
1914
|
+
z_range = max(z_max - z_min, 1e-12)
|
|
1915
|
+
num = len(curves)
|
|
1916
|
+
y_n = np.linspace(0, size_y, num) if num > 1 else np.zeros(1)
|
|
1917
|
+
self.gl_scale = (x_min, x_range)
|
|
1918
|
+
self.gl_y_name, self.gl_y_texts = y_name, y_texts
|
|
1919
|
+
fg = ren.sel_theme["PG_FG"]
|
|
1920
|
+
grid_color = ren.pg.mkColor(fg)
|
|
1921
|
+
grid_color.setAlphaF(0.25)
|
|
1922
|
+
grid = ren.gl.GLGridItem(color=grid_color)
|
|
1923
|
+
grid.setSize(size_x, size_y)
|
|
1924
|
+
grid.setSpacing(size_x / 10, size_y / 10)
|
|
1925
|
+
grid.translate(size_x / 2, size_y / 2, 0)
|
|
1926
|
+
view.addItem(grid)
|
|
1927
|
+
points, values = [], []
|
|
1928
|
+
for i, (x, y) in enumerate(curves):
|
|
1929
|
+
pos = np.column_stack([(x - x_min) / x_range * size_x,
|
|
1930
|
+
np.full(len(x), y_n[i]),
|
|
1931
|
+
(y - z_min) / z_range * size_z])
|
|
1932
|
+
points.append(pos)
|
|
1933
|
+
# Point values for hovering: x, curve index, intensity
|
|
1934
|
+
values.append(np.column_stack([x, np.full(len(x), i), y]))
|
|
1935
|
+
is_current = i == current
|
|
1936
|
+
color = util.COLORS["red"] if is_current else util.COLORS["blue"]
|
|
1937
|
+
view.addItem(ren.gl.GLLinePlotItem(
|
|
1938
|
+
pos=pos, color=self.gl_color(color, 1.0 if is_current
|
|
1939
|
+
else 0.8),
|
|
1940
|
+
width=2.5 if is_current else 1.0, antialias=True,
|
|
1941
|
+
mode="line_strip"))
|
|
1942
|
+
self.gl_points = np.vstack(points)
|
|
1943
|
+
self.gl_values = np.vstack(values)
|
|
1944
|
+
labels = [
|
|
1945
|
+
((size_x / 2, -0.12 * size_y, 0), self.x_label()),
|
|
1946
|
+
((0, -0.06 * size_y, 0), f"{x_min:.3g}"),
|
|
1947
|
+
((size_x, -0.06 * size_y, 0), f"{x_max:.3g}"),
|
|
1948
|
+
((size_x * 1.04, size_y / 2, 0), y_name),
|
|
1949
|
+
((size_x * 1.02, 0, 0), y_texts[0]),
|
|
1950
|
+
((size_x * 1.02, size_y, 0), y_texts[-1]),
|
|
1951
|
+
((0, size_y * 1.02, size_z), f"Intensity max {z_max:.3g}")]
|
|
1952
|
+
font = ren.QFont(ren.QApplication.font())
|
|
1953
|
+
font.setPointSize(max(font.pointSize() - 2, 1))
|
|
1954
|
+
for pos, text in labels:
|
|
1955
|
+
view.addItem(ren.gl.GLTextItem(pos=pos, text=str(text),
|
|
1956
|
+
color=ren.pg.mkColor(fg),
|
|
1957
|
+
font=font))
|
|
1958
|
+
self.gl_marker = ren.gl.GLLinePlotItem(
|
|
1959
|
+
color=self.gl_color(util.COLORS["yellow"]), width=2.0,
|
|
1960
|
+
antialias=True, mode="line_strip")
|
|
1961
|
+
view.addItem(self.gl_marker)
|
|
1962
|
+
self.update_gl_marker()
|
|
1963
|
+
|
|
1964
|
+
def update_gl_marker(self):
|
|
1965
|
+
"""Line at the q of the q-slice center, across all curves."""
|
|
1966
|
+
x_value = self.gl_marker_x()
|
|
1967
|
+
if self.gl_marker is None or x_value is None:
|
|
1968
|
+
return
|
|
1969
|
+
x_min, x_range = self.gl_scale
|
|
1970
|
+
size_x, size_y, _ = util.GL_BOX
|
|
1971
|
+
x = (x_value - x_min) / x_range * size_x
|
|
1972
|
+
self.gl_marker.setData(pos=np.array([[x, 0, 0], [x, size_y, 0]]))
|
|
1973
|
+
|
|
1974
|
+
|
|
1975
|
+
class MultiLinesViewer(GLWaterfallMixin, EddtViewer,
|
|
1976
|
+
ren.MultiLinesViewerUI):
|
|
1977
|
+
"""Patterns of all images at a row, in 3D (x = q, y = image, z =
|
|
1978
|
+
intensity), or a 2D waterfall without PyOpenGL."""
|
|
1979
|
+
|
|
1980
|
+
stack_mode = True
|
|
1981
|
+
|
|
1982
|
+
def gl_marker_x(self):
|
|
1983
|
+
data = self.dataset
|
|
1984
|
+
return None if data is None else self.slider_x.value() * data.x_step
|
|
1985
|
+
|
|
1986
|
+
def update_profile(self):
|
|
1987
|
+
if self.gl_view is None:
|
|
1988
|
+
return super().update_profile()
|
|
1989
|
+
data = self.dataset
|
|
1990
|
+
if data is None or self.row is None:
|
|
1991
|
+
return
|
|
1992
|
+
idx = self.slider_img.value()
|
|
1993
|
+
patterns = data.row_patterns(self.row)
|
|
1994
|
+
self.pattern_curves = [(data.x_list, patterns[i], f"image_{i}")
|
|
1995
|
+
for i in range(data.depth)]
|
|
1996
|
+
self.draw_gl_curves([(x, y) for x, y, _ in self.pattern_curves], idx,
|
|
1997
|
+
data.motor_name,
|
|
1998
|
+
[f"{p:.4g}" for p in data.positions])
|
|
1999
|
+
self.lbl_gl_title.setText(f"Patterns of all images at row "
|
|
2000
|
+
f"{self.row} | Red: "
|
|
2001
|
+
f"{self.position_text(data, idx)}")
|
|
2002
|
+
|
|
2003
|
+
|
|
2004
|
+
class MultiScansViewer(GLWaterfallMixin, PositionsMixin, ViewerLogic,
|
|
2005
|
+
ren.MultiScansViewerUI):
|
|
2006
|
+
"""Viewer of several 1D scans with the same number of images; the
|
|
2007
|
+
patterns of all scans are shown in 3D (x = q, y = scan, z =
|
|
2008
|
+
intensity)."""
|
|
2009
|
+
|
|
2010
|
+
def gl_marker_x(self):
|
|
2011
|
+
if not self.datasets:
|
|
2012
|
+
return None
|
|
2013
|
+
data, _ = self.current()
|
|
2014
|
+
return self.slider_x.value() * data.x_step
|
|
2015
|
+
|
|
2016
|
+
def scan_paths(self):
|
|
2017
|
+
return [p.strip() for p in self.edit_path.text().split(";")
|
|
2018
|
+
if p.strip()]
|
|
2019
|
+
|
|
2020
|
+
def num_images(self, path):
|
|
2021
|
+
"""Number of images of a scan (folder of tif files or HDF file), or
|
|
2022
|
+
None if unknown."""
|
|
2023
|
+
if os.path.isdir(path):
|
|
2024
|
+
return len(util.find_files(path))
|
|
2025
|
+
if path.lower().endswith(util.HDF_EXT) and os.path.isfile(path):
|
|
2026
|
+
key = self.combo_hdf_key.currentText().strip()
|
|
2027
|
+
try:
|
|
2028
|
+
return util.hdf_num_images(path, key) if key else None
|
|
2029
|
+
except OSError:
|
|
2030
|
+
return None
|
|
2031
|
+
return None
|
|
2032
|
+
|
|
2033
|
+
def add_scans(self, paths):
|
|
2034
|
+
"""Add scans to the list, dropping (with a warning) those whose
|
|
2035
|
+
number of images differs from the first scan, then load."""
|
|
2036
|
+
current = self.scan_paths()
|
|
2037
|
+
for path in paths:
|
|
2038
|
+
if path.lower().endswith(util.HDF_EXT) and \
|
|
2039
|
+
not self.combo_hdf_key.count():
|
|
2040
|
+
self.update_hdf_keys(path)
|
|
2041
|
+
new = [p for p in dict.fromkeys(paths) if p not in current]
|
|
2042
|
+
counts = {p: self.num_images(p) for p in current + new}
|
|
2043
|
+
known = [c for c in counts.values() if c is not None]
|
|
2044
|
+
if current and counts.get(current[0]) is not None:
|
|
2045
|
+
ref = counts[current[0]]
|
|
2046
|
+
elif known:
|
|
2047
|
+
# Most common number of images among the selected scans
|
|
2048
|
+
ref = max(set(known), key=known.count)
|
|
2049
|
+
else:
|
|
2050
|
+
ref = None
|
|
2051
|
+
kept, dropped = [], []
|
|
2052
|
+
for path in current + new:
|
|
2053
|
+
count = counts[path]
|
|
2054
|
+
if ref is not None and count is not None and count != ref:
|
|
2055
|
+
dropped.append(f"{scan_name_of(path)}: {count} images")
|
|
2056
|
+
else:
|
|
2057
|
+
kept.append(path)
|
|
2058
|
+
self.edit_path.setText("; ".join(kept))
|
|
2059
|
+
self.update_positions()
|
|
2060
|
+
if dropped:
|
|
2061
|
+
QMessageBox.warning(
|
|
2062
|
+
self, "Scans dropped",
|
|
2063
|
+
f"All scans must have the same number of images ({ref}). "
|
|
2064
|
+
f"Dropped:\n" + "\n".join(dropped))
|
|
2065
|
+
if kept:
|
|
2066
|
+
self.load_data()
|
|
2067
|
+
|
|
2068
|
+
@ren.safe_call
|
|
2069
|
+
def view_scans(self, paths):
|
|
2070
|
+
"""Replace the scans with folders / HDF files (e.g. selected in the
|
|
2071
|
+
Data browser); the first one gives the HDF key, metadata and
|
|
2072
|
+
q-step."""
|
|
2073
|
+
self.show_input(paths[0])
|
|
2074
|
+
self.add_scans(paths)
|
|
2075
|
+
|
|
2076
|
+
@ren.safe_call
|
|
2077
|
+
def browse_folder(self):
|
|
2078
|
+
folders = select_folders(self, "Select scan folder(s) of tif "
|
|
2079
|
+
"files", self.last_folder("data"))
|
|
2080
|
+
if folders:
|
|
2081
|
+
self.remember_folder("data", os.path.dirname(folders[0]))
|
|
2082
|
+
self.add_scans(folders)
|
|
2083
|
+
|
|
2084
|
+
@ren.safe_call
|
|
2085
|
+
def browse_file(self):
|
|
2086
|
+
paths, _ = QFileDialog.getOpenFileNames(
|
|
2087
|
+
self, "Select data file(s)", self.last_folder("data"),
|
|
2088
|
+
"Data (*.hdf *.h5 *.hdf5 *.nxs *.tif *.tiff);;All files (*.*)")
|
|
2089
|
+
if not paths:
|
|
2090
|
+
return
|
|
2091
|
+
self.remember_folder("data", paths[0])
|
|
2092
|
+
# A tif file stands for its folder
|
|
2093
|
+
scans = [p if p.lower().endswith(util.HDF_EXT)
|
|
2094
|
+
else os.path.dirname(p) for p in paths]
|
|
2095
|
+
self.add_scans(list(dict.fromkeys(scans)))
|
|
2096
|
+
|
|
2097
|
+
@ren.safe_call
|
|
2098
|
+
def load_data(self):
|
|
2099
|
+
paths = self.scan_paths()
|
|
2100
|
+
if not paths:
|
|
2101
|
+
raise ValueError("Please select the folders/files of the scans!")
|
|
2102
|
+
options = self.input_options()
|
|
2103
|
+
# The metadata of the first scan gives the positions of all scans
|
|
2104
|
+
options["metadata_path"] = self.metadata_for_all()
|
|
2105
|
+
for path in paths:
|
|
2106
|
+
if not self.check_scan_input(path, options["hdf_key"]):
|
|
2107
|
+
return
|
|
2108
|
+
# Scans share the memory budget; bigger ones are read on demand
|
|
2109
|
+
options["max_memory_mb"] = util.SCAN_IN_MEMORY_MB / len(paths)
|
|
2110
|
+
|
|
2111
|
+
def task(cancel_event):
|
|
2112
|
+
datasets = []
|
|
2113
|
+
try:
|
|
2114
|
+
for k, path in enumerate(paths):
|
|
2115
|
+
def progress(text, k=k):
|
|
2116
|
+
self.set_progress(f"Scan {k + 1}/{len(paths)}: "
|
|
2117
|
+
f"{text}")
|
|
2118
|
+
|
|
2119
|
+
data = util.load_scan(path, cancel_event=cancel_event,
|
|
2120
|
+
progress=progress, **options)
|
|
2121
|
+
if data is None:
|
|
2122
|
+
break
|
|
2123
|
+
datasets.append(data)
|
|
2124
|
+
except Exception:
|
|
2125
|
+
for data in datasets:
|
|
2126
|
+
data.close()
|
|
2127
|
+
raise
|
|
2128
|
+
if len(datasets) < len(paths):
|
|
2129
|
+
for data in datasets:
|
|
2130
|
+
data.close()
|
|
2131
|
+
return None
|
|
2132
|
+
return paths, datasets
|
|
2133
|
+
|
|
2134
|
+
self.run_worker(task, self.on_data_loaded, "Loading data",
|
|
2135
|
+
f"Loading {len(paths)} scan(s)...")
|
|
2136
|
+
|
|
2137
|
+
def on_data_loaded(self, result):
|
|
2138
|
+
if result is None:
|
|
2139
|
+
self.set_status("Loading cancelled.")
|
|
2140
|
+
return
|
|
2141
|
+
paths, datasets = result
|
|
2142
|
+
# Same number of images as the first scan (e.g. HDF scans unchecked
|
|
2143
|
+
# when added)
|
|
2144
|
+
ref = datasets[0].depth
|
|
2145
|
+
dropped = [f"{d.name}: {d.depth} images" for d in datasets
|
|
2146
|
+
if d.depth != ref]
|
|
2147
|
+
if dropped:
|
|
2148
|
+
for data in datasets:
|
|
2149
|
+
if data.depth != ref:
|
|
2150
|
+
data.close()
|
|
2151
|
+
pairs = [(p, d) for p, d in zip(paths, datasets)
|
|
2152
|
+
if d.depth == ref]
|
|
2153
|
+
paths, datasets = [p for p, _ in pairs], [d for _, d in pairs]
|
|
2154
|
+
self.edit_path.setText("; ".join(paths))
|
|
2155
|
+
QMessageBox.warning(
|
|
2156
|
+
self, "Scans dropped",
|
|
2157
|
+
f"All scans must have the same number of images ({ref}). "
|
|
2158
|
+
f"Dropped:\n" + "\n".join(dropped))
|
|
2159
|
+
for data in self.datasets or []:
|
|
2160
|
+
data.close()
|
|
2161
|
+
self.datasets = datasets
|
|
2162
|
+
self.row = None
|
|
2163
|
+
self.clear_profile()
|
|
2164
|
+
depth = max(d.depth for d in self.datasets)
|
|
2165
|
+
self.slider_img.set_range(depth - 1)
|
|
2166
|
+
self.slider_scan.set_range(len(self.datasets) - 1)
|
|
2167
|
+
self.slider_x.set_range(max(d.width for d in self.datasets) - 1)
|
|
2168
|
+
self.slider_img.set_value(0, notify=False)
|
|
2169
|
+
self.slider_scan.set_value(0, notify=False)
|
|
2170
|
+
self.slider_x.set_value(self.datasets[0].width // 2, notify=False)
|
|
2171
|
+
self.refresh_all()
|
|
2172
|
+
for plot in (self.p_img, self.p_slice):
|
|
2173
|
+
plot.enableAutoRange()
|
|
2174
|
+
notes = [f"{d.name}: {d.position_note}" for d in self.datasets
|
|
2175
|
+
if d.position_note]
|
|
2176
|
+
first = self.datasets[0]
|
|
2177
|
+
positions = " ".join(notes) or (
|
|
2178
|
+
"Positions: image index." if first.motor_name == "Image"
|
|
2179
|
+
else f"Positions: {first.motor_name}.")
|
|
2180
|
+
self.set_status(f"Loaded {len(self.datasets)} scan(s): "
|
|
2181
|
+
f"{', '.join(d.name for d in self.datasets)}. "
|
|
2182
|
+
f"{positions}{lazy_note(self.datasets)}")
|
|
2183
|
+
self.check_x_step()
|
|
2184
|
+
self.warn_positions(notes)
|
|
2185
|
+
|
|
2186
|
+
def current(self):
|
|
2187
|
+
data = self.datasets[self.slider_scan.value()]
|
|
2188
|
+
return data, min(self.slider_img.value(), data.depth - 1)
|
|
2189
|
+
|
|
2190
|
+
def update_image(self):
|
|
2191
|
+
if not self.datasets:
|
|
2192
|
+
return
|
|
2193
|
+
data, idx = self.current()
|
|
2194
|
+
self.show_scan_image(self.p_img, data.image(idx), data.x_step)
|
|
2195
|
+
self.set_title(self.p_img, f"Scan: {data.name} | "
|
|
2196
|
+
f"{self.position_text(data, idx)}")
|
|
2197
|
+
self.update_qslice()
|
|
2198
|
+
self.update_profile()
|
|
2199
|
+
|
|
2200
|
+
def update_qslice(self):
|
|
2201
|
+
if not self.datasets:
|
|
2202
|
+
return
|
|
2203
|
+
data, idx = self.current()
|
|
2204
|
+
x_idx = min(self.slider_x.value(), data.width - 1)
|
|
2205
|
+
self.qslice_raw = data.q_slice(x_idx, self.radius())
|
|
2206
|
+
self.show_qslice(self.qslice_raw, data.motor_name)
|
|
2207
|
+
self.set_title(self.p_slice, f"Scan: {data.name} | Mean around "
|
|
2208
|
+
f"{self.x_name()}="
|
|
2209
|
+
f"{x_idx * data.x_step:.4g}")
|
|
2210
|
+
self.set_span(x_idx, data.x_step)
|
|
2211
|
+
self.set_crosshairs(idx)
|
|
2212
|
+
|
|
2213
|
+
def update_profile(self):
|
|
2214
|
+
if not self.datasets or self.row is None:
|
|
2215
|
+
return
|
|
2216
|
+
img_idx = self.slider_img.value()
|
|
2217
|
+
curves = []
|
|
2218
|
+
for data in self.datasets:
|
|
2219
|
+
if img_idx < data.depth and self.row < data.height:
|
|
2220
|
+
curves.append((data.x_list, data.pattern(img_idx, self.row),
|
|
2221
|
+
data.name))
|
|
2222
|
+
else:
|
|
2223
|
+
curves.append((data.x_list, np.zeros(data.width),
|
|
2224
|
+
data.name))
|
|
2225
|
+
current = self.slider_scan.value()
|
|
2226
|
+
if self.gl_view is not None:
|
|
2227
|
+
self.pattern_curves = curves
|
|
2228
|
+
self.draw_gl_curves([(x, y) for x, y, _ in curves], current,
|
|
2229
|
+
"Scan", [d.name for d in self.datasets])
|
|
2230
|
+
data = self.datasets[current]
|
|
2231
|
+
self.lbl_gl_title.setText(
|
|
2232
|
+
f"Patterns of all scans at row {self.row} | "
|
|
2233
|
+
f"{self.position_text(data, min(img_idx, data.depth - 1))}"
|
|
2234
|
+
f" | Red: {data.name}")
|
|
2235
|
+
return
|
|
2236
|
+
self.plot_waterfall(curves, current, "Scan index (offset)")
|
|
2237
|
+
self.set_title(self.p_prof, f"Patterns at row {self.row} | Image "
|
|
2238
|
+
f"{img_idx}")
|
|
2239
|
+
|
|
2240
|
+
def on_click(self, plot, point):
|
|
2241
|
+
if not self.datasets:
|
|
2242
|
+
return
|
|
2243
|
+
data, _ = self.current()
|
|
2244
|
+
if plot is self.p_img:
|
|
2245
|
+
self.row = int(np.clip(round(point.y()), 0, data.height - 1))
|
|
2246
|
+
self.slider_x.set_value(data.x_index(point.x()), notify=False)
|
|
2247
|
+
self.update_qslice()
|
|
2248
|
+
self.update_profile()
|
|
2249
|
+
elif plot is self.p_slice:
|
|
2250
|
+
self.row = int(np.clip(round(point.x()), 0, data.height - 1))
|
|
2251
|
+
self.slider_img.set_value(int(np.clip(round(point.y()), 0,
|
|
2252
|
+
data.depth - 1)))
|
|
2253
|
+
elif plot is self.p_prof:
|
|
2254
|
+
self.slider_x.set_value(data.x_index(point.x()))
|
|
2255
|
+
|
|
2256
|
+
|
|
2257
|
+
class Scan2DViewer(Positions2DMixin, ViewerLogic, ren.Scan2DViewerUI):
|
|
2258
|
+
"""Viewer of one 2D scan (tif files loaded on demand, or a 4D HDF),
|
|
2259
|
+
with the positions of its rows and columns from the metadata."""
|
|
2260
|
+
|
|
2261
|
+
hdf_ndims = (3, 4)
|
|
2262
|
+
|
|
2263
|
+
def __init__(self):
|
|
2264
|
+
super().__init__()
|
|
2265
|
+
for edit in (self.edit_scan_nrow, self.edit_scan_ncol):
|
|
2266
|
+
edit.editingFinished.connect(self.update_positions)
|
|
2267
|
+
self.scan_grid_box.setEnabled(False)
|
|
2268
|
+
self.lbl_scan_grid.setEnabled(False)
|
|
2269
|
+
|
|
2270
|
+
def scan_grid(self):
|
|
2271
|
+
if not self.scan_grid_box.isEnabled():
|
|
2272
|
+
return None
|
|
2273
|
+
nrow = self.get_value(self.edit_scan_nrow, "Rows", int,
|
|
2274
|
+
allow_none=True)
|
|
2275
|
+
ncol = self.get_value(self.edit_scan_ncol, "Columns", int,
|
|
2276
|
+
allow_none=True)
|
|
2277
|
+
return nrow, ncol, self.combo_scan_order.currentText()
|
|
2278
|
+
|
|
2279
|
+
def update_positions(self):
|
|
2280
|
+
# The rows, columns and scan order are only for 3D HDF datasets
|
|
2281
|
+
path = self.first_path()
|
|
2282
|
+
ndim = None
|
|
2283
|
+
if os.path.isfile(path) and path.lower().endswith(util.HDF_EXT):
|
|
2284
|
+
try:
|
|
2285
|
+
ndim = util.hdf_ndim(path,
|
|
2286
|
+
self.combo_hdf_key.currentText().strip())
|
|
2287
|
+
except OSError:
|
|
2288
|
+
pass
|
|
2289
|
+
self.scan_grid_box.setEnabled(ndim == 3)
|
|
2290
|
+
self.lbl_scan_grid.setEnabled(ndim == 3)
|
|
2291
|
+
super().update_positions()
|
|
2292
|
+
|
|
2293
|
+
def input_options(self):
|
|
2294
|
+
options = super().input_options()
|
|
2295
|
+
options["scan_grid"] = self.scan_grid()
|
|
2296
|
+
return options
|
|
2297
|
+
|
|
2298
|
+
def apply_motor_labels(self):
|
|
2299
|
+
"""Names of the scan axes on the sliders and the q-slice choice."""
|
|
2300
|
+
data = self.dataset
|
|
2301
|
+
for slider, (name, _) in zip((self.slider_row, self.slider_col),
|
|
2302
|
+
data.motors):
|
|
2303
|
+
slider.label.setText(f"{name} (index)")
|
|
2304
|
+
index = self.combo_slice_axis.currentIndex()
|
|
2305
|
+
self.combo_slice_axis.blockSignals(True)
|
|
2306
|
+
self.combo_slice_axis.clear()
|
|
2307
|
+
self.combo_slice_axis.addItems([f"Axis 0: {data.motors[0][0]}",
|
|
2308
|
+
f"Axis 1: {data.motors[1][0]}"])
|
|
2309
|
+
self.combo_slice_axis.setCurrentIndex(max(index, 0))
|
|
2310
|
+
self.combo_slice_axis.blockSignals(False)
|
|
2311
|
+
|
|
2312
|
+
def position_title(self, row, col):
|
|
2313
|
+
(name0, pos0), (name1, pos1) = self.dataset.motors
|
|
2314
|
+
return f"{name0} = {pos0[row]:.6g} | {name1} = {pos1[col]:.6g}"
|
|
2315
|
+
|
|
2316
|
+
@ren.safe_call
|
|
2317
|
+
def load_data(self):
|
|
2318
|
+
try:
|
|
2319
|
+
dataset = util.Scan2DDataset(self.edit_path.text(),
|
|
2320
|
+
**self.input_options())
|
|
2321
|
+
except util.WrongDimensionError as error:
|
|
2322
|
+
self.offer_other_viewers(error)
|
|
2323
|
+
return
|
|
2324
|
+
if self.dataset is not None:
|
|
2325
|
+
self.dataset.close()
|
|
2326
|
+
self.dataset = dataset
|
|
2327
|
+
self.row = None
|
|
2328
|
+
self.qslice_key = None
|
|
2329
|
+
self.clear_profile()
|
|
2330
|
+
self.slider_row.set_range(dataset.nrow - 1)
|
|
2331
|
+
self.slider_col.set_range(dataset.ncol - 1)
|
|
2332
|
+
self.slider_x.set_range(dataset.width - 1)
|
|
2333
|
+
self.slider_row.set_value(0, notify=False)
|
|
2334
|
+
self.slider_col.set_value(0, notify=False)
|
|
2335
|
+
self.slider_x.set_value(dataset.width // 2, notify=False)
|
|
2336
|
+
self.apply_motor_labels()
|
|
2337
|
+
self.refresh_all()
|
|
2338
|
+
for plot in (self.p_img, self.p_slice):
|
|
2339
|
+
plot.enableAutoRange()
|
|
2340
|
+
order = f" Scan order: {dataset.scan_order}." \
|
|
2341
|
+
if dataset.scan_order else ""
|
|
2342
|
+
self.set_status(f"Loaded 2D scan {dataset.name}: "
|
|
2343
|
+
f"{dataset.nrow} x {dataset.ncol} images of shape "
|
|
2344
|
+
f"({dataset.height}, {dataset.width}).{order} "
|
|
2345
|
+
f"{self.positions_status()}")
|
|
2346
|
+
self.check_x_step()
|
|
2347
|
+
self.warn_positions(dataset.position_notes)
|
|
2348
|
+
|
|
2349
|
+
def indices(self):
|
|
2350
|
+
return self.slider_row.value(), self.slider_col.value()
|
|
2351
|
+
|
|
2352
|
+
def update_image(self):
|
|
2353
|
+
data = self.dataset
|
|
2354
|
+
if data is None:
|
|
2355
|
+
return
|
|
2356
|
+
row, col = self.indices()
|
|
2357
|
+
self.show_scan_image(self.p_img, data.get_image(row, col),
|
|
2358
|
+
data.x_step)
|
|
2359
|
+
self.set_title(self.p_img, self.position_title(row, col))
|
|
2360
|
+
self.update_qslice()
|
|
2361
|
+
self.update_profile()
|
|
2362
|
+
|
|
2363
|
+
def update_qslice(self):
|
|
2364
|
+
data = self.dataset
|
|
2365
|
+
if data is None:
|
|
2366
|
+
return
|
|
2367
|
+
axis = self.combo_slice_axis.currentIndex()
|
|
2368
|
+
row, col = self.indices()
|
|
2369
|
+
fixed = col if axis == 0 else row
|
|
2370
|
+
x_idx = self.slider_x.value()
|
|
2371
|
+
radius = self.radius()
|
|
2372
|
+
key = (axis, fixed, x_idx, radius)
|
|
2373
|
+
self.set_span(x_idx, data.x_step)
|
|
2374
|
+
if key != self.qslice_key:
|
|
2375
|
+
fixed_slider = self.slider_col if axis == 0 else self.slider_row
|
|
2376
|
+
needs_read = self.qslice_key is None or \
|
|
2377
|
+
self.qslice_key[:2] != (axis, fixed)
|
|
2378
|
+
if self.slider_x.is_dragging() or (
|
|
2379
|
+
needs_read and fixed_slider.is_dragging()):
|
|
2380
|
+
# Load when the slider is released
|
|
2381
|
+
return
|
|
2382
|
+
if needs_read:
|
|
2383
|
+
self.set_status(f"Loading q-slices along "
|
|
2384
|
+
f"{data.motors[axis][0]}...")
|
|
2385
|
+
QApplication.processEvents()
|
|
2386
|
+
self.qslice_raw = data.q_slice(axis, fixed, x_idx, radius)
|
|
2387
|
+
self.qslice_key = key
|
|
2388
|
+
if needs_read:
|
|
2389
|
+
self.set_status(f"Loaded q-slices along "
|
|
2390
|
+
f"{data.motors[axis][0]}.")
|
|
2391
|
+
self.show_qslice(self.qslice_raw, data.motors[axis][0])
|
|
2392
|
+
self.set_title(self.p_slice, f"Mean around {self.x_name()}="
|
|
2393
|
+
f"{x_idx * data.x_step:.4g}")
|
|
2394
|
+
self.set_crosshairs(row if axis == 0 else col)
|
|
2395
|
+
|
|
2396
|
+
def update_profile(self):
|
|
2397
|
+
data = self.dataset
|
|
2398
|
+
if data is None or self.row is None:
|
|
2399
|
+
return
|
|
2400
|
+
row, col = self.indices()
|
|
2401
|
+
self.plot_single(data.x_list, data.get_image(row, col)[self.row],
|
|
2402
|
+
f"Pattern at row {self.row} | "
|
|
2403
|
+
f"{self.position_title(row, col)}")
|
|
2404
|
+
|
|
2405
|
+
def on_click(self, plot, point):
|
|
2406
|
+
data = self.dataset
|
|
2407
|
+
if data is None:
|
|
2408
|
+
return
|
|
2409
|
+
if plot is self.p_img:
|
|
2410
|
+
self.row = int(np.clip(round(point.y()), 0, data.height - 1))
|
|
2411
|
+
self.slider_x.set_value(data.x_index(point.x()), notify=False)
|
|
2412
|
+
self.update_qslice()
|
|
2413
|
+
self.update_profile()
|
|
2414
|
+
elif plot is self.p_slice:
|
|
2415
|
+
self.row = int(np.clip(round(point.x()), 0, data.height - 1))
|
|
2416
|
+
slider = self.slider_row if self.combo_slice_axis.currentIndex() \
|
|
2417
|
+
== 0 else self.slider_col
|
|
2418
|
+
slider.set_value(int(np.clip(round(point.y()), 0,
|
|
2419
|
+
slider.spin.maximum())))
|
|
2420
|
+
elif plot is self.p_prof:
|
|
2421
|
+
self.slider_x.set_value(data.x_index(point.x()))
|
|
2422
|
+
|
|
2423
|
+
|
|
2424
|
+
class Volume4DViewer(Positions2DMixin, ViewerLogic, ren.Volume4DViewerUI):
|
|
2425
|
+
"""Viewer of a 4D HDF dataset (q, Z, rows, columns): volume at a
|
|
2426
|
+
q-range in 3D, q-Z image, 2D slice of the volume and pattern. Data are
|
|
2427
|
+
read on demand; big files can be downsampled."""
|
|
2428
|
+
|
|
2429
|
+
hdf_ndims = (4, 4)
|
|
2430
|
+
position_title = Scan2DViewer.position_title
|
|
2431
|
+
|
|
2432
|
+
def apply_motor_labels(self):
|
|
2433
|
+
"""Names of the scan axes on the sliders, slices and 3D view."""
|
|
2434
|
+
(name0, _), (name1, _) = self.dataset.motors
|
|
2435
|
+
self.slider_row.label.setText(name0)
|
|
2436
|
+
self.slider_col.label.setText(name1)
|
|
2437
|
+
self.align_slider_labels()
|
|
2438
|
+
combo = self.combo_slice_dir
|
|
2439
|
+
index = combo.currentIndex()
|
|
2440
|
+
combo.blockSignals(True)
|
|
2441
|
+
combo.clear()
|
|
2442
|
+
combo.addItems([f"Fixed {name0}: {name1} vs Z",
|
|
2443
|
+
f"Fixed {name1}: {name0} vs Z",
|
|
2444
|
+
f"Fixed Z: {name0} vs {name1}"])
|
|
2445
|
+
combo.setCurrentIndex(max(index, 0))
|
|
2446
|
+
combo.blockSignals(False)
|
|
2447
|
+
if self.gl_view is not None:
|
|
2448
|
+
self.draw_gl_frame()
|
|
2449
|
+
self.draw_volume()
|
|
2450
|
+
|
|
2451
|
+
@ren.safe_call
|
|
2452
|
+
def load_data(self):
|
|
2453
|
+
try:
|
|
2454
|
+
dataset = util.Volume4DDataset(self.edit_path.text(),
|
|
2455
|
+
**self.input_options())
|
|
2456
|
+
except util.WrongDimensionError as error:
|
|
2457
|
+
self.offer_other_viewers(error)
|
|
2458
|
+
return
|
|
2459
|
+
if self.dataset is not None:
|
|
2460
|
+
self.dataset.close()
|
|
2461
|
+
self.dataset = dataset
|
|
2462
|
+
self.volume = self.volume_key = None
|
|
2463
|
+
self.clear_profile()
|
|
2464
|
+
for slider, num, value in (
|
|
2465
|
+
(self.slider_x, dataset.width, dataset.width // 2),
|
|
2466
|
+
(self.slider_row, dataset.nrow, 0),
|
|
2467
|
+
(self.slider_col, dataset.ncol, 0),
|
|
2468
|
+
(self.slider_z, dataset.height, dataset.height // 2)):
|
|
2469
|
+
slider.set_range(num - 1)
|
|
2470
|
+
slider.set_value(value, notify=False)
|
|
2471
|
+
self.edit_ds_output.setText(
|
|
2472
|
+
util.downsample_output_path(dataset.source))
|
|
2473
|
+
self.apply_motor_labels()
|
|
2474
|
+
self.refresh_all()
|
|
2475
|
+
for plot in self.plots:
|
|
2476
|
+
plot.enableAutoRange()
|
|
2477
|
+
if self.gl_view is not None:
|
|
2478
|
+
self.reset_gl_camera()
|
|
2479
|
+
nbytes = util.format_bytes(dataset.volume_nbytes(self.radius()))
|
|
2480
|
+
self.set_status(f"Loaded 4D dataset {dataset.name}: (q, Z, rows, "
|
|
2481
|
+
f"columns) = {dataset.shape}; {nbytes} read per "
|
|
2482
|
+
f"q-range. {self.positions_status()}")
|
|
2483
|
+
self.check_x_step()
|
|
2484
|
+
self.warn_positions(dataset.position_notes)
|
|
2485
|
+
|
|
2486
|
+
def indices(self):
|
|
2487
|
+
return (self.slider_row.value(), self.slider_col.value(),
|
|
2488
|
+
self.slider_z.value())
|
|
2489
|
+
|
|
2490
|
+
def refresh_all(self):
|
|
2491
|
+
self.update_image()
|
|
2492
|
+
self.update_volume()
|
|
2493
|
+
|
|
2494
|
+
def update_image(self):
|
|
2495
|
+
"""q-Z image at the scan position, its pattern and the slice."""
|
|
2496
|
+
data = self.dataset
|
|
2497
|
+
if data is None:
|
|
2498
|
+
return
|
|
2499
|
+
if self.slider_row.is_dragging() or self.slider_col.is_dragging():
|
|
2500
|
+
# The slice comes from the volume in memory; the image waits
|
|
2501
|
+
self.update_slice()
|
|
2502
|
+
return
|
|
2503
|
+
row, col, _ = self.indices()
|
|
2504
|
+
self.show_scan_image(self.p_img, data.get_image(row, col),
|
|
2505
|
+
data.x_step)
|
|
2506
|
+
self.set_title(self.p_img, self.position_title(row, col))
|
|
2507
|
+
self.update_z()
|
|
2508
|
+
|
|
2509
|
+
def update_z(self):
|
|
2510
|
+
if self.dataset is None:
|
|
2511
|
+
return
|
|
2512
|
+
self.update_profile()
|
|
2513
|
+
self.update_slice()
|
|
2514
|
+
|
|
2515
|
+
def update_profile(self):
|
|
2516
|
+
data = self.dataset
|
|
2517
|
+
row, col, z = self.indices()
|
|
2518
|
+
self.plot_single(data.x_list, data.get_image(row, col)[z],
|
|
2519
|
+
f"Pattern at Z {z} | {self.position_title(row, col)}")
|
|
2520
|
+
self.img_row_line.setValue(z)
|
|
2521
|
+
self.img_row_line.show()
|
|
2522
|
+
|
|
2523
|
+
def update_volume(self):
|
|
2524
|
+
"""Volume at the q-range: read when the Q slider is released."""
|
|
2525
|
+
data = self.dataset
|
|
2526
|
+
if data is None:
|
|
2527
|
+
return
|
|
2528
|
+
x_idx, radius = self.slider_x.value(), self.radius()
|
|
2529
|
+
self.set_span(x_idx, data.x_step)
|
|
2530
|
+
if self.slider_x.is_dragging():
|
|
2531
|
+
return
|
|
2532
|
+
key = (x_idx, radius)
|
|
2533
|
+
if key != self.volume_key:
|
|
2534
|
+
loading = not data.has_volume(*key)
|
|
2535
|
+
if loading:
|
|
2536
|
+
self.set_status(
|
|
2537
|
+
f"Loading the volume at {self.x_name()} index {x_idx} "
|
|
2538
|
+
f"({util.format_bytes(data.volume_nbytes(radius))})...")
|
|
2539
|
+
QApplication.processEvents()
|
|
2540
|
+
self.volume = data.volume(*key)
|
|
2541
|
+
self.volume_key = key
|
|
2542
|
+
self.draw_volume()
|
|
2543
|
+
if loading:
|
|
2544
|
+
self.set_status(f"Volume at {self.x_name()} = "
|
|
2545
|
+
f"{x_idx * data.x_step:.4g} loaded.")
|
|
2546
|
+
self.update_slice()
|
|
2547
|
+
|
|
2548
|
+
update_qslice = update_volume
|
|
2549
|
+
|
|
2550
|
+
def update_slice(self):
|
|
2551
|
+
"""2D slice of the volume, with the crosshair of the indices."""
|
|
2552
|
+
data, vol = self.dataset, self.volume
|
|
2553
|
+
if data is None or vol is None:
|
|
2554
|
+
return
|
|
2555
|
+
row, col, z = self.indices()
|
|
2556
|
+
(name0, pos0), (name1, pos1) = data.motors
|
|
2557
|
+
mode = self.combo_slice_dir.currentIndex()
|
|
2558
|
+
z_label = "Z (strip index)"
|
|
2559
|
+
if mode == 0:
|
|
2560
|
+
mat, xlabel, ylabel = vol[:, row, :].T, z_label, name1
|
|
2561
|
+
hval, vval, fixed = col, z, f"{name0} = {pos0[row]:.6g}"
|
|
2562
|
+
elif mode == 1:
|
|
2563
|
+
mat, xlabel, ylabel = vol[:, :, col].T, z_label, name0
|
|
2564
|
+
hval, vval, fixed = row, z, f"{name1} = {pos1[col]:.6g}"
|
|
2565
|
+
else:
|
|
2566
|
+
mat, xlabel, ylabel = vol[z], f"{name1} (index)", name0
|
|
2567
|
+
hval, vval, fixed = row, col, f"Z = {z}"
|
|
2568
|
+
self.qslice_raw = mat
|
|
2569
|
+
self.show_image(self.p_slice, mat)
|
|
2570
|
+
self.set_label(self.p_slice, "bottom", xlabel)
|
|
2571
|
+
self.set_label(self.p_slice, "left", f"{ylabel} (index)")
|
|
2572
|
+
self.set_title(self.p_slice, f"Mean around {self.x_name()}="
|
|
2573
|
+
f"{self.volume_key[0] * data.x_step:.4g}"
|
|
2574
|
+
f" | {fixed}")
|
|
2575
|
+
self.slice_hline.setValue(hval)
|
|
2576
|
+
self.slice_vline.setValue(vval)
|
|
2577
|
+
self.slice_hline.show()
|
|
2578
|
+
self.slice_vline.show()
|
|
2579
|
+
self.apply_slice_aspect()
|
|
2580
|
+
self.update_gl_plane()
|
|
2581
|
+
|
|
2582
|
+
def pixel_size(self):
|
|
2583
|
+
sizes = [self.get_value(edit, f"Pixel size {name}")
|
|
2584
|
+
for edit, name in zip(self.edit_pixel, "xyz")]
|
|
2585
|
+
if min(sizes) <= 0:
|
|
2586
|
+
raise ValueError("Pixel sizes must be positive!")
|
|
2587
|
+
return sizes
|
|
2588
|
+
|
|
2589
|
+
def gl_box(self):
|
|
2590
|
+
"""Size of the 3D box with the real ratio; the longest side is
|
|
2591
|
+
the one of util.GL_BOX."""
|
|
2592
|
+
data = self.dataset
|
|
2593
|
+
if data is None:
|
|
2594
|
+
return util.GL_BOX
|
|
2595
|
+
px, py, pz = self.pixel_size()
|
|
2596
|
+
dims = np.array([data.ncol * px, data.nrow * py, data.height * pz])
|
|
2597
|
+
return tuple(dims / dims.max() * max(util.GL_BOX))
|
|
2598
|
+
|
|
2599
|
+
def reset_gl_camera(self):
|
|
2600
|
+
size_x, size_y, size_z = self.gl_box()
|
|
2601
|
+
self.gl_view.setCameraPosition(
|
|
2602
|
+
pos=ren.QVector3D(size_x / 2, size_y / 2, size_z / 2),
|
|
2603
|
+
distance=1.6 * max(size_x, size_y, size_z), elevation=25,
|
|
2604
|
+
azimuth=-60)
|
|
2605
|
+
|
|
2606
|
+
def apply_slice_aspect(self):
|
|
2607
|
+
"""Real ratio of the 2D slice with the 'equal' aspect."""
|
|
2608
|
+
if ren.display["aspect"] != "equal" or self.volume is None:
|
|
2609
|
+
return
|
|
2610
|
+
px, py, pz = self.pixel_size()
|
|
2611
|
+
mode = self.combo_slice_dir.currentIndex()
|
|
2612
|
+
# Image x / y: Z / columns, Z / rows, columns / rows
|
|
2613
|
+
ratio = (pz / px, pz / py, px / py)[mode]
|
|
2614
|
+
self.p_slice.getViewBox().setAspectLocked(True, ratio)
|
|
2615
|
+
|
|
2616
|
+
@ren.safe_call
|
|
2617
|
+
def apply_pixel_size(self):
|
|
2618
|
+
self.pixel_size()
|
|
2619
|
+
if self.dataset is None or self.gl_view is None:
|
|
2620
|
+
self.update_slice()
|
|
2621
|
+
return
|
|
2622
|
+
self.draw_gl_frame()
|
|
2623
|
+
self.draw_volume()
|
|
2624
|
+
self.update_slice()
|
|
2625
|
+
self.reset_gl_camera()
|
|
2626
|
+
|
|
2627
|
+
def thresholds(self):
|
|
2628
|
+
tmin = self.get_value(self.edit_tmin, "Threshold min %")
|
|
2629
|
+
tmax = self.get_value(self.edit_tmax, "Threshold max %")
|
|
2630
|
+
if not 0 <= tmin < tmax <= 100:
|
|
2631
|
+
raise ValueError("Thresholds must satisfy 0 <= Min < Max <= 100!")
|
|
2632
|
+
return tmin, tmax
|
|
2633
|
+
|
|
2634
|
+
@ren.safe_call
|
|
2635
|
+
def apply_thresholds(self):
|
|
2636
|
+
self.draw_volume()
|
|
2637
|
+
|
|
2638
|
+
def apply_display_settings(self, auto_range=False):
|
|
2639
|
+
super().apply_display_settings(auto_range)
|
|
2640
|
+
self.apply_slice_aspect()
|
|
2641
|
+
self.draw_volume()
|
|
2642
|
+
|
|
2643
|
+
def draw_gl_frame(self):
|
|
2644
|
+
"""Box, axis names and the marker of the slice plane."""
|
|
2645
|
+
view = self.gl_view
|
|
2646
|
+
view.clear()
|
|
2647
|
+
self.gl_volume = None
|
|
2648
|
+
size_x, size_y, size_z = self.gl_box()
|
|
2649
|
+
fg = ren.pg.mkColor(ren.sel_theme["PG_FG"])
|
|
2650
|
+
box = ren.gl.GLBoxItem()
|
|
2651
|
+
box.setSize(size_x, size_y, size_z)
|
|
2652
|
+
box.setColor(fg)
|
|
2653
|
+
view.addItem(box)
|
|
2654
|
+
(name0, _), (name1, _) = self.dataset.motors
|
|
2655
|
+
font = ren.QFont(ren.QApplication.font())
|
|
2656
|
+
font.setPointSize(max(font.pointSize() - 2, 1))
|
|
2657
|
+
for pos, text in (((size_x / 2, -0.08 * size_y, 0), name1),
|
|
2658
|
+
((-0.08 * size_x, size_y / 2, 0), name0),
|
|
2659
|
+
((0, 0, size_z * 1.04), "Z (strip 0 on top)")):
|
|
2660
|
+
view.addItem(ren.gl.GLTextItem(pos=pos, text=str(text),
|
|
2661
|
+
color=fg, font=font))
|
|
2662
|
+
self.gl_plane = ren.gl.GLLinePlotItem(
|
|
2663
|
+
color=GLWaterfallMixin.gl_color(util.COLORS["yellow"]),
|
|
2664
|
+
width=2.0, antialias=True, mode="line_strip")
|
|
2665
|
+
view.addItem(self.gl_plane)
|
|
2666
|
+
|
|
2667
|
+
def draw_volume(self):
|
|
2668
|
+
"""Volume with the colormap and contrast of the images; alpha grows
|
|
2669
|
+
with the intensity, voxels outside the thresholds are hidden."""
|
|
2670
|
+
vol = self.volume
|
|
2671
|
+
if vol is None:
|
|
2672
|
+
return
|
|
2673
|
+
if self.p_proj is not None:
|
|
2674
|
+
self.show_image(self.p_proj, vol.mean(axis=0))
|
|
2675
|
+
return
|
|
2676
|
+
step = max(1, int(np.ceil((vol.size / util.GL_MAX_VOXELS) ** (1 / 3))))
|
|
2677
|
+
sub = vol[::step, ::step, ::step]
|
|
2678
|
+
data = util.log_scale(sub) if ren.display["scale"] == "log" else sub
|
|
2679
|
+
tmin, tmax = self.thresholds()
|
|
2680
|
+
low, high = np.percentile(data, (tmin, tmax))
|
|
2681
|
+
vmin, vmax = util.get_levels(data, ren.display["pmin"],
|
|
2682
|
+
ren.display["pmax"])
|
|
2683
|
+
norm = np.clip((data - vmin) / max(vmax - vmin, 1e-12), 0, 1)
|
|
2684
|
+
rgba = ren.get_colormap(ren.display["cmap"]).map(
|
|
2685
|
+
norm.ravel(), mode="byte").reshape(norm.shape + (4,))
|
|
2686
|
+
alpha = norm * (util.GL_VOLUME_ALPHA * 255)
|
|
2687
|
+
alpha[(data < low) | (data > high)] = 0
|
|
2688
|
+
rgba[..., 3] = alpha.astype(np.ubyte)
|
|
2689
|
+
# GL axes: x = column, y = row, z = strip (strip 0 on top)
|
|
2690
|
+
rgba = np.ascontiguousarray(rgba[::-1].transpose(2, 1, 0, 3))
|
|
2691
|
+
if self.gl_volume is None:
|
|
2692
|
+
self.gl_volume = ren.gl.GLVolumeItem(rgba, sliceDensity=1,
|
|
2693
|
+
smooth=True,
|
|
2694
|
+
glOptions="translucent")
|
|
2695
|
+
self.gl_view.addItem(self.gl_volume)
|
|
2696
|
+
else:
|
|
2697
|
+
self.gl_volume.setData(rgba)
|
|
2698
|
+
size_x, size_y, size_z = self.gl_box()
|
|
2699
|
+
self.gl_volume.resetTransform()
|
|
2700
|
+
self.gl_volume.scale(size_x / rgba.shape[0], size_y / rgba.shape[1],
|
|
2701
|
+
size_z / rgba.shape[2])
|
|
2702
|
+
self.update_gl_plane()
|
|
2703
|
+
|
|
2704
|
+
def update_gl_plane(self):
|
|
2705
|
+
if self.gl_plane is None or self.dataset is None:
|
|
2706
|
+
return
|
|
2707
|
+
data = self.dataset
|
|
2708
|
+
row, col, z = self.indices()
|
|
2709
|
+
sx, sy, sz = self.gl_box()
|
|
2710
|
+
mode = self.combo_slice_dir.currentIndex()
|
|
2711
|
+
if mode == 0:
|
|
2712
|
+
y = (row + 0.5) / data.nrow * sy
|
|
2713
|
+
pts = [[0, y, 0], [sx, y, 0], [sx, y, sz], [0, y, sz]]
|
|
2714
|
+
elif mode == 1:
|
|
2715
|
+
x = (col + 0.5) / data.ncol * sx
|
|
2716
|
+
pts = [[x, 0, 0], [x, sy, 0], [x, sy, sz], [x, 0, sz]]
|
|
2717
|
+
else:
|
|
2718
|
+
h = (data.height - z - 0.5) / data.height * sz
|
|
2719
|
+
pts = [[0, 0, h], [sx, 0, h], [sx, sy, h], [0, sy, h]]
|
|
2720
|
+
self.gl_plane.setData(pos=np.array(pts + pts[:1], dtype=float))
|
|
2721
|
+
|
|
2722
|
+
def on_click(self, plot, point):
|
|
2723
|
+
data = self.dataset
|
|
2724
|
+
if data is None:
|
|
2725
|
+
return
|
|
2726
|
+
x, y = int(round(point.x())), int(round(point.y()))
|
|
2727
|
+
if plot is self.p_img:
|
|
2728
|
+
self.slider_z.set_value(y)
|
|
2729
|
+
self.slider_x.set_value(data.x_index(point.x()))
|
|
2730
|
+
elif plot is self.p_prof:
|
|
2731
|
+
self.slider_x.set_value(data.x_index(point.x()))
|
|
2732
|
+
elif plot is self.p_slice:
|
|
2733
|
+
mode = self.combo_slice_dir.currentIndex()
|
|
2734
|
+
if mode == 0:
|
|
2735
|
+
self.slider_z.set_value(x, notify=False)
|
|
2736
|
+
self.slider_col.set_value(y)
|
|
2737
|
+
elif mode == 1:
|
|
2738
|
+
self.slider_z.set_value(x, notify=False)
|
|
2739
|
+
self.slider_row.set_value(y)
|
|
2740
|
+
else:
|
|
2741
|
+
self.slider_col.set_value(x, notify=False)
|
|
2742
|
+
self.slider_row.set_value(y)
|
|
2743
|
+
|
|
2744
|
+
@ren.safe_call
|
|
2745
|
+
def browse_ds_output(self):
|
|
2746
|
+
start = self.edit_ds_output.text().strip() or \
|
|
2747
|
+
self.last_folder("output")
|
|
2748
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
2749
|
+
self, "Downsampled output file", start,
|
|
2750
|
+
"HDF (*.hdf *.h5 *.hdf5)")
|
|
2751
|
+
if path:
|
|
2752
|
+
self.remember_folder("output", path)
|
|
2753
|
+
self.edit_ds_output.setText(path)
|
|
2754
|
+
|
|
2755
|
+
@ren.safe_call
|
|
2756
|
+
def run_downsample(self):
|
|
2757
|
+
source = self.edit_path.text().strip()
|
|
2758
|
+
key = self.combo_hdf_key.currentText().strip()
|
|
2759
|
+
if not (os.path.isfile(source)
|
|
2760
|
+
and source.lower().endswith(util.HDF_EXT)) or not key:
|
|
2761
|
+
raise ValueError("Select a 4D HDF file and its HDF key as "
|
|
2762
|
+
"input!")
|
|
2763
|
+
bins = tuple(spin.value() for spin in self.spin_bins)
|
|
2764
|
+
if bins == (1, 1, 1, 1):
|
|
2765
|
+
raise ValueError("Set a bin larger than 1!")
|
|
2766
|
+
chunks = util.parse_chunks(self.edit_ds_chunks.text())
|
|
2767
|
+
output = self.edit_ds_output.text().strip() or \
|
|
2768
|
+
util.downsample_output_path(source)
|
|
2769
|
+
out_key = util.check_output_key(self.edit_ds_key.text())
|
|
2770
|
+
if os.path.exists(output):
|
|
2771
|
+
answer = QMessageBox.question(self, "Overwrite",
|
|
2772
|
+
f"{output} exists. Overwrite?")
|
|
2773
|
+
if answer != QMessageBox.Yes:
|
|
2774
|
+
return
|
|
2775
|
+
data = self.dataset
|
|
2776
|
+
if data is not None and Path(data.source).resolve() == \
|
|
2777
|
+
Path(output).resolve():
|
|
2778
|
+
data.close()
|
|
2779
|
+
self.dataset = None
|
|
2780
|
+
|
|
2781
|
+
def task(cancel_event):
|
|
2782
|
+
return util.downsample_4d(source, key, output, out_key, bins,
|
|
2783
|
+
chunks, report=self.set_progress,
|
|
2784
|
+
cancelled=cancel_event.is_set)
|
|
2785
|
+
|
|
2786
|
+
self.run_worker(task, lambda result: self.on_downsampled(
|
|
2787
|
+
result, output, out_key), "Downsampling", "Starting...")
|
|
2788
|
+
|
|
2789
|
+
def on_downsampled(self, result, output, out_key):
|
|
2790
|
+
message, cancelled = result
|
|
2791
|
+
self.set_status(message)
|
|
2792
|
+
if cancelled or not self.check_ds_load.isChecked():
|
|
2793
|
+
return
|
|
2794
|
+
# The binned q-step is read from the output
|
|
2795
|
+
self.edit_step.clear()
|
|
2796
|
+
self.set_path(output)
|
|
2797
|
+
self.combo_hdf_key.setCurrentText(out_key)
|
|
2798
|
+
self.load_data()
|
|
2799
|
+
|
|
2800
|
+
|
|
2801
|
+
# ---------------------------------------------------------------------------
|
|
2802
|
+
# Application controller
|
|
2803
|
+
# ---------------------------------------------------------------------------
|
|
2804
|
+
|
|
2805
|
+
class EdviewInteraction(QObject):
|
|
2806
|
+
"""Primary controller of the EDView application."""
|
|
2807
|
+
|
|
2808
|
+
def __init__(self, base_folder=None):
|
|
2809
|
+
super().__init__()
|
|
2810
|
+
self.shut_down = False
|
|
2811
|
+
self.app = QApplication.instance() or QApplication(sys.argv)
|
|
2812
|
+
self.app.setApplicationName(util.APP_NAME)
|
|
2813
|
+
if os.path.exists(ren.ICON_PATH):
|
|
2814
|
+
self.app.setWindowIcon(QIcon(ren.ICON_PATH))
|
|
2815
|
+
self.app.aboutToQuit.connect(self.shutdown)
|
|
2816
|
+
self.app.setFont(ren.select_ui_font(point_size=util.FONT_SIZE))
|
|
2817
|
+
self.tooltip_wrapper = ren.ToolTipWrapper()
|
|
2818
|
+
self.app.installEventFilter(self.tooltip_wrapper)
|
|
2819
|
+
config = util.load_config() or {}
|
|
2820
|
+
theme = config.get("theme", ren.DEFAULT_THEME)
|
|
2821
|
+
if theme not in ren.THEMES:
|
|
2822
|
+
theme = ren.DEFAULT_THEME
|
|
2823
|
+
ren.apply_theme(self.app, theme)
|
|
2824
|
+
self.browser = BrowserTab(base_folder)
|
|
2825
|
+
self.correction = CorrectionTab()
|
|
2826
|
+
self.browser.add_to_correction = self.correction.add_inputs
|
|
2827
|
+
self.viewers = {"EDDT viewer": EddtViewer(),
|
|
2828
|
+
"Multiple-lines viewer": MultiLinesViewer(),
|
|
2829
|
+
"Multiple-scans viewer": MultiScansViewer(),
|
|
2830
|
+
"2D-scan viewer": Scan2DViewer(),
|
|
2831
|
+
"4D viewer": Volume4DViewer()}
|
|
2832
|
+
self.tabs = [self.browser, self.correction] + \
|
|
2833
|
+
list(self.viewers.values())
|
|
2834
|
+
pages = [(self.browser, "Data browser"),
|
|
2835
|
+
(self.correction, "Data correction")] + \
|
|
2836
|
+
[(tab, name) for name, tab in self.viewers.items()]
|
|
2837
|
+
self.main_win = ren.MainWindow(pages)
|
|
2838
|
+
|
|
2839
|
+
def view_in(name, path):
|
|
2840
|
+
viewer = self.viewers[name]
|
|
2841
|
+
self.main_win.tab_widget.setCurrentWidget(viewer)
|
|
2842
|
+
viewer.show_input(path)
|
|
2843
|
+
viewer.load_data()
|
|
2844
|
+
|
|
2845
|
+
def metadata_to(name, path):
|
|
2846
|
+
viewer = self.viewers[name]
|
|
2847
|
+
self.main_win.tab_widget.setCurrentWidget(viewer)
|
|
2848
|
+
viewer.edit_metadata.setText(path)
|
|
2849
|
+
viewer.load_metadata()
|
|
2850
|
+
|
|
2851
|
+
def view_scans(paths):
|
|
2852
|
+
viewer = self.viewers[scans_viewer]
|
|
2853
|
+
self.main_win.tab_widget.setCurrentWidget(viewer)
|
|
2854
|
+
viewer.view_scans(paths)
|
|
2855
|
+
|
|
2856
|
+
scans_viewer = "Multiple-scans viewer"
|
|
2857
|
+
self.browser.scans_viewer = scans_viewer
|
|
2858
|
+
self.browser.view_scans = view_scans
|
|
2859
|
+
viewer_ndims = {name: viewer.hdf_ndims for name, viewer in
|
|
2860
|
+
self.viewers.items()}
|
|
2861
|
+
self.browser.viewer_ndims = viewer_ndims
|
|
2862
|
+
for name, viewer in self.viewers.items():
|
|
2863
|
+
viewer.viewer_name = name
|
|
2864
|
+
viewer.viewer_ndims = viewer_ndims
|
|
2865
|
+
viewer.open_in = view_in
|
|
2866
|
+
self.browser.view_in = view_in
|
|
2867
|
+
self.browser.metadata_to = metadata_to
|
|
2868
|
+
self.main_win.combo_theme.blockSignals(True)
|
|
2869
|
+
self.main_win.combo_theme.setCurrentText(theme)
|
|
2870
|
+
self.main_win.combo_theme.blockSignals(False)
|
|
2871
|
+
self.main_win.combo_theme.currentTextChanged.connect(
|
|
2872
|
+
self.on_theme_changed)
|
|
2873
|
+
self.main_win.close_handler = self.on_close_requested
|
|
2874
|
+
win = self.main_win
|
|
2875
|
+
for combo in (win.combo_cmap, win.combo_scale, win.combo_aspect):
|
|
2876
|
+
combo.currentTextChanged.connect(
|
|
2877
|
+
lambda _t: self.on_display_changed())
|
|
2878
|
+
for edit in (win.edit_pmin, win.edit_pmax):
|
|
2879
|
+
edit.editingFinished.connect(self.on_contrast_entered)
|
|
2880
|
+
win.btn_reset.clicked.connect(self.reset_display)
|
|
2881
|
+
|
|
2882
|
+
def on_display_changed(self):
|
|
2883
|
+
"""Apply the colormap, scale and aspect to the images of all tabs."""
|
|
2884
|
+
win = self.main_win
|
|
2885
|
+
aspect = win.combo_aspect.currentText()
|
|
2886
|
+
aspect_changed = aspect != ren.display["aspect"]
|
|
2887
|
+
ren.display.update(cmap=win.combo_cmap.currentText(),
|
|
2888
|
+
scale=win.combo_scale.currentText(),
|
|
2889
|
+
aspect=aspect)
|
|
2890
|
+
self.redraw_images(auto_range=aspect_changed)
|
|
2891
|
+
|
|
2892
|
+
def on_contrast_entered(self):
|
|
2893
|
+
win = self.main_win
|
|
2894
|
+
try:
|
|
2895
|
+
pmin = util.to_number(win.edit_pmin.text(), "Min %")
|
|
2896
|
+
pmax = util.to_number(win.edit_pmax.text(), "Max %")
|
|
2897
|
+
if not 0 <= pmin < pmax <= 100:
|
|
2898
|
+
raise ValueError("Percentiles must satisfy 0 <= Min < Max "
|
|
2899
|
+
"<= 100!")
|
|
2900
|
+
except ValueError as error:
|
|
2901
|
+
QMessageBox.critical(win, "Error", str(error))
|
|
2902
|
+
win.edit_pmin.setText(f"{ren.display['pmin']:g}")
|
|
2903
|
+
win.edit_pmax.setText(f"{ren.display['pmax']:g}")
|
|
2904
|
+
return
|
|
2905
|
+
if (pmin, pmax) == (ren.display["pmin"], ren.display["pmax"]):
|
|
2906
|
+
return
|
|
2907
|
+
ren.display.update(pmin=pmin, pmax=pmax)
|
|
2908
|
+
self.redraw_images()
|
|
2909
|
+
|
|
2910
|
+
def redraw_images(self, auto_range=False):
|
|
2911
|
+
QApplication.setOverrideCursor(Qt.WaitCursor)
|
|
2912
|
+
try:
|
|
2913
|
+
for tab in self.tabs:
|
|
2914
|
+
try:
|
|
2915
|
+
tab.apply_display_settings(auto_range)
|
|
2916
|
+
except Exception as error:
|
|
2917
|
+
traceback.print_exc()
|
|
2918
|
+
tab.set_status(f"Error: {error}")
|
|
2919
|
+
finally:
|
|
2920
|
+
QApplication.restoreOverrideCursor()
|
|
2921
|
+
|
|
2922
|
+
def reset_display(self):
|
|
2923
|
+
"""Default contrast, and full view of the plots of the current
|
|
2924
|
+
tab."""
|
|
2925
|
+
win = self.main_win
|
|
2926
|
+
pmin, pmax = (float(v) for v in util.IMAGE_PERCENTILES)
|
|
2927
|
+
win.edit_pmin.setText(f"{pmin:g}")
|
|
2928
|
+
win.edit_pmax.setText(f"{pmax:g}")
|
|
2929
|
+
if (pmin, pmax) != (ren.display["pmin"], ren.display["pmax"]):
|
|
2930
|
+
ren.display.update(pmin=pmin, pmax=pmax)
|
|
2931
|
+
self.redraw_images()
|
|
2932
|
+
for plot in getattr(win.tab_widget.currentWidget(), "plots", []):
|
|
2933
|
+
plot.enableAutoRange()
|
|
2934
|
+
|
|
2935
|
+
def on_theme_changed(self, theme):
|
|
2936
|
+
self.main_win.setUpdatesEnabled(False)
|
|
2937
|
+
try:
|
|
2938
|
+
ren.apply_theme(self.app, theme)
|
|
2939
|
+
for tab in self.tabs:
|
|
2940
|
+
tab.refresh_plot_theme()
|
|
2941
|
+
finally:
|
|
2942
|
+
self.main_win.setUpdatesEnabled(True)
|
|
2943
|
+
util.update_config(theme=theme)
|
|
2944
|
+
|
|
2945
|
+
def on_close_requested(self):
|
|
2946
|
+
"""Stop running calculations. Return False to cancel closing."""
|
|
2947
|
+
busy = [tab for tab in self.tabs if tab.is_busy()]
|
|
2948
|
+
if busy:
|
|
2949
|
+
answer = QMessageBox.question(self.main_win, "Quit",
|
|
2950
|
+
"A calculation is running. Quit "
|
|
2951
|
+
"anyway?")
|
|
2952
|
+
if answer != QMessageBox.Yes:
|
|
2953
|
+
return False
|
|
2954
|
+
self.shutdown()
|
|
2955
|
+
return True
|
|
2956
|
+
|
|
2957
|
+
def shutdown(self):
|
|
2958
|
+
"""Cancel the running calculations, wait for them to stop (each
|
|
2959
|
+
step must finish first) and close the open HDF files. Called on
|
|
2960
|
+
closing the window and on quitting (e.g. Ctrl+C)."""
|
|
2961
|
+
if self.shut_down:
|
|
2962
|
+
return
|
|
2963
|
+
self.shut_down = True
|
|
2964
|
+
busy = [tab for tab in self.tabs if tab.is_busy()]
|
|
2965
|
+
for tab in self.tabs:
|
|
2966
|
+
tab.closing = True
|
|
2967
|
+
for tab in busy:
|
|
2968
|
+
tab.cancel_event.set()
|
|
2969
|
+
for tab in busy:
|
|
2970
|
+
tab.worker.join(util.EXIT_WAIT_S / len(busy))
|
|
2971
|
+
if tab.worker.is_alive():
|
|
2972
|
+
print(f"Warning: a calculation of the {type(tab).__name__} "
|
|
2973
|
+
f"didn't stop in time.", file=sys.stderr, flush=True)
|
|
2974
|
+
for viewer in self.viewers.values():
|
|
2975
|
+
for data in viewer.loaded_datasets():
|
|
2976
|
+
try:
|
|
2977
|
+
data.close()
|
|
2978
|
+
except Exception:
|
|
2979
|
+
traceback.print_exc()
|
|
2980
|
+
|
|
2981
|
+
def run(self):
|
|
2982
|
+
self.main_win.show()
|
|
2983
|
+
self.main_win.center_on_screen()
|
|
2984
|
+
return self.app.exec()
|