microeye 2.3.2__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.
Files changed (190) hide show
  1. microEye/__init__.py +47 -0
  2. microEye/_version.py +2 -0
  3. microEye/analysis/__init__.py +1 -0
  4. microEye/analysis/checklist_dialog.py +143 -0
  5. microEye/analysis/cmosMaps.py +228 -0
  6. microEye/analysis/filters/__init__.py +9 -0
  7. microEye/analysis/filters/base.py +21 -0
  8. microEye/analysis/filters/spatial.py +338 -0
  9. microEye/analysis/filters/temporal.py +76 -0
  10. microEye/analysis/fitting/__init__.py +0 -0
  11. microEye/analysis/fitting/fit.py +680 -0
  12. microEye/analysis/fitting/nena.py +375 -0
  13. microEye/analysis/fitting/phasor_fit.py +90 -0
  14. microEye/analysis/fitting/processing.py +317 -0
  15. microEye/analysis/fitting/psf/__init__.py +6 -0
  16. microEye/analysis/fitting/psf/extract.py +1129 -0
  17. microEye/analysis/fitting/psf/rubost_mean.py +150 -0
  18. microEye/analysis/fitting/psf/spline.py +167 -0
  19. microEye/analysis/fitting/psf/stats/__init__.py +12 -0
  20. microEye/analysis/fitting/psf/stats/core.py +295 -0
  21. microEye/analysis/fitting/psf/stats/curve_fit.py +708 -0
  22. microEye/analysis/fitting/psf/stats/io.py +104 -0
  23. microEye/analysis/fitting/psf/stats/slope_fit.py +171 -0
  24. microEye/analysis/fitting/psf/temp.py +147 -0
  25. microEye/analysis/fitting/psf/test.py +47 -0
  26. microEye/analysis/fitting/pyfit3Dcspline/CPU/CPUfunctions.py +657 -0
  27. microEye/analysis/fitting/pyfit3Dcspline/CPU/CPUmleFit_LM.py +1336 -0
  28. microEye/analysis/fitting/pyfit3Dcspline/CPU/CPUsplineLib.py +270 -0
  29. microEye/analysis/fitting/pyfit3Dcspline/CPU/__init__.py +1 -0
  30. microEye/analysis/fitting/pyfit3Dcspline/GPU/GPUfunctions.py +609 -0
  31. microEye/analysis/fitting/pyfit3Dcspline/GPU/GPUmleFit_LM_EMCCD.py +1396 -0
  32. microEye/analysis/fitting/pyfit3Dcspline/GPU/GPUmleFit_LM_sCMOS.py +1426 -0
  33. microEye/analysis/fitting/pyfit3Dcspline/GPU/GPUsplineLib.py +231 -0
  34. microEye/analysis/fitting/pyfit3Dcspline/GPU/__init__.py +2 -0
  35. microEye/analysis/fitting/pyfit3Dcspline/__init__.py +10 -0
  36. microEye/analysis/fitting/pyfit3Dcspline/constants.py +27 -0
  37. microEye/analysis/fitting/pyfit3Dcspline/mainfunctions.py +903 -0
  38. microEye/analysis/fitting/results.py +917 -0
  39. microEye/analysis/fitting/results_stats.py +251 -0
  40. microEye/analysis/fitting/tardis.py +209 -0
  41. microEye/analysis/multi_viewer.py +568 -0
  42. microEye/analysis/processing/__init__.py +1 -0
  43. microEye/analysis/processing/frc.py +120 -0
  44. microEye/analysis/rendering/__init__.py +3 -0
  45. microEye/analysis/rendering/base.py +452 -0
  46. microEye/analysis/rendering/cloud.py +215 -0
  47. microEye/analysis/rendering/core.py +47 -0
  48. microEye/analysis/rendering/volumetric.py +198 -0
  49. microEye/analysis/tools/__init__.py +0 -0
  50. microEye/analysis/tools/kymograms.py +1079 -0
  51. microEye/analysis/tools/roi_selectors.py +556 -0
  52. microEye/analysis/utils/__init__.py +3 -0
  53. microEye/analysis/utils/coordinates.py +18 -0
  54. microEye/analysis/utils/images.py +68 -0
  55. microEye/analysis/utils/windows.py +19 -0
  56. microEye/analysis/viewer/__init__.py +3 -0
  57. microEye/analysis/viewer/image_options_widget.py +615 -0
  58. microEye/analysis/viewer/images.py +1225 -0
  59. microEye/analysis/viewer/layers_widget.py +415 -0
  60. microEye/analysis/viewer/localizations.py +1304 -0
  61. microEye/analysis/viewer/psf.py +1003 -0
  62. microEye/analysis/viewer/volume.py +456 -0
  63. microEye/hardware/__init__.py +3 -0
  64. microEye/hardware/cams/__init__.py +29 -0
  65. microEye/hardware/cams/camera_calibration.py +99 -0
  66. microEye/hardware/cams/camera_list.py +528 -0
  67. microEye/hardware/cams/camera_options.py +694 -0
  68. microEye/hardware/cams/camera_panel.py +941 -0
  69. microEye/hardware/cams/dummy/__init__.py +1 -0
  70. microEye/hardware/cams/dummy/dummy_panel.py +759 -0
  71. microEye/hardware/cams/jobs.py +497 -0
  72. microEye/hardware/cams/line_profiler.py +99 -0
  73. microEye/hardware/cams/linescan/IR_Cam.py +474 -0
  74. microEye/hardware/cams/linescan/__init__.py +1 -0
  75. microEye/hardware/cams/micam.py +524 -0
  76. microEye/hardware/cams/pco/__init__.py +58 -0
  77. microEye/hardware/cams/pco/enums.py +382 -0
  78. microEye/hardware/cams/pco/pco_cam.py +761 -0
  79. microEye/hardware/cams/pco/pco_panel.py +477 -0
  80. microEye/hardware/cams/shortcuts.py +312 -0
  81. microEye/hardware/cams/thorlabs/__init__.py +1 -0
  82. microEye/hardware/cams/thorlabs/thorlabs.py +1508 -0
  83. microEye/hardware/cams/thorlabs/thorlabs_panel.py +850 -0
  84. microEye/hardware/cams/ueye/__init__.py +1 -0
  85. microEye/hardware/cams/ueye/ueye_camera.py +1023 -0
  86. microEye/hardware/cams/ueye/ueye_panel.py +861 -0
  87. microEye/hardware/cams/vimba/__init__.py +1 -0
  88. microEye/hardware/cams/vimba/vimba_cam.py +1000 -0
  89. microEye/hardware/cams/vimba/vimba_panel.py +813 -0
  90. microEye/hardware/device.py +60 -0
  91. microEye/hardware/lasers/__init__.py +13 -0
  92. microEye/hardware/lasers/io_matchbox.py +791 -0
  93. microEye/hardware/lasers/io_params.py +85 -0
  94. microEye/hardware/lasers/io_single_laser.py +742 -0
  95. microEye/hardware/lasers/laser_relay.py +594 -0
  96. microEye/hardware/mieye/__init__.py +1 -0
  97. microEye/hardware/mieye/acquisition_manager.py +467 -0
  98. microEye/hardware/mieye/devices_manager.py +533 -0
  99. microEye/hardware/mieye/miEye.py +659 -0
  100. microEye/hardware/misc/__init__.py +0 -0
  101. microEye/hardware/misc/acquisition_view.py +71 -0
  102. microEye/hardware/misc/reglo.py +761 -0
  103. microEye/hardware/misc/temp.py +188 -0
  104. microEye/hardware/port_config.py +59 -0
  105. microEye/hardware/protocols/__init__.py +2 -0
  106. microEye/hardware/protocols/actions.py +402 -0
  107. microEye/hardware/protocols/actions_items.py +703 -0
  108. microEye/hardware/protocols/designer.py +244 -0
  109. microEye/hardware/protocols/scene_manager.py +191 -0
  110. microEye/hardware/protocols/serialization.py +97 -0
  111. microEye/hardware/pycromanager/__init__.py +16 -0
  112. microEye/hardware/pycromanager/core.py +1433 -0
  113. microEye/hardware/pycromanager/devices.py +461 -0
  114. microEye/hardware/pycromanager/enums.py +107 -0
  115. microEye/hardware/pycromanager/headless.py +153 -0
  116. microEye/hardware/pycromanager/utils.py +34 -0
  117. microEye/hardware/pycromanager/widgets/__init__.py +5 -0
  118. microEye/hardware/pycromanager/widgets/bridges.py +407 -0
  119. microEye/hardware/pycromanager/widgets/headless_manager.py +258 -0
  120. microEye/hardware/pycromanager/widgets/headless_options.py +224 -0
  121. microEye/hardware/pycromanager/widgets/pycro_panel.py +455 -0
  122. microEye/hardware/stages/__init__.py +18 -0
  123. microEye/hardware/stages/elliptec/__init__.py +5 -0
  124. microEye/hardware/stages/elliptec/baseDevice.py +314 -0
  125. microEye/hardware/stages/elliptec/device.py +384 -0
  126. microEye/hardware/stages/elliptec/deviceID.py +212 -0
  127. microEye/hardware/stages/elliptec/devicePort.py +379 -0
  128. microEye/hardware/stages/elliptec/deviceStatus.py +65 -0
  129. microEye/hardware/stages/elliptec/devicesView.py +706 -0
  130. microEye/hardware/stages/elliptec/ellDevices.py +134 -0
  131. microEye/hardware/stages/elliptec/messageUpdater.py +34 -0
  132. microEye/hardware/stages/elliptec/motorInfo.py +153 -0
  133. microEye/hardware/stages/elliptec/stage.py +62 -0
  134. microEye/hardware/stages/elliptec/test.py +139 -0
  135. microEye/hardware/stages/kinesis/__init__.py +1 -0
  136. microEye/hardware/stages/kinesis/kdc101/__init__.py +1 -0
  137. microEye/hardware/stages/kinesis/kdc101/enums.py +1002 -0
  138. microEye/hardware/stages/kinesis/kdc101/factory.py +171 -0
  139. microEye/hardware/stages/kinesis/kdc101/kdc101.py +718 -0
  140. microEye/hardware/stages/kinesis/kinesis.py +776 -0
  141. microEye/hardware/stages/piezo_concept.py +607 -0
  142. microEye/hardware/stages/stabilizer.py +785 -0
  143. microEye/hardware/stages/stage.py +89 -0
  144. microEye/hardware/widgets/__init__.py +10 -0
  145. microEye/hardware/widgets/controller.py +246 -0
  146. microEye/hardware/widgets/devices.py +133 -0
  147. microEye/hardware/widgets/focusWidget.py +264 -0
  148. microEye/hardware/widgets/qlist_slider.py +113 -0
  149. microEye/hardware/widgets/scan_acquisition.py +424 -0
  150. microEye/icons/1024.png +0 -0
  151. microEye/icons/128.png +0 -0
  152. microEye/icons/16.png +0 -0
  153. microEye/icons/24.png +0 -0
  154. microEye/icons/256.png +0 -0
  155. microEye/icons/32.png +0 -0
  156. microEye/icons/48.png +0 -0
  157. microEye/icons/512.png +0 -0
  158. microEye/icons/64.png +0 -0
  159. microEye/icons/__init__.py +0 -0
  160. microEye/icons/close.svg +88 -0
  161. microEye/icons/mieye.png +0 -0
  162. microEye/icons/min.svg +83 -0
  163. microEye/icons/viewer.png +0 -0
  164. microEye/launcher.py +42 -0
  165. microEye/qt.py +181 -0
  166. microEye/utils/__init__.py +2 -0
  167. microEye/utils/enum_encoder.py +10 -0
  168. microEye/utils/expandable_groupbox.py +93 -0
  169. microEye/utils/gui_helper.py +457 -0
  170. microEye/utils/hid/__init__.py +8 -0
  171. microEye/utils/hid/controller.py +153 -0
  172. microEye/utils/hid/device.py +63 -0
  173. microEye/utils/hid/enums.py +140 -0
  174. microEye/utils/hid/utils.py +58 -0
  175. microEye/utils/labelled_slider.py +134 -0
  176. microEye/utils/metadata.py +599 -0
  177. microEye/utils/metadata_tree.py +718 -0
  178. microEye/utils/micro_launcher.py +245 -0
  179. microEye/utils/parameter_tree.py +325 -0
  180. microEye/utils/pyscripting.py +444 -0
  181. microEye/utils/retry_exec.py +35 -0
  182. microEye/utils/start_gui.py +112 -0
  183. microEye/utils/thread_worker.py +115 -0
  184. microEye/utils/uImage.py +1512 -0
  185. microeye-2.3.2.dist-info/METADATA +401 -0
  186. microeye-2.3.2.dist-info/RECORD +190 -0
  187. microeye-2.3.2.dist-info/WHEEL +5 -0
  188. microeye-2.3.2.dist-info/entry_points.txt +2 -0
  189. microeye-2.3.2.dist-info/licenses/LICENSE +674 -0
  190. microeye-2.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1225 @@
1
+ import json
2
+ import math
3
+ import os
4
+ import threading
5
+ import traceback
6
+ from typing import Union
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import pyqtgraph as pg
11
+ import tifffile as tf
12
+ from numba import cuda
13
+ from ome_types import OME
14
+
15
+ if cuda.is_available():
16
+ from microEye.analysis.fitting.pyfit3Dcspline.mainfunctions import GPUmleFit_LM
17
+ else:
18
+
19
+ def GPUmleFit_LM(*args):
20
+ pass
21
+
22
+
23
+ from microEye.analysis.checklist_dialog import ChecklistDialog
24
+ from microEye.analysis.cmosMaps import cmosMaps
25
+ from microEye.analysis.filters import BandpassFilter, TemporalMedianFilter
26
+ from microEye.analysis.fitting import psf, pyfit3Dcspline
27
+ from microEye.analysis.fitting.fit import *
28
+ from microEye.analysis.fitting.phasor_fit import phasor_fit
29
+ from microEye.analysis.fitting.results import (
30
+ FittingMethod,
31
+ FittingResults,
32
+ ResultsUnits,
33
+ )
34
+ from microEye.analysis.tools.kymograms import KymogramWidget
35
+ from microEye.analysis.viewer.image_options_widget import FittingOptions, Parameters
36
+ from microEye.analysis.viewer.layers_widget import ImageItemsWidget
37
+ from microEye.qt import (
38
+ QDateTime,
39
+ Qt,
40
+ QtCore,
41
+ QtGui,
42
+ QtWidgets,
43
+ Signal,
44
+ Slot,
45
+ getOpenFileName,
46
+ getSaveFileName,
47
+ )
48
+ from microEye.utils.gui_helper import *
49
+ from microEye.utils.labelled_slider import LabelledSlider
50
+ from microEye.utils.metadata_tree import MetadataEditorTree, MetaParams
51
+ from microEye.utils.thread_worker import QThreadWorker
52
+ from microEye.utils.uImage import (
53
+ WORD,
54
+ TiffSeqHandler,
55
+ ZarrImageSequence,
56
+ saveZarrImage,
57
+ uImage,
58
+ )
59
+
60
+
61
+ class StackView(QtWidgets.QWidget):
62
+ '''
63
+ A class for viewing and interacting with image stacks in a PyQt5 application.
64
+ '''
65
+
66
+ localizedData = Signal(str)
67
+
68
+ def __init__(self, path: str, mask_pattern: str = None):
69
+ '''
70
+ Initialize the StackView.
71
+
72
+ Parameters
73
+ ----------
74
+ path : str
75
+ The path to the image stack.
76
+ mask_pattern : str, optional
77
+ A pattern to the mask file, by default None.
78
+ '''
79
+ super().__init__()
80
+
81
+ self.setWindowTitle(path.split('/')[-1])
82
+
83
+ self.path = path
84
+ self.stack_handler = self.getStackHandler(path, mask_pattern)
85
+ self.stack_handler.open()
86
+ self._threadpool = QtCore.QThreadPool.globalInstance()
87
+ self._lock = threading.Lock()
88
+
89
+ self.main_layout = QtWidgets.QHBoxLayout()
90
+ self.setLayout(self.main_layout)
91
+
92
+ # Graphics layout
93
+ self.initGraphics()
94
+
95
+ # Tab Widget
96
+ self.tab_widget = QtWidgets.QTabWidget()
97
+
98
+ self.main_layout.addWidget(self.tab_widget, 2)
99
+
100
+ # initialize the Prefit/Fitting Options tab
101
+ self.setupOptionsTab()
102
+
103
+ # Layers tab
104
+ self.setupLayersTab()
105
+
106
+ # Kymogram tab
107
+ self.setupKymogramTab()
108
+
109
+ # CMOS maps tab
110
+ self.setupCMOSMapsTab()
111
+
112
+ # Load Metadata
113
+ self.load_ome_metadata()
114
+
115
+ self.addStackLayers()
116
+
117
+ self.connnectSignals()
118
+ self.centerROI()
119
+
120
+ def connnectSignals(self):
121
+ self.roi.sigRegionChanged.connect(self.region_changed)
122
+ self.roi.sigRegionChangeFinished.connect(self.slider_changed)
123
+
124
+ self.fitting_options_widget.localizeData.connect(self.localize)
125
+ self.fitting_options_widget.extractPSF.connect(self.extract_psf)
126
+ self.fitting_options_widget.saveCropped.connect(self.save_cropped_img)
127
+ self.fitting_options_widget.roiEnabled.connect(self.change_roi_visibility)
128
+ self.fitting_options_widget.roiChanged.connect(self.roi_changed)
129
+ self.fitting_options_widget.paramsChanged.connect(self.slider_changed)
130
+
131
+ self.frames_slider.valueChanged.connect(self.slider_changed)
132
+ self.z_slider.valueChanged.connect(self.slider_changed)
133
+ self.lr_0.sigRegionChangeFinished.connect(self.slider_changed)
134
+
135
+ def initGraphics(self):
136
+ # A plot area (ViewBox + axes) for displaying the image
137
+ self.uImage = None
138
+ self.image_widget = pg.GraphicsLayoutWidget()
139
+ graphicsLayout = self.image_widget.ci
140
+ self.image_widget.setMinimumWidth(300)
141
+
142
+ # Create the ViewBox
143
+ self.view_box: pg.ViewBox = graphicsLayout.addViewBox(
144
+ row=0, col=0, invertY=True
145
+ )
146
+
147
+ self.view_box.setAspectLocked(True)
148
+ self.view_box.setAutoVisible(True)
149
+ self.view_box.enableAutoRange()
150
+ self.view_box.invertY(True)
151
+
152
+ self.empty_image = np.zeros(self.stack_handler.shape[-2:], dtype=np.uint8)
153
+ self.empty_alpha = np.zeros(
154
+ self.stack_handler.shape[-2:] + (4,), dtype=np.uint8
155
+ )
156
+
157
+ # histogram item
158
+ self.histogram_item = pg.HistogramLUTItem(
159
+ gradientPosition='bottom', orientation='horizontal'
160
+ )
161
+ self.levels_maps = []
162
+
163
+ self.image_widget.addItem(self.histogram_item, row=1, col=0)
164
+
165
+ # Add ROI
166
+ self.roi = pg.RectROI(
167
+ [-8, 14], [6, 5], scaleSnap=True, translateSnap=True, movable=False
168
+ )
169
+ self.roi.addTranslateHandle([0, 0], [0.5, 0.5])
170
+ self.roi.setZValue(1000)
171
+ self.roi.setVisible(False)
172
+ self.view_box.addItem(self.roi)
173
+
174
+ # Add ScatterPlotItem for localizations
175
+ self.scatter_locs = pg.ScatterPlotItem()
176
+ self.scatter_locs.setBrush(color='b')
177
+ self.scatter_locs.setSymbol('x')
178
+ self.scatter_locs.setZValue(999) # Ensure points are on top of image
179
+ self.view_box.addItem(self.scatter_locs)
180
+
181
+ # Add the two sub-main layouts
182
+ self.main_layout.addWidget(self.image_widget, 3)
183
+
184
+ def setImage(self, image: np.ndarray, autoLevels: bool = True, **kwargs):
185
+ '''Set the image data.'''
186
+ if image is None or self.image_layers.currentLayer is None:
187
+ return
188
+
189
+ index = kwargs.pop('index', self.image_layers.currentIndex)
190
+
191
+ self.image_layers.getImageItemAt(index).setImage(
192
+ image, autoLevels=autoLevels, **kwargs
193
+ )
194
+
195
+ def addImageItem(
196
+ self,
197
+ image: np.ndarray,
198
+ opacity: float = 1.0,
199
+ compMode='SourceOver',
200
+ name='Layer',
201
+ ):
202
+ """Add an image item to the view.
203
+
204
+ Parameters
205
+ ----------
206
+ image : np.ndarray
207
+ The image data.
208
+ opacity : float, optional
209
+ The opacity of the image, by default 1.0.
210
+ compMode : str, optional
211
+ The composition mode, by default 'SourceOver'.
212
+ name : str, optional
213
+ The name of the image item layer, by default 'Layer'.
214
+
215
+ Returns
216
+ -------
217
+ pg.ImageItem
218
+ The added image item.
219
+ """
220
+ # Create the ImageItem and set its view to self.view_box
221
+ image_item = self.image_layers.add_layer(image, opacity, compMode, name=name)
222
+ self.levels_maps.append({})
223
+
224
+ # Add the ImageItem to the ViewBox
225
+ self.view_box.addItem(image_item)
226
+
227
+ return image_item
228
+
229
+ def addStackLayers(self):
230
+ if self.stack_handler is None:
231
+ return
232
+
233
+ # Get the last part of the path
234
+ path = (
235
+ self.stack_handler.path
236
+ if len(self.stack_handler.path.split('/')) < 3
237
+ else '/'.join(self.stack_handler.path.split('/')[-2:])
238
+ )
239
+
240
+ count = self.image_layers.count()
241
+
242
+ nChannel = self.stack_handler.shapeTCZYX()[
243
+ 1
244
+ ] # TODO: add stack shape method pop-up
245
+ for idx in range(nChannel + 1):
246
+ image_item = self.addImageItem(
247
+ self.empty_image if count < 1 else self.empty_alpha,
248
+ compMode='SourceOver' if count < 1 else 'Plus',
249
+ name=path if idx < nChannel else 'Localization Layer',
250
+ )
251
+
252
+ self.image_layers.currentIndex = 0
253
+
254
+ def setupOptionsTab(self):
255
+ self.image_control_layout = QtWidgets.QFormLayout()
256
+ self.image_control_layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
257
+
258
+ self.frames_label = QtWidgets.QLabel('Time Axis:')
259
+ self.frames_slider = LabelledSlider(
260
+ None, True, (0, self.stack_handler.shapeTCZYX()[0] - 1)
261
+ )
262
+ self.c_label = QtWidgets.QLabel('Channel Axis:')
263
+ self.c_slider = LabelledSlider(
264
+ None, True, (0, self.stack_handler.shapeTCZYX()[1] - 1)
265
+ )
266
+ self.z_label = QtWidgets.QLabel('Z Axis:')
267
+ self.z_slider = LabelledSlider(
268
+ None, True, (0, self.stack_handler.shapeTCZYX()[2] - 1)
269
+ )
270
+
271
+ # Hist plotWidget
272
+ self.histogram = pg.PlotWidget()
273
+ green_pen = pg.mkPen(color='g')
274
+ self._bins = np.arange(WORD)
275
+ green_brush = pg.mkBrush(0, 255, 0, 32)
276
+
277
+ self.plot_refs = []
278
+ # Add hist channels plot references
279
+ colors = 'brgcyk'
280
+ for idx in range(self.stack_handler.shapeTCZYX()[1]):
281
+ ref = self.histogram.plot(
282
+ self._bins, np.zeros_like(self._bins), pen=pg.mkPen(color=colors[idx])
283
+ )
284
+ self.plot_refs.append(ref)
285
+
286
+ self.lr_0 = pg.LinearRegionItem(
287
+ (0, WORD - 1),
288
+ bounds=(0, WORD - 1),
289
+ pen=green_pen,
290
+ brush=green_brush,
291
+ movable=True,
292
+ swapMode='push',
293
+ span=(0.0, 1),
294
+ )
295
+ self.histogram.addItem(self.lr_0)
296
+
297
+ if self.frames_slider.maximum() > 0:
298
+ self.image_control_layout.addRow(self.frames_label, self.frames_slider)
299
+ if self.c_slider.maximum() > 0:
300
+ self.image_control_layout.addRow(self.c_label, self.c_slider)
301
+ if self.z_slider.maximum() > 0:
302
+ self.image_control_layout.addRow(self.z_label, self.z_slider)
303
+ self.image_control_layout.addRow(self.histogram)
304
+
305
+ self.fitting_options_widget = FittingOptions(
306
+ shape=self.stack_handler.shapeTCZYX()
307
+ )
308
+
309
+ # Localization GroupBox
310
+ self.export_options = ChecklistDialog(
311
+ 'Exported Columns',
312
+ [
313
+ 'Super-res image',
314
+ ]
315
+ + UNIQUE_COLUMNS,
316
+ checked=True,
317
+ parent=self,
318
+ )
319
+
320
+ self.prefit_widget, self.prefit_options_layout = create_widget(
321
+ QtWidgets.QVBoxLayout
322
+ )
323
+ layout_add_elements(
324
+ self.prefit_options_layout,
325
+ self.image_control_layout,
326
+ self.fitting_options_widget,
327
+ )
328
+ self.prefit_options_layout.addStretch()
329
+
330
+ self.tab_widget.addTab(self.prefit_widget, 'Prefit/Fitting Options')
331
+
332
+ def get_param(self, param_name: Parameters):
333
+ '''
334
+ Get a parameter by name from the cache of image_prefit_widget.
335
+ '''
336
+ return self.fitting_options_widget.get_param(param_name)
337
+
338
+ @Slot()
339
+ def save_cropped_img(self):
340
+ if self.stack_handler is None:
341
+ return
342
+
343
+ filename, _ = getSaveFileName(
344
+ self,
345
+ 'Save Cropped Image',
346
+ directory=os.path.dirname(self.path),
347
+ filter='Zarr Files (*.zarr)',
348
+ )
349
+
350
+ if len(filename) > 0:
351
+ roiInfo = self.get_roi_info()
352
+
353
+ def work_func(**kwargs):
354
+ try:
355
+ if roiInfo is not None:
356
+ origin, dim = roiInfo
357
+
358
+ saveZarrImage(
359
+ filename,
360
+ self.stack_handler,
361
+ ySlice=slice(int(origin[1]), int(origin[1] + dim[1])),
362
+ xSlice=slice(int(origin[0]), int(origin[0] + dim[0])),
363
+ )
364
+ else:
365
+ origin, dim = None, None
366
+
367
+ saveZarrImage(filename, self.stack_handler)
368
+ except Exception:
369
+ traceback.print_exc()
370
+
371
+ def done(results):
372
+ self.get_param(Parameters.SAVE_CROPPED_IMAGE).setOpts(enabled=True)
373
+
374
+ self.worker = QThreadWorker(work_func)
375
+ self.worker.signals.result.connect(done)
376
+ # Execute
377
+ self.get_param(Parameters.SAVE_CROPPED_IMAGE).setOpts(enabled=False)
378
+ self._threadpool.start(self.worker)
379
+
380
+ def setupLayersTab(self):
381
+ # Layers tab
382
+ self.image_layers = ImageItemsWidget()
383
+ self.image_layers.setReadonly()
384
+
385
+ self.image_layers.layerChanged.connect(self.updateLayer)
386
+ self.image_layers.layerRemoved.connect(
387
+ lambda index: self.levels_maps.pop(index)
388
+ )
389
+
390
+ self.tab_widget.addTab(self.image_layers, 'Layers')
391
+
392
+ def updateLayer(self, current: int, previous: int, imageItem: pg.ImageItem):
393
+ '''Update the layer settings.
394
+
395
+ Parameters
396
+ ----------
397
+ current : int
398
+ The current layer index.
399
+ previous : int
400
+ The previous layer index.
401
+ imageItem : pg.ImageItem
402
+ The image item.
403
+ '''
404
+ if current == -1 or imageItem is None:
405
+ return
406
+
407
+ if previous >= 0 and previous < len(self.levels_maps):
408
+ self.levels_maps[previous]['colorMap'] = (
409
+ self.histogram_item.gradient.colorMap()
410
+ )
411
+ self.levels_maps[previous]['levels'] = self.histogram_item.getLevels()
412
+
413
+ self.histogram_item.setImageItem(imageItem)
414
+
415
+ if current >= 0 and current < len(self.levels_maps):
416
+ self.histogram_item.gradient.setColorMap(
417
+ self.levels_maps[current].get('colorMap', None)
418
+ )
419
+ self.histogram_item.setLevels(
420
+ *self.levels_maps[current].get('levels', None)
421
+ )
422
+
423
+ def setupKymogramTab(self):
424
+ # Creating the kymogram tab layout
425
+ self.kymogram_widget = KymogramWidget(
426
+ max_window=self.stack_handler.shapeTCZYX()[0]
427
+ )
428
+
429
+ # self.kymogram_widget.setMaximum(self.stack_handler.shapeTCZYX()[0] - 1)
430
+ self.kymogram_widget.displayClicked.connect(self.kymogram_display_clicked)
431
+ self.kymogram_widget.extractClicked.connect(self.kymogram_btn_clicked)
432
+
433
+ self.tab_widget.addTab(self.kymogram_widget, 'Kymogram')
434
+
435
+ def kymogram_display_clicked(self, data: np.ndarray):
436
+ cv2.destroyAllWindows()
437
+
438
+ uImg = uImage(data)
439
+ uImg.equalizeLUT()
440
+ # self.image.setImage(uImg._view, autoLevels=True)
441
+ cv2.imshow('Kymogram', uImg._view)
442
+
443
+ def kymogram_btn_clicked(self):
444
+ if self.stack_handler is None:
445
+ return
446
+
447
+ cv2.destroyAllWindows()
448
+
449
+ self.kymogram_widget.extract_kymogram(
450
+ self.stack_handler,
451
+ self.frames_slider.value(),
452
+ self.frames_slider.maximum(),
453
+ self.get_roi_info(),
454
+ )
455
+
456
+ def setupCMOSMapsTab(self):
457
+ # CMOS maps tab
458
+ self.cmos_maps_group = cmosMaps()
459
+ self.tab_widget.addTab(self.cmos_maps_group, 'CMOS Maps')
460
+
461
+ def centerROI(self):
462
+ '''
463
+ Centers the region of interest (ROI) and fits it to the image.
464
+ '''
465
+ x = self.stack_handler.shape[-1]
466
+ y = self.stack_handler.shape[-2]
467
+
468
+ self.roi.setSize([x, y])
469
+ self.roi.setPos([0, 0])
470
+ self.roi.maxBounds = QtCore.QRectF(0, 0, x, y)
471
+
472
+ def get_roi_info(self):
473
+ if self.get_param(Parameters.ENABLE_ROI).value():
474
+ origin = self.roi.pos() # ROI (x,y)
475
+ dim = self.roi.size() # ROI (w,h)
476
+ return (round(origin[0]), round(origin[1])), (int(dim[0]), int(dim[1]))
477
+ else:
478
+ return None
479
+
480
+ def set_roi_info(self, x: int, y: int, width: int, height: int):
481
+ shape = self.stack_handler.shapeTCZYX()
482
+ x = min(max(0, x), shape[-1] - 1)
483
+ y = min(max(0, y), shape[-2] - 1)
484
+ width = min(max(1, width), shape[-1] - x)
485
+ height = min(max(1, height), shape[-2] - y)
486
+ self.roi.setPos([x, y]) # ROI (x,y)
487
+ self.roi.setSize([width, height]) # ROI (w,h)
488
+
489
+ def get_roi_txt(self):
490
+ if self.get_param(Parameters.ENABLE_ROI).value():
491
+ pixel_size = self.get_param(Parameters.PIXEL_SIZE).value()
492
+ return (
493
+ ' | ROI Pos. ('
494
+ + '{:.0f}, {:.0f}), '
495
+ + 'Size ({:.0f}, {:.0f})/({:.3f} um, {:.3f} um)'
496
+ ).format(
497
+ *self.roi.pos(),
498
+ *self.roi.size(),
499
+ *(self.roi.size() * pixel_size / 1000),
500
+ )
501
+
502
+ return ''
503
+
504
+ @Slot(tuple)
505
+ def roi_changed(self, value: tuple[int, int, int, int]):
506
+ self.set_roi_info(*value)
507
+
508
+ @Slot()
509
+ def region_changed(self):
510
+ x, y = self.roi.pos()
511
+ w, h = self.roi.size()
512
+ self.fitting_options_widget.set_roi(x, y, w, h)
513
+
514
+ @Slot()
515
+ def change_roi_visibility(self):
516
+ if self.get_param(Parameters.ENABLE_ROI).value():
517
+ self.roi.setVisible(True)
518
+ else:
519
+ self.roi.setVisible(False)
520
+
521
+ def load_ome_metadata(self):
522
+ if isinstance(self.stack_handler, TiffSeqHandler):
523
+ with tf.TiffFile(self.stack_handler._tiff_seq.files[0]) as fl:
524
+ if fl.is_ome:
525
+ ome_metadata = OME.from_xml(fl.ome_metadata)
526
+
527
+ self.metadata_editor = MetadataEditorTree()
528
+ self.metadata_editor.pop_OME_XML(ome_metadata)
529
+
530
+ self.tab_widget.addTab(self.metadata_editor, 'OME Metadata')
531
+ self.get_param(Parameters.PIXEL_SIZE).setValue(
532
+ self.metadata_editor.get_param_value(MetaParams.PX_SIZE)
533
+ )
534
+
535
+ @Slot()
536
+ def slider_changed(self):
537
+ if self.stack_handler is not None:
538
+ self.update_display()
539
+
540
+ def update_histogram(self):
541
+ self.lr_0.setBounds([0, self.uImage._max])
542
+
543
+ min_max = None
544
+ if not self.get_param(Parameters.AUTO_STRETCH).value():
545
+ min_max = tuple(map(math.ceil, self.lr_0.getRegion()))
546
+
547
+ self.uImage.equalizeLUT(min_max, True)
548
+
549
+ # TODO: Update plotrefs
550
+ if self.uImage._hist.ndim == 1:
551
+ self.plot_refs[0].setData(self.uImage._hist)
552
+ elif self.uImage._hist.ndim == 2:
553
+ for idx in range(self.uImage._hist.shape[1]):
554
+ self.plot_refs[idx].setData(self.uImage._hist[:, idx])
555
+
556
+ if self.get_param(Parameters.AUTO_STRETCH).value():
557
+ self.lr_0.sigRegionChangeFinished.disconnect(self.slider_changed)
558
+ self.lr_0.setRegion([self.uImage._min, self.uImage._max])
559
+ self.histogram.setXRange(self.uImage._min, self.uImage._max)
560
+ self.lr_0.sigRegionChangeFinished.connect(self.slider_changed)
561
+
562
+ def update_images(self):
563
+ if self.uImage._view.ndim == 2:
564
+ # self.image_items[0][1] = self.uImage._view
565
+ self.setImage(self.uImage._view, index=0)
566
+ elif self.uImage._view.ndim == 3:
567
+ for idx in range(self.uImage._view.shape[2]):
568
+ # self.image_items[idx][1] = self.uImage._view[..., idx]
569
+ self.setImage(self.uImage._view[..., idx], index=idx)
570
+
571
+ def apply_cmos_maps(self, image):
572
+ varim = None
573
+ if self.cmos_maps_group.active.isChecked():
574
+ res = self.cmos_maps_group.getMaps()
575
+ if res is not None and res[0].shape == image.shape:
576
+ image = image * res[0]
577
+ image = image - res[1]
578
+ varim = res[2]
579
+ return varim
580
+
581
+ def apply_temporal_median_filter(self, image, roiInfo):
582
+ if self.get_param(Parameters.TM_FILTER_ENABLED).value():
583
+ filter = TemporalMedianFilter(
584
+ self.get_param(Parameters.TM_FILTER_WINDOW_SIZE).value()
585
+ )
586
+ frames = filter.getFrames(
587
+ self.frames_slider.value(),
588
+ self.stack_handler,
589
+ None,
590
+ self.z_slider.value(),
591
+ )
592
+ image = filter.run(image, frames, roiInfo)
593
+ return image
594
+
595
+ def update_display(self):
596
+ image = self.stack_handler.getSlice(
597
+ self.frames_slider.value(), self.c_slider.value(), self.z_slider.value()
598
+ )
599
+
600
+ varim = self.apply_cmos_maps(image)
601
+
602
+ roiInfo = self.get_roi_info()
603
+
604
+ image = self.apply_temporal_median_filter(image, roiInfo)
605
+
606
+ self.uImage = uImage(image)
607
+
608
+ self.update_histogram()
609
+
610
+ self.update_images()
611
+
612
+ if self.get_param(Parameters.REALTIME_LOCALIZATION).value():
613
+ if image.ndim == 2:
614
+ self.apply_realtime_localization(image, varim, roiInfo)
615
+ else:
616
+ self.image_layers.getImageItemAt(-1).setImage(
617
+ self.empty_alpha, autoLevels=False
618
+ )
619
+ self.scatter_locs.clear()
620
+
621
+ def preprocess_image(self, image: uImage, roi_info):
622
+ if roi_info is not None:
623
+ origin, dim = roi_info
624
+ img = image._view[
625
+ int(origin[1]) : int(origin[1] + dim[1]),
626
+ int(origin[0]) : int(origin[0] + dim[0]),
627
+ ]
628
+ else:
629
+ origin, dim = None, None
630
+ img = image._view
631
+
632
+ # Apply bandpass filter
633
+ img = self.fitting_options_widget.get_image_filter().run(img)
634
+
635
+ # Threshold the image
636
+ _, th_img = cv2.threshold(
637
+ img,
638
+ np.quantile(img, 1 - 1e-4)
639
+ * self.get_param(Parameters.RELATIVE_THRESHOLD_MIN).value(),
640
+ 255,
641
+ cv2.THRESH_BINARY,
642
+ )
643
+
644
+ if self.get_param(Parameters.RELATIVE_THRESHOLD_MAX).value() < 1.0:
645
+ _, th2 = cv2.threshold(
646
+ img,
647
+ np.max(img) * self.get_param(Parameters.RELATIVE_THRESHOLD_MAX).value(),
648
+ 1,
649
+ cv2.THRESH_BINARY_INV,
650
+ )
651
+ th_img = th_img * th2
652
+
653
+ if self.get_param(Parameters.SHOW_FILTER).value():
654
+ cv2.namedWindow('Thresholded filtered Img.', cv2.WINDOW_NORMAL)
655
+ cv2.imshow('Thresholded filtered Img.', th_img)
656
+
657
+ return th_img, img, origin
658
+
659
+ def detect_and_display_keypoints(self, th_img, img, origin):
660
+ # Detect blobs
661
+ points, im_with_keypoints = (
662
+ self.fitting_options_widget.get_detector().find_peaks_preview(th_img, img)
663
+ )
664
+
665
+ # Show keypoints
666
+ if self.get_param(Parameters.SHOW_FILTER).value():
667
+ cv2.namedWindow('Approx. Loc.', cv2.WINDOW_NORMAL)
668
+ cv2.imshow('Approx. Loc.', im_with_keypoints)
669
+
670
+ if len(points) > 0 and origin is not None:
671
+ points[:, 0] += origin[0]
672
+ points[:, 1] += origin[1]
673
+
674
+ return points
675
+
676
+ def fit_keypoints(self, image, varim, points, return_points=False):
677
+ '''Fit detected points using selected fitting method.
678
+
679
+ Parameters
680
+ ----------
681
+ image : ndarray
682
+ Input image
683
+ varim : ndarray
684
+ Variance image (optional)
685
+ points : ndarray
686
+ Initial point coordinates
687
+ return_points : bool
688
+ If True, returns fitted point coordinates instead of visualization
689
+
690
+ Returns
691
+ -------
692
+ ndarray
693
+ Either visualization image with fitted keypoints or array of fitted
694
+ coordinates
695
+ '''
696
+ if len(points) == 0:
697
+ return None
698
+
699
+ method = self.fitting_options_widget.get_fitting_method()
700
+ sz = self.get_param(Parameters.ROI_SIZE).value()
701
+ fitted_coords = None
702
+
703
+ if method == FittingMethod._2D_Phasor_CPU:
704
+ fitted_coords = phasor_fit(image, points, True, sz)
705
+ else:
706
+ if varim is None:
707
+ varims = None
708
+ rois, coords = pyfit3Dcspline.get_roi_list(image, points, sz)
709
+ else:
710
+ rois, varims, coords = pyfit3Dcspline.get_roi_list_CMOS(
711
+ image, varim, points, sz
712
+ )
713
+ Params = None
714
+
715
+ PSF_param = np.array([self.get_param(Parameters.INITIAL_SIGMA).value()])
716
+
717
+ if method == FittingMethod._2D_Gauss_MLE_fixed_sigma:
718
+ Params, CRLBs, LogLikelihood = pyfit3Dcspline.CPUmleFit_LM(
719
+ rois, 1, PSF_param, varims, 0
720
+ )
721
+ elif method == FittingMethod._2D_Gauss_MLE_free_sigma:
722
+ Params, CRLBs, LogLikelihood = pyfit3Dcspline.CPUmleFit_LM(
723
+ rois, 2, PSF_param, varims, 0
724
+ )
725
+ elif method == FittingMethod._2D_Gauss_MLE_elliptical_sigma:
726
+ Params, CRLBs, LogLikelihood = pyfit3Dcspline.CPUmleFit_LM(
727
+ rois, 4, PSF_param, varims, 0
728
+ )
729
+ elif method == FittingMethod._3D_Gauss_MLE_cspline_sigma:
730
+ Params, CRLBs, LogLikelihood = pyfit3Dcspline.CPUmleFit_LM(
731
+ rois, 5, np.ones((64, 4, 4, 4), dtype=np.float32), varims, 0
732
+ )
733
+
734
+ fitted_coords = coords + Params[:, :2]
735
+
736
+ if fitted_coords is None:
737
+ return None
738
+
739
+ if return_points:
740
+ return fitted_coords
741
+
742
+ # Draw visualization
743
+ keypoints = [cv2.KeyPoint(*point, size=1.0) for point in fitted_coords[:, :2]]
744
+ vis_img = cv2.drawKeypoints(
745
+ self.empty_image,
746
+ keypoints,
747
+ None,
748
+ (0, 0, 255),
749
+ cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS,
750
+ )
751
+
752
+ return vis_img
753
+
754
+ def apply_realtime_localization(self, image, varim, roiInfo):
755
+ th_img, img, origin = self.preprocess_image(self.uImage, roiInfo)
756
+
757
+ # Detect blobs.
758
+ points = self.detect_and_display_keypoints(th_img, img, origin)
759
+
760
+ # im_with_keypoints = (
761
+ # self.fit_keypoints(image, varim, points) if len(points) > 0 else None
762
+ # )
763
+
764
+ # if im_with_keypoints is not None:
765
+ # alpha = self.empty_alpha.copy()
766
+ # alpha[..., :3] = im_with_keypoints
767
+ # alpha[..., 3] = im_with_keypoints[..., 2]
768
+ # self.image_layers.getImageItemAt(-1).setImage(alpha, autoLevels=False)
769
+
770
+ if len(points) > 0:
771
+ points = self.fit_keypoints(image, varim, points, return_points=True)
772
+ self.scatter_locs.setData(
773
+ pos=points + 0.5, size=10, brush='b', symbol='x', pxMode=True
774
+ )
775
+
776
+ @Slot()
777
+ def extract_psf(self):
778
+ '''Initiates the PSF extraction main thread worker.'''
779
+ if self.stack_handler is None:
780
+ return
781
+
782
+ filename, _ = getSaveFileName(
783
+ self,
784
+ 'Save PSF',
785
+ filter='PSF HDF5 files (*.psf.h5)',
786
+ directory=os.path.dirname(self.path),
787
+ )
788
+
789
+ if len(filename) > 0:
790
+
791
+ def done(res):
792
+ self.get_param(Parameters.LOCALIZE).setOpts(enabled=True)
793
+ self.get_param(Parameters.EXTRACT_PSF).setOpts(enabled=True)
794
+ if res is not None:
795
+ self.localizedData.emit(filename)
796
+
797
+ print('\nPSF Extraction Protocol:')
798
+ # Any other args, kwargs are passed to the run function
799
+ self.worker = QThreadWorker(self.extraction_protocol, filename)
800
+ self.worker.signals.result.connect(done)
801
+
802
+ # Execute
803
+ self.get_param(Parameters.LOCALIZE).setOpts(enabled=False)
804
+ self.get_param(Parameters.EXTRACT_PSF).setOpts(enabled=False)
805
+ self._threadpool.start(self.worker)
806
+
807
+ def extraction_protocol(self, filename: str, **kwargs):
808
+ method = self.fitting_options_widget.get_fitting_method()
809
+ frames_list = None
810
+ params = None
811
+ crlbs = None
812
+ loglike = None
813
+
814
+ if (
815
+ method == FittingMethod._2D_Phasor_CPU
816
+ or not cuda.is_available()
817
+ or not self.get_param(Parameters.LOCALIZE_GPU).value()
818
+ ):
819
+ print('\nCPU Fit')
820
+ # Any other args, kwargs are passed to the run function
821
+ frames_list, params, crlbs, loglike = self.localizeStackCPU()
822
+ else:
823
+ print('\nGPU Fit')
824
+ # Any other args, kwargs are passed to the run function
825
+ frames_list, params, crlbs, loglike = self.localizeStackGPU()
826
+
827
+ print('\nPSF Extraction:')
828
+ results = psf.get_psf_rois(
829
+ self.stack_handler,
830
+ frames_list,
831
+ params,
832
+ crlbs,
833
+ loglike,
834
+ method.value,
835
+ self.get_param(Parameters.PIXEL_SIZE).value(),
836
+ self.get_param(Parameters.PSF_ZSTEP).value(),
837
+ self.get_param(Parameters.ROI_SIZE).value(),
838
+ self.get_param(Parameters.PSF_UPSAMPLE).value(),
839
+ self.get_roi_info(),
840
+ self.get_param(Parameters.Z0_ENABLED).value(),
841
+ self.get_param(Parameters.Z0_METHOD).value(),
842
+ channel=self.c_slider.value(),
843
+ )
844
+
845
+ results.save_hdf(filename)
846
+
847
+ return results
848
+
849
+ @Slot()
850
+ def localize(self):
851
+ '''Initiates the localization main thread worker.'''
852
+ if self.stack_handler is None:
853
+ return
854
+
855
+ if not self.export_options.exec():
856
+ return
857
+
858
+ filename, _ = getSaveFileName(
859
+ self,
860
+ 'Save localizations',
861
+ filter='HDF5 files (*.h5);;TSV Files (*.tsv)',
862
+ directory=os.path.dirname(self.path),
863
+ )
864
+
865
+ if len(filename) > 0:
866
+ self.export_metadata_to_file(filename)
867
+ method = self.fitting_options_widget.get_fitting_method()
868
+
869
+ def done(res):
870
+ self.get_param(Parameters.LOCALIZE).setOpts(enabled=True)
871
+ self.get_param(Parameters.EXTRACT_PSF).setOpts(enabled=True)
872
+ if res is not None:
873
+ self.fittingResults.extend(res)
874
+ self.export_loc(filename)
875
+ self.localizedData.emit(filename)
876
+
877
+ if (
878
+ method == FittingMethod._2D_Phasor_CPU
879
+ or not cuda.is_available()
880
+ or not self.get_param(Parameters.LOCALIZE_GPU).value()
881
+ ):
882
+ print('\nCPU Fit')
883
+ # Any other args, kwargs are passed to the run function
884
+ self.worker = QThreadWorker(self.localizeStackCPU)
885
+ self.worker.signals.result.connect(done)
886
+ else:
887
+ print('\nGPU Fit')
888
+ # Any other args, kwargs are passed to the run function
889
+ self.worker = QThreadWorker(self.localizeStackGPU)
890
+ self.worker.signals.result.connect(done)
891
+
892
+ # Execute
893
+ self.get_param(Parameters.LOCALIZE).setOpts(enabled=False)
894
+ self.get_param(Parameters.EXTRACT_PSF).setOpts(enabled=False)
895
+ self._threadpool.start(self.worker)
896
+
897
+ def _initialize_parameters(self):
898
+ '''
899
+ Common method to initialize parameters, filters, and detectors.
900
+ '''
901
+ # method
902
+ method = self.fitting_options_widget.get_fitting_method()
903
+
904
+ # new instance of FittingResults
905
+ self.fittingResults = FittingResults(
906
+ ResultsUnits.Pixel, # unit is pixels
907
+ self.get_param(Parameters.PIXEL_SIZE).value(), # pixel projected size
908
+ method,
909
+ )
910
+
911
+ # Filters + Blob detector params
912
+ filter_obj = self.fitting_options_widget.get_image_filter()
913
+
914
+ tm_enabled = self.get_param(Parameters.TM_FILTER_ENABLED).value()
915
+
916
+ tm_window = (
917
+ self.get_param(Parameters.TM_FILTER_WINDOW_SIZE).value()
918
+ if tm_enabled
919
+ else 0
920
+ )
921
+
922
+ detector = self.fitting_options_widget.get_detector()
923
+
924
+ # ROI
925
+ roi_info = self.get_roi_info()
926
+
927
+ min_max = None
928
+ if not self.get_param(Parameters.AUTO_STRETCH).value():
929
+ min_max = tuple(map(math.ceil, self.lr_0.getRegion()))
930
+
931
+ # varim
932
+ varim = None
933
+ offset = 0
934
+ gain = 1
935
+ if self.cmos_maps_group.active.isChecked():
936
+ res = self.cmos_maps_group.getMaps()
937
+ if res:
938
+ gain = res[0]
939
+ offset = res[1]
940
+ varim = res[2]
941
+
942
+ rel_threshold = self.get_param(Parameters.RELATIVE_THRESHOLD_MIN).value()
943
+ max_threshold = self.get_param(Parameters.RELATIVE_THRESHOLD_MAX).value()
944
+ roi_size = self.get_param(Parameters.ROI_SIZE).value()
945
+
946
+ PSFparam = np.array([self.get_param(Parameters.INITIAL_SIGMA).value()])
947
+
948
+ return {
949
+ 'method': method,
950
+ 'gain': gain,
951
+ 'offset': offset,
952
+ 'varim': varim,
953
+ 'roi_info': roi_info,
954
+ 'irange': min_max,
955
+ 'rel_threshold': rel_threshold,
956
+ 'max_threshold': max_threshold,
957
+ 'tm_window': tm_window,
958
+ 'roi_size': roi_size,
959
+ 'PSFparam': PSFparam,
960
+ 'filter': filter_obj,
961
+ 'detector': detector,
962
+ 'channel': self.c_slider.value(),
963
+ 'zSlice': self.z_slider.value(),
964
+ }
965
+
966
+ def localizeStackCPU(self, **kwargs):
967
+ '''
968
+ CPU Localization main thread worker function.
969
+ '''
970
+ options = self._initialize_parameters()
971
+
972
+ frames_list, params, crlbs, loglike = localizeStackCPU(
973
+ self.stack_handler, options['filter'], options['detector'], options
974
+ )
975
+
976
+ return frames_list, params, crlbs, loglike
977
+
978
+ def localizeStackGPU(self, **kwargs):
979
+ '''GPU Localization main thread worker function.'''
980
+ options = self._initialize_parameters()
981
+
982
+ print('\nCollecting Prefit ROIs...')
983
+ start = QDateTime.currentDateTime() # timer
984
+
985
+ PSFparam = options['PSFparam']
986
+
987
+ # ROI
988
+ roi_info = options['roi_info']
989
+ if roi_info is not None:
990
+ origin = roi_info[0] # ROI (x,y)
991
+
992
+ kwargs = {
993
+ 'gain': options['gain'],
994
+ 'offset': options['offset'],
995
+ 'varim': options['varim'],
996
+ 'roi_info': options['roi_info'],
997
+ 'irange': options['irange'],
998
+ 'rel_threshold': options['rel_threshold'],
999
+ 'max_threshold': options['max_threshold'],
1000
+ 'tm_window': options['tm_window'],
1001
+ 'roi_size': options['roi_size'],
1002
+ }
1003
+
1004
+ roi_list, varim_list, coord_list, frames_list = get_rois_lists_GPU(
1005
+ self.stack_handler, options['filter'], options['detector'], **kwargs
1006
+ )
1007
+
1008
+ roi_list = np.vstack(roi_list)
1009
+ coord_list = np.vstack(coord_list)
1010
+ varim_list = None if options['varim'] is None else np.vstack(varim_list)
1011
+
1012
+ print(
1013
+ '\nROIs collected in',
1014
+ time_string_ms(start.msecsTo(QDateTime.currentDateTime())),
1015
+ )
1016
+
1017
+ if options['method'] == FittingMethod._2D_Gauss_MLE_fixed_sigma:
1018
+ params, crlbs, loglike = GPUmleFit_LM(roi_list, 1, PSFparam, varim_list, 0)
1019
+ elif options['method'] == FittingMethod._2D_Gauss_MLE_free_sigma:
1020
+ params, crlbs, loglike = GPUmleFit_LM(roi_list, 2, PSFparam, varim_list, 0)
1021
+ elif options['method'] == FittingMethod._2D_Gauss_MLE_elliptical_sigma:
1022
+ params, crlbs, loglike = GPUmleFit_LM(roi_list, 4, PSFparam, varim_list, 0)
1023
+ elif options['method'] == FittingMethod._3D_Gauss_MLE_cspline_sigma:
1024
+ params, crlbs, loglike = GPUmleFit_LM(roi_list, 5, PSFparam, varim_list, 0)
1025
+
1026
+ params = params.astype(np.float64, copy=False)
1027
+ crlbs = crlbs.astype(np.float64, copy=False)
1028
+ loglike = loglike.astype(np.float64, copy=False)
1029
+ frames_list = np.array(frames_list, dtype=np.int64)
1030
+
1031
+ if params is not None:
1032
+ params[:, :2] += np.array(coord_list)
1033
+ if len(params) > 0 and roi_info is not None:
1034
+ params[:, 0] += origin[0]
1035
+ params[:, 1] += origin[1]
1036
+
1037
+ print('\nDone...', time_string_ms(start.msecsTo(QDateTime.currentDateTime())))
1038
+
1039
+ return frames_list, params, crlbs, loglike
1040
+
1041
+ def export_loc(self, filename=None):
1042
+ '''Exports the fitting results into a file.
1043
+
1044
+ Parameters
1045
+ ----------
1046
+ filename : str, optional
1047
+ file path if None a save file dialog is shown, by default None
1048
+ '''
1049
+ if self.fittingResults is None:
1050
+ return
1051
+
1052
+ if filename is None:
1053
+ if not self.export_options.exec():
1054
+ return
1055
+
1056
+ filename, _ = getSaveFileName(
1057
+ self,
1058
+ 'Export localizations',
1059
+ filter='HDF5 files (*.h5);;TSV Files (*.tsv)',
1060
+ directory=os.path.dirname(self.path),
1061
+ )
1062
+
1063
+ if len(filename) > 0:
1064
+ options = self.export_options.toList()
1065
+
1066
+ dataFrame = self.fittingResults.dataFrame()
1067
+ exp_columns = []
1068
+ for col in dataFrame.columns:
1069
+ if col in options:
1070
+ exp_columns.append(col)
1071
+
1072
+ if exp_columns:
1073
+ if '.tsv' in filename:
1074
+ dataFrame.to_csv(
1075
+ filename,
1076
+ index=False,
1077
+ columns=exp_columns,
1078
+ float_format=self.export_options.export_precision.text(),
1079
+ sep='\t',
1080
+ encoding='utf-8',
1081
+ )
1082
+ elif '.h5' in filename:
1083
+ dataFrame[exp_columns].to_hdf(
1084
+ filename, key='microEye', index=False, complevel=0
1085
+ )
1086
+
1087
+ def update_lists(self, result: np.ndarray):
1088
+ '''Extends the fitting results by results emitted
1089
+ by a thread worker.
1090
+
1091
+ Parameters
1092
+ ----------
1093
+ result : np.ndarray
1094
+ [description]
1095
+ '''
1096
+ if result is not None:
1097
+ with self._lock:
1098
+ self.fittingResults.extend(result)
1099
+ self.thread_done += 1
1100
+
1101
+ def get_protocol_metadata(self, path):
1102
+ state = self.fitting_options_widget.param_tree.saveState(filter='user')
1103
+ metadata = {
1104
+ 'images': self.path,
1105
+ 'localizations file': path,
1106
+ 'intensity range': tuple(map(math.ceil, self.lr_0.getRegion())),
1107
+ 'cmos maps': {
1108
+ 'enabled': self.cmos_maps_group.active.isChecked(),
1109
+ },
1110
+ }
1111
+ dir_name = os.path.dirname(path)
1112
+ root_name, _ = os.path.splitext(os.path.basename(path))
1113
+ metadata['path'] = f'{dir_name}/{root_name}_protocol.json'
1114
+
1115
+ state['Others'] = metadata
1116
+ return state
1117
+
1118
+ def set_protocol_from_metadata(self, metadata: dict):
1119
+ others = metadata.pop('Others', None)
1120
+ self.fitting_options_widget.param_tree.restoreState(metadata)
1121
+ # Set intensity scaling
1122
+ lr_range = others.get('intensity range', None)
1123
+ if lr_range:
1124
+ self.lr_0.setRegion(tuple(map(math.ceil, lr_range)))
1125
+
1126
+ # Set cmos maps
1127
+ cmos_maps_metadata: dict = others.get('cmos maps', {})
1128
+ self.cmos_maps_group.active.setChecked(
1129
+ cmos_maps_metadata.get('enabled', self.cmos_maps_group.active.isChecked())
1130
+ )
1131
+
1132
+ def import_metadata_from_file(self, filepath=None):
1133
+ if filepath is None:
1134
+ filepath, _ = getOpenFileName(
1135
+ self,
1136
+ 'Import Metadata',
1137
+ filter='JSON files (*.json);;All Files (*)',
1138
+ directory=os.path.dirname(self.path),
1139
+ )
1140
+
1141
+ if len(filepath) > 0:
1142
+ try:
1143
+ with open(filepath) as file:
1144
+ metadata = json.load(file)
1145
+ # Do something with the imported metadata
1146
+ self.set_protocol_from_metadata(metadata)
1147
+ except Exception as e:
1148
+ # Handle any errors that might occur during file reading
1149
+ print(f'Error importing metadata: {e}')
1150
+
1151
+ def export_metadata_to_file(self, filepath=None):
1152
+ if filepath is None:
1153
+ filepath, _ = getSaveFileName(
1154
+ self,
1155
+ 'Export Metadata',
1156
+ filter='JSON files (*.json);;All Files (*)',
1157
+ directory=os.path.dirname(self.path),
1158
+ )
1159
+
1160
+ if len(filepath) > 0:
1161
+ try:
1162
+ metadata = self.get_protocol_metadata(filepath)
1163
+ with open(metadata['Others']['path'], 'w') as file:
1164
+ json.dump(metadata, file, indent=2)
1165
+ except Exception as e:
1166
+ # Handle any errors that might occur during file writing
1167
+ print(f'Error exporting metadata: {e}')
1168
+
1169
+ def closeEvent(self, event):
1170
+ if (
1171
+ self.get_param(Parameters.SAVE_CROPPED_IMAGE).opts['enabled']
1172
+ and self.get_param(Parameters.LOCALIZE).opts['enabled']
1173
+ and self.get_param(Parameters.EXTRACT_PSF).opts['enabled']
1174
+ ):
1175
+ # Ask the user if they really want to close the widget
1176
+ reply = QtWidgets.QMessageBox.question(
1177
+ self,
1178
+ 'Confirmation',
1179
+ 'Are you sure you want to close the widget?',
1180
+ QtWidgets.QMessageBox.StandardButton.Yes
1181
+ | QtWidgets.QMessageBox.StandardButton.No,
1182
+ QtWidgets.QMessageBox.StandardButton.No,
1183
+ )
1184
+
1185
+ if reply == QtWidgets.QMessageBox.StandardButton.Yes:
1186
+ # User clicked "Yes," close the widget
1187
+ self.stack_handler.close()
1188
+ event.accept()
1189
+ else:
1190
+ # User clicked "No," ignore the close event
1191
+ event.ignore()
1192
+ else:
1193
+ event.ignore()
1194
+ QtWidgets.QMessageBox.warning(
1195
+ self, 'Warning', 'Cannot close while workers are active!'
1196
+ )
1197
+
1198
+ def getStackHandler(self, path: str, mask_pattern: str = None):
1199
+ '''
1200
+ Get the image sequence handler based on the provided
1201
+ path and mask pattern.
1202
+
1203
+ Parameters
1204
+ ----------
1205
+ path : str
1206
+ The path to the image sequence.
1207
+ mask_pattern : str, optional
1208
+ The pattern for masking the image sequence in case of Tiff sequence,
1209
+ by default None.
1210
+
1211
+ Returns
1212
+ -------
1213
+ Union[ZarrImageSequence, TiffSeqHandler]
1214
+ An instance of the image sequence handler.
1215
+ '''
1216
+ if os.path.isdir(path) and not path.endswith('.zarr'):
1217
+ if not mask_pattern:
1218
+ raise ValueError('No mask pattern provided for a directory path')
1219
+ return TiffSeqHandler(tf.TiffSequence(f'{path}/{mask_pattern}'))
1220
+ elif os.path.isdir(path) and path.endswith('.zarr'):
1221
+ return ZarrImageSequence(path)
1222
+ elif os.path.isfile(path) and (path.endswith('.tif') or path.endswith('.tiff')):
1223
+ return TiffSeqHandler(tf.TiffSequence([path]))
1224
+ else:
1225
+ raise ValueError('Unsupported file format')