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,169 @@
1
+ import pickle
2
+ from dataclasses import dataclass
3
+ from collections import defaultdict
4
+ import logging
5
+ from pathlib import Path
6
+ from os import listdir
7
+
8
+ from .keys import (AbstractKey, FolderKey, FolderH5Key, FolderPathKey,
9
+ ImageKey, ImagePathKey, H5_FORMAT, RemoveWeakrefs, CIFFileKey,
10
+ AVAILABLE_IMAGE_FORMATS, CIF_EXTENSIONS)
11
+
12
+
13
+ class ProjectRootKey(FolderKey):
14
+ def __init__(self, *, project_path: Path = None, h5source_path: Path = None):
15
+ super().__init__(project_path= project_path, path=project_path, parent=None)
16
+ self.path: Path = project_path
17
+ self.h5_path: Path = h5source_path
18
+
19
+ self._valid = True
20
+
21
+ if self.h5_path:
22
+ self._project_name = self.h5_path.name
23
+ elif self.path:
24
+ self._project_name = self.path.name
25
+ else:
26
+ self._project_name = 'EMPTY PROJECT'
27
+ self._valid = False
28
+
29
+ self.update()
30
+
31
+ def is_valid(self) -> bool:
32
+ return self._valid
33
+
34
+ def __eq__(self, other):
35
+ if isinstance(other, ProjectRootKey):
36
+ return self.h5_path == other.h5_path and self.path == other.path
37
+
38
+ def __hash__(self):
39
+ if self.h5_path is not None:
40
+ return hash(self.h5_path)
41
+ if self.path is not None:
42
+ return hash(self.path)
43
+
44
+ def _file_key(self) -> str:
45
+ return self.name
46
+
47
+ @property
48
+ def name(self):
49
+ return self._project_name
50
+
51
+ @property
52
+ def parent(self):
53
+ return
54
+
55
+ def add_path(self, path: Path):
56
+ if path.is_dir():
57
+ folder_key = FolderPathKey(project_path = self.path, parent = self, path=path)
58
+ for f in self._folder_children:
59
+ if folder_key.path == f.path:
60
+ return f, False
61
+ self._folder_children.append(folder_key)
62
+ for image in listdir(folder_key.path):
63
+ if (image.endswith(AVAILABLE_IMAGE_FORMATS)):
64
+ image_key = ImagePathKey(project_path=self.path, parent=folder_key, path=Path(image))
65
+ folder_key._image_children.append(image_key)
66
+ return folder_key, True
67
+ elif path.is_file() and path.suffix in AVAILABLE_IMAGE_FORMATS:
68
+ key = ImagePathKey(project_path = self.path, parent = self, path=path)
69
+ for c in self._image_children:
70
+ if key.path == c.path:
71
+ return c, False
72
+ self._image_children.append(key)
73
+ return key, True
74
+ elif path.is_file() and path.suffix in CIF_EXTENSIONS:
75
+ key = CIFFileKey(project_path = self.path, parent = self, path=path)
76
+ for c in self._cif_files:
77
+ if key.path == c.path:
78
+ key = CIFFileKey(project_path=self.path, parent=self, path=path, duplicate_num=c.duplicate_num + 1)
79
+ self._cif_files.append(key)
80
+ return key, True
81
+ elif path.is_file() and path.suffix in H5_FORMAT:
82
+ key = FolderH5Key(project_path = self.path, parent =self, h5path=path)
83
+ self._folder_children.append(key)
84
+ return key, True
85
+
86
+ def remove_key(self, key: AbstractKey):
87
+ if isinstance(key, FolderKey):
88
+ try:
89
+ self._folder_children.remove(key)
90
+ except ValueError:
91
+ return
92
+ elif isinstance(key, ImageKey):
93
+ try:
94
+ self._image_children.remove(key)
95
+ except ValueError:
96
+ return
97
+ elif isinstance(key, CIFFileKey):
98
+ try:
99
+ self._cif_files.remove(key)
100
+ except ValueError:
101
+ return
102
+
103
+ def expand_tree(self, folder_key: FolderKey = None):
104
+ folder_key = folder_key or self
105
+
106
+ for child_folder in folder_key.folder_children:
107
+ child_folder.update()
108
+ self.expand_tree(child_folder)
109
+
110
+
111
+ @dataclass
112
+ class H5ProjectConfig:
113
+ save_to_h5: bool = False
114
+
115
+
116
+ class ProjectStructure(object):
117
+ log = logging.getLogger(__name__)
118
+
119
+ def __init__(self):
120
+ self._root: ProjectRootKey or None = None
121
+ self.config = defaultdict(lambda: False)
122
+ self.path: Path or None = None
123
+
124
+ @property
125
+ def project_opened(self):
126
+ return self._root is not None
127
+
128
+ @property
129
+ def root(self) -> ProjectRootKey or None:
130
+ return self._root
131
+
132
+ def save(self, restore: bool = True):
133
+ if self.path and self.root and self.path.is_dir():
134
+ with RemoveWeakrefs(self.root, restore=restore):
135
+ with open(str(self.path.resolve() / 'project_structure'), 'wb') as f:
136
+ pickle.dump(self.root, f)
137
+
138
+ def open_project(self, path: Path):
139
+ self.close_project()
140
+
141
+ self.path = path
142
+
143
+ if self.path.is_file():
144
+ raise ValueError(f'Project path is a file: {self.path.resolve()}')
145
+
146
+ self.path.mkdir(exist_ok=True, parents=True)
147
+
148
+ pickle_file = self.path / 'project_structure'
149
+
150
+ if pickle_file.is_file():
151
+ try:
152
+ with open(str(pickle_file.resolve()), 'rb') as f:
153
+ self._root = pickle.load(f)
154
+ RemoveWeakrefs.restore(self._root)
155
+ except Exception as err:
156
+ pickle_file.unlink()
157
+ self.log.exception(err)
158
+
159
+ if not self._root:
160
+ self._root = ProjectRootKey(project_path=self.path)
161
+
162
+ def save_and_close(self):
163
+ self.save(False)
164
+ self.close_project()
165
+
166
+ def close_project(self):
167
+ self._root = None
168
+ self.path = None
169
+ self.config = defaultdict(lambda: False)
@@ -0,0 +1,76 @@
1
+ from datetime import datetime as dt
2
+ from pathlib import Path
3
+
4
+ from .object_file_manager import _ObjectFileManager
5
+ from .keys import RemoveWeakrefs
6
+
7
+ class _ReadFits(_ObjectFileManager):
8
+ NAME = 'fits'
9
+
10
+ def init(self):
11
+ path = self.project_structure.path
12
+
13
+ if path:
14
+ self.folder: Path = path / self.NAME
15
+
16
+ def _get_path(self, fit_key: tuple):
17
+ key, name = fit_key
18
+ return self.folder / key.file_name(name)
19
+
20
+ def __getitem__(self, item):
21
+ key, name = item
22
+ # if not key.is_project:
23
+ # return self._get_pickle(self._get_path(key))
24
+ # if self.project_structure.config[key.h5path]:
25
+ # return self._process_h5_group(key.h5path, key.h5key, self._get_h5, key)
26
+ return self._get_pickle(self._get_path(item))
27
+ # if res is not None:
28
+ # return res
29
+ # return self._process_h5_group(key.h5path, key.h5key, self._get_h5, key)
30
+
31
+ def __delitem__(self, item):
32
+ key, name = item
33
+ # if not key.is_project:
34
+ # return self._del_pickle(self._get_path(key))
35
+ # if self.project_structure.config[key.h5path]:
36
+ # return self._process_h5_group(key.h5path, key.h5key, self._del_h5, key)
37
+ # else:
38
+ return self._del_pickle(self._get_path(item))
39
+
40
+ def __setitem__(self, item, value):
41
+ # key, name = item
42
+ # if key.is_project and self.project_structure.config[key.h5path]:
43
+ # return self._process_h5_group(key.h5path, key.h5key, self._set_h5, key, value)
44
+ # else:
45
+ try:
46
+ return self._set_pickle(self._get_path(item), value)
47
+ except Exception as err:
48
+ self.log.exception(err)
49
+ return
50
+
51
+ def get_multi_fit(self):
52
+ return MultiFitFileManager(self.project_structure)
53
+
54
+
55
+ class MultiFitFileManager(_ObjectFileManager):
56
+ NAME = 'fits'
57
+
58
+ def __init__(self, project_structure):
59
+ super().__init__(project_structure)
60
+ self.folder: Path = self.folder / dt.now().strftime('multi fit %d %m %y - %H %M %S')
61
+ self.folder.mkdir()
62
+
63
+ def __getitem__(self, item):
64
+ fit_object = super().__getitem__(item)
65
+ if fit_object:
66
+ fit_object.image_key = item
67
+ return fit_object
68
+
69
+ def __setitem__(self, key, value):
70
+ with RemoveWeakrefs(value.image_key):
71
+ super().__setitem__(key, value)
72
+
73
+ def delete(self):
74
+ for path in self.folder.iterdir():
75
+ path.unlink()
76
+ self.folder.rmdir()
@@ -0,0 +1,54 @@
1
+ from h5py import Group
2
+
3
+ from .object_file_manager import _ObjectFileManager
4
+ from .keys import FolderKey
5
+ from ..geometry import Geometry
6
+
7
+
8
+ class _DefaultGeometry(_ObjectFileManager):
9
+ NAME = 'geometries'
10
+
11
+ def _get_path(self, key: FolderKey):
12
+ if key is not None:
13
+ if key.parent:
14
+ return self.folder / f'default_geometry_{key.parent.name}'
15
+ else:
16
+ return self.folder / f'default_geometry_{key.name}'
17
+ else:
18
+ return self.folder / f'default_geometry'
19
+
20
+ @staticmethod
21
+ def get_h5(h5group: Group, key: FolderKey):
22
+ return Geometry.fromdict(dict(h5group.attrs))
23
+
24
+ @staticmethod
25
+ def set_h5(h5group: Group, key: FolderKey, value: Geometry):
26
+ h5group.attrs.update(value.to_dict())
27
+
28
+ @staticmethod
29
+ def del_h5(h5group: Group, key: FolderKey):
30
+ for key in Geometry.keys():
31
+ if key in h5group.parent.attrs.keys():
32
+ del h5group.attrs[key]
33
+
34
+
35
+ class _ReadGeometry(_ObjectFileManager):
36
+ NAME = 'geometries'
37
+
38
+ def __init__(self, *args, **kwargs):
39
+ super().__init__(*args, **kwargs)
40
+ self.default = _DefaultGeometry(*args, **kwargs)
41
+
42
+ @staticmethod
43
+ def get_h5(h5group: Group, key):
44
+ return Geometry.fromdict(dict(h5group.attrs))
45
+
46
+ @staticmethod
47
+ def set_h5(h5group: Group, key, value: Geometry):
48
+ h5group.attrs.update(value.to_dict())
49
+
50
+ @staticmethod
51
+ def del_h5(h5group: Group, key):
52
+ for key in Geometry.keys():
53
+ if key in h5group.attrs.keys():
54
+ del h5group.attrs[key]
@@ -0,0 +1,31 @@
1
+ from h5py import Group
2
+ from .npy_file_manager import _ReadNpy
3
+ from pathlib import Path
4
+
5
+ class _ReadImage(_ReadNpy):
6
+ NAME = 'images'
7
+
8
+ def init(self):
9
+ path = self.project_structure.path
10
+
11
+ if path:
12
+ self.folder: Path = path / self.NAME
13
+ @staticmethod
14
+ def get_h5(h5group: Group, key):
15
+ pass
16
+
17
+ @staticmethod
18
+ def set_h5(h5group: Group, key, image):
19
+ _ReadImage.del_h5(h5group, key)
20
+ h5group.create_dataset('image', data=image)
21
+
22
+ @staticmethod
23
+ def del_h5(h5group: Group, key):
24
+ if 'image' in h5group.keys():
25
+ del h5group['image']
26
+
27
+ def __getitem__(self, key):
28
+ internal_path = self._get_path(key)
29
+ if internal_path.is_file():
30
+ return self._get_pickle(internal_path)
31
+ return key.get_image()
@@ -0,0 +1,40 @@
1
+ from h5py import Group
2
+ from pathlib import Path
3
+ from .object_file_manager import _ObjectFileManager
4
+ from .keys import RemoveWeakrefs, FolderKey
5
+
6
+
7
+ class ImportManager(object):
8
+ _class = None
9
+
10
+ @classmethod
11
+ def RoiMetaData(cls):
12
+ if not cls._class:
13
+ from ..rois import RoiMetaData
14
+ cls._class = RoiMetaData
15
+ return cls._class
16
+
17
+ class _ReadMetaData(_ObjectFileManager):
18
+ NAME = 'rois_meta_data'
19
+
20
+ def __getitem__(self, item: FolderKey):
21
+ roi_meta_data = super().__getitem__(item)
22
+ if roi_meta_data:
23
+ roi_meta_data.folder_key = item.clean_copy()
24
+ return roi_meta_data
25
+
26
+ def __setitem__(self, key: FolderKey, value):
27
+ with RemoveWeakrefs(value.folder_key):
28
+ super().__setitem__(key, value)
29
+
30
+ @staticmethod
31
+ def get_h5(h5group: Group, key: FolderKey):
32
+ return ImportManager.RoiMetaData().from_h5(key, h5group)
33
+
34
+ @staticmethod
35
+ def set_h5(h5group: Group, key: FolderKey, value: 'RoiMetaData'):
36
+ value.to_h5(h5group)
37
+
38
+ @staticmethod
39
+ def del_h5(h5group: Group, key):
40
+ ImportManager.RoiMetaData().del_h5(h5group)
@@ -0,0 +1,22 @@
1
+ from h5py import Group
2
+ from pathlib import Path
3
+ from .npy_file_manager import _ReadNpy
4
+
5
+
6
+ class _ReadPolarImage(_ReadNpy):
7
+ NAME = 'polar_images'
8
+
9
+ @staticmethod
10
+ def get_h5(h5group: Group, key):
11
+ if 'polar_image' in h5group.keys():
12
+ return h5group['polar_image'][()]
13
+
14
+ @staticmethod
15
+ def set_h5(h5group: Group, key, image):
16
+ _ReadPolarImage.del_h5(h5group, key)
17
+ h5group.create_dataset('polar_image', data=image)
18
+
19
+ @staticmethod
20
+ def del_h5(h5group: Group, key):
21
+ if 'polar_image' in h5group.keys():
22
+ del h5group['polar_image']
@@ -0,0 +1,6 @@
1
+ from .object_file_manager import _ObjectFileManager
2
+ from pathlib import Path
3
+
4
+
5
+ class _ReadRadialProfile(_ObjectFileManager):
6
+ NAME = 'radial_profiles'
@@ -0,0 +1,39 @@
1
+ import logging
2
+
3
+ from h5py import Group
4
+
5
+ from .object_file_manager import _ObjectFileManager
6
+ from ..rois.roi_data import RoiData
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class _ReadRoiData(_ObjectFileManager):
12
+ NAME = 'roi_data'
13
+
14
+ @staticmethod
15
+ def get_h5(h5group: Group, key):
16
+ if 'roi_data' in h5group.keys():
17
+ roi_dict = {
18
+ k: v[()] for k, v in h5group['roi_data'].items()
19
+ }
20
+ roi_data = RoiData.from_dict(roi_dict)
21
+ return roi_data
22
+
23
+ @staticmethod
24
+ def set_h5(h5group: Group, key, value: RoiData):
25
+ if 'roi_data' in h5group.keys():
26
+ del h5group['roi_data']
27
+
28
+ rois_dict = value.to_dict()
29
+ roi_group = h5group.create_group('roi_data')
30
+ for key, arr in rois_dict.items():
31
+ try:
32
+ roi_group.create_dataset(key, data=arr)
33
+ except Exception as err:
34
+ logger.exception(err)
35
+
36
+ @staticmethod
37
+ def del_h5(h5group: Group, key):
38
+ if 'roi_data' in h5group.keys():
39
+ del h5group['roi_data']
@@ -0,0 +1,5 @@
1
+ from .functions import FittingType, FITTING_FUNCTIONS
2
+ from .background import BackgroundType
3
+ from .fit import Fit
4
+ from .fit_object import FitObject
5
+ from .range_strategy import RangeStrategy, RangeStrategyType
@@ -0,0 +1,92 @@
1
+ from enum import Enum
2
+ from abc import abstractmethod
3
+ from typing import Dict
4
+
5
+ import numpy as np
6
+
7
+ from .utils import Roi
8
+
9
+ __all__ = [
10
+ 'BackgroundType',
11
+ 'BACKGROUNDS',
12
+ 'Background',
13
+ 'LinearBackground',
14
+ 'ConstantBackground',
15
+ ]
16
+
17
+
18
+ class BackgroundType(Enum):
19
+ constant = 'Constant'
20
+ linear = 'Linear'
21
+
22
+
23
+ class Background(object):
24
+ PARAM_NAMES: tuple = ()
25
+ NUM: int = 0
26
+ TYPE: BackgroundType = None
27
+
28
+ is_default: bool = True
29
+
30
+ AMP_PADDING: float = 1.
31
+
32
+ @staticmethod
33
+ @abstractmethod
34
+ def _bounds(x: np.ndarray, y: np.ndarray) -> tuple:
35
+ pass
36
+
37
+ def bounds(self, x: np.ndarray, y: np.ndarray, roi: Roi = None):
38
+ return self._bounds(x, y)
39
+
40
+ @abstractmethod
41
+ def __call__(self, x: np.ndarray, *params) -> np.ndarray:
42
+ pass
43
+
44
+ @abstractmethod
45
+ def amp_bounds(self, x: np.ndarray, y: np.ndarray, params: list) -> tuple:
46
+ pass
47
+
48
+
49
+ class ConstantBackground(Background):
50
+ PARAM_NAMES = ('constant background',)
51
+ NUM = 1
52
+ TYPE = BackgroundType.constant
53
+
54
+ @staticmethod
55
+ def _bounds(x: np.ndarray, y: np.ndarray) -> tuple:
56
+ min_y = np.nanmin(y.min)
57
+
58
+ return [min_y], [np.nanmax(y)], [min(0, min_y)]
59
+
60
+ def __call__(self, x: np.ndarray, *params) -> np.ndarray:
61
+ return params[-1] * np.ones_like(x)
62
+
63
+ def amp_bounds(self, x: np.ndarray, y: np.ndarray, params: list) -> tuple:
64
+ amp = np.nanmax(y) * self.AMP_PADDING - params[0]
65
+ return amp, max(np.nanmax(y), amp * 2), min(amp, 0)
66
+
67
+
68
+ class LinearBackground(Background):
69
+ PARAM_NAMES = ('background (slope)', 'background (level)')
70
+ NUM = 2
71
+ TYPE = BackgroundType.linear
72
+
73
+ @staticmethod
74
+ def _bounds(x: np.ndarray, y: np.ndarray) -> tuple:
75
+ dx = (x[-1] - x[0]) or 1
76
+ b1 = (y[-1] - y[0]) / dx
77
+ b2 = y[0] - x[0] * b1
78
+
79
+ return [b1, b2], [b1 + abs(b1) / 2, b2 + abs(b2) / 2], [b1 - abs(b1) / 2, b2 - abs(b2) / 2]
80
+
81
+ def __call__(self, x: np.ndarray, *params) -> np.ndarray:
82
+ return params[-2] * x + params[-1]
83
+
84
+ def amp_bounds(self, x: np.ndarray, y: np.ndarray, params: list) -> tuple:
85
+ amp = np.nanmax(y) * self.AMP_PADDING - (y[0] + y[-1]) / 2
86
+ return amp, max(np.nanmax(y), amp * 2), min(amp, 0)
87
+
88
+
89
+ BACKGROUNDS: Dict[BackgroundType, Background.__class__] = {
90
+ BackgroundType.constant: ConstantBackground,
91
+ BackgroundType.linear: LinearBackground,
92
+ }
@@ -0,0 +1,128 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Tuple
5
+ import logging
6
+
7
+ import numpy as np
8
+ from scipy.optimize import curve_fit
9
+
10
+ from .functions import FittingFunction
11
+ from .background import Background
12
+ from .utils import Roi
13
+ from .range_strategy import RangeStrategy
14
+
15
+
16
+ @dataclass
17
+ class Fit:
18
+ roi: Roi
19
+
20
+ r_range: Tuple[float, float]
21
+ x_range: Tuple[int, int]
22
+ x: np.ndarray
23
+ y: np.ndarray
24
+
25
+ init_curve: np.ndarray
26
+ init_params: list
27
+ lower_bounds: list
28
+ upper_bounds: list
29
+
30
+ fitted_params: list
31
+ fit_errors: list
32
+ fitting_curve: np.ndarray
33
+ background_curve: np.ndarray
34
+
35
+ fitting_function: FittingFunction
36
+ background: Background
37
+ range_strategy: RangeStrategy
38
+ sigma: float = None
39
+ x_profile: np.ndarray = None
40
+ y_profile: np.ndarray = None
41
+
42
+ @property
43
+ def param_names(self):
44
+ return [*self.fitting_function.PARAM_NAMES, *self.background.PARAM_NAMES]
45
+
46
+ @property
47
+ def bounds(self):
48
+ return tuple(self.lower_bounds), tuple(self.upper_bounds)
49
+
50
+ def update(self, **params):
51
+ for k, v in params.items():
52
+ setattr(self, k, v)
53
+
54
+ def update_fit(self, update_bounds: bool = True):
55
+ if self.roi.movable:
56
+ if update_bounds and self.x.size:
57
+ self.init_params, self.upper_bounds, self.lower_bounds = self.fitting_function.bounds(
58
+ self.x, self.y, self.roi, self.background)
59
+ else:
60
+ self.fitting_function.set_roi_from_params(self.roi, self.init_params)
61
+
62
+ self.background_curve = self.background(self.x, *self.init_params)
63
+ self.init_curve = self.fitting_function(self.x, self.background, *self.init_params)
64
+
65
+ if self.fitted_params:
66
+ self.fitting_curve = self.fitting_function(self.x, self.background, *self.fitted_params)
67
+
68
+ def set_background(self, background: Background, update: bool = True):
69
+ self.background = background
70
+ if update:
71
+ self.update_fit()
72
+
73
+ def set_function(self, fitting_function: FittingFunction, update: bool = True):
74
+ self.fitting_function = fitting_function
75
+ if update:
76
+ self.update_fit()
77
+
78
+ def do_fit(self) -> None:
79
+ if not self.y.size or not self.x.size:
80
+ return
81
+ try:
82
+ func = self.fitting_function.get_func(self.background)
83
+ popt, pcov = curve_fit(func, self.x, self.y, self.init_params,
84
+ bounds=self.bounds)
85
+ perr = np.sqrt(np.diag(pcov))
86
+
87
+ self.fitted_params = popt.tolist()
88
+ self.init_params = self.fitted_params
89
+ self.fit_errors = perr.tolist()
90
+ self.fitting_curve = func(self.x, *popt)
91
+ self.background_curve = self.background(self.x, *popt)
92
+ self.init_curve = self.fitting_curve
93
+ self.update_roi_fit_dict()
94
+ self.fitting_function.set_roi_from_params(self.roi, self.fitted_params)
95
+ except (ValueError, RuntimeError) as err:
96
+ logging.exception(err)
97
+ return
98
+
99
+ def set_roi_from_params(self, params=None):
100
+ if params is None:
101
+ if self.fitted_params is None:
102
+ return
103
+ params = self.fitted_params
104
+ if not params:
105
+ return
106
+ self.fitting_function.set_roi_from_params(self.roi, params)
107
+
108
+ def set_roi_from_range(self):
109
+ r1, r2 = self.r_range
110
+ roi = self.roi
111
+ roi.radius = (r1 + r2) / 2
112
+ roi.width = (r2 - r1) / 2
113
+
114
+ def update_roi_fit_dict(self):
115
+ self.roi.fitted_parameters = {}
116
+
117
+ if self.fitted_params is not None:
118
+ self.roi.fitted_parameters.update(dict(zip(self.param_names, self.fitted_params)))
119
+ self.roi.fitted_parameters['fitted_params'] = self.fitted_params
120
+ self.roi.fitted_parameters['fit_errors'] = self.fit_errors
121
+
122
+ self.roi.fitted_parameters['fitting_function'] = self.fitting_function.TYPE
123
+ self.roi.fitted_parameters['background'] = self.background.TYPE
124
+ self.roi.fitted_parameters['lower_bounds'] = self.lower_bounds
125
+ self.roi.fitted_parameters['init_params'] = self.init_params
126
+ self.roi.fitted_parameters['upper_bounds'] = self.upper_bounds
127
+ self.roi.fitted_parameters['r_range'] = self.r_range
128
+ self.roi.fitted_parameters['x_range'] = self.x_range