TemDataBrowser 1.1__tar.gz → 1.3__tar.gz

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.
@@ -2,6 +2,9 @@ name: Publish Python distribution to Pypi and testpypi
2
2
 
3
3
  on: push
4
4
 
5
+ env:
6
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
7
+
5
8
  jobs:
6
9
  build:
7
10
  name: Build distribution
@@ -9,6 +12,8 @@ jobs:
9
12
 
10
13
  steps:
11
14
  - uses: actions/checkout@v4
15
+ with:
16
+ fetch-depth: 0
12
17
  - name: Set up Python
13
18
  uses: actions/setup-python@v5
14
19
  with:
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Peter Ercius
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,16 +1,29 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: TemDataBrowser
3
- Version: 1.1
3
+ Version: 1.3
4
4
  Summary: Graphical user interface to view transmission electron microscopy data.
5
5
  Author-email: Peter Ercius <percius@lbl.gov>
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/ercius/TemDataBrowser
8
+ Project-URL: Homepage, https://github.com/ercius/TemDataBrowser
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Scientific/Engineering :: Visualization
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
6
16
  Requires-Python: >=3.10
7
17
  Description-Content-Type: text/markdown
18
+ License-File: LICENSE
8
19
  Requires-Dist: numpy
9
20
  Requires-Dist: pyqtgraph
21
+ Requires-Dist: qtpy
10
22
  Requires-Dist: ScopeFoundry>=1.5
11
23
  Requires-Dist: ncempy>=1.15
12
24
  Requires-Dist: scipy
13
25
  Requires-Dist: imageio>2.17
26
+ Dynamic: license-file
14
27
 
15
28
  # TemDataBrowser
16
29
  A graphical user interface based on ScopeFoundry for viewing TEM data.
@@ -20,7 +33,7 @@ A graphical user interface based on ScopeFoundry for viewing TEM data.
20
33
  # Installation
21
34
  First install QT bindings. For example:
22
35
 
23
- `$ pip install PyQt5`
36
+ `$ pip install PyQt6`
24
37
 
25
38
  Then install this package and the rest of the dependencies:
26
39
 
@@ -6,7 +6,7 @@ A graphical user interface based on ScopeFoundry for viewing TEM data.
6
6
  # Installation
7
7
  First install QT bindings. For example:
8
8
 
9
- `$ pip install PyQt5`
9
+ `$ pip install PyQt6`
10
10
 
11
11
  Then install this package and the rest of the dependencies:
12
12
 
@@ -0,0 +1,392 @@
1
+ from importlib.metadata import version
2
+ from pathlib import Path
3
+
4
+ __version__ = version("TemDataBrowser")
5
+ import functools
6
+ import json
7
+ import re
8
+
9
+ from ScopeFoundry import BaseApp
10
+ from ScopeFoundry.helper_funcs import load_qt_ui_from_pkg
11
+ from ScopeFoundry.data_browser import DataBrowser, DataBrowserView
12
+ from qtpy import QtCore, QtWidgets, QtGui
13
+ import pyqtgraph as pg
14
+ import numpy as np
15
+
16
+ import imageio.v3 as iio
17
+ import ncempy
18
+
19
+ # Use row-major instead of col-major
20
+ pg.setConfigOption('imageAxisOrder', 'row-major')
21
+
22
+ # Every line of the FEI tomography-parameter log is prefixed with a fixed-width
23
+ # "MM/DD/YY HH:MM:SS " timestamp; what follows it is indented to show which section a
24
+ # parameter belongs to.
25
+ _TIMESTAMP_RE = re.compile(r'^\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} ')
26
+ _VALUE_KEY = '_value'
27
+
28
+
29
+ def _parse_fei_value(raw):
30
+ raw = raw.strip()
31
+ if raw == '':
32
+ return None
33
+ if raw in ('Yes', 'ON'):
34
+ return True
35
+ if raw in ('No', 'OFF'):
36
+ return False
37
+ try:
38
+ return float(raw)
39
+ except ValueError:
40
+ return raw
41
+
42
+
43
+ def _parse_fei_parameters(lines):
44
+ """Parse the vendor tomography-parameter log into a nested dict.
45
+
46
+ Section headers (e.g. "STEM imaging mode", "Check Focus") repeat parameter names
47
+ like "Periodicity (high tilt range)" under different settings, so a flat dict would
48
+ have later sections silently overwrite earlier ones. Indentation depth tells sections
49
+ apart from their children, so it is used to nest rather than flatten them.
50
+
51
+ A line can be a leaf, a header with no value of its own ("STEM imaging mode"), or
52
+ both at once ("Check Focus: Yes" has its own value and also has Periodicity settings
53
+ indented beneath it) -- every line is therefore pushed as a potential parent, and
54
+ _collapse resolves what it actually turned out to be once all its children are known.
55
+ """
56
+ root = {}
57
+ stack = [(-1, root)]
58
+ for raw_line in lines:
59
+ line = _TIMESTAMP_RE.sub('', raw_line)
60
+ stripped = line.strip()
61
+ if not stripped:
62
+ continue
63
+
64
+ # The stack must unwind to this line's depth before deciding whether to skip it,
65
+ # or a skipped section header (e.g. a "-----" rule right after a depth-1 line)
66
+ # would leave a stale frame on the stack and misparent everything that follows.
67
+ depth = len(line) - len(line.lstrip(' '))
68
+ while stack[-1][0] >= depth:
69
+ stack.pop()
70
+
71
+ if set(stripped) == {'-'}:
72
+ continue # decorative rule; never has children of its own
73
+ parent = stack[-1][1]
74
+
75
+ if ':' in stripped:
76
+ key, _, value = stripped.partition(':')
77
+ key, value = key.strip(), _parse_fei_value(value)
78
+ else:
79
+ key, value = stripped, None
80
+
81
+ node = {_VALUE_KEY: value}
82
+ parent[key] = node
83
+ stack.append((depth, node))
84
+
85
+ _collapse(root)
86
+ return root
87
+
88
+
89
+ def _collapse(node):
90
+ """Resolve each {_value, ...children} node into its final shape.
91
+
92
+ No children and no value -> True (a bare flag like "STEM imaging mode" turned out
93
+ to introduce no sub-parameters). No children, a value -> that value. Children and no
94
+ value -> a dict of just the children. Both -> a dict of the children plus 'value'.
95
+ """
96
+ for key, child in node.items():
97
+ value = child.pop(_VALUE_KEY)
98
+ _collapse(child)
99
+ if not child:
100
+ node[key] = value if value is not None else True
101
+ elif value is not None:
102
+ child['value'] = value
103
+ node[key] = child
104
+ else:
105
+ node[key] = child
106
+
107
+ class imageioView(DataBrowserView):
108
+ """ Handles most normal image types like TIF, PNG, etc."""
109
+
110
+ # This name is used in the GUI for the DataBrowser
111
+ name = 'Image viewer (imageio)'
112
+
113
+ def setup(self):
114
+ # create the GUI and viewer settings, runs once at program start up
115
+ # self.ui should be a QWidget of some sort, here we use a pyqtgraph ImageView
116
+ self.ui = self.imview = pg.ImageView()
117
+
118
+ def is_file_supported(self, fname):
119
+ # Tells the DataBrowser whether this plug-in would likely be able
120
+ # to read the given file name
121
+ # here we are using the file extension to make a guess
122
+ ext = Path(fname).suffix
123
+ return ext.lower() in ['.png', '.tif', '.tiff', '.jpg']
124
+
125
+ def on_change_data_filename(self, fname):
126
+ # A new file has been selected by the user, load and display it
127
+ try:
128
+ self.data = iio.imread(fname)
129
+ self.imview.setImage(self.data.swapaxes(0, 1))
130
+ except Exception as err:
131
+ # When a failure to load occurs, zero out image
132
+ # and show error message
133
+ self.imview.setImage(np.zeros((10,10)))
134
+ self.databrowser.ui.statusbar.showMessage(
135
+ "failed to load %s:\n%s" %(fname, err))
136
+ raise(err)
137
+
138
+ class TemView(DataBrowserView):
139
+ """ Data browser for common S/TEM file types
140
+
141
+ """
142
+
143
+ # This name is used in the GUI for the DataBrowser
144
+ name = 'TEM data viewer'
145
+
146
+ def setup(self):
147
+ """ create the GUI and viewer settings, runs once at program start up
148
+ self.ui should be a QWidget of some sort, here we use a pyqtgraph ImageView
149
+ """
150
+ #self.ui = self.imview = pg.ImageView()
151
+ #self.viewbox = self.imview.getView()
152
+ self.plt = pg.PlotItem(labels={'bottom':('X',''),'left':('Y','')})
153
+ self.ui = self.imview = pg.ImageView(view=self.plt)
154
+ self.imview.ui.roiBtn.hide()
155
+ self.imview.ui.menuBtn.hide()
156
+
157
+ def is_file_supported(self, fname):
158
+ """ Tells the DataBrowser whether this plug-in would likely be able
159
+ to read the given file name. Here we are using the file extension
160
+ to make a guess
161
+ """
162
+ ext = Path(fname).suffix.lower()
163
+ return ext in ['.dm3', '.dm4', '.mrc', '.ali', '.rec', '.emd', '.ser', '.img']
164
+
165
+ def on_change_data_filename(self, fname):
166
+ """ A new file has been selected by the user, load and display it
167
+ """
168
+ try:
169
+ is_stemtomo = False
170
+ print(f'Loading {fname}...')
171
+ if Path(fname).suffix.lower() == '.emd':
172
+ # Check for special STEMTomo7 Berkeley EMD files
173
+ try:
174
+ with ncempy.io.emd.fileEMD(fname) as f0:
175
+ if 'data' in f0.file_hdl:
176
+ if 'stemtomo version' in f0.file_hdl['data'].attrs:
177
+ is_stemtomo = True
178
+ except ncempy.io.emd.NoEmdDataSets:
179
+ # Velox files throw this error, they are not Berkeley EMD files
180
+ is_stemtomo = False
181
+
182
+ file = ncempy.read(fname)
183
+
184
+ # Remove singular dimensions
185
+ self.data = np.squeeze(file['data'])
186
+
187
+ # Test for > 3D data and reduce if possible
188
+ if self.data.ndim == 4 and is_stemtomo:
189
+ print(f'Warning: only showing 1 image per tilt angle for STEMTomo7 data.')
190
+ self.data = self.data[:,0,:,:]
191
+ elif self.data.ndim == 4:
192
+ print(f'Warning: Reducing {self.data.ndim}-D data to 3-D.')
193
+ self.data = self.data[0,:,:,:]
194
+ elif self.data.ndim > 4:
195
+ print(f'{self.data.ndim}-D data files are not supported.')
196
+
197
+ xscale = file['pixelSize'][-2]
198
+ yscale = file['pixelSize'][-1]
199
+ self.imview.setImage(self.data)
200
+ img = self.imview.getImageItem()
201
+
202
+ if file['pixelUnit'][-1] in ('um', 'µm', '[u_m]', 'u_m'):
203
+ unit_scale = 1e-6
204
+ unit = 'm'
205
+ elif file['pixelUnit'][-1] in ('m', ):
206
+ unit_scale = 1
207
+ unit = 'm'
208
+ elif file['pixelUnit'][-1] in ('nm', '[n_m]', 'n_m'):
209
+ unit_scale = 1e-9
210
+ unit = 'm'
211
+ elif file['pixelUnit'][-1] in ('A', 'Ang', ):
212
+ unit_scale = 1e-10
213
+ unit = 'm'
214
+ else:
215
+ unit_scale = 1
216
+ xscale = 1
217
+ yscale = 1
218
+ unit = 'pixels'
219
+ tr = QtGui.QTransform()
220
+ img.setTransform(tr.scale(xscale * unit_scale, yscale * unit_scale))
221
+
222
+ # Set the labels
223
+ p1_bottom = self.plt.getAxis('bottom')
224
+ p1_bottom.setLabel('X', units=unit)
225
+ p1_left = self.plt.getAxis('left')
226
+ p1_left.setLabel('Y', units=unit)
227
+
228
+ self.plt.autoRange()
229
+
230
+ except Exception as err:
231
+ # When a failure to load occurs, zero out image
232
+ # and show error message
233
+ self.imview.setImage(np.zeros((10,10)))
234
+ self.databrowser.ui.statusbar.showMessage(
235
+ f'failed to load {fname}:\n{err}')
236
+ raise(err)
237
+
238
+ class TemMetadataView(DataBrowserView):
239
+ """ A viewer to read meta data from a file and display it as text.
240
+
241
+ """
242
+ name = 'TEM metadata viewer'
243
+
244
+ def setup(self):
245
+ self.ui = QtWidgets.QTextEdit("File metadata")
246
+
247
+ @staticmethod
248
+ @functools.lru_cache(maxsize=10, typed=False)
249
+ def get_dm_metadata(fname):
250
+ """ Reads important metadata from DM files"""
251
+ with ncempy.io.dm.fileDM(fname) as f:
252
+ meta_data = f.getMetadata(index=0)
253
+
254
+ return meta_data
255
+
256
+ @staticmethod
257
+ @functools.lru_cache(maxsize=10, typed=False)
258
+ def get_mrc_metadata(path):
259
+ """ Reads important metadata from MRC and related files."""
260
+ with ncempy.io.mrc.fileMRC(path) as f:
261
+ meta_data = f.getMetadata()
262
+
263
+ # Read tilt angles from .rawtlt file if it exists
264
+ rawtltName = Path(path).with_suffix('.rawtlt')
265
+ if rawtltName.exists():
266
+ with open(rawtltName, 'r') as f1:
267
+ tilts = list(map(float, f1))
268
+ meta_data['tilt angles'] = tilts
269
+
270
+ # Read FEI parameters from .txt file if it exists
271
+ FEIparameters = Path(path).with_suffix('.txt')
272
+ if FEIparameters.exists():
273
+ try:
274
+ with open(FEIparameters, 'r', encoding='utf-8-sig') as f2:
275
+ lines = f2.readlines()
276
+ except UnicodeDecodeError:
277
+ with open(FEIparameters, 'r', encoding='cp1252') as f2:
278
+ lines = f2.readlines()
279
+ meta_data['fei_parameters'] = _parse_fei_parameters(lines)
280
+
281
+ return meta_data
282
+
283
+ @staticmethod
284
+ @functools.lru_cache(maxsize=10, typed=False)
285
+ def get_emd_metadata(path):
286
+ """ Reads important metadata from EMD Berkeley files."""
287
+ with ncempy.io.emd.fileEMD(path) as f:
288
+ meta_data = f.getMetadata(0) # 0 = index into f.list_data
289
+ return meta_data
290
+
291
+ @staticmethod
292
+ @functools.lru_cache(maxsize=10, typed=False)
293
+ def get_velox_metadata(path):
294
+ """ Reads important metadata from Velox EMD files."""
295
+ with ncempy.io.emdVelox.fileEMDVelox(path) as f:
296
+ if f.list_data is None:
297
+ return None
298
+ meta_data = f.getMetadata(0) # 0 = index into f.list_data
299
+ return meta_data
300
+
301
+ @staticmethod
302
+ @functools.lru_cache(maxsize=10, typed=False)
303
+ def get_ser_metadata(path):
304
+ with ncempy.io.ser.fileSER(path) as f:
305
+ # Returns global metadata for the whole file
306
+ meta_data = f.getMetadata()
307
+
308
+ # Get additional metadata from the first dataset
309
+ _, extra_metadata = f.getDataset(0)
310
+ meta_data.update(extra_metadata)
311
+
312
+ # Get the header information
313
+ meta_data.update(f.head)
314
+
315
+ # Clean the dictionary
316
+ for k, v in meta_data.items():
317
+ if isinstance(v, bytes):
318
+ meta_data[k] = v.decode('UTF8')
319
+
320
+ return meta_data
321
+
322
+ @staticmethod
323
+ @functools.lru_cache(maxsize=10, typed=False)
324
+ def get_emi_metadata(fname):
325
+ return ncempy.io.ser.read_emi(fname)
326
+
327
+ @staticmethod
328
+ @functools.lru_cache(maxsize=10, typed=False)
329
+ def get_img_metadata(fname):
330
+ with ncempy.io.smv.fileSMV(fname) as f0:
331
+ meta_data = f0.getMetadata()
332
+ return meta_data
333
+
334
+ def on_change_data_filename(self, fname):
335
+ ext = Path(fname).suffix.lower()
336
+
337
+ meta_data = {'file name': str(fname)}
338
+ if ext in ('.dm3', '.dm4'):
339
+ meta_data = self.get_dm_metadata(fname)
340
+ elif ext in ('.mrc', '.rec', '.ali'):
341
+ meta_data = self.get_mrc_metadata(fname)
342
+ elif ext in ('.emd',):
343
+ try:
344
+ meta_data = self.get_emd_metadata(fname)
345
+ except ncempy.io.emd.NoEmdDataSets:
346
+ velox_meta = self.get_velox_metadata(fname)
347
+ if velox_meta is not None:
348
+ meta_data = velox_meta
349
+ else:
350
+ meta_data = {'file name': str(fname), 'error': 'No EMD datasets found'}
351
+ elif ext in ('.ser',):
352
+ meta_data = self.get_ser_metadata(fname)
353
+ elif ext in ('.emi',):
354
+ meta_data = self.get_emi_metadata(fname)
355
+ elif ext in ('.img',):
356
+ meta_data = self.get_img_metadata(fname)
357
+
358
+ txt = f'file name = {fname}\n'
359
+ for k, v in meta_data.items():
360
+ if isinstance(v, dict):
361
+ v = json.dumps(v, indent=2, default=str)
362
+ line = f'{k} = {v}\n'
363
+ txt += line
364
+ self.ui.setText(txt)
365
+
366
+ def is_file_supported(self, fname):
367
+ ext = Path(fname).suffix
368
+ return ext.lower() in ('.dm3', '.dm4', '.mrc', '.ali', '.rec', '.ser', '.emi', '.img', '.emd')
369
+
370
+ def open_file():
371
+ """Start the graphical user interface from inside a python interpreter."""
372
+ main()
373
+
374
+ def main():
375
+ """ This starts the graphical user interface and loads the views."""
376
+ import sys
377
+
378
+ app = DataBrowser(sys.argv)
379
+ app.settings['browse_dir'] = Path.home()
380
+ app.ui.setWindowTitle("TemDataBrowser")
381
+
382
+ # Load views here
383
+ # Last loaded is the first one tried
384
+ app.load_view(TemMetadataView(app))
385
+ app.load_view(imageioView(app))
386
+ app.load_view(TemView(app))
387
+ sys.exit(app.exec_())
388
+
389
+
390
+ if __name__ == '__main__':
391
+ main()
392
+
@@ -1,16 +1,29 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: TemDataBrowser
3
- Version: 1.1
3
+ Version: 1.3
4
4
  Summary: Graphical user interface to view transmission electron microscopy data.
5
5
  Author-email: Peter Ercius <percius@lbl.gov>
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/ercius/TemDataBrowser
8
+ Project-URL: Homepage, https://github.com/ercius/TemDataBrowser
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Scientific/Engineering :: Visualization
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
6
16
  Requires-Python: >=3.10
7
17
  Description-Content-Type: text/markdown
18
+ License-File: LICENSE
8
19
  Requires-Dist: numpy
9
20
  Requires-Dist: pyqtgraph
21
+ Requires-Dist: qtpy
10
22
  Requires-Dist: ScopeFoundry>=1.5
11
23
  Requires-Dist: ncempy>=1.15
12
24
  Requires-Dist: scipy
13
25
  Requires-Dist: imageio>2.17
26
+ Dynamic: license-file
14
27
 
15
28
  # TemDataBrowser
16
29
  A graphical user interface based on ScopeFoundry for viewing TEM data.
@@ -20,7 +33,7 @@ A graphical user interface based on ScopeFoundry for viewing TEM data.
20
33
  # Installation
21
34
  First install QT bindings. For example:
22
35
 
23
- `$ pip install PyQt5`
36
+ `$ pip install PyQt6`
24
37
 
25
38
  Then install this package and the rest of the dependencies:
26
39
 
@@ -1,4 +1,5 @@
1
1
  .gitignore
2
+ LICENSE
2
3
  README.md
3
4
  pyproject.toml
4
5
  run_TemDataBrowser.py
@@ -9,5 +10,7 @@ TemDataBrowser.egg-info/SOURCES.txt
9
10
  TemDataBrowser.egg-info/dependency_links.txt
10
11
  TemDataBrowser.egg-info/entry_points.txt
11
12
  TemDataBrowser.egg-info/requires.txt
13
+ TemDataBrowser.egg-info/scm_file_list.json
14
+ TemDataBrowser.egg-info/scm_version.json
12
15
  TemDataBrowser.egg-info/top_level.txt
13
16
  TemDataBrowser/images/TemDataBrowser_window.png
@@ -1,5 +1,6 @@
1
1
  numpy
2
2
  pyqtgraph
3
+ qtpy
3
4
  ScopeFoundry>=1.5
4
5
  ncempy>=1.15
5
6
  scipy
@@ -0,0 +1,12 @@
1
+ {
2
+ "files": [
3
+ ".github/workflows/publish-to-pypi.yml",
4
+ ".gitignore",
5
+ "LICENSE",
6
+ "README.md",
7
+ "TemDataBrowser/__init__.py",
8
+ "TemDataBrowser/images/TemDataBrowser_window.png",
9
+ "pyproject.toml",
10
+ "run_TemDataBrowser.py"
11
+ ]
12
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "1.3",
3
+ "distance": 0,
4
+ "node": "gce406edf0b29367fc7a38fc35023bb4aa14d72db",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-09-14"
8
+ }
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools", "setuptools-scm"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "TemDataBrowser"
7
+ authors = [{name = "Peter Ercius", email="percius@lbl.gov"}]
8
+ description = "Graphical user interface to view transmission electron microscopy data."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Science/Research",
16
+ "Topic :: Scientific/Engineering :: Visualization",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ ]
22
+ dependencies = ["numpy","pyqtgraph","qtpy","ScopeFoundry>=1.5","ncempy>=1.15","scipy","imageio>2.17"]
23
+ dynamic = ["version"]
24
+
25
+ [tool.setuptools_scm]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/ercius/TemDataBrowser"
29
+ Homepage = "https://github.com/ercius/TemDataBrowser"
30
+
31
+ [project.scripts]
32
+ TemDataBrowser = "TemDataBrowser:open_file"
@@ -1,459 +0,0 @@
1
- #from __future__ import division, print_function, absolute_import
2
-
3
- from pathlib import Path
4
- from collections import OrderedDict
5
- import functools
6
-
7
- from ScopeFoundry import BaseApp
8
- from ScopeFoundry.helper_funcs import load_qt_ui_from_pkg
9
- from ScopeFoundry.data_browser import DataBrowser, DataBrowserView
10
- from qtpy import QtCore, QtWidgets, QtGui
11
- import pyqtgraph as pg
12
- import numpy as np
13
- from ScopeFoundry.logged_quantity import LQCollection
14
- import argparse
15
-
16
- import imageio.v3 as iio
17
- import ncempy
18
-
19
- # Use row-major instead of col-major
20
- pg.setConfigOption('imageAxisOrder', 'row-major')
21
-
22
- class imageioView(DataBrowserView):
23
- """ Handles most normal image types like TIF, PNG, etc."""
24
-
25
- # This name is used in the GUI for the DataBrowser
26
- name = 'Image viewer (imageio)'
27
-
28
- def setup(self):
29
- # create the GUI and viewer settings, runs once at program start up
30
- # self.ui should be a QWidget of some sort, here we use a pyqtgraph ImageView
31
- self.ui = self.imview = pg.ImageView()
32
-
33
- def is_file_supported(self, fname):
34
- # Tells the DataBrowser whether this plug-in would likely be able
35
- # to read the given file name
36
- # here we are using the file extension to make a guess
37
- ext = Path(fname).suffix
38
- return ext.lower() in ['.png', '.tif', '.tiff', '.jpg']
39
-
40
- def on_change_data_filename(self, fname):
41
- # A new file has been selected by the user, load and display it
42
- try:
43
- self.data = iio.imread(fname)
44
- self.imview.setImage(self.data.swapaxes(0, 1))
45
- except Exception as err:
46
- # When a failure to load occurs, zero out image
47
- # and show error message
48
- self.imview.setImage(np.zeros((10,10)))
49
- self.databrowser.ui.statusbar.showMessage(
50
- "failed to load %s:\n%s" %(fname, err))
51
- raise(err)
52
-
53
- class TemView(DataBrowserView):
54
- """ Data browser for common S/TEM file types
55
-
56
- """
57
-
58
- # This name is used in the GUI for the DataBrowser
59
- name = 'TEM data viewer'
60
-
61
- def setup(self):
62
- """ create the GUI and viewer settings, runs once at program start up
63
- self.ui should be a QWidget of some sort, here we use a pyqtgraph ImageView
64
- """
65
- #self.ui = self.imview = pg.ImageView()
66
- #self.viewbox = self.imview.getView()
67
- self.plt = pg.PlotItem(labels={'bottom':('X',''),'left':('Y','')})
68
- self.ui = self.imview = pg.ImageView(view=self.plt)
69
- self.imview.ui.roiBtn.hide()
70
- self.imview.ui.menuBtn.hide()
71
-
72
- def is_file_supported(self, fname):
73
- """ Tells the DataBrowser whether this plug-in would likely be able
74
- to read the given file name. Here we are using the file extension
75
- to make a guess
76
- """
77
- ext = Path(fname).suffix.lower()
78
- return ext in ['.dm3', '.dm4', '.mrc', '.ali', '.rec', '.emd', '.ser', '.img']
79
-
80
- def on_change_data_filename(self, fname):
81
- """ A new file has been selected by the user, load and display it
82
- """
83
- try:
84
- is_stemtomo = False
85
- print(f'Loading {fname}...')
86
- if Path(fname).suffix.lower() == '.emd':
87
- # Check for special STEMTomo7 Berkeley EMD files
88
- try:
89
- with ncempy.io.emd.fileEMD(fname) as f0:
90
- if 'data' in f0.file_hdl:
91
- if 'stemtomo version' in f0.file_hdl['data'].attrs:
92
- is_stemtomo = True
93
- except ncempy.io.emd.NoEmdDataSets:
94
- # Velox files throw this error, they are not Berkeley EMD files
95
- is_stemtomo = False
96
-
97
- file = ncempy.read(fname)
98
-
99
- # Remove singular dimensions
100
- self.data = np.squeeze(file['data'])
101
-
102
- # Test for > 3D data and reduce if possible
103
- if self.data.ndim == 4 and is_stemtomo:
104
- print(f'Warning: only showing 1 image per tilt angle for STEMTomo7 data.')
105
- self.data = self.data[:,0,:,:]
106
- elif self.data.ndim == 4:
107
- print(f'Warning: Reducing {self.data.ndim}-D data to 3-D.')
108
- self.data = self.data[0,:,:,:]
109
- elif self.data.ndim > 4:
110
- print(f'{self.data.ndim}-D data files are not supported.')
111
-
112
- xscale = file['pixelSize'][-2]
113
- yscale = file['pixelSize'][-1]
114
- self.imview.setImage(self.data)
115
- img = self.imview.getImageItem()
116
-
117
- if file['pixelUnit'][-1] in ('um', 'µm', '[u_m]', 'u_m'):
118
- unit_scale = 1e-6
119
- unit = 'm'
120
- elif file['pixelUnit'][-1] in ('m', ):
121
- unit_scale = 1
122
- unit = 'm'
123
- elif file['pixelUnit'][-1] in ('nm', '[n_m]', 'n_m'):
124
- unit_scale = 1e-9
125
- unit = 'm'
126
- elif file['pixelUnit'][-1] in ('A', 'Ang', ):
127
- unit_scale = 1e-10
128
- unit = 'm'
129
- else:
130
- unit_scale = 1
131
- xscale = 1
132
- yscale = 1
133
- unit = 'pixels'
134
- tr = QtGui.QTransform()
135
- img.setTransform(tr.scale(xscale * unit_scale, yscale * unit_scale))
136
-
137
- # Set the labels
138
- p1_bottom = self.plt.getAxis('bottom')
139
- p1_bottom.setLabel('X', units=unit)
140
- p1_left = self.plt.getAxis('left')
141
- p1_left.setLabel('Y', units=unit)
142
-
143
- self.plt.autoRange()
144
-
145
- except Exception as err:
146
- # When a failure to load occurs, zero out image
147
- # and show error message
148
- self.imview.setImage(np.zeros((10,10)))
149
- self.databrowser.ui.statusbar.showMessage(
150
- f'failed to load {fname}:\n{err}')
151
- raise(err)
152
-
153
- class TemMetadataView(DataBrowserView):
154
- """ A viewer to read meta data from a file and display it as text.
155
-
156
- """
157
- name = 'TEM metadata viewer'
158
-
159
- def setup(self):
160
- self.ui = QtWidgets.QTextEdit("File metadata")
161
-
162
- @staticmethod
163
- @functools.lru_cache(maxsize=10, typed=False)
164
- def get_dm_metadata(fname):
165
- """ Reads important metadata from DM files"""
166
- metaData = {}
167
- with ncempy.io.dm.fileDM(fname, on_memory=True) as dm1:
168
- # Only keep the most useful tags as meta data
169
- for kk, ii in dm1.allTags.items():
170
- # Most useful starting tags
171
- prefix1 = 'ImageList.{}.ImageTags.'.format(dm1.numObjects)
172
- prefix2 = 'ImageList.{}.ImageData.'.format(dm1.numObjects)
173
- pos1 = kk.find(prefix1)
174
- pos2 = kk.find(prefix2)
175
- if pos1 > -1:
176
- sub = kk[pos1 + len(prefix1):]
177
- metaData[sub] = ii
178
- elif pos2 > -1:
179
- sub = kk[pos2 + len(prefix2):]
180
- metaData[sub] = ii
181
-
182
- # Remove unneeded keys
183
- for jj in list(metaData):
184
- if jj.find('frame sequence') > -1:
185
- del metaData[jj]
186
- elif jj.find('Private') > -1:
187
- del metaData[jj]
188
- elif jj.find('Reference Images') > -1:
189
- del metaData[jj]
190
- elif jj.find('Frame.Intensity') > -1:
191
- del metaData[jj]
192
- elif jj.find('Area.Transform') > -1:
193
- del metaData[jj]
194
- elif jj.find('Parameters.Objects') > -1:
195
- del metaData[jj]
196
- elif jj.find('Device.Parameters') > -1:
197
- del metaData[jj]
198
-
199
- # Store the X and Y pixel size, offset and unit
200
- try:
201
- metaData['PhysicalSizeX'] = metaData['Calibrations.Dimension.1.Scale']
202
- metaData['PhysicalSizeXOrigin'] = metaData['Calibrations.Dimension.1.Origin']
203
- metaData['PhysicalSizeXUnit'] = metaData['Calibrations.Dimension.1.Units']
204
- metaData['PhysicalSizeY'] = metaData['Calibrations.Dimension.2.Scale']
205
- metaData['PhysicalSizeYOrigin'] = metaData['Calibrations.Dimension.2.Origin']
206
- metaData['PhysicalSizeYUnit'] = metaData['Calibrations.Dimension.2.Units']
207
- except:
208
- metaData['PhysicalSizeX'] = 1
209
- metaData['PhysicalSizeXOrigin'] = 0
210
- metaData['PhysicalSizeXUnit'] = ''
211
- metaData['PhysicalSizeY'] = 1
212
- metaData['PhysicalSizeYOrigin'] = 0
213
- metaData['PhysicalSizeYUnit'] = ''
214
-
215
- return metaData
216
-
217
- @staticmethod
218
- @functools.lru_cache(maxsize=10, typed=False)
219
- def get_mrc_metadata(path):
220
- """ Reads important metadata from MRC and related files."""
221
- metaData = {}
222
-
223
- # Open file and parse the header
224
- with ncempy.io.mrc.fileMRC(path) as mrc1:
225
- pass
226
-
227
- # Save most useful metaData
228
- metaData['axisOrientations'] = mrc1.axisOrientations # meta data information from the mrc header
229
- metaData['cellAngles'] = mrc1.cellAngles
230
-
231
- if hasattr(mrc1, 'FEIinfo'):
232
- # add in the special FEIinfo if it exists
233
- try:
234
- if isinstance(mrc1.FEIinfo, dict):
235
- metaData.update(mrc1.FEIinfo)
236
- except TypeError:
237
- pass
238
-
239
- # Store the X and Y pixel size, offset and unit
240
- # Test for bad pixel sizes which happens often
241
- if mrc1.voxelSize[2] > 0:
242
- metaData['PhysicalSizeX'] = mrc1.voxelSize[2] * 1e-10 # change Angstroms to meters
243
- metaData['PhysicalSizeXOrigin'] = 0
244
- metaData['PhysicalSizeXUnit'] = 'm'
245
- else:
246
- metaData['PhysicalSizeX'] = 1
247
- metaData['PhysicalSizeXOrigin'] = 0
248
- metaData['PhysicalSizeXUnit'] = ''
249
- if mrc1.voxelSize[1] > 0:
250
- metaData['PhysicalSizeY'] = mrc1.voxelSize[1] * 1e-10 # change Angstroms to meters
251
- metaData['PhysicalSizeYOrigin'] = 0
252
- metaData['PhysicalSizeYUnit'] = 'm'
253
- else:
254
- metaData['PhysicalSizeY'] = 1
255
- metaData['PhysicalSizeYOrigin'] = 0
256
- metaData['PhysicalSizeYUnit'] = ''
257
-
258
- metaData['FileName'] = path
259
-
260
- rawtltName = Path(path).with_suffix('.rawtlt')
261
- if rawtltName.exists():
262
- with open(rawtltName, 'r') as f1:
263
- tilts = map(float, f1)
264
- metaData['tilt angles'] = tilts
265
-
266
- FEIparameters = Path(path).with_suffix('.txt')
267
- if FEIparameters.exists():
268
- with open(FEIparameters, 'r') as f2:
269
- lines = f2.readlines()
270
- pp1 = list([ii[18:].strip().split(':')] for ii in lines[3:-1])
271
- pp2 = {}
272
- for ll in pp1:
273
- try:
274
- pp2[ll[0]] = float(ll[1])
275
- except:
276
- pass # skip lines with no data
277
- metaData.update(pp2)
278
-
279
- return metaData
280
-
281
- @staticmethod
282
- @functools.lru_cache(maxsize=10, typed=False)
283
- def get_emd_metadata(path):
284
- """ Reads important metadata from EMD Berkeley files."""
285
- metaData = {}
286
- with ncempy.io.emd.fileEMD(path) as emd0:
287
- try:
288
- metaData.update(emd0.user.attrs)
289
- except AttributeError:
290
- pass
291
- try:
292
- metaData.update(emd0.microscope.attrs)
293
- except AttributeError:
294
- pass
295
- try:
296
- metaData.update(emd0.sample.attrs)
297
- except AttributeError:
298
- pass
299
- dims = emd0.get_emddims(emd0.list_emds[0])
300
- dimX = dims[-1]
301
- dimY = dims[-2]
302
- metaData['PhysicalSizeX'] = dimX[0][1] - dimX[0][0]
303
- metaData['PhysicalSizeXOrigin'] = dimX[0][0]
304
- metaData['PhysicalSizeXUnit'] = dimX[2].replace('_', '')
305
- metaData['PhysicalSizeY'] = dimY[0][1] - dimY[0][0]
306
- metaData['PhysicalSizeYOrigin'] = dimY[0][0]
307
- metaData['PhysicalSizeYUnit'] = dimY[2].replace('_', '')
308
- return metaData
309
-
310
-
311
- @staticmethod
312
- @functools.lru_cache(maxsize=10, typed=False)
313
- def get_velox_metadata(path):
314
- """ Reads important metadata from Velox EMD files."""
315
- import json
316
- metaData = {}
317
- with ncempy.io.emdVelox.fileEMDVelox(path) as f0:
318
- if f0.list_data is None:
319
- return metaData
320
- dataGroup = f0.list_data[0]
321
- dataset0 = dataGroup['Data']
322
-
323
- # Convert JSON metadata to dict
324
- mData = f0.list_data[0]['Metadata'][:, 0]
325
- validMetaDataIndex = np.where(mData > 0) # find valid metadata
326
- mData = mData[validMetaDataIndex].tostring() # change to string
327
- mDataS = json.loads(mData.decode('utf-8', 'ignore')) # load UTF-8 string as JSON and output dict
328
- metaData['pixel sizes'] = []
329
- metaData['pixel units'] = []
330
- try:
331
- # Store the X and Y pixel size, offset and unit
332
- metaData['PhysicalSizeX'] = float(mDataS['BinaryResult']['PixelSize']['width'])
333
- metaData['PhysicalSizeXOrigin'] = float(mDataS['BinaryResult']['Offset']['x'])
334
- metaData['PhysicalSizeXUnit'] = mDataS['BinaryResult']['PixelUnitX']
335
- metaData['PhysicalSizeY'] = float(mDataS['BinaryResult']['PixelSize']['height'])
336
- metaData['PhysicalSizeYOrigin'] = float(mDataS['BinaryResult']['Offset']['y'])
337
- metaData['PhysicalSizeYUnit'] = mDataS['BinaryResult']['PixelUnitY']
338
- except:
339
- metaData['PhysicalSizeX'] = 1
340
- metaData['PhysicalSizeXOrigin'] = 0
341
- metaData['PhysicalSizeXUnit'] = ''
342
- metaData['PhysicalSizeY'] = 1
343
- metaData['PhysicalSizeYOrigin'] = 0
344
- metaData['PhysicalSizeYUnit'] = ''
345
-
346
- metaData.update(mDataS)
347
-
348
- metaData['shape'] = dataset0.shape
349
- return metaData
350
-
351
- @staticmethod
352
- @functools.lru_cache(maxsize=10, typed=False)
353
- def get_ser_metadata(fname):
354
- metaData = {}
355
- with ncempy.io.ser.fileSER(fname) as ser1:
356
- data, metaData = ser1.getDataset(0) # have to get 1 image and its meta data
357
-
358
- # Add extra meta data from the EMI file if it exists
359
- if ser1._emi is not None:
360
- metaData.update(ser1._emi)
361
-
362
- metaData.update(ser1.head) # some header data for the ser file
363
-
364
- # Clean the dictionary
365
- for k, v in metaData.items():
366
- if isinstance(v, bytes):
367
- metaData[k] = v.decode('UTF8')
368
-
369
- # Store the X and Y pixel size, offset and unit
370
- try:
371
- metaData['PhysicalSizeX'] = metaData['Calibration'][0]['CalibrationDelta']
372
- metaData['PhysicalSizeXOrigin'] = metaData['Calibration'][0]['CalibrationOffset']
373
- metaData['PhysicalSizeXUnit'] = 'm' # always meters
374
- metaData['PhysicalSizeY'] = metaData['Calibration'][1]['CalibrationDelta']
375
- metaData['PhysicalSizeYOrigin'] = metaData['Calibration'][1]['CalibrationOffset']
376
- metaData['PhysicalSizeYUnit'] = 'm' # always meters
377
- except:
378
- metaData['PhysicalSizeX'] = 1
379
- metaData['PhysicalSizeXOrigin'] = 0
380
- metaData['PhysicalSizeXUnit'] = ''
381
- metaData['PhysicalSizeY'] = 1
382
- metaData['PhysicalSizeYOrigin'] = 0
383
- metaData['PhysicalSizeYUnit'] = ''
384
-
385
- return metaData
386
-
387
- @staticmethod
388
- @functools.lru_cache(maxsize=10, typed=False)
389
- def get_emi_metadata(fname):
390
- return ncempy.io.ser.read_emi(fname)
391
-
392
- @staticmethod
393
- @functools.lru_cache(maxsize=10, typed=False)
394
- def get_img_metadata(fname):
395
- print(fname)
396
- with ncempy.io.smv.fileSMV(fname) as f0:
397
- md = f0.header_info
398
- return md
399
-
400
- def on_change_data_filename(self, fname):
401
- ext = Path(fname).suffix
402
-
403
- meta_data = {'file name': str(fname)}
404
- if ext in ('.dm3', '.dm4'):
405
- meta_data = self.get_dm_metadata(fname)
406
- elif ext in ('.mrc', '.rec', '.ali'):
407
- meta_data = self.get_mrc_metadata(fname)
408
- elif ext in ('.emd',):
409
- try:
410
- # Parse the file to see if any EMD datasets exist
411
- # if not then it throws a NoEmdDataSets error
412
- with ncempy.io.emd.fileEMD(fname) as f0:
413
- meta_data = f0.getMetadata(0)
414
- except ncempy.io.emd.NoEmdDataSets:
415
- with ncempy.io.emdVelox.fileEMDVelox(fname) as f0:
416
- if f0.list_data is not None:
417
- meta_data = f0.getMetadata(0)
418
- else:
419
- meta_data = {'file name': str(fname), 'error': 'No EMD datasets found'}
420
- elif ext in ('.ser',):
421
- meta_data = self.get_ser_metadata(fname)
422
- elif ext in ('.emi',):
423
- meta_data = self.get_emi_metadata(fname)
424
- elif ext in ('.img',):
425
- meta_data = self.get_img_metadata(fname)
426
-
427
- txt = f'file name = {fname}\n'
428
- for k, v in meta_data.items():
429
- line = f'{k} = {v}\n'
430
- txt += line
431
- self.ui.setText(txt)
432
-
433
- def is_file_supported(self, fname):
434
- ext = Path(fname).suffix
435
- return ext.lower() in ('.dm3', '.dm4', '.mrc', '.ali', '.rec', '.ser', '.emi', '.img')
436
-
437
- def open_file():
438
- """Start the graphical user interface from inside a python interpreter."""
439
- main()
440
-
441
- def main():
442
- """ This starts the graphical user interface and loads the views."""
443
- import sys
444
-
445
- app = DataBrowser(sys.argv)
446
- app.settings['browse_dir'] = Path.home()
447
- app.ui.setWindowTitle("TemDataBrowser")
448
-
449
- # Load views here
450
- # Last loaded is the first one tried
451
- app.load_view(TemMetadataView(app))
452
- app.load_view(imageioView(app))
453
- app.load_view(TemView(app))
454
- sys.exit(app.exec_())
455
-
456
-
457
- if __name__ == '__main__':
458
- main()
459
-
@@ -1,15 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools", "setuptools-scm"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "TemDataBrowser"
7
- authors = [{name = "Peter Ercius", email="percius@lbl.gov"}]
8
- description = "Graphical user interface to view transmission electron microscopy data."
9
- readme = "README.md"
10
- requires-python = ">=3.10"
11
- dependencies = ["numpy","pyqtgraph","ScopeFoundry>=1.5","ncempy>=1.15","scipy","imageio>2.17"]
12
- version = "1.1"
13
-
14
- [project.scripts]
15
- TemDataBrowser = "TemDataBrowser:open_file"
File without changes
File without changes