py4D-browser-flexloader 0.0.5__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.
- py4d_browser_flexloader-0.0.5.dist-info/METADATA +113 -0
- py4d_browser_flexloader-0.0.5.dist-info/RECORD +10 -0
- py4d_browser_flexloader-0.0.5.dist-info/WHEEL +5 -0
- py4d_browser_flexloader-0.0.5.dist-info/licenses/LICENSE.txt +675 -0
- py4d_browser_flexloader-0.0.5.dist-info/top_level.txt +1 -0
- py4d_browser_plugin/flexloader/__init__.py +10 -0
- py4d_browser_plugin/flexloader/backends.py +219 -0
- py4d_browser_plugin/flexloader/dialog.py +359 -0
- py4d_browser_plugin/flexloader/flexloader.py +116 -0
- py4d_browser_plugin/flexloader/selection.py +287 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Iterable
|
|
6
|
+
|
|
7
|
+
import h5py
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class DataNode:
|
|
12
|
+
path: str
|
|
13
|
+
name: str
|
|
14
|
+
kind: str
|
|
15
|
+
backend: str
|
|
16
|
+
shape: tuple[int, ...] | None = None
|
|
17
|
+
dtype: str | None = None
|
|
18
|
+
chunks: tuple[int, ...] | None = None
|
|
19
|
+
attrs: dict[str, str] = field(default_factory=dict)
|
|
20
|
+
children: list["DataNode"] = field(default_factory=list)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def is_array(self) -> bool:
|
|
24
|
+
return self.kind == "array"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DataSource:
|
|
28
|
+
backend = "unknown"
|
|
29
|
+
|
|
30
|
+
def __init__(self, filepath: str):
|
|
31
|
+
self.filepath = filepath
|
|
32
|
+
self._arrays: dict[str, Any] = {}
|
|
33
|
+
|
|
34
|
+
def scan(self) -> DataNode:
|
|
35
|
+
raise NotImplementedError
|
|
36
|
+
|
|
37
|
+
def get_array(self, path: str):
|
|
38
|
+
return self._arrays[path]
|
|
39
|
+
|
|
40
|
+
def close(self) -> None:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def open_source(filepath: str) -> DataSource:
|
|
45
|
+
path = Path(filepath)
|
|
46
|
+
suffixes = [suffix.lower() for suffix in path.suffixes]
|
|
47
|
+
if path.is_dir() or ".zarr" in suffixes or suffixes[-2:] == [".zarr", ".zip"]:
|
|
48
|
+
return ZarrSource(filepath)
|
|
49
|
+
else:
|
|
50
|
+
return HDF5Source(filepath)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class HDF5Source(DataSource):
|
|
54
|
+
backend = "HDF5"
|
|
55
|
+
|
|
56
|
+
def __init__(self, filepath: str):
|
|
57
|
+
super().__init__(filepath)
|
|
58
|
+
self._file = h5py.File(filepath, "r")
|
|
59
|
+
self._root: DataNode | None = None
|
|
60
|
+
|
|
61
|
+
def scan(self) -> DataNode:
|
|
62
|
+
self._arrays.clear()
|
|
63
|
+
self._root = self._scan_group(self._file, "/")
|
|
64
|
+
return self._root
|
|
65
|
+
|
|
66
|
+
def close(self) -> None:
|
|
67
|
+
self._file.close()
|
|
68
|
+
|
|
69
|
+
def _scan_group(self, group: h5py.Group, path: str) -> DataNode:
|
|
70
|
+
node = DataNode(
|
|
71
|
+
path=path,
|
|
72
|
+
name="/" if path == "/" else path.rsplit("/", 1)[-1],
|
|
73
|
+
kind="group",
|
|
74
|
+
backend=self.backend,
|
|
75
|
+
attrs=_stringify_attrs(group.attrs),
|
|
76
|
+
)
|
|
77
|
+
for name in group.keys():
|
|
78
|
+
child = group[name]
|
|
79
|
+
child_path = f"/{name}" if path == "/" else f"{path}/{name}"
|
|
80
|
+
if isinstance(child, h5py.Dataset):
|
|
81
|
+
self._arrays[child_path] = child
|
|
82
|
+
node.children.append(
|
|
83
|
+
DataNode(
|
|
84
|
+
path=child_path,
|
|
85
|
+
name=name,
|
|
86
|
+
kind="array",
|
|
87
|
+
backend=self.backend,
|
|
88
|
+
shape=tuple(int(size) for size in child.shape),
|
|
89
|
+
dtype=str(child.dtype),
|
|
90
|
+
chunks=tuple(child.chunks) if child.chunks is not None else None,
|
|
91
|
+
attrs=_stringify_attrs(child.attrs),
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
elif isinstance(child, h5py.Group):
|
|
95
|
+
node.children.append(self._scan_group(child, child_path))
|
|
96
|
+
return node
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ZarrSource(DataSource):
|
|
100
|
+
backend = "Zarr"
|
|
101
|
+
|
|
102
|
+
def __init__(self, filepath: str):
|
|
103
|
+
super().__init__(filepath)
|
|
104
|
+
try:
|
|
105
|
+
import zarr
|
|
106
|
+
except ImportError as exc:
|
|
107
|
+
raise ImportError("The flexloader Zarr backend requires zarr.") from exc
|
|
108
|
+
|
|
109
|
+
self._zarr = zarr
|
|
110
|
+
self._store = None
|
|
111
|
+
suffixes = [suffix.lower() for suffix in Path(filepath).suffixes]
|
|
112
|
+
if suffixes[-2:] == [".zarr", ".zip"] or suffixes[-1:] == [".zip"]:
|
|
113
|
+
try:
|
|
114
|
+
self._store = zarr.storage.ZipStore(filepath, mode="r")
|
|
115
|
+
self._root = zarr.open(store=self._store, mode="r")
|
|
116
|
+
except Exception:
|
|
117
|
+
self._store = None
|
|
118
|
+
self._root = zarr.open(filepath, mode="r")
|
|
119
|
+
else:
|
|
120
|
+
self._root = zarr.open(filepath, mode="r")
|
|
121
|
+
self._root_node: DataNode | None = None
|
|
122
|
+
|
|
123
|
+
def scan(self) -> DataNode:
|
|
124
|
+
self._arrays.clear()
|
|
125
|
+
if _is_zarr_array(self._root):
|
|
126
|
+
self._root_node = self._scan_array(self._root, "/")
|
|
127
|
+
else:
|
|
128
|
+
self._root_node = self._scan_group(self._root, "/")
|
|
129
|
+
return self._root_node
|
|
130
|
+
|
|
131
|
+
def close(self) -> None:
|
|
132
|
+
if self._store is not None:
|
|
133
|
+
close = getattr(self._store, "close", None)
|
|
134
|
+
if close is not None:
|
|
135
|
+
close()
|
|
136
|
+
|
|
137
|
+
def _scan_group(self, group, path: str) -> DataNode:
|
|
138
|
+
node = DataNode(
|
|
139
|
+
path=path,
|
|
140
|
+
name="/" if path == "/" else path.rsplit("/", 1)[-1],
|
|
141
|
+
kind="group",
|
|
142
|
+
backend=self.backend,
|
|
143
|
+
attrs=_stringify_attrs(getattr(group, "attrs", {})),
|
|
144
|
+
)
|
|
145
|
+
for name, child in _iter_zarr_children(group):
|
|
146
|
+
child_path = f"/{name}" if path == "/" else f"{path}/{name}"
|
|
147
|
+
if _is_zarr_array(child):
|
|
148
|
+
self._arrays[child_path] = child
|
|
149
|
+
chunks = getattr(child, "chunks", None)
|
|
150
|
+
node.children.append(
|
|
151
|
+
DataNode(
|
|
152
|
+
path=child_path,
|
|
153
|
+
name=name,
|
|
154
|
+
kind="array",
|
|
155
|
+
backend=self.backend,
|
|
156
|
+
shape=tuple(int(size) for size in child.shape),
|
|
157
|
+
dtype=str(child.dtype),
|
|
158
|
+
chunks=tuple(chunks) if chunks is not None else None,
|
|
159
|
+
attrs=_stringify_attrs(getattr(child, "attrs", {})),
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
else:
|
|
163
|
+
node.children.append(self._scan_group(child, child_path))
|
|
164
|
+
return node
|
|
165
|
+
|
|
166
|
+
def _scan_array(self, array, path: str) -> DataNode:
|
|
167
|
+
self._arrays[path] = array
|
|
168
|
+
chunks = getattr(array, "chunks", None)
|
|
169
|
+
return DataNode(
|
|
170
|
+
path=path,
|
|
171
|
+
name=Path(self.filepath).name if path == "/" else path.rsplit("/", 1)[-1],
|
|
172
|
+
kind="array",
|
|
173
|
+
backend=self.backend,
|
|
174
|
+
shape=tuple(int(size) for size in array.shape),
|
|
175
|
+
dtype=str(array.dtype),
|
|
176
|
+
chunks=tuple(chunks) if chunks is not None else None,
|
|
177
|
+
attrs=_stringify_attrs(getattr(array, "attrs", {})),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _iter_zarr_children(group) -> Iterable[tuple[str, Any]]:
|
|
182
|
+
try:
|
|
183
|
+
yield from group.items()
|
|
184
|
+
return
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
for name in group.keys():
|
|
190
|
+
yield name, group[name]
|
|
191
|
+
except Exception:
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _is_zarr_array(obj) -> bool:
|
|
196
|
+
return hasattr(obj, "shape") and hasattr(obj, "dtype") and not hasattr(obj, "keys")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _stringify_attrs(attrs) -> dict[str, str]:
|
|
200
|
+
out: dict[str, str] = {}
|
|
201
|
+
try:
|
|
202
|
+
items = attrs.items()
|
|
203
|
+
except Exception:
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
for key, value in items:
|
|
207
|
+
text = repr(_to_plain_value(value))
|
|
208
|
+
if len(text) > 300:
|
|
209
|
+
text = text[:297] + "..."
|
|
210
|
+
out[str(key)] = text
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _to_plain_value(value):
|
|
215
|
+
if hasattr(value, "tolist"):
|
|
216
|
+
return value.tolist()
|
|
217
|
+
if isinstance(value, bytes):
|
|
218
|
+
return value.decode(errors="replace")
|
|
219
|
+
return value
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pyqtgraph as pg
|
|
8
|
+
from PyQt5.QtCore import Qt
|
|
9
|
+
from PyQt5.QtWidgets import (
|
|
10
|
+
QAbstractItemView,
|
|
11
|
+
QComboBox,
|
|
12
|
+
QDialog,
|
|
13
|
+
QFileDialog,
|
|
14
|
+
QGridLayout,
|
|
15
|
+
QGroupBox,
|
|
16
|
+
QHBoxLayout,
|
|
17
|
+
QLabel,
|
|
18
|
+
QMessageBox,
|
|
19
|
+
QPushButton,
|
|
20
|
+
QSpinBox,
|
|
21
|
+
QSplitter,
|
|
22
|
+
QTextEdit,
|
|
23
|
+
QTreeWidget,
|
|
24
|
+
QTreeWidgetItem,
|
|
25
|
+
QVBoxLayout,
|
|
26
|
+
QWidget,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
from .backends import DataNode, DataSource, open_source
|
|
30
|
+
from .selection import ALL_ROLES, DATACUBE_ROLES, DimensionSelection, default_roles
|
|
31
|
+
from .selection import ROLE_FIXED, ROLE_FLATTENED_SCAN, default_scan_shape
|
|
32
|
+
from .selection import load_preview_arrays, validate_selection
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from py4D_browser import DataViewer
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FlexLoaderDialog(QDialog):
|
|
39
|
+
def __init__(self, filepath: str, parent: "DataViewer"):
|
|
40
|
+
super().__init__(parent)
|
|
41
|
+
self.parent_viewer = parent
|
|
42
|
+
self.filepath = filepath
|
|
43
|
+
self.source: DataSource | None = None
|
|
44
|
+
self.root_node: DataNode | None = None
|
|
45
|
+
self.selected_node: DataNode | None = None
|
|
46
|
+
self.role_boxes: list[QComboBox] = []
|
|
47
|
+
self.index_boxes: list[QSpinBox] = []
|
|
48
|
+
self.scan_y_boxes: list[QSpinBox] = []
|
|
49
|
+
self.scan_x_boxes: list[QSpinBox] = []
|
|
50
|
+
self.preview_button: QPushButton | None = None
|
|
51
|
+
self.diffraction_preview: pg.ImageView | None = None
|
|
52
|
+
self.axial_bf_preview: pg.ImageView | None = None
|
|
53
|
+
self.preview_status: QLabel | None = None
|
|
54
|
+
|
|
55
|
+
self.setWindowTitle(f"Flex Loader - {Path(filepath).name}")
|
|
56
|
+
self.resize(900, 600)
|
|
57
|
+
self._build_layout()
|
|
58
|
+
self._open_source(filepath)
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def select_hdf5_file(cls, parent) -> str | None:
|
|
62
|
+
filename, _ = QFileDialog.getOpenFileName(
|
|
63
|
+
parent,
|
|
64
|
+
"Open HDF5 Data",
|
|
65
|
+
"",
|
|
66
|
+
"HDF5 (*.h5 *.hdf5 *.emd *.mat *.py4dstem);;Any file (*)",
|
|
67
|
+
)
|
|
68
|
+
return filename or None
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def select_zarr_directory(cls, parent) -> str | None:
|
|
72
|
+
directory = QFileDialog.getExistingDirectory(parent, "Open Zarr Directory", "")
|
|
73
|
+
return directory or None
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def select_zarr_zip_file(cls, parent) -> str | None:
|
|
77
|
+
filename, _ = QFileDialog.getOpenFileName(
|
|
78
|
+
parent,
|
|
79
|
+
"Open Zarr Zip File",
|
|
80
|
+
"",
|
|
81
|
+
"Zarr Zip (*.zip *.zarr.zip);;Any file (*)",
|
|
82
|
+
)
|
|
83
|
+
return filename or None
|
|
84
|
+
|
|
85
|
+
def closeEvent(self, event):
|
|
86
|
+
self.close_source()
|
|
87
|
+
super().closeEvent(event)
|
|
88
|
+
|
|
89
|
+
def close_source(self) -> None:
|
|
90
|
+
if self.source is not None:
|
|
91
|
+
self.source.close()
|
|
92
|
+
self.source = None
|
|
93
|
+
|
|
94
|
+
def _build_layout(self) -> None:
|
|
95
|
+
layout = QVBoxLayout(self)
|
|
96
|
+
|
|
97
|
+
splitter = QSplitter(Qt.Horizontal)
|
|
98
|
+
layout.addWidget(splitter)
|
|
99
|
+
|
|
100
|
+
self.tree = QTreeWidget()
|
|
101
|
+
self.tree.setHeaderLabels(["Dataset", "Shape", "Type"])
|
|
102
|
+
self.tree.setSelectionMode(QAbstractItemView.SingleSelection)
|
|
103
|
+
self.tree.currentItemChanged.connect(self._tree_selection_changed)
|
|
104
|
+
splitter.addWidget(self.tree)
|
|
105
|
+
|
|
106
|
+
right_panel = QWidget()
|
|
107
|
+
right_layout = QVBoxLayout(right_panel)
|
|
108
|
+
splitter.addWidget(right_panel)
|
|
109
|
+
|
|
110
|
+
self.details = QTextEdit()
|
|
111
|
+
self.details.setReadOnly(True)
|
|
112
|
+
right_layout.addWidget(self.details, stretch=1)
|
|
113
|
+
|
|
114
|
+
self.mapping_box = QGroupBox("Dimension Mapping")
|
|
115
|
+
self.mapping_layout = QGridLayout(self.mapping_box)
|
|
116
|
+
right_layout.addWidget(self.mapping_box)
|
|
117
|
+
|
|
118
|
+
self.preview_box = QGroupBox("Preview")
|
|
119
|
+
preview_layout = QVBoxLayout(self.preview_box)
|
|
120
|
+
preview_top_layout = QHBoxLayout()
|
|
121
|
+
self.preview_button = QPushButton("Update Preview")
|
|
122
|
+
self.preview_button.setEnabled(False)
|
|
123
|
+
self.preview_button.clicked.connect(self._update_preview)
|
|
124
|
+
preview_top_layout.addWidget(self.preview_button)
|
|
125
|
+
self.preview_status = QLabel("Select a dataset and valid mapping.")
|
|
126
|
+
preview_top_layout.addWidget(self.preview_status, stretch=1)
|
|
127
|
+
preview_layout.addLayout(preview_top_layout)
|
|
128
|
+
|
|
129
|
+
preview_image_layout = QHBoxLayout()
|
|
130
|
+
self.diffraction_preview = _make_image_view()
|
|
131
|
+
self.axial_bf_preview = _make_image_view()
|
|
132
|
+
preview_image_layout.addWidget(_labeled_widget("Central DP", self.diffraction_preview))
|
|
133
|
+
preview_image_layout.addWidget(_labeled_widget("Axial BF", self.axial_bf_preview))
|
|
134
|
+
preview_layout.addLayout(preview_image_layout)
|
|
135
|
+
right_layout.addWidget(self.preview_box, stretch=1)
|
|
136
|
+
|
|
137
|
+
button_layout = QHBoxLayout()
|
|
138
|
+
button_layout.addStretch()
|
|
139
|
+
self.load_button = QPushButton("Load")
|
|
140
|
+
self.load_button.setEnabled(False)
|
|
141
|
+
self.load_button.clicked.connect(self.accept)
|
|
142
|
+
button_layout.addWidget(self.load_button)
|
|
143
|
+
cancel_button = QPushButton("Cancel")
|
|
144
|
+
cancel_button.clicked.connect(self.reject)
|
|
145
|
+
button_layout.addWidget(cancel_button)
|
|
146
|
+
layout.addLayout(button_layout)
|
|
147
|
+
|
|
148
|
+
splitter.setSizes([360, 540])
|
|
149
|
+
|
|
150
|
+
def _open_source(self, filepath: str) -> None:
|
|
151
|
+
try:
|
|
152
|
+
self.source = open_source(filepath)
|
|
153
|
+
self.root_node = self.source.scan()
|
|
154
|
+
except Exception as exc:
|
|
155
|
+
QMessageBox.critical(self, "Could not open file", str(exc))
|
|
156
|
+
self.reject()
|
|
157
|
+
return
|
|
158
|
+
self._populate_tree()
|
|
159
|
+
|
|
160
|
+
def _populate_tree(self) -> None:
|
|
161
|
+
self.tree.clear()
|
|
162
|
+
if self.root_node is None:
|
|
163
|
+
return
|
|
164
|
+
root_item = self._make_tree_item(self.root_node)
|
|
165
|
+
self.tree.addTopLevelItem(root_item)
|
|
166
|
+
self._add_tree_children(root_item, self.root_node)
|
|
167
|
+
self.tree.expandItem(root_item)
|
|
168
|
+
|
|
169
|
+
def _add_tree_children(self, parent_item: QTreeWidgetItem, parent_node: DataNode):
|
|
170
|
+
for child in parent_node.children:
|
|
171
|
+
item = self._make_tree_item(child)
|
|
172
|
+
parent_item.addChild(item)
|
|
173
|
+
self._add_tree_children(item, child)
|
|
174
|
+
|
|
175
|
+
def _make_tree_item(self, node: DataNode) -> QTreeWidgetItem:
|
|
176
|
+
shape = "" if node.shape is None else " x ".join(str(size) for size in node.shape)
|
|
177
|
+
dtype = node.kind if node.dtype is None else node.dtype
|
|
178
|
+
item = QTreeWidgetItem([node.name, shape, dtype])
|
|
179
|
+
item.setData(0, Qt.UserRole, node)
|
|
180
|
+
item.setToolTip(0, node.path)
|
|
181
|
+
return item
|
|
182
|
+
|
|
183
|
+
def _tree_selection_changed(self, current: QTreeWidgetItem, _previous) -> None:
|
|
184
|
+
node = current.data(0, Qt.UserRole) if current is not None else None
|
|
185
|
+
self.selected_node = node if isinstance(node, DataNode) else None
|
|
186
|
+
self._update_details()
|
|
187
|
+
self._build_mapping_controls()
|
|
188
|
+
self._mapping_changed()
|
|
189
|
+
self._clear_preview()
|
|
190
|
+
|
|
191
|
+
def _update_details(self) -> None:
|
|
192
|
+
node = self.selected_node
|
|
193
|
+
if node is None:
|
|
194
|
+
self.details.clear()
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
lines = [
|
|
198
|
+
f"Path: {node.path}",
|
|
199
|
+
f"Backend: {node.backend}",
|
|
200
|
+
f"Kind: {node.kind}",
|
|
201
|
+
]
|
|
202
|
+
if node.shape is not None:
|
|
203
|
+
lines.append(f"Shape: {node.shape}")
|
|
204
|
+
if node.dtype is not None:
|
|
205
|
+
lines.append(f"Dtype: {node.dtype}")
|
|
206
|
+
if node.chunks is not None:
|
|
207
|
+
lines.append(f"Chunks: {node.chunks}")
|
|
208
|
+
if node.attrs:
|
|
209
|
+
lines.append("")
|
|
210
|
+
lines.append("Attributes:")
|
|
211
|
+
for key, value in sorted(node.attrs.items()):
|
|
212
|
+
lines.append(f" {key}: {value}")
|
|
213
|
+
self.details.setPlainText("\n".join(lines))
|
|
214
|
+
|
|
215
|
+
def _build_mapping_controls(self) -> None:
|
|
216
|
+
self._clear_mapping_controls()
|
|
217
|
+
node = self.selected_node
|
|
218
|
+
if node is None or node.shape is None:
|
|
219
|
+
return
|
|
220
|
+
|
|
221
|
+
headers = ["Axis", "Size", "Role", "Fixed Index", "Scan Y", "Scan X"]
|
|
222
|
+
for col, label in enumerate(headers):
|
|
223
|
+
self.mapping_layout.addWidget(QLabel(label), 0, col)
|
|
224
|
+
|
|
225
|
+
defaults = default_roles(len(node.shape))
|
|
226
|
+
for axis, size in enumerate(node.shape):
|
|
227
|
+
axis_label = QLabel(str(axis))
|
|
228
|
+
size_label = QLabel(str(size))
|
|
229
|
+
|
|
230
|
+
role_box = QComboBox()
|
|
231
|
+
role_box.addItems(ALL_ROLES)
|
|
232
|
+
role_box.setCurrentText(defaults[axis])
|
|
233
|
+
role_box.currentTextChanged.connect(self._mapping_changed)
|
|
234
|
+
self.role_boxes.append(role_box)
|
|
235
|
+
|
|
236
|
+
index_box = QSpinBox()
|
|
237
|
+
index_box.setRange(0, max(0, int(size) - 1))
|
|
238
|
+
index_box.setEnabled(defaults[axis] == ROLE_FIXED)
|
|
239
|
+
index_box.valueChanged.connect(self._mapping_changed)
|
|
240
|
+
self.index_boxes.append(index_box)
|
|
241
|
+
|
|
242
|
+
scan_y, scan_x = default_scan_shape(int(size))
|
|
243
|
+
scan_y_box = QSpinBox()
|
|
244
|
+
scan_y_box.setRange(1, max(1, int(size)))
|
|
245
|
+
scan_y_box.setValue(scan_y)
|
|
246
|
+
scan_y_box.setEnabled(defaults[axis] == ROLE_FLATTENED_SCAN)
|
|
247
|
+
scan_y_box.valueChanged.connect(self._mapping_changed)
|
|
248
|
+
self.scan_y_boxes.append(scan_y_box)
|
|
249
|
+
|
|
250
|
+
scan_x_box = QSpinBox()
|
|
251
|
+
scan_x_box.setRange(1, max(1, int(size)))
|
|
252
|
+
scan_x_box.setValue(scan_x)
|
|
253
|
+
scan_x_box.setEnabled(defaults[axis] == ROLE_FLATTENED_SCAN)
|
|
254
|
+
scan_x_box.valueChanged.connect(self._mapping_changed)
|
|
255
|
+
self.scan_x_boxes.append(scan_x_box)
|
|
256
|
+
|
|
257
|
+
row = axis + 1
|
|
258
|
+
self.mapping_layout.addWidget(axis_label, row, 0)
|
|
259
|
+
self.mapping_layout.addWidget(size_label, row, 1)
|
|
260
|
+
self.mapping_layout.addWidget(role_box, row, 2)
|
|
261
|
+
self.mapping_layout.addWidget(index_box, row, 3)
|
|
262
|
+
self.mapping_layout.addWidget(scan_y_box, row, 4)
|
|
263
|
+
self.mapping_layout.addWidget(scan_x_box, row, 5)
|
|
264
|
+
|
|
265
|
+
def _clear_mapping_controls(self) -> None:
|
|
266
|
+
while self.mapping_layout.count():
|
|
267
|
+
item = self.mapping_layout.takeAt(0)
|
|
268
|
+
widget = item.widget()
|
|
269
|
+
if widget is not None:
|
|
270
|
+
widget.deleteLater()
|
|
271
|
+
self.role_boxes.clear()
|
|
272
|
+
self.index_boxes.clear()
|
|
273
|
+
self.scan_y_boxes.clear()
|
|
274
|
+
self.scan_x_boxes.clear()
|
|
275
|
+
|
|
276
|
+
def _update_axis_control_states(self) -> None:
|
|
277
|
+
for role_box, index_box, scan_y_box, scan_x_box in zip(
|
|
278
|
+
self.role_boxes, self.index_boxes, self.scan_y_boxes, self.scan_x_boxes
|
|
279
|
+
):
|
|
280
|
+
role = role_box.currentText()
|
|
281
|
+
index_box.setEnabled(role == ROLE_FIXED)
|
|
282
|
+
scan_y_box.setEnabled(role == ROLE_FLATTENED_SCAN)
|
|
283
|
+
scan_x_box.setEnabled(role == ROLE_FLATTENED_SCAN)
|
|
284
|
+
|
|
285
|
+
def _mapping_changed(self, *_args) -> None:
|
|
286
|
+
self._update_axis_control_states()
|
|
287
|
+
self._update_load_enabled()
|
|
288
|
+
self._clear_preview()
|
|
289
|
+
|
|
290
|
+
def _update_load_enabled(self) -> None:
|
|
291
|
+
node = self.selected_node
|
|
292
|
+
if node is None or not node.is_array or node.shape is None:
|
|
293
|
+
self.load_button.setEnabled(False)
|
|
294
|
+
self.preview_button.setEnabled(False)
|
|
295
|
+
return
|
|
296
|
+
try:
|
|
297
|
+
validate_selection(node.shape, self.get_selection())
|
|
298
|
+
ok = True
|
|
299
|
+
except ValueError:
|
|
300
|
+
ok = False
|
|
301
|
+
self.load_button.setEnabled(ok)
|
|
302
|
+
self.preview_button.setEnabled(ok)
|
|
303
|
+
|
|
304
|
+
def _clear_preview(self) -> None:
|
|
305
|
+
if self.diffraction_preview is not None:
|
|
306
|
+
self.diffraction_preview.clear()
|
|
307
|
+
if self.axial_bf_preview is not None:
|
|
308
|
+
self.axial_bf_preview.clear()
|
|
309
|
+
if self.preview_status is not None:
|
|
310
|
+
self.preview_status.setText("Preview not updated.")
|
|
311
|
+
|
|
312
|
+
def _update_preview(self) -> None:
|
|
313
|
+
node = self.selected_node
|
|
314
|
+
source = self.source
|
|
315
|
+
if node is None or source is None or not node.is_array:
|
|
316
|
+
return
|
|
317
|
+
try:
|
|
318
|
+
array = source.get_array(node.path)
|
|
319
|
+
previews = load_preview_arrays(array, self.get_selection())
|
|
320
|
+
diffraction = np.sqrt(np.maximum(previews.diffraction, 0))
|
|
321
|
+
axial_bf = previews.axial_bf
|
|
322
|
+
self.diffraction_preview.setImage(diffraction.T, autoLevels=True)
|
|
323
|
+
self.axial_bf_preview.setImage(axial_bf.T, autoLevels=True)
|
|
324
|
+
self.preview_status.setText(previews.description)
|
|
325
|
+
except Exception as exc:
|
|
326
|
+
QMessageBox.critical(self, "Could not update preview", str(exc))
|
|
327
|
+
raise
|
|
328
|
+
|
|
329
|
+
def get_selection(self) -> DimensionSelection:
|
|
330
|
+
scan_shapes = []
|
|
331
|
+
for role_box, scan_y_box, scan_x_box in zip(
|
|
332
|
+
self.role_boxes, self.scan_y_boxes, self.scan_x_boxes
|
|
333
|
+
):
|
|
334
|
+
if role_box.currentText() == ROLE_FLATTENED_SCAN:
|
|
335
|
+
scan_shapes.append((scan_y_box.value(), scan_x_box.value()))
|
|
336
|
+
else:
|
|
337
|
+
scan_shapes.append(None)
|
|
338
|
+
return DimensionSelection(
|
|
339
|
+
tuple(box.currentText() for box in self.role_boxes),
|
|
340
|
+
tuple(box.value() for box in self.index_boxes),
|
|
341
|
+
tuple(scan_shapes),
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _make_image_view() -> pg.ImageView:
|
|
346
|
+
view = pg.ImageView()
|
|
347
|
+
view.setMinimumHeight(180)
|
|
348
|
+
view.ui.roiBtn.hide()
|
|
349
|
+
view.ui.menuBtn.hide()
|
|
350
|
+
return view
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _labeled_widget(label: str, widget: QWidget) -> QWidget:
|
|
354
|
+
panel = QWidget()
|
|
355
|
+
layout = QVBoxLayout(panel)
|
|
356
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
357
|
+
layout.addWidget(QLabel(label))
|
|
358
|
+
layout.addWidget(widget)
|
|
359
|
+
return panel
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from PyQt5.QtWidgets import QAction, QMessageBox, QWidget
|
|
7
|
+
|
|
8
|
+
from .dialog import FlexLoaderDialog
|
|
9
|
+
from .selection import load_datacube_array
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from py4D_browser import DataViewer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FlexLoaderPlugin(QWidget):
|
|
16
|
+
plugin_id = "chiahao3.flexloader"
|
|
17
|
+
display_name = "Flex Loader"
|
|
18
|
+
uses_plugin_menu = True
|
|
19
|
+
|
|
20
|
+
def __init__(self, parent: "DataViewer", plugin_menu, **kwargs):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.parent = parent
|
|
23
|
+
self.flexloader_menu = plugin_menu
|
|
24
|
+
|
|
25
|
+
self.load_action = QAction("Load HDF5 File...", self)
|
|
26
|
+
self.load_action.triggered.connect(self.launch_hdf5_file_loader)
|
|
27
|
+
self.flexloader_menu.addAction(self.load_action)
|
|
28
|
+
|
|
29
|
+
self.load_zarr_action = QAction("Load Zarr Directory...", self)
|
|
30
|
+
self.load_zarr_action.triggered.connect(self.launch_zarr_directory_loader)
|
|
31
|
+
self.flexloader_menu.addAction(self.load_zarr_action)
|
|
32
|
+
|
|
33
|
+
self.load_zarr_zip_action = QAction("Load Zarr Zip File...", self)
|
|
34
|
+
self.load_zarr_zip_action.triggered.connect(self.launch_zarr_zip_loader)
|
|
35
|
+
self.flexloader_menu.addAction(self.load_zarr_zip_action)
|
|
36
|
+
|
|
37
|
+
def close(self):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
def launch_hdf5_file_loader(self) -> None:
|
|
41
|
+
filepath = FlexLoaderDialog.select_hdf5_file(self.parent)
|
|
42
|
+
self.launch_loader(filepath)
|
|
43
|
+
|
|
44
|
+
def launch_zarr_directory_loader(self) -> None:
|
|
45
|
+
filepath = FlexLoaderDialog.select_zarr_directory(self.parent)
|
|
46
|
+
self.launch_loader(filepath)
|
|
47
|
+
|
|
48
|
+
def launch_zarr_zip_loader(self) -> None:
|
|
49
|
+
filepath = FlexLoaderDialog.select_zarr_zip_file(self.parent)
|
|
50
|
+
self.launch_loader(filepath)
|
|
51
|
+
|
|
52
|
+
def launch_loader(self, filepath: str | None) -> None:
|
|
53
|
+
if not filepath:
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
dialog = FlexLoaderDialog(filepath, parent=self.parent)
|
|
57
|
+
if dialog.exec_() != dialog.Accepted:
|
|
58
|
+
dialog.close_source()
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
node = dialog.selected_node
|
|
62
|
+
source = dialog.source
|
|
63
|
+
if node is None or source is None or not node.is_array:
|
|
64
|
+
dialog.close_source()
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
import py4DSTEM
|
|
69
|
+
|
|
70
|
+
raw_array = source.get_array(node.path)
|
|
71
|
+
array = load_datacube_array(raw_array, dialog.get_selection())
|
|
72
|
+
array = np.asarray(array)
|
|
73
|
+
datacube = py4DSTEM.DataCube(array)
|
|
74
|
+
_set_default_pixel_calibration(datacube)
|
|
75
|
+
_install_datacube(self.parent, datacube, f"{filepath}:{node.path}")
|
|
76
|
+
except Exception as exc:
|
|
77
|
+
QMessageBox.critical(self.parent, "Could not load dataset", str(exc))
|
|
78
|
+
raise
|
|
79
|
+
finally:
|
|
80
|
+
dialog.close_source()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _set_default_pixel_calibration(datacube) -> None:
|
|
84
|
+
calibration = getattr(datacube, "calibration", None)
|
|
85
|
+
if calibration is None:
|
|
86
|
+
return
|
|
87
|
+
setters = [
|
|
88
|
+
("set_R_pixel_size", 1.0),
|
|
89
|
+
("set_R_pixel_units", "pixels"),
|
|
90
|
+
("set_Q_pixel_size", 1.0),
|
|
91
|
+
("set_Q_pixel_units", "pixels"),
|
|
92
|
+
]
|
|
93
|
+
for method_name, value in setters:
|
|
94
|
+
method = getattr(calibration, method_name, None)
|
|
95
|
+
if method is not None:
|
|
96
|
+
method(value)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _install_datacube(parent: "DataViewer", datacube, window_title: str) -> None:
|
|
100
|
+
if hasattr(parent, "set_datacube"):
|
|
101
|
+
parent.set_datacube(datacube, window_title)
|
|
102
|
+
return
|
|
103
|
+
|
|
104
|
+
parent.datacube = datacube
|
|
105
|
+
if hasattr(parent, "update_scalebars"):
|
|
106
|
+
parent.update_scalebars()
|
|
107
|
+
parent.update_diffraction_space_view(reset=True)
|
|
108
|
+
parent.update_real_space_view(reset=True)
|
|
109
|
+
parent.setWindowTitle(window_title)
|
|
110
|
+
if hasattr(parent, "signal_datacube_changed"):
|
|
111
|
+
parent.signal_datacube_changed.emit()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# TODO: Re-evaluate lazy HDF5/Zarr-backed loading after confirming that the
|
|
115
|
+
# current py4DSTEM.DataCube and py4DGUI view code fully support non-ndarray
|
|
116
|
+
# data through repeated slicing, summation, max projection, and transpose paths.
|