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,273 @@
1
+ from typing import Type
2
+ from copy import deepcopy
3
+
4
+ import numpy as np
5
+ from scipy.ndimage import gaussian_filter1d
6
+
7
+ from ..app import App
8
+ from .background import *
9
+ from .functions import *
10
+ from .fit import Fit
11
+ from .utils import _get_dummy_bounds, Roi
12
+ from .range_strategy import RangeStrategy, RangeStrategyType
13
+
14
+
15
+ class FitHolder(object):
16
+ MINIMAL_NUM: int = 5
17
+
18
+ def __init__(self):
19
+ self.app = App()
20
+ self.polar_image = None
21
+ self.fit = None
22
+ self.default_fitting: Type[FittingFunction] = Gaussian
23
+ self.default_background: Type[Background] = LinearBackground
24
+ self.default_range_strategy: RangeStrategy = RangeStrategy()
25
+
26
+ self.update_data()
27
+
28
+ def update_data(self):
29
+ self.polar_image = self.app.polar_image
30
+
31
+ if self.polar_image is None:
32
+ return
33
+
34
+ self.r_axis = self.app.geometry.r_axis
35
+ self.phi_axis = self.app.geometry.phi_axis
36
+ self.r_delta = (np.nanmax(self.r_axis) - np.nanmin(self.r_axis)) / self.r_axis.size
37
+ self.min_range: float = self.r_delta * self.MINIMAL_NUM
38
+ self.phi_delta = (np.nanmax(self.phi_axis) - np.nanmin(self.phi_axis)) / self.phi_axis.size
39
+ self.r_profile = np.nanmean(self.polar_image,axis=0)
40
+ self.aspect_ratio = self._aspect_ratio()
41
+ self.bounds = self._bounds()
42
+
43
+ # fit methods:
44
+
45
+ def new_fit(self, roi: Roi):
46
+ self.fit = self.init_fit_from_roi(roi)
47
+
48
+ return self.fit
49
+
50
+ def set_default_fit(self, roi):
51
+ roi.fitted_parameters = {}
52
+ self.fit = self.init_fit_from_roi(roi)
53
+ return self.fit
54
+
55
+ def set_default_bounds(self, roi):
56
+ if not roi.fitted_parameters:
57
+ return self.set_default_fit(roi)
58
+
59
+ for k in ('init_params', 'lower_bounds', 'upper_bounds', 'r_range'):
60
+ if k in roi.fitted_parameters:
61
+ roi.fitted_parameters.pop(k)
62
+
63
+ self.fit = self.init_fit_from_roi(roi)
64
+ return self.fit
65
+
66
+ def set_roi_from_range(self):
67
+ if not self.fit:
68
+ return
69
+ self.fit.set_roi_from_range()
70
+ self.fit.roi.fitted_parameters = {'r_range': self.fit.r_range}
71
+ self.fit = self.init_fit_from_roi(self.fit.roi)
72
+
73
+ def set_auto_range(self, roi=None, rel_pad: float = 3., const_pad: float = 5.):
74
+ update_fit = not bool(roi)
75
+
76
+ if roi is None:
77
+ if self.fit is None:
78
+ return
79
+ roi = self.fit.roi
80
+
81
+ r1, r2 = self._get_r_range(roi, self.default_range_strategy.range_factor)
82
+ pad = np.abs(r2 - r1) * rel_pad + const_pad
83
+ r1_large, r2_large = r1 - pad, r2 + pad
84
+ x1, x2, x1l, x2l = (
85
+ self._get_r_coords(r1),
86
+ self._get_r_coords(r2),
87
+ self._get_r_coords(r1_large),
88
+ self._get_r_coords(r2_large),
89
+ )
90
+
91
+ x, y, x_profile, y_profile = self._get_x_y(roi, x1l, x2l)
92
+
93
+ y_size = y_profile.size
94
+ y_profile_corrected = y_profile - (
95
+ y_profile[0] + (y_profile[-1] - y_profile[0]) / y_size * np.linspace(0, y_size, y_size)
96
+ )
97
+
98
+ y_profile_corrected = gaussian_filter1d(y_profile_corrected, 2)
99
+
100
+ left_indices = np.where(np.diff(np.sign(np.diff(y_profile_corrected[x1l:x1]))) > 0)[0]
101
+ if left_indices.size:
102
+ x1l = x1l + left_indices[-1]
103
+
104
+ right_indices = np.where(np.diff(np.sign(np.diff(y_profile_corrected[x2:x2l]))) > 0)[0]
105
+ if right_indices.size:
106
+ x2l = x2 + right_indices[0]
107
+
108
+ r1, r2 = self._get_r_from_coords(np.array([x1l, x2l]))
109
+
110
+ roi.fitted_parameters = {}
111
+ roi.fitted_parameters['r_range'] = r1, r2
112
+ fit = self.init_fit_from_roi(roi)
113
+
114
+ if update_fit:
115
+ self.fit = fit
116
+ return fit
117
+
118
+ def init_fit_from_roi(self, roi):
119
+ if not roi.fitted_parameters:
120
+ roi.fitted_parameters = {}
121
+ params = roi.fitted_parameters
122
+
123
+ if 'r_range' not in params:
124
+ r1, r2 = self._get_r_range(roi, self.default_range_strategy.range_factor)
125
+ else:
126
+ r1, r2 = params['r_range']
127
+
128
+ x1, x2 = self._get_r_coords(r1), self._get_r_coords(r2)
129
+ x, y, x_profile, y_profile = self._get_x_y(roi, x1, x2)
130
+
131
+ if 'background' in params:
132
+ background: Background = BACKGROUNDS[params['background']]()
133
+ function: FittingFunction = FITTING_FUNCTIONS[params['fitting_function']]()
134
+ else:
135
+ background: Background = self.default_background()
136
+ function: FittingFunction = self.default_fitting()
137
+
138
+ fitted_params = params.get('fitted_params', [])
139
+ fit_errors = params.get('fit_errors', [])
140
+
141
+ if x.size:
142
+ (
143
+ default_init_params,
144
+ default_upper_bounds,
145
+ default_lower_bounds,
146
+ ) = function.bounds(x, y, roi, background, params_from_roi=True)
147
+ else:
148
+ (
149
+ default_init_params,
150
+ default_upper_bounds,
151
+ default_lower_bounds,
152
+ ) = _get_dummy_bounds(function.NUM + background.NUM)
153
+
154
+ init_params, upper_bounds, lower_bounds = (
155
+ params.get('init_params', default_init_params),
156
+ params.get('upper_bounds', default_upper_bounds),
157
+ params.get('lower_bounds', default_lower_bounds)
158
+ )
159
+
160
+ background_curve = background(x, *init_params)
161
+ init_curve = function(x, background, *init_params)
162
+
163
+ if fitted_params:
164
+ fitting_curve = function(x, background, *fitted_params)
165
+ else:
166
+ fitting_curve = None
167
+
168
+ fit = Fit(roi=roi, r_range=(r1, r2), x_range=(x1, x2),
169
+ x=x, y=y, init_curve=init_curve, init_params=init_params,
170
+ lower_bounds=lower_bounds, upper_bounds=upper_bounds,
171
+ fitted_params=fitted_params, fit_errors=fit_errors, fitting_curve=fitting_curve,
172
+ fitting_function=function, background=background,
173
+ background_curve=background_curve, range_strategy=deepcopy(self.default_range_strategy),
174
+ x_profile=x_profile, y_profile=y_profile)
175
+
176
+ fit.update_roi_fit_dict()
177
+
178
+ return fit
179
+
180
+ def remove_fit(self):
181
+ self.fit = None
182
+
183
+ # fit properties:
184
+
185
+ def set_range_strategy(self, range_strategy: RangeStrategy, update: bool = True):
186
+ range_strategy.is_default = False
187
+ self.default_range_strategy = range_strategy
188
+ if not self.fit:
189
+ return
190
+
191
+ self.fit.range_strategy = range_strategy
192
+ if update:
193
+ self.update_fit_data(update_fit=True)
194
+
195
+ def set_background(self, background_type: BackgroundType):
196
+ background = BACKGROUNDS[background_type]
197
+ self.default_background = background
198
+ if not self.fit:
199
+ return
200
+ if self.fit.background.TYPE != background_type:
201
+ self.fit.set_background(background())
202
+ self.fit.background.is_default = False
203
+
204
+ def set_function(self, fitting_type: FittingType):
205
+ fitting_function = FITTING_FUNCTIONS[fitting_type]
206
+ self.default_fitting = fitting_function
207
+ if not self.fit:
208
+ return
209
+ if self.fit.fitting_function.TYPE != fitting_function:
210
+ self.fit.set_function(fitting_function())
211
+ self.fit.fitting_function.is_default = False
212
+
213
+ # private
214
+
215
+ def update_fit_data(self, update_r_range: bool = True, *, update_fit: bool = True, **kwargs):
216
+ fit = self.fit
217
+ if not fit:
218
+ return
219
+
220
+ if update_r_range and fit.range_strategy.strategy_type.value == RangeStrategyType.adjust.value:
221
+ fit.r_range = r1, r2 = self._get_r_range(fit.roi, fit.range_strategy.range_factor)
222
+ else:
223
+ r1, r2 = fit.r_range
224
+ x1, x2 = self._get_r_coords(r1), self._get_r_coords(r2)
225
+ fit.x, fit.y, fit.x_profile, fit.y_profile = self._get_x_y(fit.roi, x1, x2)
226
+
227
+ if update_fit:
228
+ fit.update_fit(**kwargs)
229
+
230
+ # Private methods for calculating geometric properties
231
+
232
+ def _get_r_range(self, roi: Roi, factor: float):
233
+ r1, r2 = roi.radius - roi.width * (factor + 1), roi.radius + roi.width * (factor + 1)
234
+ return min(r1, roi.radius - self.min_range / 2), max(r2, roi.radius + self.min_range / 2)
235
+
236
+ def _get_x_y(self, roi: Roi, x1: int, x2: int):
237
+ x_profile = self.r_axis.copy()
238
+ x = x_profile[x1:x2]
239
+ #remove nans
240
+ x = x[~np.isnan(x)]
241
+
242
+ if not roi.has_fixed_angles():
243
+ y_profile = self.r_profile.copy()
244
+ else:
245
+ p1, p2 = self._get_p_coords(roi.angle - roi.angle_std / 2), \
246
+ self._get_p_coords(roi.angle + roi.angle_std / 2)
247
+ y_profile = np.nanmean(self.polar_image[max(0, p1):min(p2, self.phi_axis.size - 1)],axis=0)
248
+
249
+ y = y_profile[x1:x2]
250
+
251
+ if x.size != y.size:
252
+ raise ValueError(f'x.size != y.size: {x.size} != {y.size}')
253
+
254
+ return x, y, x_profile, y_profile
255
+
256
+ def _get_r_coords(self, r):
257
+ r = np.clip(r, np.nanmin(self.r_axis), np.nanmax(self.r_axis))
258
+ return int(round((r - np.nanmin(self.r_axis)) / self.r_delta))
259
+
260
+ def _get_r_from_coords(self, x):
261
+ return x * self.r_delta + np.nanmin(self.r_axis)
262
+
263
+ def _get_p_coords(self, p):
264
+ p = np.clip(p, np.nanmin(self.phi_axis), np.nanmax(self.phi_axis))
265
+ return int(round((p - np.nanmin(self.phi_axis)) / self.phi_delta))
266
+
267
+ def _aspect_ratio(self):
268
+ p, r = self.phi_axis, self.r_axis
269
+ return (np.nanmax(p) - np.nanmin(p)) * p.size / np.nanmax(r) - np.nanmin(r) / r.size
270
+
271
+ def _bounds(self):
272
+ p = self.phi_axis
273
+ return (np.nanmax(p) + np.nanmin(p)) / 2, (np.nanmax(p) - np.nanmin(p))
@@ -0,0 +1,247 @@
1
+ from typing import Dict, Type
2
+ import numpy as np
3
+ from copy import deepcopy
4
+
5
+ from ..file_manager import ImageKey
6
+ from ..profiles import SavedProfile
7
+ from ..utils import smooth_curve, baseline_correction
8
+ from .background import *
9
+ from .functions import *
10
+ from .fit import Fit
11
+ from .utils import _get_dummy_bounds, Roi, RoiTypes
12
+ from .range_strategy import RangeStrategy, RangeStrategyType
13
+
14
+
15
+ class FitObject(object):
16
+ MINIMAL_NUM: int = 5
17
+
18
+ def __init__(self, image_key: ImageKey, polar_image: np.ndarray,
19
+ r_axis: np.ndarray, phi_axis: np.ndarray, *, saved_profile: SavedProfile = None,
20
+ update_baseline: bool = False):
21
+ self.image_key = image_key
22
+
23
+ self.polar_image = polar_image
24
+ self.r_axis = r_axis
25
+ self.phi_axis = phi_axis
26
+ self.r_delta = (np.nanmax(r_axis) - np.nanmin(r_axis)) / r_axis.size
27
+ self.min_range: float = self.r_delta * self.MINIMAL_NUM
28
+ self.phi_delta = (np.nanmax(phi_axis) - np.nanmin(phi_axis)) / phi_axis.size
29
+ self.r_profile = np.nanmean(polar_image,axis=0)
30
+ self.aspect_ratio = self._aspect_ratio()
31
+ self.bounds = self._bounds()
32
+
33
+ self.fits: Dict[int, Fit] = {}
34
+ self.name: str = ''
35
+ self.is_fitted: bool = False
36
+ self.saved_profile: SavedProfile or None = None
37
+
38
+ self.default_fitting: Type[FittingFunction] = Gaussian
39
+ self.default_background: Type[Background] = LinearBackground
40
+ self.default_range_strategy: RangeStrategy = RangeStrategy()
41
+ self.default_sigma: float = 0
42
+
43
+ if saved_profile:
44
+ self.set_profile(saved_profile, update_baseline)
45
+
46
+ # profile methods:
47
+
48
+ def set_profile(self, saved_profile: SavedProfile, update_baseline: bool = False):
49
+ if np.any(saved_profile.x != self.r_axis):
50
+ return
51
+
52
+ self.saved_profile = saved_profile
53
+ self.default_sigma = saved_profile.sigma
54
+
55
+ if update_baseline:
56
+ self.update_baseline()
57
+ else:
58
+ self.r_profile = smooth_curve(saved_profile.raw_data, saved_profile.sigma)
59
+ if saved_profile.baseline is not None:
60
+ self.r_profile = self.r_profile - saved_profile.baseline
61
+
62
+ self.update_fit_data(update_r_range=False, update_fit=True)
63
+
64
+ def update_baseline(self):
65
+ if self.saved_profile:
66
+ if not self.saved_profile.x_range:
67
+ self.saved_profile = None
68
+ return
69
+ self.saved_profile.x = self.r_axis
70
+ r1, r2 = self.saved_profile.x_range
71
+ x1, x2 = self._get_r_coords(r1), self._get_r_coords(r2)
72
+ self.saved_profile.raw_data = np.nanmean(self.polar_image,axis=0)
73
+ self.r_profile = smooth_curve(self.saved_profile.raw_data, self.saved_profile.sigma)
74
+
75
+ baseline = np.zeros_like(self.r_profile)
76
+
77
+ baseline[x1:x2] = baseline_correction(
78
+ self.r_profile[x1:x2], self.saved_profile.baseline_params.smoothness,
79
+ self.saved_profile.baseline_params.asymmetry)
80
+
81
+ self.saved_profile.baseline = baseline
82
+ self.r_profile = self.r_profile - baseline
83
+ self.update_fit_data(update_r_range=False, update_fit=True)
84
+
85
+ def clear_profile(self):
86
+ self.saved_profile = None
87
+ self.r_profile = np.nanmean(self.polar_image,axis=0)
88
+
89
+ # fit methods:
90
+
91
+ def add_fit(self, fit: Fit):
92
+ self.fits[fit.roi.key] = fit
93
+ fit.roi.movable = True
94
+ update_r_range = fit.range_strategy.strategy_type == RangeStrategyType.adjust
95
+ self.update_fit_data(fit, update_r_range, update_fit=True)
96
+
97
+ def new_fit(self, roi: Roi):
98
+ r1, r2 = self._get_r_range(roi, self.default_range_strategy.range_factor)
99
+
100
+ x1, x2 = self._get_r_coords(r1), self._get_r_coords(r2)
101
+ x, y = self._get_x_y(roi, x1, x2)
102
+
103
+ background: Background = self.default_background()
104
+ function: FittingFunction = self.default_fitting()
105
+
106
+ if x.size:
107
+ init_params, upper_bounds, lower_bounds = function.bounds(x, y, roi, background, params_from_roi=True)
108
+ else:
109
+ init_params, upper_bounds, lower_bounds = _get_dummy_bounds(function.NUM + background.NUM)
110
+
111
+ background_curve = background(x, *init_params)
112
+ init_curve = function(x, background, *init_params)
113
+
114
+ fit = Fit(roi=roi, r_range=(r1, r2), x_range=(x1, x2),
115
+ x=x, y=y, init_curve=init_curve, init_params=init_params,
116
+ lower_bounds=lower_bounds, upper_bounds=upper_bounds,
117
+ fitted_params=[], fit_errors=[], fitting_curve=None,
118
+ fitting_function=function, background=background,
119
+ background_curve=background_curve, range_strategy=deepcopy(self.default_range_strategy))
120
+
121
+ self.fits[roi.key] = fit
122
+
123
+ return fit
124
+
125
+ def update_fit_data(self, fit: Fit = None, update_r_range: bool = True, *, update_fit: bool = False, **kwargs):
126
+ if fit:
127
+ self._update_fit_data(fit, update_r_range, update_fit=update_fit, **kwargs)
128
+ else:
129
+ for fit in self.fits.values():
130
+ self._update_fit_data(fit, update_r_range, update_fit=update_fit, **kwargs)
131
+
132
+ def remove_fit(self, fit: Fit):
133
+ try:
134
+ del self.fits[fit.roi.key]
135
+ except KeyError:
136
+ return
137
+
138
+ # fit properties:
139
+
140
+ def set_sigma(self, sigma: float, fit: Fit = None):
141
+ if fit:
142
+ fit.sigma = sigma
143
+ self.update_fit_data(fit, update_fit=True)
144
+ else:
145
+ self._update_default_sigma(sigma)
146
+
147
+ for fit in self.fits.values():
148
+ if fit.sigma is None:
149
+ self.update_fit_data(fit, update_fit=True)
150
+
151
+ def set_range_strategy(self, range_strategy: RangeStrategy, fit: Fit = None, update: bool = True):
152
+ if fit:
153
+ range_strategy.is_default = False
154
+ fit.range_strategy = range_strategy
155
+ if update:
156
+ self.update_fit_data(fit, update_fit=True)
157
+ else:
158
+ range_strategy.is_default = True
159
+ self.default_range_strategy = range_strategy
160
+ for fit in self.fits.values():
161
+ if fit.range_strategy.is_default:
162
+ fit.range_strategy = deepcopy(range_strategy)
163
+ if update:
164
+ self.update_fit_data(fit, update_fit=True)
165
+
166
+ def set_background(self, background_type: BackgroundType, fit: Fit = None, update: bool = True):
167
+ background = BACKGROUNDS[background_type]
168
+ if fit and fit.background.TYPE != background_type:
169
+ fit.set_background(background())
170
+ fit.background.is_default = False
171
+ elif self.default_background.TYPE != background_type:
172
+ self.default_background = background
173
+ for fit in self.fits.values():
174
+ if fit.background.is_default:
175
+ fit.set_background(background(), update)
176
+ fit.background.is_default = True
177
+
178
+ def set_function(self, fitting_type: FittingType, fit: Fit = None, update: bool = True):
179
+ fitting_function = FITTING_FUNCTIONS[fitting_type]
180
+ if fit and fit.fitting_function.TYPE != fitting_function:
181
+ fit.set_function(fitting_function())
182
+ fit.fitting_function.is_default = False
183
+ elif self.default_fitting.TYPE != fitting_type:
184
+ self.default_fitting = fitting_function
185
+ for fit in self.fits.values():
186
+ if fit.fitting_function.is_default:
187
+ fit.set_function(fitting_function(), update)
188
+ fit .fitting_function.is_default = True
189
+
190
+ # private
191
+
192
+ def _update_fit_data(self, fit: Fit, update_r_range: bool = True, *, update_fit: bool = False, **kwargs):
193
+ if update_r_range and fit.range_strategy.strategy_type.value == RangeStrategyType.adjust.value:
194
+ fit.r_range = r1, r2 = self._get_r_range(fit.roi, fit.range_strategy.range_factor)
195
+ else:
196
+ r1, r2 = fit.r_range
197
+ x1, x2 = self._get_r_coords(r1), self._get_r_coords(r2)
198
+ fit.x, fit.y = self._get_x_y(fit.roi, x1, x2, fit.sigma)
199
+
200
+ if update_fit:
201
+ fit.update_fit(**kwargs)
202
+
203
+ def _update_default_sigma(self, sigma: float):
204
+ self.default_sigma = sigma
205
+ self.r_profile = smooth_curve(np.nanmean(self.polar_image,axis=0), sigma)
206
+
207
+ if self.saved_profile:
208
+ self.saved_profile.sigma = sigma
209
+ if self.saved_profile.baseline is not None:
210
+ self.r_profile = self.r_profile - self.saved_profile.baseline
211
+
212
+ # Private methods for calculating geometric properties
213
+
214
+ def _get_r_range(self, roi: Roi, factor: float):
215
+ r1, r2 = roi.radius - roi.width * (factor + 1), roi.radius + roi.width * (factor + 1)
216
+ return min(r1, roi.radius - self.min_range / 2), max(r2, roi.radius + self.min_range / 2)
217
+
218
+ def _get_x_y(self, roi: Roi, x1: int, x2: int, sigma: float = None):
219
+ x = self.r_axis[x1:x2]
220
+
221
+ if not roi.has_fixed_angles():
222
+ if sigma is None:
223
+ y = self.r_profile[x1:x2]
224
+ else:
225
+ y = smooth_curve(np.nanmean(self.polar_image[:, x1:x2],axis=0), sigma)
226
+ else:
227
+ if sigma is None:
228
+ sigma = self.default_sigma
229
+ p1, p2 = self._get_p_coords(roi.angle - roi.angle_std / 2), \
230
+ self._get_p_coords(roi.angle + roi.angle_std / 2)
231
+ y = smooth_curve(np.nanmean(self.polar_image[max(0, p1):min(p2, self.phi_axis.size - 1), x1:x2],axis=0), sigma)
232
+
233
+ return x, y
234
+
235
+ def _get_r_coords(self, r):
236
+ return int((r - np.nanmin(self.r_axis)) / self.r_delta)
237
+
238
+ def _get_p_coords(self, p):
239
+ return int((p - np.nanmin(self.phi_axis)) / self.phi_delta)
240
+
241
+ def _aspect_ratio(self):
242
+ p, r = self.phi_axis, self.r_axis
243
+ return (np.nanmax(p) - np.nanmin(p)) * p.size / (np.nanmax(r) - np.nanmin(r)) / r.size
244
+
245
+ def _bounds(self):
246
+ p = self.phi_axis
247
+ return (np.nanmax(p) + np.nanmin(p)) / 2, (np.nanmax(p) - np.nanmin(p))
@@ -0,0 +1,107 @@
1
+ from enum import Enum
2
+ from abc import abstractmethod
3
+ from typing import Tuple, Dict, Callable
4
+
5
+ import numpy as np
6
+
7
+ from .utils import Roi, _update_bounds
8
+ from .background import Background
9
+
10
+ __all__ = ['FittingType', 'FittingFunction', 'FITTING_FUNCTIONS', 'Gaussian', 'Lorentzian']
11
+
12
+
13
+ class FittingType(Enum):
14
+ gaussian = 'Gaussian'
15
+ lorentzian = 'Lorentzian'
16
+
17
+
18
+ class FittingFunction(object):
19
+ NAME: str = ''
20
+ PARAM_NAMES: tuple = ()
21
+ NUM: int = 0
22
+ TYPE: FittingType = None
23
+ is_default: bool = True
24
+
25
+ def __init__(self, *args, **kwargs):
26
+ pass
27
+
28
+ def get_func(self, background: Background) -> Callable:
29
+ def func(x: np.ndarray, *params):
30
+ return self.__call__(x, background, *params)
31
+
32
+ return func
33
+
34
+ def __call__(self, x: np.ndarray, background: Background, *params) -> np.ndarray:
35
+ return self.func(x, *params[:self.NUM]) + background(x, *params[self.NUM:])
36
+
37
+ @staticmethod
38
+ @abstractmethod
39
+ def func(x: np.ndarray, *params):
40
+ pass
41
+
42
+ @staticmethod
43
+ @abstractmethod
44
+ def set_roi_from_params(roi: Roi, params: list):
45
+ pass
46
+
47
+ @staticmethod
48
+ @abstractmethod
49
+ def set_params_from_roi(roi: Roi, params: list):
50
+ pass
51
+
52
+ @staticmethod
53
+ @abstractmethod
54
+ def _bounds(x: np.ndarray, y: np.ndarray, roi: Roi, background: Background):
55
+ pass
56
+
57
+ @classmethod
58
+ def bounds(cls, x: np.ndarray, y: np.ndarray, roi: Roi, background: Background, params_from_roi: bool = False):
59
+ if params_from_roi:
60
+ return _update_bounds(roi, list(cls.PARAM_NAMES) + list(background.PARAM_NAMES),
61
+ *cls._bounds(x, y, roi, background))
62
+ else:
63
+ return cls._bounds(x, y, roi, background)
64
+
65
+
66
+ class Gaussian(FittingFunction):
67
+ NAME: str = 'Gaussian'
68
+ PARAM_NAMES: tuple = ('peak height', 'radius', 'width')
69
+ NUM = 3
70
+ TYPE = FittingType.gaussian
71
+
72
+ @staticmethod
73
+ def func(x: np.ndarray, *params):
74
+ amp, mu, sigma, *_ = params
75
+ return amp * np.exp(- 2 * (x - mu) ** 2 / sigma ** 2)
76
+
77
+ @staticmethod
78
+ def set_roi_from_params(roi: Roi, params: list):
79
+ roi.radius = params[1]
80
+ roi.width = params[2]
81
+
82
+ @staticmethod
83
+ def _bounds(x: np.ndarray, y: np.ndarray, roi: Roi, background: Background):
84
+ init_b, upper_b, lower_b = background.bounds(x, y, roi)
85
+ amp, amp_max, amp_min = background.amp_bounds(x, y, init_b)
86
+
87
+ return ([amp, roi.radius, roi.width] + init_b,
88
+ [amp_max, roi.radius + roi.width / 2, roi.width * 2] + upper_b,
89
+ [amp_min, roi.radius - roi.width / 2, 0] + lower_b)
90
+
91
+
92
+ class Lorentzian(Gaussian):
93
+ NAME: str = 'Lorentzian'
94
+ PARAM_NAMES: tuple = ('peak height', 'radius', 'width')
95
+ TYPE = FittingType.lorentzian
96
+
97
+ @staticmethod
98
+ def func(x: np.ndarray, *params):
99
+ amp, mu, sigma, *_ = params
100
+ w = (sigma / 2) ** 2
101
+ return amp * w / (w + (x - mu) ** 2)
102
+
103
+
104
+ FITTING_FUNCTIONS: Dict[FittingType, FittingFunction.__class__] = {
105
+ FittingType.gaussian: Gaussian,
106
+ FittingType.lorentzian: Lorentzian,
107
+ }
@@ -0,0 +1,14 @@
1
+ from enum import Enum
2
+ from dataclasses import dataclass
3
+
4
+
5
+ class RangeStrategyType(Enum):
6
+ fixed = 'Fixed'
7
+ adjust = 'Adjust'
8
+
9
+
10
+ @dataclass
11
+ class RangeStrategy:
12
+ range_factor: float = 1
13
+ strategy_type: RangeStrategyType = RangeStrategyType.adjust
14
+ is_default: bool = True
@@ -0,0 +1,17 @@
1
+ from ..rois.roi import Roi, RoiTypes
2
+
3
+
4
+ def _update_bounds(roi: Roi, param_names, init_params, upper_bounds, lower_bounds):
5
+ if roi.fitted_parameters:
6
+ try:
7
+ new_init_params = [roi.fitted_parameters[k] for k in param_names]
8
+ for j, (l, i, u) in enumerate(zip(lower_bounds, new_init_params, upper_bounds)):
9
+ if l <= i <= u:
10
+ init_params[j] = i
11
+ except KeyError:
12
+ pass
13
+ return init_params, upper_bounds, lower_bounds
14
+
15
+
16
+ def _get_dummy_bounds(num: int):
17
+ return [0.5] * num, [1] * num, [0] * num