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,542 @@
1
+ import logging
2
+ from os.path import splitext
3
+ from pathlib import Path
4
+ from typing import List, Union
5
+ import re
6
+ import weakref
7
+ from abc import abstractmethod
8
+ from copy import deepcopy
9
+ from pathvalidate import sanitize_filename
10
+
11
+ from ..read_image import read_image
12
+
13
+ from h5py import File, Group, Dataset
14
+
15
+ AVAILABLE_IMAGE_FORMATS = tuple('.tif .tiff .edf .edf.gz'.split())
16
+ GLOB_IMAGE_FORMATS = 'edf, tiff, h5 files (*.tiff *.edf *.tif *.edf.gz *.h5 *.hdf5)'
17
+ H5_FORMAT = tuple('.h5 .hdf5'.split())
18
+ CIF_EXTENSIONS = '.cif'
19
+ CIF_FORMAT = 'CIF files (*.cif)'
20
+
21
+ PROJECT_KEY = '__GIWAXS_PROJECT__'
22
+ IMAGE_PROJECT_KEY = '__GIWAXS_IMAGE_GROUP__'
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def _check_project(h5path: Path) -> bool or None:
28
+ try:
29
+ with File(str(h5path.resolve()), 'r') as f:
30
+ if PROJECT_KEY in f.attrs.keys():
31
+ return True
32
+ else:
33
+ return False
34
+ except Exception as err:
35
+ logger.exception(err)
36
+ return
37
+
38
+
39
+ def _file_name(key: str, name: str = ''):
40
+ return f'{key}{"_" if name else ""}{name}.giwaxs'
41
+
42
+ def validate_filename(name: str = '') -> str:
43
+ """
44
+ Remove special characters from filename, such as _,/,|
45
+ """
46
+ #remove extension from filename
47
+ name = splitext(name)[0]
48
+ name = ''.join(e for e in name if e.isalnum())
49
+ return sanitize_filename(name)
50
+
51
+ class InvalidKey(Exception):
52
+ """The corresponding data does not exist or corrupted."""
53
+
54
+
55
+ class AbstractKey(object):
56
+ is_project = False
57
+
58
+ def __init__(self, project_path, parent=None, **kwargs):
59
+ self._parent = weakref.ref(parent) if parent else None
60
+ self.project_path = project_path
61
+
62
+ def file_name(self, name: str = '') -> str:
63
+ return re.sub(r'[^\w\-_\. ]', '_', _file_name(self._file_key(), name))
64
+
65
+ @abstractmethod
66
+ def _file_key(self) -> str:
67
+ pass
68
+
69
+ @property
70
+ def name(self):
71
+ return
72
+
73
+ @property
74
+ def parent(self) -> 'AbstractKey' or None:
75
+ return self._parent() if self._parent else None
76
+
77
+ def remove_parent(self) -> 'AbstractKey' or None:
78
+ parent = self.parent
79
+ self._parent = None
80
+ return parent
81
+
82
+ def set_parent(self, parent: 'AbstractKey'):
83
+ self._parent = weakref.ref(parent)
84
+
85
+ @abstractmethod
86
+ def __eq__(self, other):
87
+ pass
88
+
89
+ @abstractmethod
90
+ def __hash__(self):
91
+ pass
92
+
93
+ @abstractmethod
94
+ def is_valid(self) -> bool:
95
+ pass
96
+
97
+
98
+ class FolderKey(AbstractKey):
99
+ def __init__(self, project_path: Path, parent: 'FolderKey', **kwargs):
100
+ super().__init__(project_path=project_path, parent=parent, **kwargs)
101
+ self._image_children: List[ImageKey] = []
102
+ self._cif_files: List[CIFFileKey] = []
103
+ self._folder_children: List[FolderKey] = []
104
+ self._updated: bool = False
105
+
106
+ def is_updated(self) -> bool:
107
+ return self._updated
108
+
109
+ @property
110
+ def image_children(self):
111
+ yield from self._image_children
112
+
113
+ @property
114
+ def cif_files(self):
115
+ yield from self._cif_files
116
+
117
+ @property
118
+ def folder_children(self):
119
+ yield from self._folder_children
120
+
121
+ @property
122
+ def images_num(self):
123
+ return len(self._image_children)
124
+
125
+ @property
126
+ def folders_num(self):
127
+ return len(self._folder_children)
128
+
129
+ def update(self):
130
+ self.clear()
131
+ self._updated = True
132
+
133
+ def clear(self):
134
+ self._image_children: List[ImageKey] = []
135
+ self._folder_children: List[FolderKey] = []
136
+
137
+ def detach_subfolders(self) -> List['FolderKey']:
138
+ subfolders, self._folder_children = self._folder_children, []
139
+ return subfolders
140
+
141
+ def attach_subfolders(self, subfolders):
142
+ self._folder_children = subfolders
143
+
144
+ def clean_copy(self):
145
+ with RemoveWeakrefs(self, restore=True, remove_subfolders=True):
146
+ return deepcopy(self)
147
+
148
+ def image_idx(self, key: 'ImageKey'):
149
+ try:
150
+ return self._image_children.index(key)
151
+ except ValueError:
152
+ return
153
+
154
+ def cif_idx(self, key: 'CIFFileKey'):
155
+ try:
156
+ return self._cif_files.index(key)
157
+ except ValueError:
158
+ return
159
+
160
+ def image_by_key(self, idx: int):
161
+ try:
162
+ return self._image_children[idx]
163
+ except IndexError:
164
+ return
165
+
166
+ def get_next_image(self, key: 'ImageKey') -> 'ImageKey' or None:
167
+ if not self._image_children:
168
+ return
169
+ idx = key.idx
170
+ if idx is None:
171
+ idx = key.idx = self.image_idx(key)
172
+ if idx is None:
173
+ return
174
+ if idx + 1 < len(self._image_children):
175
+ return self._image_children[idx + 1]
176
+
177
+ def remove_image(self, key: 'ImageKey'):
178
+ idx = self.image_idx(key)
179
+ if idx is None:
180
+ return
181
+ self._image_children.remove(key)
182
+ for i in range(idx, len(self._image_children)):
183
+ self._image_children[i].idx = i
184
+
185
+ def remove_cif(self, key: 'CIFFileKey'):
186
+ idx = self.cif_idx(key)
187
+ if idx is None:
188
+ return
189
+ self._cif_files.remove(key)
190
+ for i in range(idx, len(self._cif_files)):
191
+ self._cif_files[i].idx = i
192
+
193
+ def __contains__(self, item):
194
+ if not (isinstance(item, AbstractKey)):
195
+ return False
196
+ if item == self:
197
+ return True
198
+ for image in self.image_children:
199
+ if image == item:
200
+ return True
201
+ return any((item in folder for folder in self.folder_children))
202
+
203
+
204
+ class ImageKey(AbstractKey):
205
+ def __init__(self, project_path: Path, parent=None, idx: int = None, **kwargs):
206
+ super().__init__(project_path=project_path, parent=parent, **kwargs)
207
+ self.idx = idx
208
+ self.qxy: float = 2.7
209
+ self.qz: float = 2.7
210
+
211
+ def set_qxy(self, qxy):
212
+ self.qxy = qxy
213
+
214
+ def set_qz(self, qz):
215
+ self.qz = qz
216
+
217
+ def get_q_range(self):
218
+ return [self.qxy,self.qz]
219
+
220
+ @abstractmethod
221
+ def get_image(self):
222
+ pass
223
+
224
+ def clean_copy(self):
225
+ with RemoveWeakrefs(self, restore=True):
226
+ return deepcopy(self)
227
+
228
+ def __contains__(self, item):
229
+ if self == item:
230
+ return True
231
+ return False
232
+
233
+
234
+ class PathKey(AbstractKey):
235
+ def __init__(self, project_path: Path, parent, *, path: Path, **kwargs):
236
+ self._path = path
237
+ super().__init__(project_path, parent, **kwargs)
238
+
239
+ @property
240
+ def path(self):
241
+ return self._path
242
+
243
+ @property
244
+ def name(self):
245
+ return validate_filename(self._path.name)
246
+
247
+ def _file_key(self) -> str:
248
+ full_path = self._path.resolve()
249
+ try:
250
+ return full_path.relative_to(self.project_path)
251
+ except:
252
+ return ''
253
+
254
+ def __eq__(self, other):
255
+ if isinstance(other, self.__class__):
256
+ return self._path == other._path
257
+ else:
258
+ return False
259
+
260
+ def __hash__(self):
261
+ return hash(self._path)
262
+
263
+ def __repr__(self):
264
+ return self.name
265
+
266
+
267
+ class CIFFileKey(PathKey):
268
+ def __init__(self, project_path: Path, parent: FolderKey, *, path: Path,
269
+ duplicate_num = 0, idx: int = None):
270
+
271
+ super().__init__(project_path, parent, path=path, idx=idx)
272
+ self._is_visible = True
273
+ self.powder_diffraction = False
274
+ self.orientation = [0,0,1]
275
+ self.en = 18000
276
+ #duplicates are needed to have one cif-file with multiple contact planes
277
+ self.duplicate_num = duplicate_num
278
+
279
+ def change_powder_diffraction(self):
280
+ self.powder_diffraction = not self.powder_diffraction
281
+ return self.powder_diffraction
282
+
283
+ def change_show_hide(self):
284
+ self._is_visible = not self._is_visible
285
+ return self._is_visible
286
+
287
+ @property
288
+ def name(self):
289
+ if self.duplicate_num == 0:
290
+ return validate_filename(self._path.name)
291
+ else:
292
+ return validate_filename(self._path.name) + str(self.duplicate_num)
293
+
294
+ def is_visible(self):
295
+ return self._is_visible
296
+
297
+ def get_cif_path(self):
298
+ try:
299
+ return self._path
300
+ except Exception as err:
301
+ logger.exception(err)
302
+ return
303
+
304
+ def is_valid(self) -> bool:
305
+ return self._path.is_file()
306
+
307
+ def clean_copy(self):
308
+ with RemoveWeakrefs(self, restore=True):
309
+ return deepcopy(self)
310
+
311
+ def __contains__(self, item):
312
+ if self == item:
313
+ return True
314
+ return False
315
+
316
+
317
+ class H5Key(AbstractKey):
318
+ def __init__(self, project_path: Path, parent, *, h5path: Path, h5key: str = '', is_project: bool = None, **kwargs):
319
+ super().__init__(project_path, parent, **kwargs)
320
+ self._h5path: Path = h5path
321
+ self._h5key: str = h5key
322
+ self._is_project = is_project
323
+ if self._is_project is None:
324
+ self._is_project = _check_project(h5path)
325
+
326
+ @property
327
+ def h5path(self):
328
+ return self._h5path
329
+
330
+ @property
331
+ def h5key(self):
332
+ return self._h5key
333
+
334
+ @property
335
+ def is_project(self):
336
+ return self._is_project
337
+
338
+ @property
339
+ def name(self):
340
+ return self._h5key.split('/')[-1] if self._h5key else self._h5path.name
341
+
342
+ def _file_key(self) -> str:
343
+ return '-'.join((str(self._h5path.resolve()), self._h5key))
344
+
345
+ def __eq__(self, other):
346
+ if isinstance(other, self.__class__):
347
+ return (self._h5path == other._h5path and
348
+ self._h5key == other._h5key)
349
+ else:
350
+ return False
351
+
352
+ def __hash__(self):
353
+ return hash((self._h5path, self._h5key))
354
+
355
+ def __repr__(self):
356
+ return self.name
357
+
358
+
359
+ class FolderH5Key(FolderKey, H5Key):
360
+ def __init__(self, project_path: Path, parent: FolderKey, *, h5path: Path,
361
+ h5key: str = '', is_project: bool = None):
362
+ super().__init__(project_path, parent, h5path=h5path, h5key=h5key, is_project=is_project)
363
+
364
+ def update(self):
365
+ super().update()
366
+ try:
367
+ with File(str(self._h5path.resolve()), 'r') as f:
368
+ if self._h5key:
369
+ f = f[self._h5key]
370
+ for key in sorted(list(f.keys())):
371
+ item = f[key]
372
+ if isinstance(item, Group):
373
+ if self.is_project and IMAGE_PROJECT_KEY in item.attrs.keys():
374
+ self._image_children.append(
375
+ ImageH5Key(project_path=self.project_path, parent=self, h5path=self._h5path,
376
+ h5key='/'.join((self._h5key, key)), is_project=True, idx=len(self._image_children)))
377
+ else:
378
+ self._folder_children.append(
379
+ FolderH5Key(project_path=self.project_path, parent=self, h5path=self._h5path,
380
+ h5key='/'.join((self._h5key, key)),
381
+ is_project=self.is_project))
382
+ elif isinstance(item, Dataset) and len(item.shape) == 2:
383
+ self._image_children.append(
384
+ ImageH5Key(project_path=self.project_path, parent=self, h5path=self._h5path,
385
+ h5key='/'.join((self._h5key, key)),
386
+ is_project=False, idx=len(self._image_children)))
387
+ except Exception as err:
388
+ raise InvalidKey(err)
389
+
390
+ def is_valid(self) -> bool:
391
+ try:
392
+ with File(str(self._h5path.resolve()), 'r') as f:
393
+ if self._h5key:
394
+ f = f[self._h5key]
395
+ if isinstance(f, Group):
396
+ return True
397
+ else:
398
+ return False
399
+ except (FileNotFoundError, KeyError, IOError):
400
+ return False
401
+ except Exception as err:
402
+ logger.exception(err)
403
+ return False
404
+
405
+ class FolderPathKey(FolderKey, PathKey):
406
+ def __init__(self, project_path: Path, parent: FolderKey, *, path: Path):
407
+ super().__init__(project_path, parent, path=path)
408
+
409
+ def update(self):
410
+ super().update()
411
+ try:
412
+ for p in sorted(list(self._path.iterdir())):
413
+ if p.is_dir():
414
+ self._folder_children.append(FolderPathKey(self.project_path, self, path=p))
415
+ elif p.suffix in H5_FORMAT:
416
+ self._folder_children.append(FolderH5Key(self.project_path, self, h5path=p))
417
+ elif p.suffix in AVAILABLE_IMAGE_FORMATS:
418
+ self._image_children.append(ImagePathKey(self.project_path, self, path=p, idx=len(self._image_children)))
419
+ except Exception as err:
420
+ raise InvalidKey(err)
421
+
422
+ def is_valid(self) -> bool:
423
+ return self._path.is_dir()
424
+
425
+
426
+ class ImagePathKey(ImageKey, PathKey):
427
+ def __init__(self, project_path: Path, parent: FolderKey, *, path: Path,
428
+ idx: int = None):
429
+ super().__init__(project_path, parent, path=path, idx=idx)
430
+
431
+ def get_image(self):
432
+ try:
433
+ return read_image(self._path)
434
+ except Exception as err:
435
+ logger.exception(err)
436
+ return
437
+
438
+ def is_valid(self) -> bool:
439
+ return self._path.is_file()
440
+
441
+
442
+ class ImageH5Key(ImageKey, H5Key):
443
+ def __init__(self, project_path: Path, parent: FolderKey, *,
444
+ h5path: Path, h5key: str, is_project: bool = False, idx: int = None):
445
+ super().__init__(project_path,
446
+ parent, h5path=h5path, h5key=h5key, is_project=is_project, idx=idx)
447
+
448
+ def get_image(self):
449
+ try:
450
+ with File(str(self._h5path.resolve()), 'r') as f:
451
+ image = f[self._h5key]
452
+ if self.is_project:
453
+ return image['image'][()]
454
+ elif len(image.shape) == 2:
455
+ return image[()]
456
+ except Exception as err:
457
+ logger.exception(err)
458
+ return
459
+
460
+ def is_valid(self) -> bool:
461
+ try:
462
+ with File(str(self._h5path.resolve()), 'r') as f:
463
+ dset = f[self._h5key]
464
+ if not self.is_project and isinstance(dset, Dataset) and len(dset.shape) == 2:
465
+ return True
466
+ elif self.is_project and isinstance(dset, Group):
467
+ return True
468
+ return False
469
+ except (FileNotFoundError, KeyError, IOError):
470
+ return False
471
+ except Exception as err:
472
+ logger.exception(err)
473
+ return False
474
+
475
+
476
+ class RemoveWeakrefs(object):
477
+ def __init__(self, key: Union[FolderKey, ImageKey], *,
478
+ remove_subfolders: bool = False,
479
+ restore: bool = True):
480
+ self.__key = key
481
+ self.__parent = None
482
+ self.__remove_subfolders: bool = remove_subfolders
483
+ self.__restore: bool = restore
484
+ self.__subfolders: List[FolderKey] = []
485
+
486
+ def __enter__(self):
487
+ if self.__remove_subfolders:
488
+ try:
489
+ self.__subfolders = self.__key.detach_subfolders()
490
+ except AttributeError:
491
+ self.__remove_subfolders = False
492
+ self.__parent = self.remove(self.__key)
493
+ return self.__key
494
+
495
+ def __exit__(self, exc_type, exc_val, exc_tb):
496
+ if self.__restore:
497
+ self.restore(self.__key, self.__parent)
498
+
499
+ if self.__remove_subfolders:
500
+ self.__key.attach_subfolders(self.__subfolders)
501
+ self.__subfolders = []
502
+ self.__parent = None
503
+
504
+ @staticmethod
505
+ def restore(key: Union[FolderKey, ImageKey], parent: FolderKey = None) -> None:
506
+ if parent:
507
+ key.set_parent(parent)
508
+ if isinstance(key, FolderKey):
509
+ _restore_parents(key, parent)
510
+
511
+ @staticmethod
512
+ def remove(key: Union[FolderKey, ImageKey]) -> FolderKey or None:
513
+ if isinstance(key, FolderKey):
514
+ _remove_parents(key)
515
+ return key.remove_parent()
516
+
517
+
518
+ def _remove_parents(key: FolderKey):
519
+ for cif_key in key._cif_files:
520
+ cif_key.remove_parent()
521
+
522
+ for image_key in key.image_children:
523
+ image_key.remove_parent()
524
+
525
+ for folder_key in key.folder_children:
526
+ folder_key.remove_parent()
527
+ _remove_parents(folder_key)
528
+
529
+
530
+ def _restore_parents(key: FolderKey, parent: FolderKey = None):
531
+ if parent:
532
+ key.set_parent(parent)
533
+
534
+ for cif_key in key._cif_files:
535
+ cif_key.set_parent(key)
536
+
537
+ for image_key in key.image_children:
538
+ image_key.set_parent(key)
539
+
540
+ for folder_key in key.folder_children:
541
+ folder_key.set_parent(folder_key)
542
+ _restore_parents(folder_key)
@@ -0,0 +1,17 @@
1
+ from pathlib import Path
2
+
3
+ import numpy as np
4
+
5
+ from .object_file_manager import _ObjectFileManager
6
+
7
+
8
+ class _ReadNpy(_ObjectFileManager):
9
+ @staticmethod
10
+ def _set_pickle(path: Path, value):
11
+ np.save(str(path.resolve()) + '.npy', value)
12
+
13
+ @staticmethod
14
+ def _get_pickle(path: Path):
15
+ if path.is_file():
16
+ return np.load(str(path.resolve()) + '.npy', allow_pickle=True)
17
+
@@ -0,0 +1,77 @@
1
+ import logging
2
+ import pickle
3
+ from pathlib import Path
4
+
5
+ from h5py import Group, File
6
+
7
+ from ..utils import InternalError
8
+ from .keys import ImageKey, AbstractKey, ImageH5Key
9
+ from .project_structure import ProjectStructure
10
+
11
+
12
+ def _check_empty_project(func):
13
+ def wrapper(self, *args, **kwargs):
14
+ if self.project_structure.project_opened:
15
+ return func(*args, **kwargs)
16
+ else:
17
+ return
18
+
19
+ return wrapper
20
+
21
+
22
+ class _ObjectFileManager(object):
23
+ log = logging.getLogger(__name__)
24
+
25
+ NAME = ''
26
+
27
+ def __init__(self, project_structure: ProjectStructure):
28
+ self.project_structure = project_structure
29
+ self.folder: Path = None
30
+ self.init()
31
+
32
+ def init(self):
33
+ path = self.project_structure.path
34
+
35
+ if path:
36
+ self.folder: Path = path / self.NAME
37
+ self.folder.mkdir(parents=True, exist_ok=True)
38
+
39
+ def _get_path(self, key: AbstractKey) -> Path:
40
+ return self.folder / key.file_name()
41
+
42
+ @staticmethod
43
+ def _set_pickle(path: Path, value):
44
+ with open(str(path.resolve()), 'wb') as f:
45
+ pickle.dump(value, f)
46
+
47
+ @staticmethod
48
+ def _get_pickle(path: Path):
49
+ if path.is_file():
50
+ with open(str(path.resolve()), 'rb') as f:
51
+ return pickle.load(f)
52
+
53
+ @staticmethod
54
+ def _del_pickle(path: Path):
55
+ if path.is_file():
56
+ path.unlink()
57
+
58
+ @staticmethod
59
+ def get_h5(h5group: Group, key: ImageKey):
60
+ pass
61
+
62
+ @staticmethod
63
+ def set_h5(h5group: Group, key: ImageKey, *args, **kwargs):
64
+ pass
65
+
66
+ @staticmethod
67
+ def del_h5(h5group: Group, key: ImageKey):
68
+ pass
69
+
70
+ def __getitem__(self, key):
71
+ return self._get_pickle(self._get_path(key))
72
+
73
+ def __delitem__(self, key):
74
+ return self._del_pickle(self._get_path(key))
75
+
76
+ def __setitem__(self, key, value):
77
+ return self._set_pickle(self._get_path(key), value)