mlgidGUI 0.4.1__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 (202) hide show
  1. mlgidGUI/__init__.py +52 -0
  2. mlgidGUI/__main__.py +7 -0
  3. mlgidGUI/__version.py +1 -0
  4. mlgidGUI/app/__init__.py +8 -0
  5. mlgidGUI/app/actions_stack.py +1 -0
  6. mlgidGUI/app/app.py +67 -0
  7. mlgidGUI/app/cif_rois/__init__.py +0 -0
  8. mlgidGUI/app/cif_rois/cif_peaks_calculation.py +57 -0
  9. mlgidGUI/app/cif_rois/cif_simulation/__init__.py +0 -0
  10. mlgidGUI/app/cif_rois/cif_simulation/data/__init__.py +0 -0
  11. mlgidGUI/app/cif_rois/cif_simulation/data/atoms.py +15 -0
  12. mlgidGUI/app/cif_rois/cif_simulation/data/export_database.py +28 -0
  13. mlgidGUI/app/cif_rois/cif_simulation/experiment.py +57 -0
  14. mlgidGUI/app/cif_rois/cif_simulation/giwaxs_sim.py +286 -0
  15. mlgidGUI/app/cif_rois/cif_simulation/int_sim.py +105 -0
  16. mlgidGUI/app/cif_rois/cif_simulation/possible_directions.py +20 -0
  17. mlgidGUI/app/cif_rois/cif_simulation/q_sim.py +159 -0
  18. mlgidGUI/app/data_manager/__init__.py +4 -0
  19. mlgidGUI/app/data_manager/data_manager.py +164 -0
  20. mlgidGUI/app/data_manager/import_from_h5.py +68 -0
  21. mlgidGUI/app/data_manager/load_data.py +78 -0
  22. mlgidGUI/app/data_manager/pascal/__init__.py +2 -0
  23. mlgidGUI/app/data_manager/pascal/annotation_fabric.py +59 -0
  24. mlgidGUI/app/data_manager/pascal/draw_objects.py +119 -0
  25. mlgidGUI/app/data_manager/pascal/exceptions.py +6 -0
  26. mlgidGUI/app/data_manager/pascal/format_convertor.py +127 -0
  27. mlgidGUI/app/data_manager/pascal/pascal_annotation.py +85 -0
  28. mlgidGUI/app/data_manager/pascal/protocol_implementations.py +28 -0
  29. mlgidGUI/app/data_manager/pascal/protocols.py +47 -0
  30. mlgidGUI/app/data_manager/pascal/utils.py +64 -0
  31. mlgidGUI/app/data_manager/save_dataset.py +57 -0
  32. mlgidGUI/app/data_manager/save_h5.py +178 -0
  33. mlgidGUI/app/data_manager/saving_parameters.py +88 -0
  34. mlgidGUI/app/debug_tracker.py +129 -0
  35. mlgidGUI/app/edf_reader.py +135 -0
  36. mlgidGUI/app/file_manager/__init__.py +201 -0
  37. mlgidGUI/app/file_manager/config_manager.py +76 -0
  38. mlgidGUI/app/file_manager/keys.py +542 -0
  39. mlgidGUI/app/file_manager/npy_file_manager.py +17 -0
  40. mlgidGUI/app/file_manager/object_file_manager.py +77 -0
  41. mlgidGUI/app/file_manager/project_structure.py +169 -0
  42. mlgidGUI/app/file_manager/read_fits.py +76 -0
  43. mlgidGUI/app/file_manager/read_geometry.py +54 -0
  44. mlgidGUI/app/file_manager/read_images.py +31 -0
  45. mlgidGUI/app/file_manager/read_meta_roi.py +40 -0
  46. mlgidGUI/app/file_manager/read_polar_images.py +22 -0
  47. mlgidGUI/app/file_manager/read_radial_profile.py +6 -0
  48. mlgidGUI/app/file_manager/read_roi_data.py +39 -0
  49. mlgidGUI/app/fitting/__init__.py +5 -0
  50. mlgidGUI/app/fitting/background.py +92 -0
  51. mlgidGUI/app/fitting/fit.py +128 -0
  52. mlgidGUI/app/fitting/fit_holder.py +273 -0
  53. mlgidGUI/app/fitting/fit_object.py +247 -0
  54. mlgidGUI/app/fitting/functions.py +107 -0
  55. mlgidGUI/app/fitting/range_strategy.py +14 -0
  56. mlgidGUI/app/fitting/utils.py +17 -0
  57. mlgidGUI/app/geometry.py +236 -0
  58. mlgidGUI/app/geometry_holder.py +131 -0
  59. mlgidGUI/app/image_holder.py +200 -0
  60. mlgidGUI/app/image_processing.py +23 -0
  61. mlgidGUI/app/polar_image.py +96 -0
  62. mlgidGUI/app/profiles/__init__.py +5 -0
  63. mlgidGUI/app/profiles/angular_profile.py +20 -0
  64. mlgidGUI/app/profiles/basic_profile.py +169 -0
  65. mlgidGUI/app/profiles/radial_profile.py +38 -0
  66. mlgidGUI/app/read_image.py +21 -0
  67. mlgidGUI/app/rois/__init__.py +4 -0
  68. mlgidGUI/app/rois/new_roi_dict.py +670 -0
  69. mlgidGUI/app/rois/roi.py +194 -0
  70. mlgidGUI/app/rois/roi_colors.py +76 -0
  71. mlgidGUI/app/rois/roi_data.py +177 -0
  72. mlgidGUI/app/rois/roi_dict.py +466 -0
  73. mlgidGUI/app/rois/roi_meta_data.py +149 -0
  74. mlgidGUI/app/structures/__init__.py +6 -0
  75. mlgidGUI/app/structures/crystal_ring.py +19 -0
  76. mlgidGUI/app/structures/crystals_holders.py +144 -0
  77. mlgidGUI/app/structures/custom_crystal.py +45 -0
  78. mlgidGUI/app/structures/get_ring_list.py +89 -0
  79. mlgidGUI/app/transformations.py +82 -0
  80. mlgidGUI/app/update/__init__.py +3 -0
  81. mlgidGUI/app/update/check_version.py +51 -0
  82. mlgidGUI/app/update/launch_program.py +15 -0
  83. mlgidGUI/app/update/script_update.py +64 -0
  84. mlgidGUI/app/utils.py +124 -0
  85. mlgidGUI/gui/__init__.py +3 -0
  86. mlgidGUI/gui/background_tasks.py +41 -0
  87. mlgidGUI/gui/background_update.py +87 -0
  88. mlgidGUI/gui/basic_widgets/__init__.py +12 -0
  89. mlgidGUI/gui/basic_widgets/buttons.py +144 -0
  90. mlgidGUI/gui/basic_widgets/labels.py +51 -0
  91. mlgidGUI/gui/basic_widgets/mouse_events.py +119 -0
  92. mlgidGUI/gui/basic_widgets/path_line.py +162 -0
  93. mlgidGUI/gui/basic_widgets/plots_1d.py +365 -0
  94. mlgidGUI/gui/basic_widgets/plots_2d.py +224 -0
  95. mlgidGUI/gui/basic_widgets/popups.py +164 -0
  96. mlgidGUI/gui/basic_widgets/progress_bar.py +127 -0
  97. mlgidGUI/gui/basic_widgets/setup_widgets.py +138 -0
  98. mlgidGUI/gui/basic_widgets/sliders.py +616 -0
  99. mlgidGUI/gui/basic_widgets/spinner.py +65 -0
  100. mlgidGUI/gui/basic_widgets/toolbars.py +19 -0
  101. mlgidGUI/gui/debug_widgets.py +388 -0
  102. mlgidGUI/gui/dock_area.py +115 -0
  103. mlgidGUI/gui/exception_message.py +42 -0
  104. mlgidGUI/gui/fitting/__init__.py +2 -0
  105. mlgidGUI/gui/fitting/fit_widget.py +966 -0
  106. mlgidGUI/gui/fitting/inplace_fit.py +536 -0
  107. mlgidGUI/gui/fitting/selected_fit_widget.py +286 -0
  108. mlgidGUI/gui/gui_main.py +349 -0
  109. mlgidGUI/gui/image_viewer.py +323 -0
  110. mlgidGUI/gui/init_window.py +170 -0
  111. mlgidGUI/gui/load_window/__init__.py +2 -0
  112. mlgidGUI/gui/load_window/load_folder.py +61 -0
  113. mlgidGUI/gui/load_window/load_h5.py +73 -0
  114. mlgidGUI/gui/notifications.py +68 -0
  115. mlgidGUI/gui/polar_image_viewer.py +153 -0
  116. mlgidGUI/gui/profiles/__init__.py +1 -0
  117. mlgidGUI/gui/profiles/angular_profile_widget.py +62 -0
  118. mlgidGUI/gui/profiles/radial_profile_widget.py +164 -0
  119. mlgidGUI/gui/project_manager/__init__.py +17 -0
  120. mlgidGUI/gui/project_manager/cif_files_widget.py +196 -0
  121. mlgidGUI/gui/project_manager/cif_results.py +146 -0
  122. mlgidGUI/gui/project_manager/metadata_widget.py +15 -0
  123. mlgidGUI/gui/project_manager/project_viewer.py +151 -0
  124. mlgidGUI/gui/project_manager/roi_widget.py +171 -0
  125. mlgidGUI/gui/roi_widgets/__init__.py +6 -0
  126. mlgidGUI/gui/roi_widgets/abstract_roi_holder.py +189 -0
  127. mlgidGUI/gui/roi_widgets/abstract_roi_widget.py +111 -0
  128. mlgidGUI/gui/roi_widgets/cif_file_widget.py +16 -0
  129. mlgidGUI/gui/roi_widgets/cif_peak_widget.py +43 -0
  130. mlgidGUI/gui/roi_widgets/confidence_level_widget.py +105 -0
  131. mlgidGUI/gui/roi_widgets/roi_1d_widget.py +136 -0
  132. mlgidGUI/gui/roi_widgets/roi_2d_rect_widget.py +98 -0
  133. mlgidGUI/gui/roi_widgets/roi_2d_ring_widget.py +203 -0
  134. mlgidGUI/gui/roi_widgets/rois_context_menu.py +150 -0
  135. mlgidGUI/gui/roi_widgets/select_roi_color_widget.py +58 -0
  136. mlgidGUI/gui/save_window/__init__.py +152 -0
  137. mlgidGUI/gui/save_window/format_box.py +33 -0
  138. mlgidGUI/gui/save_window/num_selected_widget.py +45 -0
  139. mlgidGUI/gui/save_window/options_widgets.py +105 -0
  140. mlgidGUI/gui/save_window/save_mode_box.py +30 -0
  141. mlgidGUI/gui/save_window/select_images.py +198 -0
  142. mlgidGUI/gui/tools.py +179 -0
  143. mlgidGUI/static/__init__.py +0 -0
  144. mlgidGUI/static/icons/__init__.py +0 -0
  145. mlgidGUI/static/icons/add.png +0 -0
  146. mlgidGUI/static/icons/add_yellow.png +0 -0
  147. mlgidGUI/static/icons/angular_profile.png +0 -0
  148. mlgidGUI/static/icons/arrow.png +0 -0
  149. mlgidGUI/static/icons/baseline.png +0 -0
  150. mlgidGUI/static/icons/center.png +0 -0
  151. mlgidGUI/static/icons/confirm.png +0 -0
  152. mlgidGUI/static/icons/control_widget.png +0 -0
  153. mlgidGUI/static/icons/data.png +0 -0
  154. mlgidGUI/static/icons/delete.png +0 -0
  155. mlgidGUI/static/icons/delete_yellow.png +0 -0
  156. mlgidGUI/static/icons/error.png +0 -0
  157. mlgidGUI/static/icons/find.png +0 -0
  158. mlgidGUI/static/icons/fit.png +0 -0
  159. mlgidGUI/static/icons/fix_all.png +0 -0
  160. mlgidGUI/static/icons/flip_horizontal.png +0 -0
  161. mlgidGUI/static/icons/flip_vertical.png +0 -0
  162. mlgidGUI/static/icons/folder.png +0 -0
  163. mlgidGUI/static/icons/fromfullscreen.png +0 -0
  164. mlgidGUI/static/icons/h5_folder.png +0 -0
  165. mlgidGUI/static/icons/h5_group_folder.png +0 -0
  166. mlgidGUI/static/icons/info.png +0 -0
  167. mlgidGUI/static/icons/interpolate.png +0 -0
  168. mlgidGUI/static/icons/item.png +0 -0
  169. mlgidGUI/static/icons/properties.png +0 -0
  170. mlgidGUI/static/icons/radial_profile.png +0 -0
  171. mlgidGUI/static/icons/roi_item.png +0 -0
  172. mlgidGUI/static/icons/rotate.png +0 -0
  173. mlgidGUI/static/icons/rotate_image.png +0 -0
  174. mlgidGUI/static/icons/rotate_right.png +0 -0
  175. mlgidGUI/static/icons/setup.png +0 -0
  176. mlgidGUI/static/icons/setup_white.png +0 -0
  177. mlgidGUI/static/icons/tofullscreen.png +0 -0
  178. mlgidGUI/static/icons/unfix_all.png +0 -0
  179. mlgidGUI/static/icons/update.png +0 -0
  180. mlgidGUI/static/icons/update_suggested.png +0 -0
  181. mlgidGUI/static/icons/window_icon.png +0 -0
  182. mlgidGUI/static/icons/window_icon_256.png +0 -0
  183. mlgidGUI/utils/__init__.py +1 -0
  184. mlgidGUI/utils/project2h5.py +11 -0
  185. mlgidgui-0.4.1.dist-info/METADATA +119 -0
  186. mlgidgui-0.4.1.dist-info/RECORD +202 -0
  187. mlgidgui-0.4.1.dist-info/WHEEL +5 -0
  188. mlgidgui-0.4.1.dist-info/entry_points.txt +5 -0
  189. mlgidgui-0.4.1.dist-info/licenses/LICENSE +674 -0
  190. mlgidgui-0.4.1.dist-info/top_level.txt +4 -0
  191. tests/__init__.py +0 -0
  192. tests/conftest.py +1 -0
  193. tests/fixures/__init__.py +2 -0
  194. tests/fixures/projects.py +102 -0
  195. tests/func/__init__.py +1 -0
  196. tests/func/test_loading_state.py +21 -0
  197. tests/func/test_parse_project_data.py +23 -0
  198. tests/func/test_save.py +62 -0
  199. tests/unit/__init__.py +0 -0
  200. tests/unit/rois/__init__.py +0 -0
  201. tests/unit/rois/test_basic_operations.py +18 -0
  202. tests/unit/test_add_data.py +33 -0
@@ -0,0 +1,178 @@
1
+ from typing import List
2
+ from pathlib import Path
3
+
4
+ from h5py import File, Group
5
+ import numpy as np
6
+
7
+ from ..geometry import Geometry
8
+ from .saving_parameters import SavingParameters, SaveMode
9
+ from ..file_manager import (FileManager, FolderKey, ImageKey,
10
+ IMAGE_PROJECT_KEY, PROJECT_KEY)
11
+ from ..image_holder import ImageHolder
12
+ from .load_data import ImageData, ImageDataFlags, load_image_data
13
+
14
+
15
+ class SaveH5(object):
16
+ def __init__(self, fm: FileManager, image_holder: ImageHolder):
17
+ self._fm: FileManager = fm
18
+ self._fm = fm
19
+ self._image_holder = image_holder
20
+
21
+ def save(self, params: SavingParameters) -> bool:
22
+ filepath = _get_h5_path(params.path)
23
+
24
+ save_successfull = _init_h5_project_file(filepath, params)
25
+ path_str: str = str(filepath.resolve())
26
+
27
+ for folder_key, image_keys in params.selected_images.items():
28
+ self._save_folder_as_h5(path_str, folder_key, image_keys, params)
29
+
30
+ return save_successfull
31
+
32
+ def save_for_object_detection(self, params: SavingParameters):
33
+ filepath = _get_h5_path(params.path)
34
+ count: int = 0
35
+
36
+ if not filepath.parent.exists():
37
+ raise IOError(f'Parent folder {filepath.parent} does not exist.')
38
+
39
+ path_str: str = str(filepath.resolve())
40
+
41
+ if filepath.exists():
42
+ with File(path_str, 'r') as f:
43
+ count = len(list(f.keys()))
44
+
45
+ with File(path_str, 'a') as f:
46
+ for _, image_keys in params.selected_images.items():
47
+ for image_key in image_keys:
48
+ if self._save_image_for_object_detection(f, image_key, str(count)):
49
+ count += 1
50
+
51
+ def _save_image_for_object_detection(self, f: File, image_key: ImageKey, name: str) -> bool:
52
+ image_data: ImageData = load_image_data(self._fm, self._image_holder,
53
+ image_key, flags=ImageDataFlags.POLAR_IMAGE | ImageDataFlags.GEOMETRY | ImageDataFlags.ROI_DATA)
54
+
55
+ if image_data.polar_image is None or image_data.roi_data is None or image_data.geometry is None:
56
+ return False
57
+
58
+ boxes, labels = _get_boxes_n_labels(image_data.roi_data.to_array(), image_data.geometry)
59
+
60
+ group = f.create_group(name)
61
+ group.create_dataset('polar_image', data=image_data.polar_image)
62
+ group.create_dataset('boxes', data=boxes)
63
+ group.create_dataset('labels', data=labels)
64
+ group.create_dataset('intensities', data=image_data.roi_data.intensities)
65
+ group.create_dataset('confidence_levels', data=image_data.roi_data.confidence_levels)
66
+ group.create_dataset('cif_files', data=image_data.roi_data.cif_files)
67
+ group.attrs.update(file_key=str(image_key._file_key()))
68
+
69
+ try:
70
+ group.attrs.update(path=str(image_key.path))
71
+ except AttributeError:
72
+ pass
73
+
74
+ return True
75
+
76
+ def _save_folder_as_h5(self, path: str, folder_key: FolderKey,
77
+ image_keys: List[ImageKey], params: SavingParameters):
78
+ if not image_keys:
79
+ return
80
+
81
+ with File(path, 'a') as f:
82
+ group = _get_folder_group(f, folder_key.name)
83
+
84
+ self._save_folder_data(group, folder_key, params)
85
+
86
+ for image_key in image_keys:
87
+ self._save_image_as_h5(group, image_key, params)
88
+
89
+ def _save_folder_data(self, group: Group, folder_key: FolderKey, params: SavingParameters):
90
+
91
+ if params.save_geometries:
92
+ default_geometry = self._fm.geometries.default[folder_key]
93
+ if default_geometry:
94
+ self._fm.geometries.default.set_h5(group, folder_key, default_geometry)
95
+
96
+ if params.save_roi_metadata:
97
+ roi_metadata = self._fm.rois_meta_data[folder_key]
98
+ if roi_metadata:
99
+ self._fm.rois_meta_data.set_h5(group, folder_key, roi_metadata)
100
+
101
+ def _save_image_as_h5(self,
102
+ h5group: Group,
103
+ image_key: ImageKey,
104
+ params: SavingParameters
105
+ ):
106
+
107
+ if image_key.name in h5group.keys():
108
+ del h5group[image_key.name]
109
+
110
+ img_group = h5group.create_group(image_key.name)
111
+ img_group.attrs[IMAGE_PROJECT_KEY] = True
112
+
113
+ polar_image = load_image_data(self._fm, self._image_holder, image_key, ImageDataFlags.POLAR_IMAGE).polar_image
114
+
115
+ if params.save_image:
116
+ self._fm.images.set_h5(img_group, image_key, image_key.get_image())
117
+
118
+ if params.save_polar_image and polar_image is not None:
119
+ self._fm.polar_images.set_h5(img_group, image_key, polar_image)
120
+
121
+ roi_data = self._fm.rois_data[image_key]
122
+
123
+ if roi_data:
124
+ self._fm.rois_data.set_h5(img_group, image_key, roi_data)
125
+
126
+ geometry = self._fm.geometries[image_key]
127
+
128
+ if geometry and params.save_geometries:
129
+ self._fm.geometries.set_h5(img_group, image_key, geometry)
130
+
131
+
132
+ def _init_h5_project_file(filepath: Path, params: SavingParameters) -> bool:
133
+ try:
134
+ if not filepath.parent.exists():
135
+ raise IOError(f'Parent folder {filepath.parent} does not exist.')
136
+
137
+ path_str: str = str(filepath.resolve())
138
+
139
+ if filepath.exists() and params.save_mode.value == SaveMode.create.value:
140
+ raise IOError(f'File {path_str} already exists.')
141
+
142
+ if params.save_mode.value == SaveMode.add.value:
143
+ with File(path_str, 'a') as f:
144
+ if PROJECT_KEY not in f.attrs:
145
+ raise IOError(f'Chosen file {path_str} is not a h5 project file!')
146
+
147
+ elif params.save_mode.value == SaveMode.create.value:
148
+ with File(path_str, 'w') as f:
149
+ f.attrs[PROJECT_KEY] = True
150
+ return True
151
+ except:
152
+ return False
153
+
154
+
155
+
156
+ def _get_h5_path(path: Path) -> Path:
157
+ path = path.resolve()
158
+ if path.suffix != '.h5':
159
+ name = '.'.join([path.name.split('.')[0], '.h5'])
160
+ path = path.parent / name
161
+ return path
162
+
163
+
164
+ def _get_folder_group(f: File, name: str) -> Group:
165
+ return f.create_group(name) if name not in f.keys() else f[name]
166
+
167
+
168
+ def _get_boxes_n_labels(roi_arr: np.ndarray, geometry: Geometry):
169
+ labels, boxes = [], []
170
+
171
+ for r, w, a, a_s, key, roi_type in roi_arr:
172
+ x1, x2 = geometry.r2p(r - w / 2), geometry.r2p(r + w / 2)
173
+ y1, y2 = geometry.a2p(a - a_s / 2), geometry.a2p(a + a_s / 2)
174
+
175
+ labels.append(roi_type)
176
+ boxes.append([x1, y1, x2, y2])
177
+
178
+ return np.array(boxes), np.array(labels)
@@ -0,0 +1,88 @@
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+ from typing import Dict, List
4
+ from pathlib import Path
5
+
6
+ from ..file_manager import FolderKey, ImageKey
7
+
8
+
9
+ class SaveFormats(Enum):
10
+ entire_h5 = 'Save entire project as h5 (recommended, import possible)'
11
+ partial_h5 = 'Save parts of project as h5 (import not possible)'
12
+ object_detection = 'Save as pascal-VOC dataset'
13
+ text = 'Text formats'
14
+
15
+
16
+ class TextFormats(Enum):
17
+ csv = 'csv'
18
+ txt = 'txt'
19
+
20
+
21
+ class MetaTextFormats(Enum):
22
+ json = 'json'
23
+ yaml = 'yaml'
24
+
25
+
26
+ class RoiSavingType(Enum):
27
+ group_by_image = 'Group segments by image'
28
+ group_by_time = 'Group segments by time'
29
+
30
+
31
+ class SaveMode(Enum):
32
+ create = 'New save'
33
+ add = 'Update save'
34
+
35
+
36
+ @dataclass
37
+ class SavingParameters:
38
+ selected_images: Dict[FolderKey, List[ImageKey]]
39
+ path: Path
40
+ save_mode: SaveMode = SaveMode.create
41
+
42
+ save_image: bool = True
43
+ save_polar_image: bool = True
44
+ save_geometries: bool = True
45
+ save_baselines: bool = True
46
+ save_positions: bool = True
47
+ save_roi_types: bool = True
48
+ save_roi_keys: bool = True
49
+ save_roi_metadata: bool = True
50
+
51
+ format: SaveFormats = SaveFormats.entire_h5
52
+ text_format: TextFormats = TextFormats.csv
53
+ meta_text_format: MetaTextFormats = MetaTextFormats.yaml
54
+ roi_saving_type: RoiSavingType = RoiSavingType.group_by_image
55
+
56
+ BOOL_FLAGS = {'save_image': 'Save images',
57
+ 'save_polar_image': 'Save polar images',
58
+ 'save_geometries': 'Save geometries',
59
+ 'save_baselines': 'Save baselines',
60
+ 'save_positions': 'Save roi positions',
61
+ 'save_roi_types': 'Save roi types',
62
+ 'save_roi_keys': 'Save roi keys',
63
+ 'save_roi_metadata': 'Save roi names',
64
+ }
65
+
66
+ def set_entire_h5_params(self):
67
+ self.save_image: bool = True
68
+ self.save_polar_image: bool = True
69
+ self.save_geometries: bool = True
70
+ self.save_baselines: bool = True
71
+ self.save_positions: bool = True
72
+ self.save_roi_types: bool = True
73
+ self.save_roi_keys: bool = True
74
+ self.save_roi_metadata: bool = True
75
+
76
+ def set_partial_h5_params(self):
77
+ self.save_image: bool = False
78
+ self.save_polar_image: bool = False
79
+ self.save_geometries: bool = True
80
+ self.save_baselines: bool = False
81
+ self.save_positions: bool = True
82
+ self.save_roi_types: bool = True
83
+ self.save_roi_keys: bool = False
84
+ self.save_roi_metadata: bool = False
85
+
86
+ @property
87
+ def num_images(self) -> int:
88
+ return sum(map(len, self.selected_images.values()))
@@ -0,0 +1,129 @@
1
+ from datetime import datetime as dt
2
+ from enum import Enum
3
+ import sys
4
+ from typing import Dict
5
+ import weakref
6
+ import gc
7
+ import logging
8
+
9
+ from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
10
+
11
+ from .utils import SingletonMeta
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class ObjectStatus(Enum):
17
+ EXISTS = 0
18
+ SAFELY_DELETED = 1
19
+ DELETED_BY_PYTHON = 2
20
+ DELETED_BY_C = 3
21
+
22
+
23
+ class TrackSignals(QObject):
24
+ sigObjectAdded = pyqtSignal(str)
25
+ sigStatusUpdated = pyqtSignal(list)
26
+
27
+
28
+ class ObjectTracker(QObject):
29
+ def __init__(self, obj: QObject, name: str):
30
+ super().__init__()
31
+ self.name: str = f'{obj.__class__.__name__}: {name}'
32
+ self.id: str = f'{name}: {id(obj)}, {dt.now().timestamp()}'
33
+ self.obj_ref = weakref.ref(obj)
34
+ self.status: ObjectStatus = ObjectStatus.EXISTS
35
+ self._deleted_by_c: bool = False
36
+ self._deleted_by_python: bool = False
37
+ obj.destroyed.connect(self._on_destroyed)
38
+ self.update_status()
39
+
40
+ def update_status(self) -> ObjectStatus:
41
+ try:
42
+ obj = self.obj_ref()
43
+ if obj is None:
44
+ self._deleted_by_python = True
45
+ except LookupError:
46
+ logger.debug('LookupError in tracker')
47
+ self._deleted_by_python = True
48
+ except RuntimeError:
49
+ logger.debug('RuntimeError in tracker')
50
+ self._deleted_by_c = True
51
+
52
+ if self._deleted_by_c and self._deleted_by_python:
53
+ self.status = ObjectStatus.SAFELY_DELETED
54
+ elif self._deleted_by_c and not self._deleted_by_python:
55
+ self.status = ObjectStatus.DELETED_BY_C
56
+ elif not self._deleted_by_c and self._deleted_by_python:
57
+ self.status = ObjectStatus.DELETED_BY_PYTHON
58
+ else:
59
+ self.status = ObjectStatus.EXISTS
60
+
61
+ return self.status
62
+
63
+ def get_referrers(self):
64
+ obj = self.get_obj()
65
+ if obj:
66
+ logger.debug(f'Number of refs = {sys.getrefcount(obj)}')
67
+ return gc.get_referrers([obj])
68
+ else:
69
+ logger.debug('Object is None!')
70
+
71
+ def get_obj(self):
72
+ try:
73
+ return self.obj_ref()
74
+ except Exception as err:
75
+ logger.exception(err)
76
+
77
+ def is_tracked(self) -> bool:
78
+ obj = self.get_obj()
79
+ if obj:
80
+ return gc.is_tracked(obj)
81
+ else:
82
+ return False
83
+
84
+ @pyqtSlot(name='onDestroyed')
85
+ def _on_destroyed(self, *args):
86
+ # logger.debug('destroyed signal in tracker')
87
+ self._deleted_by_c = True
88
+
89
+
90
+ class TrackQObjects(metaclass=SingletonMeta):
91
+ ObjectStatus: ObjectStatus = ObjectStatus
92
+
93
+ def __init__(self):
94
+ self.signals: TrackSignals = TrackSignals()
95
+ self.objects: Dict[str, ObjectTracker] = {}
96
+
97
+ def add_object(self, obj: QObject, name: str = ''):
98
+ obj_tracker = ObjectTracker(obj, name)
99
+ self.objects[obj_tracker.id] = obj_tracker
100
+ self.signals.sigObjectAdded.emit(obj_tracker.id)
101
+
102
+ def update(self, key: str = None, *, emit: bool = True):
103
+ if key:
104
+ self._update(key)
105
+ else:
106
+ updated_keys = []
107
+ for key, obj in self.objects.items():
108
+ if obj.status != obj.update_status():
109
+ updated_keys.append(key)
110
+ if emit and updated_keys:
111
+ self.signals.sigStatusUpdated.emit(updated_keys)
112
+
113
+ def _update(self, key: str):
114
+ try:
115
+ if self.objects[key].status != self.objects[key].update_status():
116
+ self.signals.sigStatusUpdated.emit([key])
117
+ except KeyError:
118
+ pass
119
+
120
+ def clear_deleted(self, status: ObjectStatus = ObjectStatus.SAFELY_DELETED):
121
+ to_delete = []
122
+ for key, obj in self.objects.items():
123
+ if obj.status == status:
124
+ to_delete.append(key)
125
+
126
+ for key in to_delete:
127
+ obj = self.objects.pop(key)
128
+ obj.deleteLater()
129
+ return to_delete
@@ -0,0 +1,135 @@
1
+ """
2
+ Interface functions for reading edf files and saving images as edf.
3
+ """
4
+
5
+ from typing import Union, Tuple, List, Dict
6
+ from pathlib import Path
7
+ from io import BytesIO
8
+ import gzip
9
+
10
+ import numpy as np
11
+
12
+ __all__ = ['read_edf', 'CorruptedFileError']
13
+
14
+
15
+ class CorruptedFileError(ValueError):
16
+ """
17
+ Raises when file cannot be read.
18
+ """
19
+
20
+
21
+ def read_edf(filepath: Union[Path, str, BytesIO], header_dict: dict = None,
22
+ return_dict: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, dict]]:
23
+ """
24
+ Parses .edf file and returns numpy array if successful. If return_dict is True,
25
+ returns tuple of image and header dict. If header_dict is provided, uses it instead of
26
+ parsing the file header, it may accelerate reading.
27
+
28
+ Raises CorruptedFileError if any parsing error occurs.
29
+
30
+ :param filepath: Union[Path, str, BytesIO]. If str provided, it will be converted to Path first.
31
+ :param header_dict: dict = None. Optional, use to accelerate parsing. Should contain
32
+ the following keys: 'headerSize', 'Size', 'DataType', 'Dim_1', 'Dim_2'.
33
+ :param return_dict: bool = False. If True, returns header_dict along with the image.
34
+ :return: np.ndarray if not return_dict else Tuple[np.ndarray, dict]]
35
+ """
36
+ data = _get_data_from_filepath(filepath) # type: bytes
37
+ image, header_dict = _read_edf_from_data(data, header_dict) # type: np.ndarray, dict
38
+ if return_dict:
39
+ return image, header_dict
40
+ else:
41
+ return image
42
+
43
+
44
+ def _get_data_from_filepath(filepath: Union[Path, str, BytesIO]) -> bytes:
45
+ if isinstance(filepath, str):
46
+ filepath = Path(filepath)
47
+
48
+ if isinstance(filepath, Path):
49
+ if not filepath.is_file():
50
+ raise FileNotFoundError(f'File {filepath} does not exist.')
51
+
52
+ if filepath.suffix == '.edf':
53
+ with open(str(filepath), 'rb') as f:
54
+ return f.read() # type: bytes
55
+ elif filepath.suffix == '.gz':
56
+ with gzip.open(str(filepath), 'rb') as f:
57
+ return f.read() # type: bytes
58
+ else:
59
+ raise TypeError(f'Unknown file extension {filepath.suffix}.')
60
+ elif isinstance(filepath, BytesIO):
61
+ return filepath.read() # type: bytes
62
+ else:
63
+ raise TypeError(f'Unknown filepath type {type(filepath).__name__}')
64
+
65
+
66
+ def _read_edf_from_data(data: bytes, header_dict: dict = None):
67
+ header_dict = header_dict or _read_header_from_data(data)
68
+ try:
69
+ header_end_index = header_dict['headerSize']
70
+ image_size = int(header_dict['Size'])
71
+ raw_image_data = data[header_end_index:header_end_index + image_size] # type: bytes
72
+ data_type = _get_numpy_type(header_dict['DataType'])
73
+ image_shape = (int(header_dict['Dim_2']), int(header_dict['Dim_1']))
74
+ except KeyError as err:
75
+ raise CorruptedFileError(f'Header dict misses key: {err}')
76
+ except IndexError as err:
77
+ raise CorruptedFileError(f'Could not read edf file, header parameters may be wrong: {err}.')
78
+
79
+ data = np.frombuffer(raw_image_data, data_type) # type: np.ndarray
80
+ data = np.rot90(np.reshape(data, image_shape))
81
+ return data, header_dict
82
+
83
+
84
+ def _read_header_from_data(data: bytes) -> dict:
85
+ header_end_index = data.find(b'}\n') + 2 # type: int
86
+ if header_end_index == 1: # data.find did not find b'}\n' symbols and returned -1
87
+ raise CorruptedFileError(f'Could not find edf header.')
88
+ header = data[1:header_end_index].decode('utf-8') # type: str
89
+ try:
90
+ header_dict = _get_header_dict(header) # type: dict
91
+ except Exception as err:
92
+ raise CorruptedFileError(f'Could not read edf header: {err}')
93
+ header_dict['headerSize'] = header_end_index
94
+ return header_dict
95
+
96
+
97
+ def _get_header_dict(header: str) -> dict:
98
+ header_dict = {}
99
+ raw_list = header.replace('\n', '').strip(). \
100
+ replace(' ', ''). \
101
+ replace('{', ''). \
102
+ replace('}', ''). \
103
+ split(';') # type: List[str]
104
+ for item in raw_list:
105
+ items = item.split('=') # type: List[str]
106
+ if len(items) == 2:
107
+ header_dict.update([items])
108
+ return header_dict
109
+
110
+
111
+ _DICT_TYPES = {
112
+ 'SIGNEDBYTE': np.int8, # "b"
113
+ 'UNSIGNEDBYTE': np.uint8, # "B"
114
+ 'SIGNEDSHORT': np.int16, # "h"
115
+ 'UNSIGNEDSHORT': np.uint16, # "H"
116
+ 'SIGNEDINTEGER': np.int32, # "i"
117
+ 'UNSIGNEDINTEGER': np.uint32, # "I"
118
+ 'SIGNEDLONG': np.int32, # "i"
119
+ 'UNSIGNEDLONG': np.uint32, # "I"
120
+ 'SIGNED64': np.int64, # "l"
121
+ 'UNSIGNED64': np.uint64, # "L"
122
+ 'FLOATVALUE': np.float32, # "f"
123
+ 'FLOAT': np.float32, # "f"
124
+ 'DOUBLEVALUE': np.float64
125
+ } # type: Dict[str, type]
126
+
127
+
128
+ def _get_numpy_type(edf_type: str) -> type:
129
+ """
130
+ Returns NumPy type based on edf type.
131
+ """
132
+ try:
133
+ return _DICT_TYPES[edf_type.upper()]
134
+ except KeyError:
135
+ raise CorruptedFileError(f'Unknown edf type {edf_type}.')